blob: 78fc6eb4baa2f0de148b14192ff09a814c57c350 [file] [log] [blame]
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001//===--- ASTWriter.cpp - AST File Writer ------------------------*- C++ -*-===//
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"
Douglas Gregor6623e1f2015-11-03 18:33:07 +000015#include "clang/Serialization/ModuleFileExtension.h"
Argyrios Kyrtzidis4bd97102010-08-20 16:03:52 +000016#include "ASTCommon.h"
Richard Smithd88a7f12015-09-01 20:35:42 +000017#include "ASTReaderInternals.h"
18#include "MultiOnDiskHashTable.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000019#include "clang/AST/ASTContext.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/DeclContextInternals.h"
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +000022#include "clang/AST/DeclFriend.h"
Richard Smith961eae52014-03-25 01:14:22 +000023#include "clang/AST/DeclLookups.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/AST/DeclTemplate.h"
Douglas Gregorfeb84b02009-04-14 21:18:50 +000025#include "clang/AST/Expr.h"
John McCallbfd822c2010-08-24 07:32:53 +000026#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000027#include "clang/AST/Type.h"
John McCall8f115c62009-10-16 21:56:05 +000028#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000029#include "clang/Basic/DiagnosticOptions.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000030#include "clang/Basic/FileManager.h"
Chris Lattner226efd32010-11-23 19:19:34 +000031#include "clang/Basic/FileSystemStatCache.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000032#include "clang/Basic/SourceManager.h"
Douglas Gregor4c7626e2009-04-13 16:31:14 +000033#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregorbfbde532009-04-10 21:16:55 +000034#include "clang/Basic/TargetInfo.h"
Douglas Gregorcb177f12012-10-16 23:40:58 +000035#include "clang/Basic/TargetOptions.h"
Douglas Gregor7b71e632009-04-27 22:23:34 +000036#include "clang/Basic/Version.h"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000037#include "clang/Basic/VersionTuple.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "clang/Lex/HeaderSearch.h"
39#include "clang/Lex/HeaderSearchOptions.h"
40#include "clang/Lex/MacroInfo.h"
41#include "clang/Lex/PreprocessingRecord.h"
42#include "clang/Lex/Preprocessor.h"
43#include "clang/Lex/PreprocessorOptions.h"
44#include "clang/Sema/IdentifierResolver.h"
45#include "clang/Sema/Sema.h"
46#include "clang/Serialization/ASTReader.h"
Richard Smithb5aaf5a2015-09-01 02:35:58 +000047#include "clang/Serialization/SerializationDiagnostic.h"
Douglas Gregore0a3a512009-04-14 21:55:33 +000048#include "llvm/ADT/APFloat.h"
49#include "llvm/ADT/APInt.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000050#include "llvm/ADT/Hashing.h"
Daniel Dunbarf8502d52009-10-17 23:52:28 +000051#include "llvm/ADT/StringExtras.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000052#include "llvm/Bitcode/BitstreamWriter.h"
Richard Smithaada85c2016-02-06 02:06:43 +000053#include "llvm/Support/Compression.h"
Justin Bognere1c147c2014-03-28 22:03:19 +000054#include "llvm/Support/EndianStream.h"
Michael J. Spencer740857f2010-12-21 16:45:57 +000055#include "llvm/Support/FileSystem.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000056#include "llvm/Support/MemoryBuffer.h"
Justin Bognerbb094f02014-04-18 19:57:06 +000057#include "llvm/Support/OnDiskHashTable.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000058#include "llvm/Support/Path.h"
Ben Langmuir487ea142014-10-23 18:05:36 +000059#include "llvm/Support/Process.h"
Douglas Gregor925296b2011-07-19 16:10:42 +000060#include <algorithm>
Chris Lattner225dd6c2009-04-11 18:40:46 +000061#include <cstdio>
Douglas Gregor09b69892011-02-10 17:09:37 +000062#include <string.h>
Douglas Gregor925296b2011-07-19 16:10:42 +000063#include <utility>
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +000064
Douglas Gregoref84c4b2009-04-09 22:27:44 +000065using namespace clang;
Sebastian Redl539c5062010-08-18 23:57:32 +000066using namespace clang::serialization;
Douglas Gregoref84c4b2009-04-09 22:27:44 +000067
Sebastian Redl3df5a082010-07-30 17:03:48 +000068template <typename T, typename Allocator>
Reid Kleckner012665e2015-05-21 00:13:09 +000069static StringRef bytes(const std::vector<T, Allocator> &v) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000070 if (v.empty()) return StringRef();
71 return StringRef(reinterpret_cast<const char*>(&v[0]),
Benjamin Kramerd47a12a2011-04-24 17:44:50 +000072 sizeof(T) * v.size());
Sebastian Redl3df5a082010-07-30 17:03:48 +000073}
Benjamin Kramerd47a12a2011-04-24 17:44:50 +000074
75template <typename T>
Reid Kleckner012665e2015-05-21 00:13:09 +000076static StringRef bytes(const SmallVectorImpl<T> &v) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000077 return StringRef(reinterpret_cast<const char*>(v.data()),
Benjamin Kramerd47a12a2011-04-24 17:44:50 +000078 sizeof(T) * v.size());
Sebastian Redl3df5a082010-07-30 17:03:48 +000079}
80
Douglas Gregoref84c4b2009-04-09 22:27:44 +000081//===----------------------------------------------------------------------===//
82// Type serialization
83//===----------------------------------------------------------------------===//
Chris Lattner7099dbc2009-04-27 06:16:06 +000084
Douglas Gregoref84c4b2009-04-09 22:27:44 +000085namespace {
Sebastian Redl42a0f6a2010-08-18 23:56:27 +000086 class ASTTypeWriter {
Sebastian Redl55c0ad52010-08-18 23:56:21 +000087 ASTWriter &Writer;
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +000088 ASTWriter::RecordDataImpl &Record;
Douglas Gregoref84c4b2009-04-09 22:27:44 +000089
90 public:
91 /// \brief Type code that corresponds to the record generated.
Sebastian Redl539c5062010-08-18 23:57:32 +000092 TypeCode Code;
Richard Smith01b2cb42014-07-26 06:37:51 +000093 /// \brief Abbreviation to use for the record, if any.
94 unsigned AbbrevToUse;
Douglas Gregoref84c4b2009-04-09 22:27:44 +000095
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +000096 ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
Sebastian Redl539c5062010-08-18 23:57:32 +000097 : Writer(Writer), Record(Record), Code(TYPE_EXT_QUAL) { }
Douglas Gregoref84c4b2009-04-09 22:27:44 +000098
99 void VisitArrayType(const ArrayType *T);
100 void VisitFunctionType(const FunctionType *T);
101 void VisitTagType(const TagType *T);
102
103#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
104#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000105#include "clang/AST/TypeNodes.def"
106 };
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +0000107} // end anonymous namespace
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000108
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000109void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
David Blaikie83d382b2011-09-23 05:06:16 +0000110 llvm_unreachable("Built-in types are never serialized");
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000111}
112
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000113void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000114 Writer.AddTypeRef(T->getElementType(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000115 Code = TYPE_COMPLEX;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000116}
117
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000118void ASTTypeWriter::VisitPointerType(const PointerType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000119 Writer.AddTypeRef(T->getPointeeType(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000120 Code = TYPE_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000121}
122
Reid Kleckner8a365022013-06-24 17:51:48 +0000123void ASTTypeWriter::VisitDecayedType(const DecayedType *T) {
124 Writer.AddTypeRef(T->getOriginalType(), Record);
125 Code = TYPE_DECAYED;
126}
127
Reid Kleckner0503a872013-12-05 01:23:43 +0000128void ASTTypeWriter::VisitAdjustedType(const AdjustedType *T) {
129 Writer.AddTypeRef(T->getOriginalType(), Record);
130 Writer.AddTypeRef(T->getAdjustedType(), Record);
131 Code = TYPE_ADJUSTED;
132}
133
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000134void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
Mike Stump11289f42009-09-09 15:08:12 +0000135 Writer.AddTypeRef(T->getPointeeType(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000136 Code = TYPE_BLOCK_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000137}
138
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000139void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
Richard Smith0f538462011-04-12 10:38:03 +0000140 Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
141 Record.push_back(T->isSpelledAsLValue());
Sebastian Redl539c5062010-08-18 23:57:32 +0000142 Code = TYPE_LVALUE_REFERENCE;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000143}
144
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000145void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
Richard Smith0f538462011-04-12 10:38:03 +0000146 Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000147 Code = TYPE_RVALUE_REFERENCE;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000148}
149
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000150void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
Mike Stump11289f42009-09-09 15:08:12 +0000151 Writer.AddTypeRef(T->getPointeeType(), Record);
152 Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000153 Code = TYPE_MEMBER_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000154}
155
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000156void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000157 Writer.AddTypeRef(T->getElementType(), Record);
158 Record.push_back(T->getSizeModifier()); // FIXME: stable values
John McCall8ccfcb52009-09-24 19:53:00 +0000159 Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000160}
161
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000162void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000163 VisitArrayType(T);
164 Writer.AddAPInt(T->getSize(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000165 Code = TYPE_CONSTANT_ARRAY;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000166}
167
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000168void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000169 VisitArrayType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000170 Code = TYPE_INCOMPLETE_ARRAY;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000171}
172
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000173void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000174 VisitArrayType(T);
Douglas Gregor04318252009-07-06 15:59:29 +0000175 Writer.AddSourceLocation(T->getLBracketLoc(), Record);
176 Writer.AddSourceLocation(T->getRBracketLoc(), Record);
Douglas Gregor8f45df52009-04-16 22:23:12 +0000177 Writer.AddStmt(T->getSizeExpr());
Sebastian Redl539c5062010-08-18 23:57:32 +0000178 Code = TYPE_VARIABLE_ARRAY;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000179}
180
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000181void ASTTypeWriter::VisitVectorType(const VectorType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000182 Writer.AddTypeRef(T->getElementType(), Record);
183 Record.push_back(T->getNumElements());
Bob Wilsonaeb56442010-11-10 21:56:12 +0000184 Record.push_back(T->getVectorKind());
Sebastian Redl539c5062010-08-18 23:57:32 +0000185 Code = TYPE_VECTOR;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000186}
187
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000188void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000189 VisitVectorType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000190 Code = TYPE_EXT_VECTOR;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000191}
192
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000193void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
Alp Toker314cc812014-01-25 16:55:45 +0000194 Writer.AddTypeRef(T->getReturnType(), Record);
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000195 FunctionType::ExtInfo C = T->getExtInfo();
196 Record.push_back(C.getNoReturn());
Eli Friedmanc5b20b52011-04-09 08:18:08 +0000197 Record.push_back(C.getHasRegParm());
Rafael Espindola49b85ab2010-03-30 22:15:11 +0000198 Record.push_back(C.getRegParm());
Douglas Gregor8c940862010-01-18 17:14:39 +0000199 // FIXME: need to stabilize encoding of calling convention...
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000200 Record.push_back(C.getCC());
John McCall31168b02011-06-15 23:02:42 +0000201 Record.push_back(C.getProducesResult());
Richard Smith01b2cb42014-07-26 06:37:51 +0000202
203 if (C.getHasRegParm() || C.getRegParm() || C.getProducesResult())
204 AbbrevToUse = 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000205}
206
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000207void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000208 VisitFunctionType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000209 Code = TYPE_FUNCTION_NO_PROTO;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000210}
211
Richard Smith564417a2014-03-20 21:47:22 +0000212static void addExceptionSpec(ASTWriter &Writer, const FunctionProtoType *T,
213 ASTWriter::RecordDataImpl &Record) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000214 Record.push_back(T->getExceptionSpecType());
215 if (T->getExceptionSpecType() == EST_Dynamic) {
216 Record.push_back(T->getNumExceptions());
217 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
218 Writer.AddTypeRef(T->getExceptionType(I), Record);
219 } else if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
220 Writer.AddStmt(T->getNoexceptExpr());
Richard Smith8b987a92012-04-21 17:47:47 +0000221 } else if (T->getExceptionSpecType() == EST_Uninstantiated) {
222 Writer.AddDeclRef(T->getExceptionSpecDecl(), Record);
223 Writer.AddDeclRef(T->getExceptionSpecTemplate(), Record);
Richard Smithd3b5c9082012-07-27 04:22:15 +0000224 } else if (T->getExceptionSpecType() == EST_Unevaluated) {
225 Writer.AddDeclRef(T->getExceptionSpecDecl(), Record);
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000226 }
Richard Smith564417a2014-03-20 21:47:22 +0000227}
228
229void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
230 VisitFunctionType(T);
Richard Smith01b2cb42014-07-26 06:37:51 +0000231
Richard Smith564417a2014-03-20 21:47:22 +0000232 Record.push_back(T->isVariadic());
233 Record.push_back(T->hasTrailingReturn());
234 Record.push_back(T->getTypeQuals());
235 Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
236 addExceptionSpec(Writer, T, Record);
Richard Smith01b2cb42014-07-26 06:37:51 +0000237
238 Record.push_back(T->getNumParams());
239 for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
240 Writer.AddTypeRef(T->getParamType(I), Record);
241
John McCall18afab72016-03-01 00:49:02 +0000242 if (T->hasExtParameterInfos()) {
243 for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
244 Record.push_back(T->getExtParameterInfo(I).getOpaqueValue());
245 }
246
Richard Smith01b2cb42014-07-26 06:37:51 +0000247 if (T->isVariadic() || T->hasTrailingReturn() || T->getTypeQuals() ||
John McCall18afab72016-03-01 00:49:02 +0000248 T->getRefQualifier() || T->getExceptionSpecType() != EST_None ||
249 T->hasExtParameterInfos())
Richard Smith01b2cb42014-07-26 06:37:51 +0000250 AbbrevToUse = 0;
251
Sebastian Redl539c5062010-08-18 23:57:32 +0000252 Code = TYPE_FUNCTION_PROTO;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000253}
254
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000255void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
John McCallb96ec562009-12-04 22:46:56 +0000256 Writer.AddDeclRef(T->getDecl(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000257 Code = TYPE_UNRESOLVED_USING;
John McCallb96ec562009-12-04 22:46:56 +0000258}
John McCallb96ec562009-12-04 22:46:56 +0000259
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000260void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000261 Writer.AddDeclRef(T->getDecl(), Record);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +0000262 assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
263 Writer.AddTypeRef(T->getCanonicalTypeInternal(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000264 Code = TYPE_TYPEDEF;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000265}
266
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000267void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
Douglas Gregor8f45df52009-04-16 22:23:12 +0000268 Writer.AddStmt(T->getUnderlyingExpr());
Sebastian Redl539c5062010-08-18 23:57:32 +0000269 Code = TYPE_TYPEOF_EXPR;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000270}
271
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000272void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000273 Writer.AddTypeRef(T->getUnderlyingType(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000274 Code = TYPE_TYPEOF;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000275}
276
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000277void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
Douglas Gregor81495f32012-02-12 18:42:33 +0000278 Writer.AddTypeRef(T->getUnderlyingType(), Record);
Anders Carlsson81df7b82009-06-24 19:06:50 +0000279 Writer.AddStmt(T->getUnderlyingExpr());
Sebastian Redl539c5062010-08-18 23:57:32 +0000280 Code = TYPE_DECLTYPE;
Anders Carlsson81df7b82009-06-24 19:06:50 +0000281}
282
Alexis Hunte852b102011-05-24 22:41:36 +0000283void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
284 Writer.AddTypeRef(T->getBaseType(), Record);
285 Writer.AddTypeRef(T->getUnderlyingType(), Record);
286 Record.push_back(T->getUTTKind());
287 Code = TYPE_UNARY_TRANSFORM;
288}
289
Richard Smith30482bc2011-02-20 03:19:35 +0000290void ASTTypeWriter::VisitAutoType(const AutoType *T) {
291 Writer.AddTypeRef(T->getDeducedType(), Record);
Richard Smithe301ba22015-11-11 02:02:15 +0000292 Record.push_back((unsigned)T->getKeyword());
Richard Smith27d807c2013-04-30 13:56:41 +0000293 if (T->getDeducedType().isNull())
294 Record.push_back(T->isDependentType());
Richard Smith30482bc2011-02-20 03:19:35 +0000295 Code = TYPE_AUTO;
296}
297
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000298void ASTTypeWriter::VisitTagType(const TagType *T) {
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +0000299 Record.push_back(T->isDependentType());
Douglas Gregorf3bccd72012-01-17 19:21:53 +0000300 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
Mike Stump11289f42009-09-09 15:08:12 +0000301 assert(!T->isBeingDefined() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000302 "Cannot serialize in the middle of a type definition");
303}
304
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000305void ASTTypeWriter::VisitRecordType(const RecordType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000306 VisitTagType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000307 Code = TYPE_RECORD;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000308}
309
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000310void ASTTypeWriter::VisitEnumType(const EnumType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000311 VisitTagType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000312 Code = TYPE_ENUM;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000313}
314
John McCall81904512011-01-06 01:58:22 +0000315void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
316 Writer.AddTypeRef(T->getModifiedType(), Record);
317 Writer.AddTypeRef(T->getEquivalentType(), Record);
318 Record.push_back(T->getAttrKind());
319 Code = TYPE_ATTRIBUTED;
320}
321
Mike Stump11289f42009-09-09 15:08:12 +0000322void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000323ASTTypeWriter::VisitSubstTemplateTypeParmType(
John McCallcebee162009-10-18 09:09:24 +0000324 const SubstTemplateTypeParmType *T) {
325 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
326 Writer.AddTypeRef(T->getReplacementType(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000327 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
John McCallcebee162009-10-18 09:09:24 +0000328}
329
330void
Douglas Gregorada4b792011-01-14 02:55:32 +0000331ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
332 const SubstTemplateTypeParmPackType *T) {
333 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
334 Writer.AddTemplateArgument(T->getArgumentPack(), Record);
335 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK;
336}
337
338void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000339ASTTypeWriter::VisitTemplateSpecializationType(
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000340 const TemplateSpecializationType *T) {
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +0000341 Record.push_back(T->isDependentType());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000342 Writer.AddTemplateName(T->getTemplateName(), Record);
343 Record.push_back(T->getNumArgs());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +0000344 for (const auto &ArgI : *T)
345 Writer.AddTemplateArgument(ArgI, Record);
Richard Smith3f1b5d02011-05-05 21:57:07 +0000346 Writer.AddTypeRef(T->isTypeAlias() ? T->getAliasedType() :
347 T->isCanonicalUnqualified() ? QualType()
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +0000348 : T->getCanonicalTypeInternal(),
349 Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000350 Code = TYPE_TEMPLATE_SPECIALIZATION;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000351}
352
353void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000354ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
Argyrios Kyrtzidis4a57bd02010-06-30 08:49:25 +0000355 VisitArrayType(T);
356 Writer.AddStmt(T->getSizeExpr());
357 Writer.AddSourceRange(T->getBracketsRange(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000358 Code = TYPE_DEPENDENT_SIZED_ARRAY;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000359}
360
361void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000362ASTTypeWriter::VisitDependentSizedExtVectorType(
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000363 const DependentSizedExtVectorType *T) {
364 // FIXME: Serialize this type (C++ only)
David Blaikie83d382b2011-09-23 05:06:16 +0000365 llvm_unreachable("Cannot serialize dependent sized extended vector types");
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000366}
367
368void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000369ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000370 Record.push_back(T->getDepth());
371 Record.push_back(T->getIndex());
372 Record.push_back(T->isParameterPack());
Chandler Carruth08836322011-05-01 00:51:33 +0000373 Writer.AddDeclRef(T->getDecl(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000374 Code = TYPE_TEMPLATE_TYPE_PARM;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000375}
376
377void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000378ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
Argyrios Kyrtzidisbfcacee2010-06-24 08:57:31 +0000379 Record.push_back(T->getKeyword());
380 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
381 Writer.AddIdentifierRef(T->getIdentifier(), Record);
Argyrios Kyrtzidise9290952010-07-02 11:55:24 +0000382 Writer.AddTypeRef(T->isCanonicalUnqualified() ? QualType()
383 : T->getCanonicalTypeInternal(),
384 Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000385 Code = TYPE_DEPENDENT_NAME;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000386}
387
388void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000389ASTTypeWriter::VisitDependentTemplateSpecializationType(
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000390 const DependentTemplateSpecializationType *T) {
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +0000391 Record.push_back(T->getKeyword());
392 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
393 Writer.AddIdentifierRef(T->getIdentifier(), Record);
394 Record.push_back(T->getNumArgs());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +0000395 for (const auto &I : *T)
396 Writer.AddTemplateArgument(I, Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000397 Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000398}
399
Douglas Gregord2fa7662010-12-20 02:24:11 +0000400void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
401 Writer.AddTypeRef(T->getPattern(), Record);
David Blaikie05785d12013-02-20 22:23:23 +0000402 if (Optional<unsigned> NumExpansions = T->getNumExpansions())
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000403 Record.push_back(*NumExpansions + 1);
404 else
405 Record.push_back(0);
Douglas Gregord2fa7662010-12-20 02:24:11 +0000406 Code = TYPE_PACK_EXPANSION;
407}
408
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000409void ASTTypeWriter::VisitParenType(const ParenType *T) {
410 Writer.AddTypeRef(T->getInnerType(), Record);
411 Code = TYPE_PAREN;
412}
413
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000414void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000415 Record.push_back(T->getKeyword());
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +0000416 Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
417 Writer.AddTypeRef(T->getNamedType(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000418 Code = TYPE_ELABORATED;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000419}
420
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000421void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
Douglas Gregor9f218892012-03-26 15:52:37 +0000422 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
John McCall2408e322010-04-27 00:57:59 +0000423 Writer.AddTypeRef(T->getInjectedSpecializationType(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000424 Code = TYPE_INJECTED_CLASS_NAME;
John McCalle78aac42010-03-10 03:28:59 +0000425}
426
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000427void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
Douglas Gregorf3bccd72012-01-17 19:21:53 +0000428 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000429 Code = TYPE_OBJC_INTERFACE;
John McCall8b07ec22010-05-15 11:32:37 +0000430}
431
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000432void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
John McCall8b07ec22010-05-15 11:32:37 +0000433 Writer.AddTypeRef(T->getBaseType(), Record);
Douglas Gregore83b9562015-07-07 03:57:53 +0000434 Record.push_back(T->getTypeArgsAsWritten().size());
435 for (auto TypeArg : T->getTypeArgsAsWritten())
Douglas Gregore9d95f12015-07-07 03:57:35 +0000436 Writer.AddTypeRef(TypeArg, Record);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000437 Record.push_back(T->getNumProtocols());
Aaron Ballman1683f7b2014-03-17 15:55:30 +0000438 for (const auto *I : T->quals())
439 Writer.AddDeclRef(I, Record);
Douglas Gregorab209d82015-07-07 03:58:42 +0000440 Record.push_back(T->isKindOfTypeAsWritten());
Sebastian Redl539c5062010-08-18 23:57:32 +0000441 Code = TYPE_OBJC_OBJECT;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000442}
443
Steve Narofffb4330f2009-06-17 22:40:22 +0000444void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000445ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
Mike Stump11289f42009-09-09 15:08:12 +0000446 Writer.AddTypeRef(T->getPointeeType(), Record);
Sebastian Redl539c5062010-08-18 23:57:32 +0000447 Code = TYPE_OBJC_OBJECT_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000448}
449
Eli Friedman0dfb8892011-10-06 23:00:33 +0000450void
451ASTTypeWriter::VisitAtomicType(const AtomicType *T) {
452 Writer.AddTypeRef(T->getValueType(), Record);
453 Code = TYPE_ATOMIC;
454}
455
Xiuli Pan9c14e282016-01-09 12:53:17 +0000456void
457ASTTypeWriter::VisitPipeType(const PipeType *T) {
458 Writer.AddTypeRef(T->getElementType(), Record);
459 Code = TYPE_PIPE;
460}
461
John McCall8f115c62009-10-16 21:56:05 +0000462namespace {
463
464class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
Sebastian Redl55c0ad52010-08-18 23:56:21 +0000465 ASTWriter &Writer;
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000466 ASTWriter::RecordDataImpl &Record;
John McCall8f115c62009-10-16 21:56:05 +0000467
468public:
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000469 TypeLocWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
John McCall8f115c62009-10-16 21:56:05 +0000470 : Writer(Writer), Record(Record) { }
471
John McCall17001972009-10-18 01:05:36 +0000472#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCall8f115c62009-10-16 21:56:05 +0000473#define TYPELOC(CLASS, PARENT) \
John McCall17001972009-10-18 01:05:36 +0000474 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +0000475#include "clang/AST/TypeLocNodes.def"
476
John McCall17001972009-10-18 01:05:36 +0000477 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
478 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +0000479};
480
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +0000481} // end anonymous namespace
John McCall8f115c62009-10-16 21:56:05 +0000482
John McCall17001972009-10-18 01:05:36 +0000483void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
484 // nothing to do
John McCall8f115c62009-10-16 21:56:05 +0000485}
John McCall17001972009-10-18 01:05:36 +0000486void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Douglas Gregorc9b7a592010-01-18 18:04:31 +0000487 Writer.AddSourceLocation(TL.getBuiltinLoc(), Record);
488 if (TL.needsExtraLocalData()) {
489 Record.push_back(TL.getWrittenTypeSpec());
490 Record.push_back(TL.getWrittenSignSpec());
491 Record.push_back(TL.getWrittenWidthSpec());
492 Record.push_back(TL.hasModeAttr());
493 }
John McCall8f115c62009-10-16 21:56:05 +0000494}
John McCall17001972009-10-18 01:05:36 +0000495void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
496 Writer.AddSourceLocation(TL.getNameLoc(), Record);
John McCall8f115c62009-10-16 21:56:05 +0000497}
John McCall17001972009-10-18 01:05:36 +0000498void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
499 Writer.AddSourceLocation(TL.getStarLoc(), Record);
John McCall8f115c62009-10-16 21:56:05 +0000500}
Reid Kleckner8a365022013-06-24 17:51:48 +0000501void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
502 // nothing to do
503}
Reid Kleckner0503a872013-12-05 01:23:43 +0000504void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
505 // nothing to do
506}
John McCall17001972009-10-18 01:05:36 +0000507void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
508 Writer.AddSourceLocation(TL.getCaretLoc(), Record);
John McCall8f115c62009-10-16 21:56:05 +0000509}
John McCall17001972009-10-18 01:05:36 +0000510void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
511 Writer.AddSourceLocation(TL.getAmpLoc(), Record);
John McCall8f115c62009-10-16 21:56:05 +0000512}
John McCall17001972009-10-18 01:05:36 +0000513void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
514 Writer.AddSourceLocation(TL.getAmpAmpLoc(), Record);
John McCall8f115c62009-10-16 21:56:05 +0000515}
John McCall17001972009-10-18 01:05:36 +0000516void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
517 Writer.AddSourceLocation(TL.getStarLoc(), Record);
Abramo Bagnara509357842011-03-05 14:42:21 +0000518 Writer.AddTypeSourceInfo(TL.getClassTInfo(), Record);
John McCall8f115c62009-10-16 21:56:05 +0000519}
John McCall17001972009-10-18 01:05:36 +0000520void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
521 Writer.AddSourceLocation(TL.getLBracketLoc(), Record);
522 Writer.AddSourceLocation(TL.getRBracketLoc(), Record);
523 Record.push_back(TL.getSizeExpr() ? 1 : 0);
524 if (TL.getSizeExpr())
525 Writer.AddStmt(TL.getSizeExpr());
John McCall8f115c62009-10-16 21:56:05 +0000526}
John McCall17001972009-10-18 01:05:36 +0000527void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
528 VisitArrayTypeLoc(TL);
529}
530void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
531 VisitArrayTypeLoc(TL);
532}
533void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
534 VisitArrayTypeLoc(TL);
535}
536void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
537 DependentSizedArrayTypeLoc TL) {
538 VisitArrayTypeLoc(TL);
539}
540void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
541 DependentSizedExtVectorTypeLoc TL) {
542 Writer.AddSourceLocation(TL.getNameLoc(), Record);
543}
544void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
545 Writer.AddSourceLocation(TL.getNameLoc(), Record);
546}
547void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
548 Writer.AddSourceLocation(TL.getNameLoc(), Record);
549}
550void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +0000551 Writer.AddSourceLocation(TL.getLocalRangeBegin(), Record);
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +0000552 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
553 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +0000554 Writer.AddSourceLocation(TL.getLocalRangeEnd(), Record);
Alp Tokerb3fd5cf2014-01-21 00:32:38 +0000555 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
556 Writer.AddDeclRef(TL.getParam(i), Record);
John McCall17001972009-10-18 01:05:36 +0000557}
558void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
559 VisitFunctionTypeLoc(TL);
560}
561void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
562 VisitFunctionTypeLoc(TL);
563}
John McCallb96ec562009-12-04 22:46:56 +0000564void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
565 Writer.AddSourceLocation(TL.getNameLoc(), Record);
566}
John McCall17001972009-10-18 01:05:36 +0000567void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
568 Writer.AddSourceLocation(TL.getNameLoc(), Record);
569}
570void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
John McCalle8595032010-01-13 20:03:27 +0000571 Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
572 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
573 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
John McCall17001972009-10-18 01:05:36 +0000574}
575void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
John McCalle8595032010-01-13 20:03:27 +0000576 Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
577 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
578 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
579 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
John McCall17001972009-10-18 01:05:36 +0000580}
581void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
582 Writer.AddSourceLocation(TL.getNameLoc(), Record);
583}
Alexis Hunte852b102011-05-24 22:41:36 +0000584void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
585 Writer.AddSourceLocation(TL.getKWLoc(), Record);
586 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
587 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
588 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
589}
Richard Smith30482bc2011-02-20 03:19:35 +0000590void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
591 Writer.AddSourceLocation(TL.getNameLoc(), Record);
592}
John McCall17001972009-10-18 01:05:36 +0000593void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
594 Writer.AddSourceLocation(TL.getNameLoc(), Record);
595}
596void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
597 Writer.AddSourceLocation(TL.getNameLoc(), Record);
598}
John McCall81904512011-01-06 01:58:22 +0000599void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
600 Writer.AddSourceLocation(TL.getAttrNameLoc(), Record);
601 if (TL.hasAttrOperand()) {
602 SourceRange range = TL.getAttrOperandParensRange();
603 Writer.AddSourceLocation(range.getBegin(), Record);
604 Writer.AddSourceLocation(range.getEnd(), Record);
605 }
606 if (TL.hasAttrExprOperand()) {
607 Expr *operand = TL.getAttrExprOperand();
608 Record.push_back(operand ? 1 : 0);
609 if (operand) Writer.AddStmt(operand);
610 } else if (TL.hasAttrEnumOperand()) {
611 Writer.AddSourceLocation(TL.getAttrEnumOperandLoc(), Record);
612 }
613}
John McCall17001972009-10-18 01:05:36 +0000614void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
615 Writer.AddSourceLocation(TL.getNameLoc(), Record);
616}
John McCallcebee162009-10-18 09:09:24 +0000617void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
618 SubstTemplateTypeParmTypeLoc TL) {
619 Writer.AddSourceLocation(TL.getNameLoc(), Record);
620}
Douglas Gregorada4b792011-01-14 02:55:32 +0000621void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
622 SubstTemplateTypeParmPackTypeLoc TL) {
623 Writer.AddSourceLocation(TL.getNameLoc(), Record);
624}
John McCall17001972009-10-18 01:05:36 +0000625void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
626 TemplateSpecializationTypeLoc TL) {
Abramo Bagnara48c05be2012-02-06 14:41:24 +0000627 Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record);
John McCall0ad16662009-10-29 08:12:44 +0000628 Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
629 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
630 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
631 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +0000632 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
633 TL.getArgLoc(i).getLocInfo(), Record);
John McCall17001972009-10-18 01:05:36 +0000634}
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000635void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
636 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
637 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
638}
Abramo Bagnara6150c882010-05-11 21:36:43 +0000639void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Abramo Bagnara9033e2b2012-02-06 19:09:27 +0000640 Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
Douglas Gregor844cb502011-03-01 18:12:44 +0000641 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
John McCall17001972009-10-18 01:05:36 +0000642}
John McCalle78aac42010-03-10 03:28:59 +0000643void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
644 Writer.AddSourceLocation(TL.getNameLoc(), Record);
645}
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +0000646void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Abramo Bagnara9033e2b2012-02-06 19:09:27 +0000647 Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +0000648 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
John McCall17001972009-10-18 01:05:36 +0000649 Writer.AddSourceLocation(TL.getNameLoc(), Record);
650}
John McCallc392f372010-06-11 00:33:02 +0000651void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
652 DependentTemplateSpecializationTypeLoc TL) {
Abramo Bagnara48c05be2012-02-06 14:41:24 +0000653 Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
Douglas Gregora7a795b2011-03-01 20:11:18 +0000654 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
Abramo Bagnarae0a70b22012-02-06 22:45:07 +0000655 Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record);
Abramo Bagnara48c05be2012-02-06 14:41:24 +0000656 Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
John McCallc392f372010-06-11 00:33:02 +0000657 Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
658 Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
659 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +0000660 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
661 TL.getArgLoc(I).getLocInfo(), Record);
John McCallc392f372010-06-11 00:33:02 +0000662}
Douglas Gregord2fa7662010-12-20 02:24:11 +0000663void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
664 Writer.AddSourceLocation(TL.getEllipsisLoc(), Record);
665}
John McCall17001972009-10-18 01:05:36 +0000666void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
667 Writer.AddSourceLocation(TL.getNameLoc(), Record);
John McCall8b07ec22010-05-15 11:32:37 +0000668}
669void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
670 Record.push_back(TL.hasBaseTypeAsWritten());
Douglas Gregore9d95f12015-07-07 03:57:35 +0000671 Writer.AddSourceLocation(TL.getTypeArgsLAngleLoc(), Record);
672 Writer.AddSourceLocation(TL.getTypeArgsRAngleLoc(), Record);
673 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
674 Writer.AddTypeSourceInfo(TL.getTypeArgTInfo(i), Record);
675 Writer.AddSourceLocation(TL.getProtocolLAngleLoc(), Record);
676 Writer.AddSourceLocation(TL.getProtocolRAngleLoc(), Record);
John McCall17001972009-10-18 01:05:36 +0000677 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
678 Writer.AddSourceLocation(TL.getProtocolLoc(i), Record);
John McCall8f115c62009-10-16 21:56:05 +0000679}
John McCallfc93cf92009-10-22 22:37:11 +0000680void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
681 Writer.AddSourceLocation(TL.getStarLoc(), Record);
John McCallfc93cf92009-10-22 22:37:11 +0000682}
Eli Friedman0dfb8892011-10-06 23:00:33 +0000683void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
684 Writer.AddSourceLocation(TL.getKWLoc(), Record);
685 Writer.AddSourceLocation(TL.getLParenLoc(), Record);
686 Writer.AddSourceLocation(TL.getRParenLoc(), Record);
687}
Xiuli Pan9c14e282016-01-09 12:53:17 +0000688void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
689 Writer.AddSourceLocation(TL.getKWLoc(), Record);
690}
John McCall8f115c62009-10-16 21:56:05 +0000691
Richard Smith01b2cb42014-07-26 06:37:51 +0000692void ASTWriter::WriteTypeAbbrevs() {
693 using namespace llvm;
694
695 BitCodeAbbrev *Abv;
696
697 // Abbreviation for TYPE_EXT_QUAL
698 Abv = new BitCodeAbbrev();
699 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
700 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
701 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals
702 TypeExtQualAbbrev = Stream.EmitAbbrev(Abv);
703
704 // Abbreviation for TYPE_FUNCTION_PROTO
705 Abv = new BitCodeAbbrev();
706 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_FUNCTION_PROTO));
707 // FunctionType
708 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ReturnType
709 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NoReturn
710 Abv->Add(BitCodeAbbrevOp(0)); // HasRegParm
711 Abv->Add(BitCodeAbbrevOp(0)); // RegParm
712 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // CC
713 Abv->Add(BitCodeAbbrevOp(0)); // ProducesResult
714 // FunctionProtoType
715 Abv->Add(BitCodeAbbrevOp(0)); // IsVariadic
716 Abv->Add(BitCodeAbbrevOp(0)); // HasTrailingReturn
717 Abv->Add(BitCodeAbbrevOp(0)); // TypeQuals
718 Abv->Add(BitCodeAbbrevOp(0)); // RefQualifier
719 Abv->Add(BitCodeAbbrevOp(EST_None)); // ExceptionSpec
720 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // NumParams
721 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
722 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Params
723 TypeFunctionProtoAbbrev = Stream.EmitAbbrev(Abv);
724}
725
Chris Lattner19cea4e2009-04-22 05:57:30 +0000726//===----------------------------------------------------------------------===//
Sebastian Redl55c0ad52010-08-18 23:56:21 +0000727// ASTWriter Implementation
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000728//===----------------------------------------------------------------------===//
729
Chris Lattner28fa4e62009-04-26 22:26:21 +0000730static void EmitBlockID(unsigned ID, const char *Name,
731 llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000732 ASTWriter::RecordDataImpl &Record) {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000733 Record.clear();
734 Record.push_back(ID);
735 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
736
737 // Emit the block name if present.
Craig Toppera13603a2014-05-22 05:54:18 +0000738 if (!Name || Name[0] == 0)
739 return;
Chris Lattner28fa4e62009-04-26 22:26:21 +0000740 Record.clear();
741 while (*Name)
742 Record.push_back(*Name++);
743 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
744}
745
746static void EmitRecordID(unsigned ID, const char *Name,
747 llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000748 ASTWriter::RecordDataImpl &Record) {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000749 Record.clear();
750 Record.push_back(ID);
751 while (*Name)
752 Record.push_back(*Name++);
753 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000754}
755
756static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000757 ASTWriter::RecordDataImpl &Record) {
Sebastian Redl539c5062010-08-18 23:57:32 +0000758#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
Chris Lattnerccac3a62009-04-27 00:49:53 +0000759 RECORD(STMT_STOP);
760 RECORD(STMT_NULL_PTR);
Richard Smith01b2cb42014-07-26 06:37:51 +0000761 RECORD(STMT_REF_PTR);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000762 RECORD(STMT_NULL);
763 RECORD(STMT_COMPOUND);
764 RECORD(STMT_CASE);
765 RECORD(STMT_DEFAULT);
766 RECORD(STMT_LABEL);
Richard Smithc202b282012-04-14 00:33:13 +0000767 RECORD(STMT_ATTRIBUTED);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000768 RECORD(STMT_IF);
769 RECORD(STMT_SWITCH);
770 RECORD(STMT_WHILE);
771 RECORD(STMT_DO);
772 RECORD(STMT_FOR);
773 RECORD(STMT_GOTO);
774 RECORD(STMT_INDIRECT_GOTO);
775 RECORD(STMT_CONTINUE);
776 RECORD(STMT_BREAK);
777 RECORD(STMT_RETURN);
778 RECORD(STMT_DECL);
Chad Rosierde70e0e2012-08-25 00:11:56 +0000779 RECORD(STMT_GCCASM);
Chad Rosiere30d4992012-08-24 23:51:02 +0000780 RECORD(STMT_MSASM);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000781 RECORD(EXPR_PREDEFINED);
782 RECORD(EXPR_DECL_REF);
783 RECORD(EXPR_INTEGER_LITERAL);
784 RECORD(EXPR_FLOATING_LITERAL);
785 RECORD(EXPR_IMAGINARY_LITERAL);
786 RECORD(EXPR_STRING_LITERAL);
787 RECORD(EXPR_CHARACTER_LITERAL);
788 RECORD(EXPR_PAREN);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000789 RECORD(EXPR_PAREN_LIST);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000790 RECORD(EXPR_UNARY_OPERATOR);
791 RECORD(EXPR_SIZEOF_ALIGN_OF);
792 RECORD(EXPR_ARRAY_SUBSCRIPT);
793 RECORD(EXPR_CALL);
794 RECORD(EXPR_MEMBER);
795 RECORD(EXPR_BINARY_OPERATOR);
796 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
797 RECORD(EXPR_CONDITIONAL_OPERATOR);
798 RECORD(EXPR_IMPLICIT_CAST);
799 RECORD(EXPR_CSTYLE_CAST);
800 RECORD(EXPR_COMPOUND_LITERAL);
801 RECORD(EXPR_EXT_VECTOR_ELEMENT);
802 RECORD(EXPR_INIT_LIST);
803 RECORD(EXPR_DESIGNATED_INIT);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000804 RECORD(EXPR_DESIGNATED_INIT_UPDATE);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000805 RECORD(EXPR_IMPLICIT_VALUE_INIT);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000806 RECORD(EXPR_NO_INIT);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000807 RECORD(EXPR_VA_ARG);
808 RECORD(EXPR_ADDR_LABEL);
809 RECORD(EXPR_STMT);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000810 RECORD(EXPR_CHOOSE);
811 RECORD(EXPR_GNU_NULL);
812 RECORD(EXPR_SHUFFLE_VECTOR);
813 RECORD(EXPR_BLOCK);
Peter Collingbourne91147592011-04-15 00:35:48 +0000814 RECORD(EXPR_GENERIC_SELECTION);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000815 RECORD(EXPR_OBJC_STRING_LITERAL);
Patrick Beard0caa3942012-04-19 00:25:12 +0000816 RECORD(EXPR_OBJC_BOXED_EXPRESSION);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000817 RECORD(EXPR_OBJC_ARRAY_LITERAL);
818 RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000819 RECORD(EXPR_OBJC_ENCODE);
820 RECORD(EXPR_OBJC_SELECTOR_EXPR);
821 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
822 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
823 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
824 RECORD(EXPR_OBJC_KVC_REF_EXPR);
825 RECORD(EXPR_OBJC_MESSAGE_EXPR);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000826 RECORD(STMT_OBJC_FOR_COLLECTION);
827 RECORD(STMT_OBJC_CATCH);
828 RECORD(STMT_OBJC_FINALLY);
829 RECORD(STMT_OBJC_AT_TRY);
830 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
831 RECORD(STMT_OBJC_AT_THROW);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000832 RECORD(EXPR_OBJC_BOOL_LITERAL);
Richard Smith01b2cb42014-07-26 06:37:51 +0000833 RECORD(STMT_CXX_CATCH);
834 RECORD(STMT_CXX_TRY);
835 RECORD(STMT_CXX_FOR_RANGE);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000836 RECORD(EXPR_CXX_OPERATOR_CALL);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000837 RECORD(EXPR_CXX_MEMBER_CALL);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000838 RECORD(EXPR_CXX_CONSTRUCT);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000839 RECORD(EXPR_CXX_TEMPORARY_OBJECT);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000840 RECORD(EXPR_CXX_STATIC_CAST);
841 RECORD(EXPR_CXX_DYNAMIC_CAST);
842 RECORD(EXPR_CXX_REINTERPRET_CAST);
843 RECORD(EXPR_CXX_CONST_CAST);
844 RECORD(EXPR_CXX_FUNCTIONAL_CAST);
Richard Smithc67fdd42012-03-07 08:35:16 +0000845 RECORD(EXPR_USER_DEFINED_LITERAL);
Richard Smithcc1b96d2013-06-12 22:31:48 +0000846 RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000847 RECORD(EXPR_CXX_BOOL_LITERAL);
848 RECORD(EXPR_CXX_NULL_PTR_LITERAL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000849 RECORD(EXPR_CXX_TYPEID_EXPR);
850 RECORD(EXPR_CXX_TYPEID_TYPE);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000851 RECORD(EXPR_CXX_THIS);
852 RECORD(EXPR_CXX_THROW);
853 RECORD(EXPR_CXX_DEFAULT_ARG);
Richard Smith01b2cb42014-07-26 06:37:51 +0000854 RECORD(EXPR_CXX_DEFAULT_INIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000855 RECORD(EXPR_CXX_BIND_TEMPORARY);
856 RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
857 RECORD(EXPR_CXX_NEW);
858 RECORD(EXPR_CXX_DELETE);
859 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
860 RECORD(EXPR_EXPR_WITH_CLEANUPS);
861 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
862 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
863 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
864 RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
865 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
Richard Smith01b2cb42014-07-26 06:37:51 +0000866 RECORD(EXPR_CXX_EXPRESSION_TRAIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000867 RECORD(EXPR_CXX_NOEXCEPT);
868 RECORD(EXPR_OPAQUE_VALUE);
Richard Smith01b2cb42014-07-26 06:37:51 +0000869 RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR);
870 RECORD(EXPR_TYPE_TRAIT);
871 RECORD(EXPR_ARRAY_TYPE_TRAIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000872 RECORD(EXPR_PACK_EXPANSION);
873 RECORD(EXPR_SIZEOF_PACK);
Richard Smith01b2cb42014-07-26 06:37:51 +0000874 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000875 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
Richard Smith01b2cb42014-07-26 06:37:51 +0000876 RECORD(EXPR_FUNCTION_PARM_PACK);
877 RECORD(EXPR_MATERIALIZE_TEMPORARY);
Peter Collingbourne41f85462011-02-09 21:07:24 +0000878 RECORD(EXPR_CUDA_KERNEL_CALL);
Richard Smith01b2cb42014-07-26 06:37:51 +0000879 RECORD(EXPR_CXX_UUIDOF_EXPR);
880 RECORD(EXPR_CXX_UUIDOF_TYPE);
881 RECORD(EXPR_LAMBDA);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000882#undef RECORD
Chris Lattner28fa4e62009-04-26 22:26:21 +0000883}
Mike Stump11289f42009-09-09 15:08:12 +0000884
Sebastian Redl55c0ad52010-08-18 23:56:21 +0000885void ASTWriter::WriteBlockInfoBlock() {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000886 RecordData Record;
887 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
Mike Stump11289f42009-09-09 15:08:12 +0000888
Sebastian Redl539c5062010-08-18 23:57:32 +0000889#define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
890#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
Mike Stump11289f42009-09-09 15:08:12 +0000891
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000892 // Control Block.
893 BLOCK(CONTROL_BLOCK);
894 RECORD(METADATA);
Ben Langmuir487ea142014-10-23 18:05:36 +0000895 RECORD(SIGNATURE);
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000896 RECORD(MODULE_NAME);
Richard Smithfa715652015-08-31 22:43:10 +0000897 RECORD(MODULE_DIRECTORY);
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000898 RECORD(MODULE_MAP_FILE);
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000899 RECORD(IMPORTS);
Douglas Gregorfad10d82012-10-18 18:36:53 +0000900 RECORD(ORIGINAL_FILE);
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000901 RECORD(ORIGINAL_PCH_DIR);
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +0000902 RECORD(ORIGINAL_FILE_ID);
Douglas Gregor3120d2c2012-10-22 18:42:04 +0000903 RECORD(INPUT_FILE_OFFSETS);
Richard Smith0516b182015-09-08 19:40:14 +0000904
905 BLOCK(OPTIONS_BLOCK);
906 RECORD(LANGUAGE_OPTIONS);
907 RECORD(TARGET_OPTIONS);
Douglas Gregor8263ffb2012-10-24 15:17:15 +0000908 RECORD(DIAGNOSTIC_OPTIONS);
Douglas Gregorc6317db2012-10-24 15:49:58 +0000909 RECORD(FILE_SYSTEM_OPTIONS);
Douglas Gregor2d302362012-10-24 16:50:34 +0000910 RECORD(HEADER_SEARCH_OPTIONS);
Douglas Gregorb6af6c22012-10-24 20:05:57 +0000911 RECORD(PREPROCESSOR_OPTIONS);
912
Douglas Gregor108cb222012-10-19 00:45:00 +0000913 BLOCK(INPUT_FILES_BLOCK);
914 RECORD(INPUT_FILE);
915
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000916 // AST Top-Level Block.
917 BLOCK(AST_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000918 RECORD(TYPE_OFFSET);
919 RECORD(DECL_OFFSET);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000920 RECORD(IDENTIFIER_OFFSET);
921 RECORD(IDENTIFIER_TABLE);
Ben Langmuir332aafe2014-01-31 01:06:56 +0000922 RECORD(EAGERLY_DESERIALIZED_DECLS);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000923 RECORD(SPECIAL_TYPES);
924 RECORD(STATISTICS);
925 RECORD(TENTATIVE_DEFINITIONS);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000926 RECORD(SELECTOR_OFFSETS);
927 RECORD(METHOD_POOL);
928 RECORD(PP_COUNTER_VALUE);
Douglas Gregor258ae542009-04-27 06:38:32 +0000929 RECORD(SOURCE_LOCATION_OFFSETS);
930 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor61cac2b2009-04-27 20:06:05 +0000931 RECORD(EXT_VECTOR_DECLS);
Richard Smithfa715652015-08-31 22:43:10 +0000932 RECORD(UNUSED_FILESCOPED_DECLS);
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +0000933 RECORD(PPD_ENTITIES_OFFSETS);
Richard Smithfa715652015-08-31 22:43:10 +0000934 RECORD(VTABLE_USES);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +0000935 RECORD(REFERENCED_SELECTOR_POOL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000936 RECORD(TU_UPDATE_LEXICAL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000937 RECORD(SEMA_DECL_REFS);
938 RECORD(WEAK_UNDECLARED_IDENTIFIERS);
939 RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000940 RECORD(UPDATE_VISIBLE);
941 RECORD(DECL_UPDATE_OFFSETS);
942 RECORD(DECL_UPDATES);
943 RECORD(CXX_BASE_SPECIFIER_OFFSETS);
944 RECORD(DIAG_PRAGMA_MAPPINGS);
Peter Collingbourne5df20e02011-02-15 19:46:30 +0000945 RECORD(CUDA_SPECIAL_DECL_REFS);
Douglas Gregor09b69892011-02-10 17:09:37 +0000946 RECORD(HEADER_SEARCH_TABLE);
Peter Collingbourne5df20e02011-02-15 19:46:30 +0000947 RECORD(FP_PRAGMA_OPTIONS);
948 RECORD(OPENCL_EXTENSIONS);
Alexis Hunt27a761d2011-05-04 23:29:54 +0000949 RECORD(DELEGATING_CTORS);
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000950 RECORD(KNOWN_NAMESPACES);
Douglas Gregor78d0b572011-08-04 16:39:39 +0000951 RECORD(MODULE_OFFSET_MAP);
952 RECORD(SOURCE_MANAGER_LINE_TABLE);
Douglas Gregor404cdde2012-01-27 01:47:08 +0000953 RECORD(OBJC_CATEGORIES_MAP);
Douglas Gregor66e4add2011-12-19 21:09:25 +0000954 RECORD(FILE_SORTED_DECLS);
955 RECORD(IMPORTED_MODULES);
Douglas Gregor404cdde2012-01-27 01:47:08 +0000956 RECORD(OBJC_CATEGORIES);
Douglas Gregorcb28f9d2012-10-09 23:05:51 +0000957 RECORD(MACRO_OFFSET);
Richard Smithfa715652015-08-31 22:43:10 +0000958 RECORD(INTERESTING_IDENTIFIERS);
959 RECORD(UNDEFINED_BUT_USED);
Richard Smithe40f2ba2013-08-07 21:41:30 +0000960 RECORD(LATE_PARSED_TEMPLATE);
Dario Domizioli13a0a382014-05-23 12:13:25 +0000961 RECORD(OPTIMIZE_PRAGMA_OPTIONS);
Nico Weber779355f2016-03-02 23:22:00 +0000962 RECORD(MSSTRUCT_PRAGMA_OPTIONS);
Nico Weber42932312016-03-03 00:17:35 +0000963 RECORD(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS);
Richard Smithfa715652015-08-31 22:43:10 +0000964 RECORD(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES);
965 RECORD(CXX_CTOR_INITIALIZERS_OFFSETS);
966 RECORD(DELETE_EXPRS_TO_ANALYZE);
Douglas Gregor358cd442012-01-15 16:58:34 +0000967
Chris Lattner28fa4e62009-04-26 22:26:21 +0000968 // SourceManager Block.
Chris Lattner64031982009-04-27 00:40:25 +0000969 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000970 RECORD(SM_SLOC_FILE_ENTRY);
971 RECORD(SM_SLOC_BUFFER_ENTRY);
972 RECORD(SM_SLOC_BUFFER_BLOB);
Richard Smithaada85c2016-02-06 02:06:43 +0000973 RECORD(SM_SLOC_BUFFER_BLOB_COMPRESSED);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +0000974 RECORD(SM_SLOC_EXPANSION_ENTRY);
Mike Stump11289f42009-09-09 15:08:12 +0000975
Chris Lattner28fa4e62009-04-26 22:26:21 +0000976 // Preprocessor Block.
Chris Lattner64031982009-04-27 00:40:25 +0000977 BLOCK(PREPROCESSOR_BLOCK);
Richard Smithec216502015-02-13 19:48:37 +0000978 RECORD(PP_MACRO_DIRECTIVE_HISTORY);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000979 RECORD(PP_MACRO_FUNCTION_LIKE);
Richard Smithd7329392015-04-21 21:46:32 +0000980 RECORD(PP_MACRO_OBJECT_LIKE);
981 RECORD(PP_MODULE_MACRO);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000982 RECORD(PP_TOKEN);
Richard Smithec216502015-02-13 19:48:37 +0000983
Richard Smithfa715652015-08-31 22:43:10 +0000984 // Submodule Block.
985 BLOCK(SUBMODULE_BLOCK);
986 RECORD(SUBMODULE_METADATA);
987 RECORD(SUBMODULE_DEFINITION);
988 RECORD(SUBMODULE_UMBRELLA_HEADER);
989 RECORD(SUBMODULE_HEADER);
990 RECORD(SUBMODULE_TOPHEADER);
991 RECORD(SUBMODULE_UMBRELLA_DIR);
992 RECORD(SUBMODULE_IMPORTS);
993 RECORD(SUBMODULE_EXPORTS);
994 RECORD(SUBMODULE_REQUIRES);
995 RECORD(SUBMODULE_EXCLUDED_HEADER);
996 RECORD(SUBMODULE_LINK_LIBRARY);
997 RECORD(SUBMODULE_CONFIG_MACRO);
998 RECORD(SUBMODULE_CONFLICT);
999 RECORD(SUBMODULE_PRIVATE_HEADER);
1000 RECORD(SUBMODULE_TEXTUAL_HEADER);
1001 RECORD(SUBMODULE_PRIVATE_TEXTUAL_HEADER);
1002
1003 // Comments Block.
1004 BLOCK(COMMENTS_BLOCK);
1005 RECORD(COMMENTS_RAW_COMMENT);
1006
Douglas Gregor12bfa382009-10-17 00:13:19 +00001007 // Decls and Types block.
1008 BLOCK(DECLTYPES_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001009 RECORD(TYPE_EXT_QUAL);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001010 RECORD(TYPE_COMPLEX);
1011 RECORD(TYPE_POINTER);
1012 RECORD(TYPE_BLOCK_POINTER);
1013 RECORD(TYPE_LVALUE_REFERENCE);
1014 RECORD(TYPE_RVALUE_REFERENCE);
1015 RECORD(TYPE_MEMBER_POINTER);
1016 RECORD(TYPE_CONSTANT_ARRAY);
1017 RECORD(TYPE_INCOMPLETE_ARRAY);
1018 RECORD(TYPE_VARIABLE_ARRAY);
1019 RECORD(TYPE_VECTOR);
1020 RECORD(TYPE_EXT_VECTOR);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001021 RECORD(TYPE_FUNCTION_NO_PROTO);
Richard Smithf1b4b8b2014-07-27 04:29:04 +00001022 RECORD(TYPE_FUNCTION_PROTO);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001023 RECORD(TYPE_TYPEDEF);
1024 RECORD(TYPE_TYPEOF_EXPR);
1025 RECORD(TYPE_TYPEOF);
1026 RECORD(TYPE_RECORD);
1027 RECORD(TYPE_ENUM);
1028 RECORD(TYPE_OBJC_INTERFACE);
Steve Narofffb4330f2009-06-17 22:40:22 +00001029 RECORD(TYPE_OBJC_OBJECT_POINTER);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001030 RECORD(TYPE_DECLTYPE);
1031 RECORD(TYPE_ELABORATED);
1032 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
1033 RECORD(TYPE_UNRESOLVED_USING);
1034 RECORD(TYPE_INJECTED_CLASS_NAME);
1035 RECORD(TYPE_OBJC_OBJECT);
1036 RECORD(TYPE_TEMPLATE_TYPE_PARM);
1037 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
1038 RECORD(TYPE_DEPENDENT_NAME);
1039 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
1040 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
1041 RECORD(TYPE_PAREN);
1042 RECORD(TYPE_PACK_EXPANSION);
1043 RECORD(TYPE_ATTRIBUTED);
1044 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
Richard Smithf1b4b8b2014-07-27 04:29:04 +00001045 RECORD(TYPE_AUTO);
1046 RECORD(TYPE_UNARY_TRANSFORM);
Eli Friedman0dfb8892011-10-06 23:00:33 +00001047 RECORD(TYPE_ATOMIC);
Richard Smithf1b4b8b2014-07-27 04:29:04 +00001048 RECORD(TYPE_DECAYED);
1049 RECORD(TYPE_ADJUSTED);
Richard Smithd61d4ac2015-08-22 20:13:39 +00001050 RECORD(LOCAL_REDECLARATIONS);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001051 RECORD(DECL_TYPEDEF);
Richard Smith01b2cb42014-07-26 06:37:51 +00001052 RECORD(DECL_TYPEALIAS);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001053 RECORD(DECL_ENUM);
1054 RECORD(DECL_RECORD);
1055 RECORD(DECL_ENUM_CONSTANT);
1056 RECORD(DECL_FUNCTION);
1057 RECORD(DECL_OBJC_METHOD);
1058 RECORD(DECL_OBJC_INTERFACE);
1059 RECORD(DECL_OBJC_PROTOCOL);
1060 RECORD(DECL_OBJC_IVAR);
1061 RECORD(DECL_OBJC_AT_DEFS_FIELD);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001062 RECORD(DECL_OBJC_CATEGORY);
1063 RECORD(DECL_OBJC_CATEGORY_IMPL);
1064 RECORD(DECL_OBJC_IMPLEMENTATION);
1065 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
1066 RECORD(DECL_OBJC_PROPERTY);
1067 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001068 RECORD(DECL_FIELD);
John McCall5e77d762013-04-16 07:28:30 +00001069 RECORD(DECL_MS_PROPERTY);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001070 RECORD(DECL_VAR);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001071 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001072 RECORD(DECL_PARM_VAR);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001073 RECORD(DECL_FILE_SCOPE_ASM);
1074 RECORD(DECL_BLOCK);
1075 RECORD(DECL_CONTEXT_LEXICAL);
1076 RECORD(DECL_CONTEXT_VISIBLE);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001077 RECORD(DECL_NAMESPACE);
1078 RECORD(DECL_NAMESPACE_ALIAS);
1079 RECORD(DECL_USING);
1080 RECORD(DECL_USING_SHADOW);
1081 RECORD(DECL_USING_DIRECTIVE);
1082 RECORD(DECL_UNRESOLVED_USING_VALUE);
1083 RECORD(DECL_UNRESOLVED_USING_TYPENAME);
1084 RECORD(DECL_LINKAGE_SPEC);
1085 RECORD(DECL_CXX_RECORD);
1086 RECORD(DECL_CXX_METHOD);
1087 RECORD(DECL_CXX_CONSTRUCTOR);
1088 RECORD(DECL_CXX_DESTRUCTOR);
1089 RECORD(DECL_CXX_CONVERSION);
1090 RECORD(DECL_ACCESS_SPEC);
1091 RECORD(DECL_FRIEND);
1092 RECORD(DECL_FRIEND_TEMPLATE);
1093 RECORD(DECL_CLASS_TEMPLATE);
1094 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
1095 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001096 RECORD(DECL_VAR_TEMPLATE);
1097 RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
1098 RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001099 RECORD(DECL_FUNCTION_TEMPLATE);
1100 RECORD(DECL_TEMPLATE_TYPE_PARM);
1101 RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
1102 RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
1103 RECORD(DECL_STATIC_ASSERT);
1104 RECORD(DECL_CXX_BASE_SPECIFIERS);
1105 RECORD(DECL_INDIRECTFIELD);
1106 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
1107
Douglas Gregor03412ba2011-06-03 02:27:19 +00001108 // Statements and Exprs can occur in the Decls and Types block.
1109 AddStmtsExprs(Stream, Record);
1110
Douglas Gregor92a96f52011-02-08 21:58:10 +00001111 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001112 RECORD(PPD_MACRO_EXPANSION);
Douglas Gregor92a96f52011-02-08 21:58:10 +00001113 RECORD(PPD_MACRO_DEFINITION);
1114 RECORD(PPD_INCLUSION_DIRECTIVE);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00001115
1116 // Decls and Types block.
1117 BLOCK(EXTENSION_BLOCK);
1118 RECORD(EXTENSION_METADATA);
1119
Chris Lattner28fa4e62009-04-26 22:26:21 +00001120#undef RECORD
1121#undef BLOCK
1122 Stream.ExitBlock();
1123}
1124
Richard Smith54cc3c22014-12-11 20:50:24 +00001125/// \brief Prepares a path for being written to an AST file by converting it
1126/// to an absolute path and removing nested './'s.
1127///
1128/// \return \c true if the path was changed.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001129static bool cleanPathForOutput(FileManager &FileMgr,
1130 SmallVectorImpl<char> &Path) {
Argyrios Kyrtzidis403cbcb2015-07-31 01:39:23 +00001131 bool Changed = FileMgr.makeAbsolutePath(Path);
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +00001132 return Changed | llvm::sys::path::remove_dots(Path);
Richard Smith54cc3c22014-12-11 20:50:24 +00001133}
1134
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001135/// \brief Adjusts the given filename to only write out the portion of the
1136/// filename that is not part of the system root directory.
Mike Stump11289f42009-09-09 15:08:12 +00001137///
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001138/// \param Filename the file name to adjust.
1139///
Richard Smith7ed1bc92014-12-05 22:42:13 +00001140/// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
1141/// the returned filename will be adjusted by this root directory.
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001142///
1143/// \returns either the original filename (if it needs no adjustment) or the
1144/// adjusted filename (which points into the @p Filename parameter).
Mike Stump11289f42009-09-09 15:08:12 +00001145static const char *
Richard Smith7ed1bc92014-12-05 22:42:13 +00001146adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001147 assert(Filename && "No file name to adjust?");
Mike Stump11289f42009-09-09 15:08:12 +00001148
Richard Smith7ed1bc92014-12-05 22:42:13 +00001149 if (BaseDir.empty())
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001150 return Filename;
Mike Stump11289f42009-09-09 15:08:12 +00001151
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001152 // Verify that the filename and the system root have the same prefix.
1153 unsigned Pos = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001154 for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
1155 if (Filename[Pos] != BaseDir[Pos])
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001156 return Filename; // Prefixes don't match.
Mike Stump11289f42009-09-09 15:08:12 +00001157
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001158 // We hit the end of the filename before we hit the end of the system root.
1159 if (!Filename[Pos])
1160 return Filename;
Mike Stump11289f42009-09-09 15:08:12 +00001161
Richard Smith7ed1bc92014-12-05 22:42:13 +00001162 // If there's not a path separator at the end of the base directory nor
1163 // immediately after it, then this isn't within the base directory.
1164 if (!llvm::sys::path::is_separator(Filename[Pos])) {
1165 if (!llvm::sys::path::is_separator(BaseDir.back()))
1166 return Filename;
1167 } else {
1168 // If the file name has a '/' at the current position, skip over the '/'.
1169 // We distinguish relative paths from absolute paths by the
1170 // absence of '/' at the beginning of relative paths.
1171 //
1172 // FIXME: This is wrong. We distinguish them by asking if the path is
1173 // absolute, which isn't the same thing. And there might be multiple '/'s
1174 // in a row. Use a better mechanism to indicate whether we have emitted an
1175 // absolute or relative path.
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001176 ++Pos;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001177 }
Mike Stump11289f42009-09-09 15:08:12 +00001178
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001179 return Filename + Pos;
1180}
Chris Lattner28fa4e62009-04-26 22:26:21 +00001181
Ben Langmuir487ea142014-10-23 18:05:36 +00001182static ASTFileSignature getSignature() {
1183 while (1) {
1184 if (ASTFileSignature S = llvm::sys::Process::GetRandomNumber())
1185 return S;
1186 // Rely on GetRandomNumber to eventually return non-zero...
1187 }
1188}
1189
Douglas Gregor112b9072012-10-18 05:31:06 +00001190/// \brief Write the control block.
Adrian Prantladbd2b12015-09-22 23:26:31 +00001191uint64_t ASTWriter::WriteControlBlock(Preprocessor &PP,
1192 ASTContext &Context,
1193 StringRef isysroot,
1194 const std::string &OutputFile) {
1195 ASTFileSignature Signature = 0;
1196
Douglas Gregorbfbde532009-04-10 21:16:55 +00001197 using namespace llvm;
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001198 Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001199 RecordData Record;
1200
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001201 // Metadata
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001202 auto *MetadataAbbrev = new BitCodeAbbrev();
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001203 MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1204 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1205 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1206 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1207 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1208 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
Richard Smithe75ee0f2015-08-17 07:13:32 +00001209 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001210 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1211 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1212 unsigned MetadataAbbrevCode = Stream.EmitAbbrev(MetadataAbbrev);
Richard Smith7ed1bc92014-12-05 22:42:13 +00001213 assert((!WritingModule || isysroot.empty()) &&
1214 "writing module as a relocatable PCH?");
Mehdi Amini57a41912015-09-10 01:46:39 +00001215 {
1216 RecordData::value_type Record[] = {METADATA, VERSION_MAJOR, VERSION_MINOR,
1217 CLANG_VERSION_MAJOR, CLANG_VERSION_MINOR,
1218 !isysroot.empty(), IncludeTimestamps,
1219 ASTHasCompilerErrors};
1220 Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1221 getClangFullRepositoryVersion());
1222 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001223 if (WritingModule) {
Chandler Carruth885e78c2015-03-24 21:18:10 +00001224 // For implicit modules we output a signature that we can use to ensure
1225 // duplicate module builds don't collide in the cache as their output order
1226 // is non-deterministic.
1227 // FIXME: Remove this when output is deterministic.
1228 if (Context.getLangOpts().ImplicitModules) {
Adrian Prantladbd2b12015-09-22 23:26:31 +00001229 Signature = getSignature();
1230 RecordData::value_type Record[] = {Signature};
Chandler Carruth885e78c2015-03-24 21:18:10 +00001231 Stream.EmitRecord(SIGNATURE, Record);
1232 }
1233
Richard Smith7ed1bc92014-12-05 22:42:13 +00001234 // Module name
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001235 auto *Abbrev = new BitCodeAbbrev();
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001236 Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1237 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1238 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00001239 RecordData::value_type Record[] = {MODULE_NAME};
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001240 Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1241 }
1242
Richard Smith7ed1bc92014-12-05 22:42:13 +00001243 if (WritingModule && WritingModule->Directory) {
Richard Smith7ed1bc92014-12-05 22:42:13 +00001244 SmallString<128> BaseDir(WritingModule->Directory->getName());
Richard Smith54cc3c22014-12-11 20:50:24 +00001245 cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
Richard Smithf7b41372015-08-13 23:47:44 +00001246
1247 // If the home of the module is the current working directory, then we
1248 // want to pick up the cwd of the build process loading the module, not
1249 // our cwd, when we load this module.
1250 if (!PP.getHeaderSearchInfo()
1251 .getHeaderSearchOpts()
1252 .ModuleMapFileHomeIsCwd ||
1253 WritingModule->Directory->getName() != StringRef(".")) {
1254 // Module directory.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001255 auto *Abbrev = new BitCodeAbbrev();
Richard Smithf7b41372015-08-13 23:47:44 +00001256 Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1257 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
1258 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1259
Mehdi Amini57a41912015-09-10 01:46:39 +00001260 RecordData::value_type Record[] = {MODULE_DIRECTORY};
Richard Smithf7b41372015-08-13 23:47:44 +00001261 Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
1262 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001263
1264 // Write out all other paths relative to the base directory if possible.
1265 BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1266 } else if (!isysroot.empty()) {
1267 // Write out paths relative to the sysroot if possible.
1268 BaseDirectory = isysroot;
1269 }
1270
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001271 // Module map file
1272 if (WritingModule) {
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001273 Record.clear();
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001274
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001275 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
1276
1277 // Primary module map file.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001278 AddPath(Map.getModuleMapFileForUniquing(WritingModule)->getName(), Record);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001279
1280 // Additional module map files.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001281 if (auto *AdditionalModMaps =
1282 Map.getAdditionalModuleMapFiles(WritingModule)) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001283 Record.push_back(AdditionalModMaps->size());
1284 for (const FileEntry *F : *AdditionalModMaps)
Richard Smith7ed1bc92014-12-05 22:42:13 +00001285 AddPath(F->getName(), Record);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001286 } else {
1287 Record.push_back(0);
1288 }
1289
1290 Stream.EmitRecord(MODULE_MAP_FILE, Record);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001291 }
1292
Douglas Gregor112b9072012-10-18 05:31:06 +00001293 // Imports
Douglas Gregor29cc6422011-08-17 21:07:30 +00001294 if (Chain) {
Douglas Gregor29cc6422011-08-17 21:07:30 +00001295 serialization::ModuleManager &Mgr = Chain->getModuleManager();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001296 Record.clear();
Douglas Gregordf0c1512011-08-18 04:12:04 +00001297
Richard Smith7f330cd2015-03-18 01:42:29 +00001298 for (auto *M : Mgr) {
Douglas Gregordf0c1512011-08-18 04:12:04 +00001299 // Skip modules that weren't directly imported.
Richard Smith7f330cd2015-03-18 01:42:29 +00001300 if (!M->isDirectlyImported())
Douglas Gregordf0c1512011-08-18 04:12:04 +00001301 continue;
1302
Richard Smith7f330cd2015-03-18 01:42:29 +00001303 Record.push_back((unsigned)M->Kind); // FIXME: Stable encoding
1304 AddSourceLocation(M->ImportLoc, Record);
1305 Record.push_back(M->File->getSize());
Richard Smithe75ee0f2015-08-17 07:13:32 +00001306 Record.push_back(getTimestampForOutput(M->File));
Richard Smith7f330cd2015-03-18 01:42:29 +00001307 Record.push_back(M->Signature);
1308 AddPath(M->FileName, Record);
Douglas Gregordf0c1512011-08-18 04:12:04 +00001309 }
Douglas Gregor29cc6422011-08-17 21:07:30 +00001310 Stream.EmitRecord(IMPORTS, Record);
1311 }
Mike Stump11289f42009-09-09 15:08:12 +00001312
Richard Smith0516b182015-09-08 19:40:14 +00001313 // Write the options block.
1314 Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
1315
Douglas Gregor112b9072012-10-18 05:31:06 +00001316 // Language options.
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001317 Record.clear();
Douglas Gregor112b9072012-10-18 05:31:06 +00001318 const LangOptions &LangOpts = Context.getLangOpts();
1319#define LANGOPT(Name, Bits, Default, Description) \
1320 Record.push_back(LangOpts.Name);
1321#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1322 Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001323#include "clang/Basic/LangOptions.def"
1324#define SANITIZER(NAME, ID) \
1325 Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
Will Dietzf54319c2013-01-18 11:30:38 +00001326#include "clang/Basic/Sanitizers.def"
Douglas Gregor112b9072012-10-18 05:31:06 +00001327
Ben Langmuircd98cb72015-06-23 18:20:18 +00001328 Record.push_back(LangOpts.ModuleFeatures.size());
1329 for (StringRef Feature : LangOpts.ModuleFeatures)
1330 AddString(Feature, Record);
1331
Douglas Gregor112b9072012-10-18 05:31:06 +00001332 Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1333 AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
Ben Langmuird4a667a2015-06-23 18:20:23 +00001334
1335 AddString(LangOpts.CurrentModule, Record);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001336
1337 // Comment options.
1338 Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001339 for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1340 AddString(I, Record);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001341 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00001342 Record.push_back(LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001343
Samuel Antaoee8fb302016-01-06 13:42:12 +00001344 // OpenMP offloading options.
1345 Record.push_back(LangOpts.OMPTargetTriples.size());
1346 for (auto &T : LangOpts.OMPTargetTriples)
1347 AddString(T.getTriple(), Record);
1348
1349 AddString(LangOpts.OMPHostIRFile, Record);
1350
Douglas Gregor112b9072012-10-18 05:31:06 +00001351 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1352
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001353 // Target options.
1354 Record.clear();
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001355 const TargetInfo &Target = Context.getTargetInfo();
1356 const TargetOptions &TargetOpts = Target.getTargetOpts();
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001357 AddString(TargetOpts.Triple, Record);
1358 AddString(TargetOpts.CPU, Record);
1359 AddString(TargetOpts.ABI, Record);
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001360 Record.push_back(TargetOpts.FeaturesAsWritten.size());
1361 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1362 AddString(TargetOpts.FeaturesAsWritten[I], Record);
1363 }
1364 Record.push_back(TargetOpts.Features.size());
1365 for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1366 AddString(TargetOpts.Features[I], Record);
1367 }
1368 Stream.EmitRecord(TARGET_OPTIONS, Record);
1369
Douglas Gregor8263ffb2012-10-24 15:17:15 +00001370 // Diagnostic options.
1371 Record.clear();
1372 const DiagnosticOptions &DiagOpts
1373 = Context.getDiagnostics().getDiagnosticOptions();
1374#define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1375#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1376 Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1377#include "clang/Basic/DiagnosticOptions.def"
1378 Record.push_back(DiagOpts.Warnings.size());
1379 for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1380 AddString(DiagOpts.Warnings[I], Record);
Richard Smith3be1cb22014-08-07 00:24:21 +00001381 Record.push_back(DiagOpts.Remarks.size());
1382 for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1383 AddString(DiagOpts.Remarks[I], Record);
Douglas Gregor8263ffb2012-10-24 15:17:15 +00001384 // Note: we don't serialize the log or serialization file names, because they
1385 // are generally transient files and will almost always be overridden.
1386 Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1387
Douglas Gregorc6317db2012-10-24 15:49:58 +00001388 // File system options.
1389 Record.clear();
Yaron Keren8dec46c2015-08-26 08:10:22 +00001390 const FileSystemOptions &FSOpts =
1391 Context.getSourceManager().getFileManager().getFileSystemOpts();
Douglas Gregorc6317db2012-10-24 15:49:58 +00001392 AddString(FSOpts.WorkingDir, Record);
1393 Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1394
Douglas Gregor2d302362012-10-24 16:50:34 +00001395 // Header search options.
1396 Record.clear();
1397 const HeaderSearchOptions &HSOpts
1398 = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1399 AddString(HSOpts.Sysroot, Record);
1400
1401 // Include entries.
1402 Record.push_back(HSOpts.UserEntries.size());
1403 for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1404 const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1405 AddString(Entry.Path, Record);
1406 Record.push_back(static_cast<unsigned>(Entry.Group));
Douglas Gregor2d302362012-10-24 16:50:34 +00001407 Record.push_back(Entry.IsFramework);
1408 Record.push_back(Entry.IgnoreSysRoot);
Douglas Gregor2d302362012-10-24 16:50:34 +00001409 }
1410
1411 // System header prefixes.
1412 Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1413 for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1414 AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1415 Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1416 }
1417
1418 AddString(HSOpts.ResourceDir, Record);
1419 AddString(HSOpts.ModuleCachePath, Record);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00001420 AddString(HSOpts.ModuleUserBuildPath, Record);
Douglas Gregor2d302362012-10-24 16:50:34 +00001421 Record.push_back(HSOpts.DisableModuleHash);
1422 Record.push_back(HSOpts.UseBuiltinIncludes);
1423 Record.push_back(HSOpts.UseStandardSystemIncludes);
1424 Record.push_back(HSOpts.UseStandardCXXIncludes);
1425 Record.push_back(HSOpts.UseLibcxx);
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00001426 // Write out the specific module cache path that contains the module files.
1427 AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
Douglas Gregor2d302362012-10-24 16:50:34 +00001428 Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1429
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001430 // Preprocessor options.
1431 Record.clear();
1432 const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1433
1434 // Macro definitions.
1435 Record.push_back(PPOpts.Macros.size());
1436 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1437 AddString(PPOpts.Macros[I].first, Record);
1438 Record.push_back(PPOpts.Macros[I].second);
1439 }
1440
1441 // Includes
1442 Record.push_back(PPOpts.Includes.size());
1443 for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1444 AddString(PPOpts.Includes[I], Record);
1445
1446 // Macro includes
1447 Record.push_back(PPOpts.MacroIncludes.size());
1448 for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1449 AddString(PPOpts.MacroIncludes[I], Record);
1450
Douglas Gregorb6368752012-10-24 23:41:50 +00001451 Record.push_back(PPOpts.UsePredefines);
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00001452 // Detailed record is important since it is used for the module cache hash.
1453 Record.push_back(PPOpts.DetailedRecord);
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001454 AddString(PPOpts.ImplicitPCHInclude, Record);
1455 AddString(PPOpts.ImplicitPTHInclude, Record);
1456 Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1457 Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1458
Richard Smith0516b182015-09-08 19:40:14 +00001459 // Leave the options block.
1460 Stream.ExitBlock();
1461
Douglas Gregora3b20262011-05-06 21:43:30 +00001462 // Original file name and file ID
Douglas Gregor45fe0362009-05-12 01:31:05 +00001463 SourceManager &SM = Context.getSourceManager();
1464 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001465 auto *FileAbbrev = new BitCodeAbbrev();
Douglas Gregorfad10d82012-10-18 18:36:53 +00001466 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1467 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
Douglas Gregor45fe0362009-05-12 01:31:05 +00001468 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1469 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
1470
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001471 Record.clear();
Douglas Gregorfad10d82012-10-18 18:36:53 +00001472 Record.push_back(ORIGINAL_FILE);
Douglas Gregora3b20262011-05-06 21:43:30 +00001473 Record.push_back(SM.getMainFileID().getOpaqueValue());
Richard Smith7ed1bc92014-12-05 22:42:13 +00001474 EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
Douglas Gregor45fe0362009-05-12 01:31:05 +00001475 }
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00001476
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +00001477 Record.clear();
1478 Record.push_back(SM.getMainFileID().getOpaqueValue());
1479 Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1480
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001481 // Original PCH directory
1482 if (!OutputFile.empty() && OutputFile != "-") {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001483 auto *Abbrev = new BitCodeAbbrev();
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001484 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1485 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1486 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1487
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001488 SmallString<128> OutputPath(OutputFile);
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001489
Argyrios Kyrtzidisc56419e2015-07-31 00:58:32 +00001490 SM.getFileManager().makeAbsolutePath(OutputPath);
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001491 StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1492
Mehdi Amini57a41912015-09-10 01:46:39 +00001493 RecordData::value_type Record[] = {ORIGINAL_PCH_DIR};
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001494 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1495 }
1496
Douglas Gregor49491f72013-03-15 22:15:07 +00001497 WriteInputFiles(Context.SourceMgr,
1498 PP.getHeaderSearchInfo().getHeaderSearchOpts(),
Douglas Gregora3dd9002013-07-22 20:48:33 +00001499 PP.getLangOpts().Modules);
Douglas Gregor72be3902012-10-19 00:38:02 +00001500 Stream.ExitBlock();
Adrian Prantladbd2b12015-09-22 23:26:31 +00001501 return Signature;
Douglas Gregor72be3902012-10-19 00:38:02 +00001502}
1503
Douglas Gregor49491f72013-03-15 22:15:07 +00001504namespace {
1505 /// \brief An input file.
1506 struct InputFileEntry {
1507 const FileEntry *File;
1508 bool IsSystemFile;
Richard Smitha8cfffa2015-11-26 02:04:16 +00001509 bool IsTransient;
Douglas Gregor49491f72013-03-15 22:15:07 +00001510 bool BufferOverridden;
1511 };
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001512} // end anonymous namespace
Douglas Gregor49491f72013-03-15 22:15:07 +00001513
1514void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1515 HeaderSearchOptions &HSOpts,
Douglas Gregora3dd9002013-07-22 20:48:33 +00001516 bool Modules) {
Douglas Gregor72be3902012-10-19 00:38:02 +00001517 using namespace llvm;
1518 Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
Mehdi Amini57a41912015-09-10 01:46:39 +00001519
Douglas Gregor72be3902012-10-19 00:38:02 +00001520 // Create input-file abbreviation.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001521 auto *IFAbbrev = new BitCodeAbbrev();
Douglas Gregor72be3902012-10-19 00:38:02 +00001522 IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001523 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
Douglas Gregor72be3902012-10-19 00:38:02 +00001524 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1525 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001526 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
Richard Smitha8cfffa2015-11-26 02:04:16 +00001527 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
Douglas Gregor72be3902012-10-19 00:38:02 +00001528 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1529 unsigned IFAbbrevCode = Stream.EmitAbbrev(IFAbbrev);
1530
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001531 // Get all ContentCache objects for files, sorted by whether the file is a
1532 // system one or not. System files go at the back, users files at the front.
Douglas Gregor49491f72013-03-15 22:15:07 +00001533 std::deque<InputFileEntry> SortedFiles;
Douglas Gregor72be3902012-10-19 00:38:02 +00001534 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1535 // Get this source location entry.
1536 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
NAKAMURA Takumideca50f2012-10-19 01:53:57 +00001537 assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
Douglas Gregor72be3902012-10-19 00:38:02 +00001538
1539 // We only care about file entries that were not overridden.
1540 if (!SLoc->isFile())
1541 continue;
1542 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001543 if (!Cache->OrigEntry)
Douglas Gregor72be3902012-10-19 00:38:02 +00001544 continue;
1545
Douglas Gregor49491f72013-03-15 22:15:07 +00001546 InputFileEntry Entry;
1547 Entry.File = Cache->OrigEntry;
1548 Entry.IsSystemFile = Cache->IsSystemFile;
Richard Smitha8cfffa2015-11-26 02:04:16 +00001549 Entry.IsTransient = Cache->IsTransient;
Douglas Gregor49491f72013-03-15 22:15:07 +00001550 Entry.BufferOverridden = Cache->BufferOverridden;
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001551 if (Cache->IsSystemFile)
Douglas Gregor49491f72013-03-15 22:15:07 +00001552 SortedFiles.push_back(Entry);
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001553 else
Douglas Gregor49491f72013-03-15 22:15:07 +00001554 SortedFiles.push_front(Entry);
1555 }
1556
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001557 unsigned UserFilesNum = 0;
1558 // Write out all of the input files.
Richard Smithec216502015-02-13 19:48:37 +00001559 std::vector<uint64_t> InputFileOffsets;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001560 for (const auto &Entry : SortedFiles) {
Douglas Gregor49491f72013-03-15 22:15:07 +00001561 uint32_t &InputFileID = InputFileIDs[Entry.File];
Argyrios Kyrtzidise65856f2012-12-11 07:48:08 +00001562 if (InputFileID != 0)
1563 continue; // already recorded this file.
1564
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001565 // Record this entry's offset.
1566 InputFileOffsets.push_back(Stream.GetCurrentBitNo());
Argyrios Kyrtzidise65856f2012-12-11 07:48:08 +00001567
1568 InputFileID = InputFileOffsets.size();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001569
Douglas Gregor49491f72013-03-15 22:15:07 +00001570 if (!Entry.IsSystemFile)
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001571 ++UserFilesNum;
1572
Douglas Gregor72be3902012-10-19 00:38:02 +00001573 // Emit size/modification time for this file.
Mehdi Amini57a41912015-09-10 01:46:39 +00001574 // And whether this file was overridden.
1575 RecordData::value_type Record[] = {
Richard Smitha8cfffa2015-11-26 02:04:16 +00001576 INPUT_FILE,
1577 InputFileOffsets.size(),
1578 (uint64_t)Entry.File->getSize(),
1579 (uint64_t)getTimestampForOutput(Entry.File),
1580 Entry.BufferOverridden,
1581 Entry.IsTransient};
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001582
Richard Smith7ed1bc92014-12-05 22:42:13 +00001583 EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
1584 }
Douglas Gregor49491f72013-03-15 22:15:07 +00001585
Douglas Gregor112b9072012-10-18 05:31:06 +00001586 Stream.ExitBlock();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001587
1588 // Create input file offsets abbreviation.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001589 auto *OffsetsAbbrev = new BitCodeAbbrev();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001590 OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1591 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001592 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1593 // input files
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001594 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
1595 unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(OffsetsAbbrev);
1596
1597 // Write input file offsets.
Mehdi Amini57a41912015-09-10 01:46:39 +00001598 RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
1599 InputFileOffsets.size(), UserFilesNum};
Reid Kleckner012665e2015-05-21 00:13:09 +00001600 Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
Douglas Gregor55abb232009-04-10 20:39:37 +00001601}
1602
Douglas Gregora7f71a92009-04-10 03:52:48 +00001603//===----------------------------------------------------------------------===//
1604// Source Manager Serialization
1605//===----------------------------------------------------------------------===//
1606
1607/// \brief Create an abbreviation for the SLocEntry that refers to a
1608/// file.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001609static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001610 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001611
1612 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00001613 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001614 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1615 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1616 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1617 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregorb41ca8f2010-03-21 22:49:54 +00001618 // FileEntry fields.
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001619 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001620 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00001621 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1622 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
Douglas Gregor8f45df52009-04-16 22:23:12 +00001623 return Stream.EmitAbbrev(Abbrev);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001624}
1625
1626/// \brief Create an abbreviation for the SLocEntry that refers to a
1627/// buffer.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001628static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001629 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001630
1631 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00001632 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001633 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1634 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1635 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1636 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1637 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregor8f45df52009-04-16 22:23:12 +00001638 return Stream.EmitAbbrev(Abbrev);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001639}
1640
1641/// \brief Create an abbreviation for the SLocEntry that refers to a
1642/// buffer's blob.
Richard Smithaada85c2016-02-06 02:06:43 +00001643static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
1644 bool Compressed) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001645 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001646
1647 auto *Abbrev = new BitCodeAbbrev();
Richard Smithaada85c2016-02-06 02:06:43 +00001648 Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED
1649 : SM_SLOC_BUFFER_BLOB));
1650 if (Compressed)
1651 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
Douglas Gregora7f71a92009-04-10 03:52:48 +00001652 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregor8f45df52009-04-16 22:23:12 +00001653 return Stream.EmitAbbrev(Abbrev);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001654}
1655
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001656/// \brief Create an abbreviation for the SLocEntry that refers to a macro
1657/// expansion.
1658static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001659 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001660
1661 auto *Abbrev = new BitCodeAbbrev();
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001662 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001663 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1664 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1665 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1666 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregor83243272009-04-15 18:05:10 +00001667 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregor8f45df52009-04-16 22:23:12 +00001668 return Stream.EmitAbbrev(Abbrev);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001669}
1670
Douglas Gregor09b69892011-02-10 17:09:37 +00001671namespace {
1672 // Trait used for the on-disk hash table of header search information.
1673 class HeaderFileInfoTrait {
1674 ASTWriter &Writer;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001675 const HeaderSearch &HS;
Douglas Gregor09b69892011-02-10 17:09:37 +00001676
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001677 // Keep track of the framework names we've used during serialization.
1678 SmallVector<char, 128> FrameworkStringData;
1679 llvm::StringMap<unsigned> FrameworkNameOffset;
1680
Douglas Gregor09b69892011-02-10 17:09:37 +00001681 public:
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001682 HeaderFileInfoTrait(ASTWriter &Writer, const HeaderSearch &HS)
1683 : Writer(Writer), HS(HS) { }
Douglas Gregor09b69892011-02-10 17:09:37 +00001684
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001685 struct key_type {
1686 const FileEntry *FE;
1687 const char *Filename;
1688 };
1689 typedef const key_type &key_type_ref;
Douglas Gregor09b69892011-02-10 17:09:37 +00001690
1691 typedef HeaderFileInfo data_type;
1692 typedef const data_type &data_type_ref;
Justin Bogner25463f12014-04-18 20:27:24 +00001693 typedef unsigned hash_value_type;
1694 typedef unsigned offset_type;
Douglas Gregor09b69892011-02-10 17:09:37 +00001695
Richard Smithe75ee0f2015-08-17 07:13:32 +00001696 hash_value_type ComputeHash(key_type_ref key) {
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001697 // The hash is based only on size/time of the file, so that the reader can
1698 // match even when symlinking or excess path elements ("foo/../", "../")
1699 // change the form of the name. However, complete path is still the key.
1700 return llvm::hash_combine(key.FE->getSize(),
Richard Smithe75ee0f2015-08-17 07:13:32 +00001701 Writer.getTimestampForOutput(key.FE));
Douglas Gregor09b69892011-02-10 17:09:37 +00001702 }
1703
1704 std::pair<unsigned,unsigned>
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001705 EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001706 using namespace llvm::support;
Richard Smith386bb072015-08-18 23:42:23 +00001707 endian::Writer<little> LE(Out);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001708 unsigned KeyLen = strlen(key.Filename) + 1 + 8 + 8;
Richard Smith386bb072015-08-18 23:42:23 +00001709 LE.write<uint16_t>(KeyLen);
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001710 unsigned DataLen = 1 + 2 + 4 + 4;
Richard Smith386bb072015-08-18 23:42:23 +00001711 for (auto ModInfo : HS.getModuleMap().findAllModulesForHeader(key.FE))
1712 if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
1713 DataLen += 4;
1714 LE.write<uint8_t>(DataLen);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001715 return std::make_pair(KeyLen, DataLen);
Douglas Gregor09b69892011-02-10 17:09:37 +00001716 }
1717
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001718 void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001719 using namespace llvm::support;
1720 endian::Writer<little> LE(Out);
1721 LE.write<uint64_t>(key.FE->getSize());
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001722 KeyLen -= 8;
Richard Smithe75ee0f2015-08-17 07:13:32 +00001723 LE.write<uint64_t>(Writer.getTimestampForOutput(key.FE));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001724 KeyLen -= 8;
1725 Out.write(key.Filename, KeyLen);
Douglas Gregor09b69892011-02-10 17:09:37 +00001726 }
1727
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001728 void EmitData(raw_ostream &Out, key_type_ref key,
Douglas Gregor09b69892011-02-10 17:09:37 +00001729 data_type_ref Data, unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001730 using namespace llvm::support;
1731 endian::Writer<little> LE(Out);
Douglas Gregor09b69892011-02-10 17:09:37 +00001732 uint64_t Start = Out.tell(); (void)Start;
1733
Richard Smith386bb072015-08-18 23:42:23 +00001734 unsigned char Flags = (Data.isImport << 4)
1735 | (Data.isPragmaOnce << 3)
1736 | (Data.DirInfo << 1)
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001737 | Data.IndexHeaderMapHeader;
Justin Bognere1c147c2014-03-28 22:03:19 +00001738 LE.write<uint8_t>(Flags);
1739 LE.write<uint16_t>(Data.NumIncludes);
Douglas Gregor09b69892011-02-10 17:09:37 +00001740
1741 if (!Data.ControllingMacro)
Justin Bognere1c147c2014-03-28 22:03:19 +00001742 LE.write<uint32_t>(Data.ControllingMacroID);
Douglas Gregor09b69892011-02-10 17:09:37 +00001743 else
Justin Bognere1c147c2014-03-28 22:03:19 +00001744 LE.write<uint32_t>(Writer.getIdentifierRef(Data.ControllingMacro));
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001745
1746 unsigned Offset = 0;
1747 if (!Data.Framework.empty()) {
1748 // If this header refers into a framework, save the framework name.
1749 llvm::StringMap<unsigned>::iterator Pos
1750 = FrameworkNameOffset.find(Data.Framework);
1751 if (Pos == FrameworkNameOffset.end()) {
1752 Offset = FrameworkStringData.size() + 1;
1753 FrameworkStringData.append(Data.Framework.begin(),
1754 Data.Framework.end());
1755 FrameworkStringData.push_back(0);
1756
1757 FrameworkNameOffset[Data.Framework] = Offset;
1758 } else
1759 Offset = Pos->second;
1760 }
Justin Bognere1c147c2014-03-28 22:03:19 +00001761 LE.write<uint32_t>(Offset);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001762
Richard Smith386bb072015-08-18 23:42:23 +00001763 // FIXME: If the header is excluded, we should write out some
1764 // record of that fact.
1765 for (auto ModInfo : HS.getModuleMap().findAllModulesForHeader(key.FE)) {
1766 if (uint32_t ModID =
1767 Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule())) {
1768 uint32_t Value = (ModID << 2) | (unsigned)ModInfo.getRole();
1769 assert((Value >> 2) == ModID && "overflow in header module info");
1770 LE.write<uint32_t>(Value);
1771 }
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001772 }
1773
Douglas Gregor09b69892011-02-10 17:09:37 +00001774 assert(Out.tell() - Start == DataLen && "Wrong data length");
1775 }
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001776
1777 const char *strings_begin() const { return FrameworkStringData.begin(); }
1778 const char *strings_end() const { return FrameworkStringData.end(); }
Douglas Gregor09b69892011-02-10 17:09:37 +00001779 };
1780} // end anonymous namespace
1781
1782/// \brief Write the header search block for the list of files that
1783///
1784/// \param HS The header search structure to save.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001785void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001786 SmallVector<const FileEntry *, 16> FilesByUID;
Douglas Gregor09b69892011-02-10 17:09:37 +00001787 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
1788
1789 if (FilesByUID.size() > HS.header_file_size())
1790 FilesByUID.resize(HS.header_file_size());
1791
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001792 HeaderFileInfoTrait GeneratorTrait(*this, HS);
Justin Bognerbb094f02014-04-18 19:57:06 +00001793 llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001794 SmallVector<const char *, 4> SavedStrings;
Douglas Gregor09b69892011-02-10 17:09:37 +00001795 unsigned NumHeaderSearchEntries = 0;
1796 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1797 const FileEntry *File = FilesByUID[UID];
1798 if (!File)
1799 continue;
1800
Richard Smith386bb072015-08-18 23:42:23 +00001801 // Get the file info. This will load info from the external source if
1802 // necessary. Skip emitting this file if we have no information on it
1803 // as a header file (in which case HFI will be null) or if it hasn't
1804 // changed since it was loaded. Also skip it if it's for a modular header
1805 // from a different module; in that case, we rely on the module(s)
1806 // containing the header to provide this information.
Richard Smithd8879c82015-08-24 21:59:32 +00001807 const HeaderFileInfo *HFI =
1808 HS.getExistingFileInfo(File, /*WantExternal*/!Chain);
1809 if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001810 continue;
Douglas Gregor09b69892011-02-10 17:09:37 +00001811
Richard Smith7ed1bc92014-12-05 22:42:13 +00001812 // Massage the file path into an appropriate form.
Douglas Gregor09b69892011-02-10 17:09:37 +00001813 const char *Filename = File->getName();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001814 SmallString<128> FilenameTmp(Filename);
1815 if (PreparePathForOutput(FilenameTmp)) {
1816 // If we performed any translation on the file name at all, we need to
1817 // save this string, since the generator will refer to it later.
1818 Filename = strdup(FilenameTmp.c_str());
Douglas Gregor09b69892011-02-10 17:09:37 +00001819 SavedStrings.push_back(Filename);
1820 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001821
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001822 HeaderFileInfoTrait::key_type key = { File, Filename };
Richard Smith386bb072015-08-18 23:42:23 +00001823 Generator.insert(key, *HFI, GeneratorTrait);
Douglas Gregor09b69892011-02-10 17:09:37 +00001824 ++NumHeaderSearchEntries;
1825 }
1826
1827 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001828 SmallString<4096> TableData;
Douglas Gregor09b69892011-02-10 17:09:37 +00001829 uint32_t BucketOffset;
1830 {
Justin Bognere1c147c2014-03-28 22:03:19 +00001831 using namespace llvm::support;
Douglas Gregor09b69892011-02-10 17:09:37 +00001832 llvm::raw_svector_ostream Out(TableData);
1833 // Make sure that no bucket is at offset 0
Justin Bognere1c147c2014-03-28 22:03:19 +00001834 endian::Writer<little>(Out).write<uint32_t>(0);
Douglas Gregor09b69892011-02-10 17:09:37 +00001835 BucketOffset = Generator.Emit(Out, GeneratorTrait);
1836 }
1837
1838 // Create a blob abbreviation
1839 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001840
1841 auto *Abbrev = new BitCodeAbbrev();
Douglas Gregor09b69892011-02-10 17:09:37 +00001842 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1843 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1844 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001845 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor09b69892011-02-10 17:09:37 +00001846 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1847 unsigned TableAbbrev = Stream.EmitAbbrev(Abbrev);
1848
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001849 // Write the header search table
Mehdi Amini57a41912015-09-10 01:46:39 +00001850 RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
1851 NumHeaderSearchEntries, TableData.size()};
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001852 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
Yaron Keren92e1b622015-03-18 10:17:07 +00001853 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
Douglas Gregor09b69892011-02-10 17:09:37 +00001854
1855 // Free all of the strings we had to duplicate.
1856 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
David Greenebae0e352013-01-15 22:09:43 +00001857 free(const_cast<char *>(SavedStrings[I]));
Douglas Gregor09b69892011-02-10 17:09:37 +00001858}
1859
Douglas Gregora7f71a92009-04-10 03:52:48 +00001860/// \brief Writes the block containing the serialized form of the
1861/// source manager.
1862///
1863/// TODO: We should probably use an on-disk hash table (stored in a
1864/// blob), indexed based on the file name, so that we only create
1865/// entries for files that we actually need. In the common case (no
1866/// errors), we probably won't have to create file entries for any of
1867/// the files in the AST.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00001868void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001869 const Preprocessor &PP) {
Douglas Gregor258ae542009-04-27 06:38:32 +00001870 RecordData Record;
1871
Chris Lattner0910e3b2009-04-10 17:16:57 +00001872 // Enter the source manager block.
Richard Smithaada85c2016-02-06 02:06:43 +00001873 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001874
1875 // Abbreviations for the various kinds of source-location entries.
Chris Lattnerc4976c732009-04-27 19:03:22 +00001876 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
1877 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
Richard Smithaada85c2016-02-06 02:06:43 +00001878 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
1879 unsigned SLocBufferBlobCompressedAbbrv =
1880 CreateSLocBufferBlobAbbrev(Stream, true);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001881 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001882
Douglas Gregor258ae542009-04-27 06:38:32 +00001883 // Write out the source location entry table. We skip the first
1884 // entry, which is always the same dummy entry.
Chris Lattner12d61d32009-04-27 19:01:47 +00001885 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor258ae542009-04-27 06:38:32 +00001886 RecordData PreloadSLocs;
Douglas Gregor925296b2011-07-19 16:10:42 +00001887 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
1888 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
Sebastian Redl5c415f32010-07-22 17:01:13 +00001889 I != N; ++I) {
Douglas Gregor8655e882009-10-16 22:46:09 +00001890 // Get this source location entry.
Douglas Gregor925296b2011-07-19 16:10:42 +00001891 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00001892 FileID FID = FileID::get(I);
1893 assert(&SourceMgr.getSLocEntry(FID) == SLoc);
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00001894
Douglas Gregor258ae542009-04-27 06:38:32 +00001895 // Record the offset of this source-location entry.
1896 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
1897
1898 // Figure out which record code to use.
1899 unsigned Code;
1900 if (SLoc->isFile()) {
Douglas Gregor9dc32122011-11-16 20:05:18 +00001901 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1902 if (Cache->OrigEntry) {
Sebastian Redl539c5062010-08-18 23:57:32 +00001903 Code = SM_SLOC_FILE_ENTRY;
Argyrios Kyrtzidis92dd4662011-06-02 20:01:46 +00001904 } else
Sebastian Redl539c5062010-08-18 23:57:32 +00001905 Code = SM_SLOC_BUFFER_ENTRY;
Douglas Gregor258ae542009-04-27 06:38:32 +00001906 } else
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001907 Code = SM_SLOC_EXPANSION_ENTRY;
Douglas Gregor258ae542009-04-27 06:38:32 +00001908 Record.clear();
1909 Record.push_back(Code);
1910
Douglas Gregor925296b2011-07-19 16:10:42 +00001911 // Starting offset of this entry within this module, so skip the dummy.
1912 Record.push_back(SLoc->getOffset() - 2);
Douglas Gregor258ae542009-04-27 06:38:32 +00001913 if (SLoc->isFile()) {
1914 const SrcMgr::FileInfo &File = SLoc->getFile();
Richard Smithb22a1d12016-03-27 20:13:24 +00001915 AddSourceLocation(File.getIncludeLoc(), Record);
Douglas Gregor258ae542009-04-27 06:38:32 +00001916 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
1917 Record.push_back(File.hasLineDirectives());
1918
1919 const SrcMgr::ContentCache *Content = File.getContentCache();
Richard Smithaada85c2016-02-06 02:06:43 +00001920 bool EmitBlob = false;
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001921 if (Content->OrigEntry) {
1922 assert(Content->OrigEntry == Content->ContentsEntry &&
Douglas Gregor9dc32122011-11-16 20:05:18 +00001923 "Writing to AST an overridden file is not supported");
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001924
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001925 // The source location entry is a file. Emit input file ID.
1926 assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
1927 Record.push_back(InputFileIDs[Content->OrigEntry]);
Mike Stump11289f42009-09-09 15:08:12 +00001928
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001929 Record.push_back(File.NumCreatedFIDs);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00001930
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00001931 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00001932 if (FDI != FileDeclIDs.end()) {
1933 Record.push_back(FDI->second->FirstDeclIndex);
1934 Record.push_back(FDI->second->DeclIDs.size());
1935 } else {
1936 Record.push_back(0);
1937 Record.push_back(0);
1938 }
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001939
1940 Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
1941
Richard Smithaada85c2016-02-06 02:06:43 +00001942 if (Content->BufferOverridden || Content->IsTransient)
1943 EmitBlob = true;
Douglas Gregor258ae542009-04-27 06:38:32 +00001944 } else {
1945 // The source location entry is a buffer. The blob associated
1946 // with this entry contains the contents of the buffer.
1947
1948 // We add one to the size so that we capture the trailing NULL
1949 // that is required by llvm::MemoryBuffer::getMemBuffer (on
1950 // the reader side).
Douglas Gregor874cc622010-03-16 00:35:39 +00001951 const llvm::MemoryBuffer *Buffer
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001952 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
Douglas Gregor258ae542009-04-27 06:38:32 +00001953 const char *Name = Buffer->getBufferIdentifier();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001954 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001955 StringRef(Name, strlen(Name) + 1));
Richard Smithaada85c2016-02-06 02:06:43 +00001956 EmitBlob = true;
Douglas Gregor258ae542009-04-27 06:38:32 +00001957
Douglas Gregor925296b2011-07-19 16:10:42 +00001958 if (strcmp(Name, "<built-in>") == 0) {
1959 PreloadSLocs.push_back(SLocEntryOffsets.size());
1960 }
Douglas Gregor258ae542009-04-27 06:38:32 +00001961 }
Richard Smithaada85c2016-02-06 02:06:43 +00001962
1963 if (EmitBlob) {
1964 // Include the implicit terminating null character in the on-disk buffer
1965 // if we're writing it uncompressed.
1966 const llvm::MemoryBuffer *Buffer =
1967 Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
1968 StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
1969
1970 // Compress the buffer if possible. We expect that almost all PCM
1971 // consumers will not want its contents.
1972 SmallString<0> CompressedBuffer;
1973 if (llvm::zlib::compress(Blob.drop_back(1), CompressedBuffer) ==
1974 llvm::zlib::StatusOK) {
1975 RecordData::value_type Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED,
1976 Blob.size() - 1};
1977 Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
1978 CompressedBuffer);
1979 } else {
1980 RecordData::value_type Record[] = {SM_SLOC_BUFFER_BLOB};
1981 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob);
1982 }
1983 }
Douglas Gregor258ae542009-04-27 06:38:32 +00001984 } else {
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001985 // The source location entry is a macro expansion.
Chandler Carruthee4c1d12011-07-26 04:56:51 +00001986 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
Richard Smithb22a1d12016-03-27 20:13:24 +00001987 AddSourceLocation(Expansion.getSpellingLoc(), Record);
1988 AddSourceLocation(Expansion.getExpansionLocStart(), Record);
1989 AddSourceLocation(Expansion.isMacroArgExpansion()
1990 ? SourceLocation()
1991 : Expansion.getExpansionLocEnd(),
1992 Record);
Douglas Gregor258ae542009-04-27 06:38:32 +00001993
1994 // Compute the token length for this macro expansion.
Douglas Gregor925296b2011-07-19 16:10:42 +00001995 unsigned NextOffset = SourceMgr.getNextLocalOffset();
Douglas Gregor8655e882009-10-16 22:46:09 +00001996 if (I + 1 != N)
Douglas Gregor925296b2011-07-19 16:10:42 +00001997 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
Douglas Gregor258ae542009-04-27 06:38:32 +00001998 Record.push_back(NextOffset - SLoc->getOffset() - 1);
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001999 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
Douglas Gregor258ae542009-04-27 06:38:32 +00002000 }
2001 }
2002
Douglas Gregor8f45df52009-04-16 22:23:12 +00002003 Stream.ExitBlock();
Douglas Gregor258ae542009-04-27 06:38:32 +00002004
2005 if (SLocEntryOffsets.empty())
2006 return;
2007
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002008 // Write the source-location offsets table into the AST block. This
Douglas Gregor258ae542009-04-27 06:38:32 +00002009 // table is used for lazily loading source-location information.
2010 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002011
2012 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00002013 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
Douglas Gregor258ae542009-04-27 06:38:32 +00002014 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
Douglas Gregor925296b2011-07-19 16:10:42 +00002015 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
Douglas Gregor258ae542009-04-27 06:38:32 +00002016 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
2017 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00002018 {
2019 RecordData::value_type Record[] = {
2020 SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
2021 SourceMgr.getNextLocalOffset() - 1 /* skip dummy */};
2022 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
2023 bytes(SLocEntryOffsets));
2024 }
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002025 // Write the source location entry preloads array, telling the AST
Douglas Gregor258ae542009-04-27 06:38:32 +00002026 // reader which source locations entries it should load eagerly.
Sebastian Redl539c5062010-08-18 23:57:32 +00002027 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregor925296b2011-07-19 16:10:42 +00002028
2029 // Write the line table. It depends on remapping working, so it must come
2030 // after the source location offsets.
2031 if (SourceMgr.hasLineTable()) {
2032 LineTableInfo &LineTable = SourceMgr.getLineTable();
2033
2034 Record.clear();
Richard Smith63078492015-09-01 07:41:55 +00002035
2036 // Emit the needed file names.
2037 llvm::DenseMap<int, int> FilenameMap;
2038 for (const auto &L : LineTable) {
2039 if (L.first.ID < 0)
2040 continue;
2041 for (auto &LE : L.second) {
2042 if (FilenameMap.insert(std::make_pair(LE.FilenameID,
2043 FilenameMap.size())).second)
2044 AddPath(LineTable.getFilename(LE.FilenameID), Record);
2045 }
2046 }
2047 Record.push_back(0);
Douglas Gregor925296b2011-07-19 16:10:42 +00002048
2049 // Emit the line entries
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002050 for (const auto &L : LineTable) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002051 // Only emit entries for local files.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002052 if (L.first.ID < 0)
Douglas Gregor925296b2011-07-19 16:10:42 +00002053 continue;
2054
2055 // Emit the file ID
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002056 Record.push_back(L.first.ID);
Douglas Gregor925296b2011-07-19 16:10:42 +00002057
2058 // Emit the line entries
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002059 Record.push_back(L.second.size());
2060 for (const auto &LE : L.second) {
2061 Record.push_back(LE.FileOffset);
2062 Record.push_back(LE.LineNo);
2063 Record.push_back(FilenameMap[LE.FilenameID]);
2064 Record.push_back((unsigned)LE.FileKind);
2065 Record.push_back(LE.IncludeOffset);
Douglas Gregor925296b2011-07-19 16:10:42 +00002066 }
2067 }
Richard Smith63078492015-09-01 07:41:55 +00002068
Douglas Gregor925296b2011-07-19 16:10:42 +00002069 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
2070 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00002071}
2072
Douglas Gregorc5046832009-04-27 18:38:38 +00002073//===----------------------------------------------------------------------===//
2074// Preprocessor Serialization
2075//===----------------------------------------------------------------------===//
2076
Argyrios Kyrtzidis0aef0f02013-03-15 22:43:10 +00002077static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
2078 const Preprocessor &PP) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002079 if (MacroInfo *MI = MD->getMacroInfo())
2080 if (MI->isBuiltinMacro())
2081 return true;
Argyrios Kyrtzidis0aef0f02013-03-15 22:43:10 +00002082
2083 if (IsModule) {
2084 SourceLocation Loc = MD->getLocation();
2085 if (Loc.isInvalid())
2086 return true;
2087 if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
2088 return true;
2089 }
2090
2091 return false;
2092}
2093
Chris Lattnereeffaef2009-04-10 17:15:23 +00002094/// \brief Writes the block containing the serialized form of the
2095/// preprocessor.
2096///
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00002097void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002098 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
2099 if (PPRec)
2100 WritePreprocessorDetail(*PPRec);
2101
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002102 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00002103 RecordData ModuleMacroRecord;
Chris Lattner0910e3b2009-04-10 17:16:57 +00002104
Chris Lattner0af3ba12009-04-13 01:29:17 +00002105 // If the preprocessor __COUNTER__ value has been bumped, remember it.
2106 if (PP.getCounterValue() != 0) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002107 RecordData::value_type Record[] = {PP.getCounterValue()};
Sebastian Redl539c5062010-08-18 23:57:32 +00002108 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
Douglas Gregoreda6a892009-04-26 00:07:37 +00002109 }
2110
2111 // Enter the preprocessor block.
Douglas Gregor796d76a2010-10-20 22:00:55 +00002112 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
Mike Stump11289f42009-09-09 15:08:12 +00002113
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002114 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
Richard Smithb5aaf5a2015-09-01 02:35:58 +00002115 // FIXME: Include a location for the use, and say which one was used.
Douglas Gregoreda6a892009-04-26 00:07:37 +00002116 if (PP.SawDateOrTime())
Richard Smithb5aaf5a2015-09-01 02:35:58 +00002117 PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
Douglas Gregor796d76a2010-10-20 22:00:55 +00002118
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002119 // Loop over all the macro directives that are live at the end of the file,
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002120 // emitting each to the PP section.
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002121
Richard Smithee977932015-05-01 21:22:17 +00002122 // Construct the list of identifiers with macro directives that need to be
2123 // serialized.
2124 SmallVector<const IdentifierInfo *, 128> MacroIdentifiers;
2125 for (auto &Id : PP.getIdentifierTable())
2126 if (Id.second->hadMacroDefinition() &&
2127 (!Id.second->isFromAST() ||
2128 Id.second->hasChangedSinceDeserialization()))
2129 MacroIdentifiers.push_back(Id.second);
Douglas Gregor2e5571d2011-02-10 18:20:09 +00002130 // Sort the set of macro definitions that need to be serialized by the
2131 // name of the macro, to provide a stable ordering.
Richard Smithee977932015-05-01 21:22:17 +00002132 std::sort(MacroIdentifiers.begin(), MacroIdentifiers.end(),
2133 llvm::less_ptr<IdentifierInfo>());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002134
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002135 // Emit the macro directives as a list and associate the offset with the
2136 // identifier they belong to.
Richard Smithee977932015-05-01 21:22:17 +00002137 for (const IdentifierInfo *Name : MacroIdentifiers) {
2138 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name);
Richard Smithd7329392015-04-21 21:46:32 +00002139 auto StartOffset = Stream.GetCurrentBitNo();
2140
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002141 // Emit the macro directives in reverse source order.
2142 for (; MD; MD = MD->getPrevious()) {
Richard Smithd7329392015-04-21 21:46:32 +00002143 // Once we hit an ignored macro, we're done: the rest of the chain
2144 // will all be ignored macros.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002145 if (shouldIgnoreMacro(MD, IsModule, PP))
Richard Smithd7329392015-04-21 21:46:32 +00002146 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002147
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002148 AddSourceLocation(MD->getLocation(), Record);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002149 Record.push_back(MD->getKind());
Richard Smithdaa69e02014-07-25 04:40:03 +00002150 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
Richard Smith3981b172015-04-30 02:16:23 +00002151 Record.push_back(getMacroRef(DefMD->getInfo(), Name));
Richard Smith713369b2015-04-23 20:40:50 +00002152 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002153 Record.push_back(VisMD->isPublic());
2154 }
Richard Smithb8b2ed62015-04-23 18:18:26 +00002155 }
Richard Smithd7329392015-04-21 21:46:32 +00002156
Richard Smithb8b2ed62015-04-23 18:18:26 +00002157 // Write out any exported module macros.
Richard Smithee977932015-05-01 21:22:17 +00002158 bool EmittedModuleMacros = false;
Richard Smithb8b2ed62015-04-23 18:18:26 +00002159 if (IsModule) {
2160 auto Leafs = PP.getLeafModuleMacros(Name);
2161 SmallVector<ModuleMacro*, 8> Worklist(Leafs.begin(), Leafs.end());
2162 llvm::DenseMap<ModuleMacro*, unsigned> Visits;
2163 while (!Worklist.empty()) {
2164 auto *Macro = Worklist.pop_back_val();
Richard Smithd7329392015-04-21 21:46:32 +00002165
Richard Smithb8b2ed62015-04-23 18:18:26 +00002166 // Emit a record indicating this submodule exports this macro.
2167 ModuleMacroRecord.push_back(
2168 getSubmoduleID(Macro->getOwningModule()));
Richard Smithee977932015-05-01 21:22:17 +00002169 ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
Richard Smithb8b2ed62015-04-23 18:18:26 +00002170 for (auto *M : Macro->overrides())
2171 ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
Richard Smithd7329392015-04-21 21:46:32 +00002172
Richard Smithb8b2ed62015-04-23 18:18:26 +00002173 Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2174 ModuleMacroRecord.clear();
Richard Smithd7329392015-04-21 21:46:32 +00002175
Richard Smithb8b2ed62015-04-23 18:18:26 +00002176 // Enqueue overridden macros once we've visited all their ancestors.
2177 for (auto *M : Macro->overrides())
2178 if (++Visits[M] == M->getNumOverridingMacros())
2179 Worklist.push_back(M);
Richard Smithee977932015-05-01 21:22:17 +00002180
2181 EmittedModuleMacros = true;
Richard Smithd7329392015-04-21 21:46:32 +00002182 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002183 }
Richard Smithd7329392015-04-21 21:46:32 +00002184
Richard Smithee977932015-05-01 21:22:17 +00002185 if (Record.empty() && !EmittedModuleMacros)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002186 continue;
2187
Richard Smithd7329392015-04-21 21:46:32 +00002188 IdentMacroDirectivesOffsetMap[Name] = StartOffset;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002189 Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2190 Record.clear();
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002191 }
Alexander Kornienko1d26c022012-09-25 17:18:14 +00002192
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002193 /// \brief Offsets of each of the macros into the bitstream, indexed by
2194 /// the local macro ID
2195 ///
2196 /// For each identifier that is associated with a macro, this map
2197 /// provides the offset into the bitstream where that macro is
2198 /// defined.
2199 std::vector<uint32_t> MacroOffsets;
2200
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002201 for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2202 const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2203 MacroInfo *MI = MacroInfosToEmit[I].MI;
2204 MacroID ID = MacroInfosToEmit[I].ID;
Douglas Gregoreb114da2010-10-01 01:03:07 +00002205
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002206 if (ID < FirstMacroID) {
2207 assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2208 continue;
Chris Lattner2199f5b2009-04-10 18:08:30 +00002209 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002210
2211 // Record the local offset of this macro.
2212 unsigned Index = ID - FirstMacroID;
2213 if (Index == MacroOffsets.size())
2214 MacroOffsets.push_back(Stream.GetCurrentBitNo());
2215 else {
2216 if (Index > MacroOffsets.size())
2217 MacroOffsets.resize(Index + 1);
2218
2219 MacroOffsets[Index] = Stream.GetCurrentBitNo();
2220 }
2221
2222 AddIdentifierRef(Name, Record);
2223 Record.push_back(inferSubmoduleIDFromLocation(MI->getDefinitionLoc()));
2224 AddSourceLocation(MI->getDefinitionLoc(), Record);
2225 AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2226 Record.push_back(MI->isUsed());
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00002227 Record.push_back(MI->isUsedForHeaderGuard());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002228 unsigned Code;
2229 if (MI->isObjectLike()) {
2230 Code = PP_MACRO_OBJECT_LIKE;
2231 } else {
2232 Code = PP_MACRO_FUNCTION_LIKE;
2233
2234 Record.push_back(MI->isC99Varargs());
2235 Record.push_back(MI->isGNUVarargs());
2236 Record.push_back(MI->hasCommaPasting());
2237 Record.push_back(MI->getNumArgs());
Daniel Marjamakie4770da2015-05-29 09:15:24 +00002238 for (const IdentifierInfo *Arg : MI->args())
2239 AddIdentifierRef(Arg, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002240 }
2241
2242 // If we have a detailed preprocessing record, record the macro definition
2243 // ID that corresponds to this macro.
2244 if (PPRec)
2245 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2246
2247 Stream.EmitRecord(Code, Record);
2248 Record.clear();
2249
2250 // Emit the tokens array.
2251 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2252 // Note that we know that the preprocessor does not have any annotation
2253 // tokens in it because they are created by the parser, and thus can't
2254 // be in a macro definition.
2255 const Token &Tok = MI->getReplacementToken(TokNo);
John McCallf413f5e2013-05-03 00:10:13 +00002256 AddToken(Tok, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002257 Stream.EmitRecord(PP_TOKEN, Record);
2258 Record.clear();
2259 }
2260 ++NumMacros;
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002261 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002262
Douglas Gregor92a96f52011-02-08 21:58:10 +00002263 Stream.ExitBlock();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002264
2265 // Write the offsets table for macro IDs.
2266 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002267
Richard Smith13090a22015-04-10 02:02:24 +00002268 auto *Abbrev = new BitCodeAbbrev();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002269 Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2270 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2271 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2272 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2273
2274 unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00002275 {
2276 RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
2277 FirstMacroID - NUM_PREDEF_MACRO_IDS};
2278 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
2279 }
Douglas Gregor92a96f52011-02-08 21:58:10 +00002280}
2281
2282void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
Argyrios Kyrtzidis7f448362011-09-19 20:40:42 +00002283 if (PPRec.local_begin() == PPRec.local_end())
Douglas Gregor92a96f52011-02-08 21:58:10 +00002284 return;
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002285
Argyrios Kyrtzidis64f63812011-09-19 20:40:25 +00002286 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002287
Douglas Gregor92a96f52011-02-08 21:58:10 +00002288 // Enter the preprocessor block.
2289 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002290
Douglas Gregoraae92242010-03-19 21:51:54 +00002291 // If the preprocessor has a preprocessing record, emit it.
2292 unsigned NumPreprocessingRecords = 0;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002293 using namespace llvm;
2294
2295 // Set up the abbreviation for
2296 unsigned InclusionAbbrev = 0;
2297 {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002298 auto *Abbrev = new BitCodeAbbrev();
Douglas Gregor92a96f52011-02-08 21:58:10 +00002299 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
Douglas Gregor92a96f52011-02-08 21:58:10 +00002300 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2301 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2302 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
Argyrios Kyrtzidisf590e092012-10-02 16:10:46 +00002303 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
Douglas Gregor92a96f52011-02-08 21:58:10 +00002304 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2305 InclusionAbbrev = Stream.EmitAbbrev(Abbrev);
2306 }
2307
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002308 unsigned FirstPreprocessorEntityID
2309 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
2310 + NUM_PREDEF_PP_ENTITY_IDS;
2311 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002312 RecordData Record;
Argyrios Kyrtzidis7f448362011-09-19 20:40:42 +00002313 for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2314 EEnd = PPRec.local_end();
Douglas Gregor0d4b4312011-08-04 17:06:18 +00002315 E != EEnd;
2316 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
Douglas Gregor92a96f52011-02-08 21:58:10 +00002317 Record.clear();
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002318
Richard Smith66a81862015-05-04 02:25:31 +00002319 PreprocessedEntityOffsets.push_back(
2320 PPEntityOffset((*E)->getSourceRange(), Stream.GetCurrentBitNo()));
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002321
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002322 if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002323 // Record this macro definition's ID.
2324 MacroDefinitions[MD] = NextPreprocessorEntityID;
Richard Smith66a81862015-05-04 02:25:31 +00002325
Douglas Gregor92a96f52011-02-08 21:58:10 +00002326 AddIdentifierRef(MD->getName(), Record);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002327 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2328 continue;
Douglas Gregoraae92242010-03-19 21:51:54 +00002329 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002330
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002331 if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
Argyrios Kyrtzidis80f78b92011-09-08 17:18:41 +00002332 Record.push_back(ME->isBuiltinMacro());
2333 if (ME->isBuiltinMacro())
2334 AddIdentifierRef(ME->getName(), Record);
2335 else
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002336 Record.push_back(MacroDefinitions[ME->getDefinition()]);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00002337 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002338 continue;
2339 }
2340
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002341 if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
Douglas Gregor92a96f52011-02-08 21:58:10 +00002342 Record.push_back(PPD_INCLUSION_DIRECTIVE);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002343 Record.push_back(ID->getFileName().size());
2344 Record.push_back(ID->wasInQuotes());
2345 Record.push_back(static_cast<unsigned>(ID->getKind()));
Argyrios Kyrtzidisf590e092012-10-02 16:10:46 +00002346 Record.push_back(ID->importedModule());
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002347 SmallString<64> Buffer;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002348 Buffer += ID->getFileName();
Argyrios Kyrtzidis8dbcfc32012-03-08 01:08:28 +00002349 // Check that the FileEntry is not null because it was not resolved and
2350 // we create a PCH even with compiler errors.
2351 if (ID->getFile())
2352 Buffer += ID->getFile()->getName();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00002353 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002354 continue;
2355 }
2356
2357 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2358 }
Douglas Gregor8f45df52009-04-16 22:23:12 +00002359 Stream.ExitBlock();
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002360
Douglas Gregoraae92242010-03-19 21:51:54 +00002361 // Write the offsets table for the preprocessing record.
2362 if (NumPreprocessingRecords > 0) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002363 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2364
Douglas Gregoraae92242010-03-19 21:51:54 +00002365 // Write the offsets table for identifier IDs.
2366 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002367
2368 auto *Abbrev = new BitCodeAbbrev();
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002369 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002370 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
Douglas Gregoraae92242010-03-19 21:51:54 +00002371 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002372 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002373
Mehdi Amini57a41912015-09-10 01:46:39 +00002374 RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
2375 FirstPreprocessorEntityID -
2376 NUM_PREDEF_PP_ENTITY_IDS};
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002377 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00002378 bytes(PreprocessedEntityOffsets));
Douglas Gregoraae92242010-03-19 21:51:54 +00002379 }
Chris Lattnereeffaef2009-04-10 17:15:23 +00002380}
2381
Richard Smith386bb072015-08-18 23:42:23 +00002382unsigned ASTWriter::getLocalOrImportedSubmoduleID(Module *Mod) {
Richard Smith080056b2015-08-18 21:53:42 +00002383 if (!Mod)
2384 return 0;
2385
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002386 llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
2387 if (Known != SubmoduleIDs.end())
2388 return Known->second;
Richard Smith386bb072015-08-18 23:42:23 +00002389
2390 if (Mod->getTopLevelModule() != WritingModule)
2391 return 0;
2392
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002393 return SubmoduleIDs[Mod] = NextSubmoduleID++;
2394}
2395
Richard Smith386bb072015-08-18 23:42:23 +00002396unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2397 // FIXME: This can easily happen, if we have a reference to a submodule that
2398 // did not result in us loading a module file for that submodule. For
2399 // instance, a cross-top-level-module 'conflict' declaration will hit this.
2400 unsigned ID = getLocalOrImportedSubmoduleID(Mod);
2401 assert((ID || !Mod) &&
2402 "asked for module ID for non-local, non-imported module");
2403 return ID;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00002404}
2405
Douglas Gregor253eefe2011-12-01 00:59:36 +00002406/// \brief Compute the number of modules within the given tree (including the
2407/// given module).
2408static unsigned getNumberOfModules(Module *Mod) {
2409 unsigned ChildModules = 0;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002410 for (auto Sub = Mod->submodule_begin(), SubEnd = Mod->submodule_end();
Douglas Gregor253eefe2011-12-01 00:59:36 +00002411 Sub != SubEnd; ++Sub)
Douglas Gregoreb90e832012-01-04 23:32:19 +00002412 ChildModules += getNumberOfModules(*Sub);
Douglas Gregor253eefe2011-12-01 00:59:36 +00002413
2414 return ChildModules + 1;
2415}
2416
Douglas Gregorde3ef502011-11-30 23:21:26 +00002417void ASTWriter::WriteSubmodules(Module *WritingModule) {
Douglas Gregor69021972011-11-30 17:33:56 +00002418 // Enter the submodule description block.
Richard Smith202210b2014-10-24 20:23:01 +00002419 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
Douglas Gregor69021972011-11-30 17:33:56 +00002420
2421 // Write the abbreviations needed for the submodules block.
2422 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002423
2424 auto *Abbrev = new BitCodeAbbrev();
Douglas Gregor69021972011-11-30 17:33:56 +00002425 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002426 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
Douglas Gregor69021972011-11-30 17:33:56 +00002427 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
2428 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2429 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
Richard Smith9bca2982014-03-08 00:03:56 +00002430 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2431 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
Douglas Gregora686e1b2012-01-27 19:52:33 +00002432 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
Douglas Gregor73441092011-12-05 22:27:44 +00002433 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
Douglas Gregor73441092011-12-05 22:27:44 +00002434 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002435 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
Douglas Gregor69021972011-11-30 17:33:56 +00002436 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2437 unsigned DefinitionAbbrev = Stream.EmitAbbrev(Abbrev);
2438
2439 Abbrev = new BitCodeAbbrev();
Douglas Gregor524e33e2011-12-08 19:11:24 +00002440 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
Douglas Gregor69021972011-11-30 17:33:56 +00002441 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2442 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(Abbrev);
2443
2444 Abbrev = new BitCodeAbbrev();
2445 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2446 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2447 unsigned HeaderAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregor524e33e2011-12-08 19:11:24 +00002448
2449 Abbrev = new BitCodeAbbrev();
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +00002450 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2451 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2452 unsigned TopHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2453
2454 Abbrev = new BitCodeAbbrev();
Douglas Gregor524e33e2011-12-08 19:11:24 +00002455 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2456 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2457 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(Abbrev);
2458
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002459 Abbrev = new BitCodeAbbrev();
2460 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
Richard Smitha3feee22013-10-28 22:18:19 +00002461 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2462 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002463 unsigned RequiresAbbrev = Stream.EmitAbbrev(Abbrev);
2464
Douglas Gregor59527662012-10-15 06:28:11 +00002465 Abbrev = new BitCodeAbbrev();
2466 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2467 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2468 unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2469
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002470 Abbrev = new BitCodeAbbrev();
Richard Smith306d8922014-10-22 23:50:56 +00002471 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
2472 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2473 unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2474
2475 Abbrev = new BitCodeAbbrev();
Lawrence Crowlb53e5482013-06-20 21:14:14 +00002476 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2477 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2478 unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2479
2480 Abbrev = new BitCodeAbbrev();
Richard Smith202210b2014-10-24 20:23:01 +00002481 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
2482 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2483 unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2484
2485 Abbrev = new BitCodeAbbrev();
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002486 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2487 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2488 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2489 unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(Abbrev);
2490
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002491 Abbrev = new BitCodeAbbrev();
2492 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2493 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2494 unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(Abbrev);
2495
Douglas Gregorfb912652013-03-20 21:10:35 +00002496 Abbrev = new BitCodeAbbrev();
2497 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2498 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
2499 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
2500 unsigned ConflictAbbrev = Stream.EmitAbbrev(Abbrev);
2501
Douglas Gregor253eefe2011-12-01 00:59:36 +00002502 // Write the submodule metadata block.
Mehdi Amini57a41912015-09-10 01:46:39 +00002503 RecordData::value_type Record[] = {getNumberOfModules(WritingModule),
2504 FirstSubmoduleID -
2505 NUM_PREDEF_SUBMODULE_IDS};
Douglas Gregor253eefe2011-12-01 00:59:36 +00002506 Stream.EmitRecord(SUBMODULE_METADATA, Record);
2507
Douglas Gregor69021972011-11-30 17:33:56 +00002508 // Write all of the submodules.
Douglas Gregorde3ef502011-11-30 23:21:26 +00002509 std::queue<Module *> Q;
Douglas Gregor69021972011-11-30 17:33:56 +00002510 Q.push(WritingModule);
Douglas Gregor69021972011-11-30 17:33:56 +00002511 while (!Q.empty()) {
Douglas Gregorde3ef502011-11-30 23:21:26 +00002512 Module *Mod = Q.front();
Douglas Gregor69021972011-11-30 17:33:56 +00002513 Q.pop();
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002514 unsigned ID = getSubmoduleID(Mod);
Mehdi Amini57a41912015-09-10 01:46:39 +00002515
2516 uint64_t ParentID = 0;
Douglas Gregor69021972011-11-30 17:33:56 +00002517 if (Mod->Parent) {
2518 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
Mehdi Amini57a41912015-09-10 01:46:39 +00002519 ParentID = SubmoduleIDs[Mod->Parent];
Douglas Gregor69021972011-11-30 17:33:56 +00002520 }
Mehdi Amini57a41912015-09-10 01:46:39 +00002521
2522 // Emit the definition of the block.
2523 {
2524 RecordData::value_type Record[] = {
2525 SUBMODULE_DEFINITION, ID, ParentID, Mod->IsFramework, Mod->IsExplicit,
2526 Mod->IsSystem, Mod->IsExternC, Mod->InferSubmodules,
2527 Mod->InferExplicitSubmodules, Mod->InferExportWildcard,
2528 Mod->ConfigMacrosExhaustive};
2529 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2530 }
2531
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002532 // Emit the requirements.
Richard Smith080056b2015-08-18 21:53:42 +00002533 for (const auto &R : Mod->Requirements) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002534 RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.second};
Richard Smith080056b2015-08-18 21:53:42 +00002535 Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.first);
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002536 }
2537
Douglas Gregor69021972011-11-30 17:33:56 +00002538 // Emit the umbrella header, if there is one.
Richard Smith2b63d152015-05-16 02:28:53 +00002539 if (auto UmbrellaHeader = Mod->getUmbrellaHeader()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002540 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
Richard Smith2b63d152015-05-16 02:28:53 +00002541 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2542 UmbrellaHeader.NameAsWritten);
2543 } else if (auto UmbrellaDir = Mod->getUmbrellaDir()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002544 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
2545 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
Richard Smith2b63d152015-05-16 02:28:53 +00002546 UmbrellaDir.NameAsWritten);
Douglas Gregor69021972011-11-30 17:33:56 +00002547 }
Richard Smith306d8922014-10-22 23:50:56 +00002548
Douglas Gregor69021972011-11-30 17:33:56 +00002549 // Emit the headers.
Richard Smith202210b2014-10-24 20:23:01 +00002550 struct {
Richard Smith3c1a41a2014-12-02 00:08:08 +00002551 unsigned RecordKind;
Richard Smith202210b2014-10-24 20:23:01 +00002552 unsigned Abbrev;
Richard Smith3c1a41a2014-12-02 00:08:08 +00002553 Module::HeaderKind HeaderKind;
Richard Smith202210b2014-10-24 20:23:01 +00002554 } HeaderLists[] = {
Richard Smith3c1a41a2014-12-02 00:08:08 +00002555 {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
2556 {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
2557 {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
Richard Smith202210b2014-10-24 20:23:01 +00002558 {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
Richard Smith3c1a41a2014-12-02 00:08:08 +00002559 Module::HK_PrivateTextual},
2560 {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
Richard Smith202210b2014-10-24 20:23:01 +00002561 };
2562 for (auto &HL : HeaderLists) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002563 RecordData::value_type Record[] = {HL.RecordKind};
Richard Smith3c1a41a2014-12-02 00:08:08 +00002564 for (auto &H : Mod->Headers[HL.HeaderKind])
2565 Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
2566 }
2567
2568 // Emit the top headers.
2569 {
2570 auto TopHeaders = Mod->getTopHeaders(PP->getFileManager());
Mehdi Amini57a41912015-09-10 01:46:39 +00002571 RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
Richard Smith3c1a41a2014-12-02 00:08:08 +00002572 for (auto *H : TopHeaders)
2573 Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, H->getName());
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +00002574 }
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002575
2576 // Emit the imports.
2577 if (!Mod->Imports.empty()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002578 RecordData Record;
Richard Smith080056b2015-08-18 21:53:42 +00002579 for (auto *I : Mod->Imports)
2580 Record.push_back(getSubmoduleID(I));
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002581 Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2582 }
2583
Douglas Gregor24bb9232011-12-02 18:58:38 +00002584 // Emit the exports.
2585 if (!Mod->Exports.empty()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002586 RecordData Record;
Richard Smith080056b2015-08-18 21:53:42 +00002587 for (const auto &E : Mod->Exports) {
2588 // FIXME: This may fail; we don't require that all exported modules
2589 // are local or imported.
2590 Record.push_back(getSubmoduleID(E.getPointer()));
2591 Record.push_back(E.getInt());
Douglas Gregor24bb9232011-12-02 18:58:38 +00002592 }
2593 Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2594 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002595
Daniel Jasperba7f2f72013-09-24 09:14:14 +00002596 //FIXME: How do we emit the 'use'd modules? They may not be submodules.
2597 // Might be unnecessary as use declarations are only used to build the
2598 // module itself.
2599
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002600 // Emit the link libraries.
Richard Smith080056b2015-08-18 21:53:42 +00002601 for (const auto &LL : Mod->LinkLibraries) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002602 RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
2603 LL.IsFramework};
Richard Smith080056b2015-08-18 21:53:42 +00002604 Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002605 }
2606
Douglas Gregorfb912652013-03-20 21:10:35 +00002607 // Emit the conflicts.
Richard Smith080056b2015-08-18 21:53:42 +00002608 for (const auto &C : Mod->Conflicts) {
Richard Smith080056b2015-08-18 21:53:42 +00002609 // FIXME: This may fail; we don't require that all conflicting modules
2610 // are local or imported.
Mehdi Amini57a41912015-09-10 01:46:39 +00002611 RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
2612 getSubmoduleID(C.Other)};
Richard Smith080056b2015-08-18 21:53:42 +00002613 Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message);
Douglas Gregorfb912652013-03-20 21:10:35 +00002614 }
2615
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002616 // Emit the configuration macros.
Richard Smith080056b2015-08-18 21:53:42 +00002617 for (const auto &CM : Mod->ConfigMacros) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002618 RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
Richard Smith080056b2015-08-18 21:53:42 +00002619 Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM);
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002620 }
2621
Douglas Gregor69021972011-11-30 17:33:56 +00002622 // Queue up the submodules of this module.
Richard Smith080056b2015-08-18 21:53:42 +00002623 for (auto *M : Mod->submodules())
2624 Q.push(M);
Douglas Gregor69021972011-11-30 17:33:56 +00002625 }
2626
2627 Stream.ExitBlock();
Richard Smith23d8d032015-05-14 00:45:20 +00002628
Richard Smith23d8d032015-05-14 00:45:20 +00002629 assert((NextSubmoduleID - FirstSubmoduleID ==
2630 getNumberOfModules(WritingModule)) &&
2631 "Wrong # of submodules; found a reference to a non-local, "
2632 "non-imported submodule?");
Douglas Gregor69021972011-11-30 17:33:56 +00002633}
2634
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002635serialization::SubmoduleID
2636ASTWriter::inferSubmoduleIDFromLocation(SourceLocation Loc) {
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002637 if (Loc.isInvalid() || !WritingModule)
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002638 return 0; // No submodule
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002639
2640 // Find the module that owns this location.
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002641 ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002642 Module *OwningMod
2643 = ModMap.inferModuleFromLocation(FullSourceLoc(Loc,PP->getSourceManager()));
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002644 if (!OwningMod)
2645 return 0;
2646
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002647 // Check whether this submodule is part of our own module.
2648 if (WritingModule != OwningMod && !OwningMod->isSubModuleOf(WritingModule))
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002649 return 0;
2650
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002651 return getSubmoduleID(OwningMod);
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002652}
2653
Argyrios Kyrtzidis0f06b982013-03-27 17:17:23 +00002654void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
2655 bool isModule) {
2656 // Make sure set diagnostic pragmas don't affect the translation unit that
2657 // imports the module.
2658 // FIXME: Make diagnostic pragma sections work properly with modules.
2659 if (isModule)
2660 return;
2661
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002662 llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
2663 DiagStateIDMap;
2664 unsigned CurrID = 0;
2665 DiagStateIDMap[&Diag.DiagStates.front()] = ++CurrID; // the command-line one.
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002666 RecordData Record;
David Blaikie9c902b52011-09-25 23:23:43 +00002667 for (DiagnosticsEngine::DiagStatePointsTy::const_iterator
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002668 I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end();
2669 I != E; ++I) {
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002670 const DiagnosticsEngine::DiagStatePoint &point = *I;
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002671 if (point.Loc.isInvalid())
2672 continue;
2673
Richard Smithb22a1d12016-03-27 20:13:24 +00002674 AddSourceLocation(point.Loc, Record);
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002675 unsigned &DiagStateID = DiagStateIDMap[point.State];
2676 Record.push_back(DiagStateID);
2677
2678 if (DiagStateID == 0) {
2679 DiagStateID = ++CurrID;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002680 for (const auto &I : *(point.State)) {
2681 if (I.second.isPragma()) {
2682 Record.push_back(I.first);
2683 Record.push_back((unsigned)I.second.getSeverity());
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002684 }
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002685 }
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002686 Record.push_back(-1); // mark the end of the diag/map pairs for this
2687 // location.
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002688 }
2689 }
2690
Argyrios Kyrtzidisb0ca9eb2010-11-05 22:20:49 +00002691 if (!Record.empty())
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002692 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002693}
2694
Richard Smithc2bb8182015-03-24 06:36:48 +00002695void ASTWriter::WriteCXXCtorInitializersOffsets() {
2696 if (CXXCtorInitializersOffsets.empty())
2697 return;
2698
Richard Smithc2bb8182015-03-24 06:36:48 +00002699 // Create a blob abbreviation for the C++ ctor initializer offsets.
2700 using namespace llvm;
2701
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002702 auto *Abbrev = new BitCodeAbbrev();
Richard Smithc2bb8182015-03-24 06:36:48 +00002703 Abbrev->Add(BitCodeAbbrevOp(CXX_CTOR_INITIALIZERS_OFFSETS));
2704 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2705 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2706 unsigned CtorInitializersOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2707
2708 // Write the base specifier offsets table.
Mehdi Amini57a41912015-09-10 01:46:39 +00002709 RecordData::value_type Record[] = {CXX_CTOR_INITIALIZERS_OFFSETS,
2710 CXXCtorInitializersOffsets.size()};
Richard Smithc2bb8182015-03-24 06:36:48 +00002711 Stream.EmitRecordWithBlob(CtorInitializersOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00002712 bytes(CXXCtorInitializersOffsets));
Richard Smithc2bb8182015-03-24 06:36:48 +00002713}
2714
Anders Carlsson9bb83e82011-03-06 18:41:18 +00002715void ASTWriter::WriteCXXBaseSpecifiersOffsets() {
2716 if (CXXBaseSpecifiersOffsets.empty())
2717 return;
2718
Anders Carlsson9bb83e82011-03-06 18:41:18 +00002719 // Create a blob abbreviation for the C++ base specifiers offsets.
2720 using namespace llvm;
2721
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002722 auto *Abbrev = new BitCodeAbbrev();
Anders Carlsson9bb83e82011-03-06 18:41:18 +00002723 Abbrev->Add(BitCodeAbbrevOp(CXX_BASE_SPECIFIER_OFFSETS));
2724 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2725 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2726 unsigned BaseSpecifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2727
Douglas Gregorc27b2872011-08-04 00:01:48 +00002728 // Write the base specifier offsets table.
Mehdi Amini57a41912015-09-10 01:46:39 +00002729 RecordData::value_type Record[] = {CXX_BASE_SPECIFIER_OFFSETS,
2730 CXXBaseSpecifiersOffsets.size()};
Anders Carlsson9bb83e82011-03-06 18:41:18 +00002731 Stream.EmitRecordWithBlob(BaseSpecifierOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00002732 bytes(CXXBaseSpecifiersOffsets));
Anders Carlsson9bb83e82011-03-06 18:41:18 +00002733}
2734
Douglas Gregorc5046832009-04-27 18:38:38 +00002735//===----------------------------------------------------------------------===//
2736// Type Serialization
2737//===----------------------------------------------------------------------===//
Chris Lattnereeffaef2009-04-10 17:15:23 +00002738
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002739/// \brief Write the representation of a type to the AST stream.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002740void ASTWriter::WriteType(QualType T) {
Argyrios Kyrtzidisa7fbbb02010-08-20 16:04:04 +00002741 TypeIdx &Idx = TypeIdxs[T];
Argyrios Kyrtzidisbb5c7eae2010-08-20 16:03:59 +00002742 if (Idx.getIndex() == 0) // we haven't seen this type before.
2743 Idx = TypeIdx(NextTypeID++);
Mike Stump11289f42009-09-09 15:08:12 +00002744
Douglas Gregor9b3932c2010-10-05 18:37:06 +00002745 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
Douglas Gregordc72caa2010-10-04 18:21:45 +00002746
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002747 // Record the offset for this type.
Argyrios Kyrtzidisbb5c7eae2010-08-20 16:03:59 +00002748 unsigned Index = Idx.getIndex() - FirstTypeID;
Sebastian Redl66c5eef2010-07-27 00:17:23 +00002749 if (TypeOffsets.size() == Index)
Douglas Gregor8f45df52009-04-16 22:23:12 +00002750 TypeOffsets.push_back(Stream.GetCurrentBitNo());
Sebastian Redl66c5eef2010-07-27 00:17:23 +00002751 else if (TypeOffsets.size() < Index) {
2752 TypeOffsets.resize(Index + 1);
2753 TypeOffsets[Index] = Stream.GetCurrentBitNo();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002754 }
2755
2756 RecordData Record;
Mike Stump11289f42009-09-09 15:08:12 +00002757
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002758 // Emit the type's representation.
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002759 ASTTypeWriter W(*this, Record);
Richard Smith01b2cb42014-07-26 06:37:51 +00002760 W.AbbrevToUse = 0;
John McCall8ccfcb52009-09-24 19:53:00 +00002761
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002762 if (T.hasLocalNonFastQualifiers()) {
2763 Qualifiers Qs = T.getLocalQualifiers();
2764 AddTypeRef(T.getLocalUnqualifiedType(), Record);
John McCall8ccfcb52009-09-24 19:53:00 +00002765 Record.push_back(Qs.getAsOpaqueValue());
Sebastian Redl539c5062010-08-18 23:57:32 +00002766 W.Code = TYPE_EXT_QUAL;
Richard Smith01b2cb42014-07-26 06:37:51 +00002767 W.AbbrevToUse = TypeExtQualAbbrev;
John McCall8ccfcb52009-09-24 19:53:00 +00002768 } else {
2769 switch (T->getTypeClass()) {
2770 // For all of the concrete, non-dependent types, call the
2771 // appropriate visitor function.
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002772#define TYPE(Class, Base) \
Mike Stump281d6d72010-01-20 02:03:14 +00002773 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002774#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002775#include "clang/AST/TypeNodes.def"
John McCall8ccfcb52009-09-24 19:53:00 +00002776 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002777 }
2778
2779 // Emit the serialized record.
Richard Smith01b2cb42014-07-26 06:37:51 +00002780 Stream.EmitRecord(W.Code, Record, W.AbbrevToUse);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002781
2782 // Flush any expressions that were written as part of this type.
Douglas Gregor8f45df52009-04-16 22:23:12 +00002783 FlushStmts();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002784}
2785
Douglas Gregorc5046832009-04-27 18:38:38 +00002786//===----------------------------------------------------------------------===//
2787// Declaration Serialization
2788//===----------------------------------------------------------------------===//
2789
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002790/// \brief Write the block containing all of the declaration IDs
2791/// lexically declared within the given DeclContext.
2792///
2793/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
2794/// bistream, or 0 if no block was written.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002795uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002796 DeclContext *DC) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002797 if (DC->decls_empty())
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002798 return 0;
2799
Douglas Gregor8f45df52009-04-16 22:23:12 +00002800 uint64_t Offset = Stream.GetCurrentBitNo();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002801 SmallVector<uint32_t, 128> KindDeclPairs;
2802 for (const auto *D : DC->decls()) {
2803 KindDeclPairs.push_back(D->getKind());
2804 KindDeclPairs.push_back(GetDeclRef(D));
2805 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002806
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002807 ++NumLexicalDeclContexts;
Mehdi Amini57a41912015-09-10 01:46:39 +00002808 RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
Richard Smith82f8fcd2015-08-06 22:07:25 +00002809 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
2810 bytes(KindDeclPairs));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002811 return Offset;
2812}
2813
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002814void ASTWriter::WriteTypeDeclOffsets() {
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002815 using namespace llvm;
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002816
2817 // Write the type offsets array
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002818 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00002819 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002820 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
Douglas Gregor5204bde2011-08-02 16:26:37 +00002821 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002822 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
2823 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00002824 {
2825 RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(),
2826 FirstTypeID - NUM_PREDEF_TYPE_IDS};
2827 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
2828 }
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002829
2830 // Write the declaration offsets array
2831 Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00002832 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002833 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
Douglas Gregorf7180622011-08-03 15:48:04 +00002834 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002835 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
2836 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00002837 {
2838 RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(),
2839 FirstDeclID - NUM_PREDEF_DECL_IDS};
2840 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
2841 }
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002842}
2843
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002844void ASTWriter::WriteFileDeclIDsMap() {
2845 using namespace llvm;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002846
Chandler Carruthb306d732015-03-27 00:31:20 +00002847 SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs(
2848 FileDeclIDs.begin(), FileDeclIDs.end());
2849 std::sort(SortedFileDeclIDs.begin(), SortedFileDeclIDs.end(),
2850 llvm::less_first());
2851
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002852 // Join the vectors of DeclIDs from all files.
Chandler Carruthb306d732015-03-27 00:31:20 +00002853 SmallVector<DeclID, 256> FileGroupedDeclIDs;
2854 for (auto &FileDeclEntry : SortedFileDeclIDs) {
2855 DeclIDInFileInfo &Info = *FileDeclEntry.second;
2856 Info.FirstDeclIndex = FileGroupedDeclIDs.size();
2857 for (auto &LocDeclEntry : Info.DeclIDs)
2858 FileGroupedDeclIDs.push_back(LocDeclEntry.second);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002859 }
2860
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002861 auto *Abbrev = new BitCodeAbbrev();
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002862 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002863 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002864 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2865 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00002866 RecordData::value_type Record[] = {FILE_SORTED_DECLS,
2867 FileGroupedDeclIDs.size()};
Reid Kleckner012665e2015-05-21 00:13:09 +00002868 Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002869}
2870
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002871void ASTWriter::WriteComments() {
2872 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +00002873 ArrayRef<RawComment *> RawComments = Context->Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002874 RecordData Record;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002875 for (const auto *I : RawComments) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002876 Record.clear();
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002877 AddSourceRange(I->getSourceRange(), Record);
2878 Record.push_back(I->getKind());
2879 Record.push_back(I->isTrailingComment());
2880 Record.push_back(I->isAlmostTrailingComment());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002881 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
2882 }
2883 Stream.ExitBlock();
2884}
2885
Douglas Gregorc5046832009-04-27 18:38:38 +00002886//===----------------------------------------------------------------------===//
2887// Global Method Pool and Selector Serialization
2888//===----------------------------------------------------------------------===//
2889
Douglas Gregore84a9da2009-04-20 20:36:09 +00002890namespace {
Douglas Gregorc78d3462009-04-24 21:10:55 +00002891// Trait used for the on-disk hash table used in the method pool.
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002892class ASTMethodPoolTrait {
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002893 ASTWriter &Writer;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002894
2895public:
2896 typedef Selector key_type;
2897 typedef key_type key_type_ref;
Mike Stump11289f42009-09-09 15:08:12 +00002898
Sebastian Redl834bb972010-08-04 17:20:04 +00002899 struct data_type {
Sebastian Redl539c5062010-08-18 23:57:32 +00002900 SelectorID ID;
Sebastian Redl834bb972010-08-04 17:20:04 +00002901 ObjCMethodList Instance, Factory;
2902 };
Douglas Gregorc78d3462009-04-24 21:10:55 +00002903 typedef const data_type& data_type_ref;
2904
Justin Bogner25463f12014-04-18 20:27:24 +00002905 typedef unsigned hash_value_type;
2906 typedef unsigned offset_type;
2907
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002908 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { }
Mike Stump11289f42009-09-09 15:08:12 +00002909
Justin Bogner25463f12014-04-18 20:27:24 +00002910 static hash_value_type ComputeHash(Selector Sel) {
Argyrios Kyrtzidis4bd97102010-08-20 16:03:52 +00002911 return serialization::ComputeHash(Sel);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002912 }
Mike Stump11289f42009-09-09 15:08:12 +00002913
2914 std::pair<unsigned,unsigned>
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002915 EmitKeyDataLength(raw_ostream& Out, Selector Sel,
Douglas Gregorc78d3462009-04-24 21:10:55 +00002916 data_type_ref Methods) {
Justin Bognere1c147c2014-03-28 22:03:19 +00002917 using namespace llvm::support;
2918 endian::Writer<little> LE(Out);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002919 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
Justin Bognere1c147c2014-03-28 22:03:19 +00002920 LE.write<uint16_t>(KeyLen);
Sebastian Redl834bb972010-08-04 17:20:04 +00002921 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
2922 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002923 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002924 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002925 DataLen += 4;
Sebastian Redl834bb972010-08-04 17:20:04 +00002926 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002927 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002928 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002929 DataLen += 4;
Justin Bognere1c147c2014-03-28 22:03:19 +00002930 LE.write<uint16_t>(DataLen);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002931 return std::make_pair(KeyLen, DataLen);
2932 }
Mike Stump11289f42009-09-09 15:08:12 +00002933
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002934 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00002935 using namespace llvm::support;
2936 endian::Writer<little> LE(Out);
Mike Stump11289f42009-09-09 15:08:12 +00002937 uint64_t Start = Out.tell();
Douglas Gregor95c13f52009-04-25 17:48:32 +00002938 assert((Start >> 32) == 0 && "Selector key offset too large");
2939 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002940 unsigned N = Sel.getNumArgs();
Justin Bognere1c147c2014-03-28 22:03:19 +00002941 LE.write<uint16_t>(N);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002942 if (N == 0)
2943 N = 1;
2944 for (unsigned I = 0; I != N; ++I)
Justin Bognere1c147c2014-03-28 22:03:19 +00002945 LE.write<uint32_t>(
2946 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
Douglas Gregorc78d3462009-04-24 21:10:55 +00002947 }
Mike Stump11289f42009-09-09 15:08:12 +00002948
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002949 void EmitData(raw_ostream& Out, key_type_ref,
Douglas Gregor4647cfa2009-04-24 21:49:02 +00002950 data_type_ref Methods, unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00002951 using namespace llvm::support;
2952 endian::Writer<little> LE(Out);
Douglas Gregor4647cfa2009-04-24 21:49:02 +00002953 uint64_t Start = Out.tell(); (void)Start;
Justin Bognere1c147c2014-03-28 22:03:19 +00002954 LE.write<uint32_t>(Methods.ID);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002955 unsigned NumInstanceMethods = 0;
Sebastian Redl834bb972010-08-04 17:20:04 +00002956 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002957 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002958 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002959 ++NumInstanceMethods;
2960
2961 unsigned NumFactoryMethods = 0;
Sebastian Redl834bb972010-08-04 17:20:04 +00002962 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002963 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002964 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002965 ++NumFactoryMethods;
2966
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002967 unsigned InstanceBits = Methods.Instance.getBits();
2968 assert(InstanceBits < 4);
Nico Weberff4b35e2014-12-27 22:14:15 +00002969 unsigned InstanceHasMoreThanOneDeclBit =
2970 Methods.Instance.hasMoreThanOneDecl();
2971 unsigned FullInstanceBits = (NumInstanceMethods << 3) |
2972 (InstanceHasMoreThanOneDeclBit << 2) |
2973 InstanceBits;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002974 unsigned FactoryBits = Methods.Factory.getBits();
2975 assert(FactoryBits < 4);
Nico Weberff4b35e2014-12-27 22:14:15 +00002976 unsigned FactoryHasMoreThanOneDeclBit =
2977 Methods.Factory.hasMoreThanOneDecl();
2978 unsigned FullFactoryBits = (NumFactoryMethods << 3) |
2979 (FactoryHasMoreThanOneDeclBit << 2) |
2980 FactoryBits;
2981 LE.write<uint16_t>(FullInstanceBits);
2982 LE.write<uint16_t>(FullFactoryBits);
Sebastian Redl834bb972010-08-04 17:20:04 +00002983 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002984 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002985 if (Method->getMethod())
2986 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
Sebastian Redl834bb972010-08-04 17:20:04 +00002987 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002988 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002989 if (Method->getMethod())
2990 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
Douglas Gregor4647cfa2009-04-24 21:49:02 +00002991
2992 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorc78d3462009-04-24 21:10:55 +00002993 }
2994};
2995} // end anonymous namespace
2996
Sebastian Redla19a67f2010-08-03 21:58:15 +00002997/// \brief Write ObjC data: selectors and the method pool.
Douglas Gregorc78d3462009-04-24 21:10:55 +00002998///
2999/// The method pool contains both instance and factory methods, stored
Sebastian Redla19a67f2010-08-03 21:58:15 +00003000/// in an on-disk hash table indexed by the selector. The hash table also
3001/// contains an empty entry for every other selector known to Sema.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003002void ASTWriter::WriteSelectors(Sema &SemaRef) {
Douglas Gregorc78d3462009-04-24 21:10:55 +00003003 using namespace llvm;
3004
Sebastian Redla19a67f2010-08-03 21:58:15 +00003005 // Do we have to do anything at all?
Sebastian Redl834bb972010-08-04 17:20:04 +00003006 if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
Sebastian Redla19a67f2010-08-03 21:58:15 +00003007 return;
Sebastian Redld95a56e2010-08-04 18:21:41 +00003008 unsigned NumTableEntries = 0;
Sebastian Redla19a67f2010-08-03 21:58:15 +00003009 // Create and write out the blob that contains selectors and the method pool.
Douglas Gregorc78d3462009-04-24 21:10:55 +00003010 {
Justin Bognerbb094f02014-04-18 19:57:06 +00003011 llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003012 ASTMethodPoolTrait Trait(*this);
Mike Stump11289f42009-09-09 15:08:12 +00003013
Sebastian Redla19a67f2010-08-03 21:58:15 +00003014 // Create the on-disk hash table representation. We walk through every
3015 // selector we've seen and look it up in the method pool.
Sebastian Redld95a56e2010-08-04 18:21:41 +00003016 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003017 for (auto &SelectorAndID : SelectorIDs) {
3018 Selector S = SelectorAndID.first;
3019 SelectorID ID = SelectorAndID.second;
Sebastian Redla19a67f2010-08-03 21:58:15 +00003020 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003021 ASTMethodPoolTrait::data_type Data = {
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003022 ID,
Sebastian Redl834bb972010-08-04 17:20:04 +00003023 ObjCMethodList(),
3024 ObjCMethodList()
3025 };
3026 if (F != SemaRef.MethodPool.end()) {
3027 Data.Instance = F->second.first;
3028 Data.Factory = F->second.second;
3029 }
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003030 // Only write this selector if it's not in an existing AST or something
Sebastian Redld95a56e2010-08-04 18:21:41 +00003031 // changed.
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003032 if (Chain && ID < FirstSelectorID) {
Sebastian Redld95a56e2010-08-04 18:21:41 +00003033 // Selector already exists. Did it change?
3034 bool changed = false;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003035 for (ObjCMethodList *M = &Data.Instance;
3036 !changed && M && M->getMethod(); M = M->getNext()) {
3037 if (!M->getMethod()->isFromASTFile())
Sebastian Redld95a56e2010-08-04 18:21:41 +00003038 changed = true;
3039 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003040 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003041 M = M->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003042 if (!M->getMethod()->isFromASTFile())
Sebastian Redld95a56e2010-08-04 18:21:41 +00003043 changed = true;
3044 }
3045 if (!changed)
3046 continue;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003047 } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
Sebastian Redl6e1a2a02010-08-04 21:22:45 +00003048 // A new method pool entry.
3049 ++NumTableEntries;
Sebastian Redld95a56e2010-08-04 18:21:41 +00003050 }
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003051 Generator.insert(S, Data, Trait);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003052 }
3053
Douglas Gregorc78d3462009-04-24 21:10:55 +00003054 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003055 SmallString<4096> MethodPool;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003056 uint32_t BucketOffset;
3057 {
Justin Bognere1c147c2014-03-28 22:03:19 +00003058 using namespace llvm::support;
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003059 ASTMethodPoolTrait Trait(*this);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003060 llvm::raw_svector_ostream Out(MethodPool);
3061 // Make sure that no bucket is at offset 0
Justin Bognere1c147c2014-03-28 22:03:19 +00003062 endian::Writer<little>(Out).write<uint32_t>(0);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003063 BucketOffset = Generator.Emit(Out, Trait);
3064 }
3065
3066 // Create a blob abbreviation
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003067 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00003068 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003069 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor95c13f52009-04-25 17:48:32 +00003070 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003071 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3072 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
3073
Douglas Gregor95c13f52009-04-25 17:48:32 +00003074 // Write the method pool
Mehdi Amini57a41912015-09-10 01:46:39 +00003075 {
3076 RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3077 NumTableEntries};
3078 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3079 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00003080
3081 // Create a blob abbreviation for the selector table offsets.
3082 Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00003083 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
Douglas Gregord4c5ed02010-10-29 22:39:52 +00003084 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
Douglas Gregor8f364fb2011-08-03 23:28:44 +00003085 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
Douglas Gregor95c13f52009-04-25 17:48:32 +00003086 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3087 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
3088
3089 // Write the selector offsets table.
Mehdi Amini57a41912015-09-10 01:46:39 +00003090 {
3091 RecordData::value_type Record[] = {
3092 SELECTOR_OFFSETS, SelectorOffsets.size(),
3093 FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3094 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3095 bytes(SelectorOffsets));
3096 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00003097 }
3098}
3099
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003100/// \brief Write the selectors referenced in @selector expression into AST file.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003101void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003102 using namespace llvm;
3103 if (SemaRef.ReferencedSelectors.empty())
3104 return;
Sebastian Redlada023c2010-08-04 20:40:17 +00003105
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003106 RecordData Record;
Sebastian Redlada023c2010-08-04 20:40:17 +00003107
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003108 // Note: this writes out all references even for a dependent AST. But it is
Sebastian Redl51c79d82010-08-04 22:21:29 +00003109 // very tricky to fix, and given that @selector shouldn't really appear in
3110 // headers, probably not worth it. It's not a correctness issue.
Chandler Carruth12c8f652015-03-27 00:55:05 +00003111 for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
3112 Selector Sel = SelectorAndLocation.first;
3113 SourceLocation Loc = SelectorAndLocation.second;
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003114 AddSelectorRef(Sel, Record);
3115 AddSourceLocation(Loc, Record);
3116 }
Sebastian Redl539c5062010-08-18 23:57:32 +00003117 Stream.EmitRecord(REFERENCED_SELECTOR_POOL, Record);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003118}
3119
Douglas Gregorc5046832009-04-27 18:38:38 +00003120//===----------------------------------------------------------------------===//
3121// Identifier Table Serialization
3122//===----------------------------------------------------------------------===//
3123
Richard Smithb3761912015-02-05 23:08:52 +00003124/// Determine the declaration that should be put into the name lookup table to
3125/// represent the given declaration in this module. This is usually D itself,
3126/// but if D was imported and merged into a local declaration, we want the most
3127/// recent local declaration instead. The chosen declaration will be the most
3128/// recent declaration in any module that imports this one.
3129static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
3130 NamedDecl *D) {
3131 if (!LangOpts.Modules || !D->isFromASTFile())
3132 return D;
3133
3134 if (Decl *Redecl = D->getPreviousDecl()) {
3135 // For Redeclarable decls, a prior declaration might be local.
3136 for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
3137 if (!Redecl->isFromASTFile())
3138 return cast<NamedDecl>(Redecl);
Richard Smithfe620d22015-03-05 23:24:12 +00003139 // If we find a decl from a (chained-)PCH stop since we won't find a
Richard Smithb3761912015-02-05 23:08:52 +00003140 // local one.
3141 if (D->getOwningModuleID() == 0)
3142 break;
3143 }
3144 } else if (Decl *First = D->getCanonicalDecl()) {
3145 // For Mergeable decls, the first decl might be local.
3146 if (!First->isFromASTFile())
3147 return cast<NamedDecl>(First);
3148 }
3149
3150 // All declarations are imported. Our most recent declaration will also be
3151 // the most recent one in anyone who imports us.
3152 return D;
3153}
3154
Douglas Gregorc78d3462009-04-24 21:10:55 +00003155namespace {
Richard Smithcf97cf62015-04-19 01:34:23 +00003156class ASTIdentifierTableTrait {
3157 ASTWriter &Writer;
3158 Preprocessor &PP;
3159 IdentifierResolver &IdResolver;
Richard Smith9c254182015-07-19 21:41:12 +00003160 bool IsModule;
Richard Smitha534a312015-07-21 23:54:07 +00003161 bool NeedDecls;
Richard Smith33e0f7e2015-07-22 02:08:40 +00003162 ASTWriter::RecordData *InterestingIdentifierOffsets;
Richard Smithcf97cf62015-04-19 01:34:23 +00003163
3164 /// \brief Determines whether this is an "interesting" identifier that needs a
3165 /// full IdentifierInfo structure written into the hash table. Notably, this
3166 /// doesn't check whether the name has macros defined; use PublicMacroIterator
3167 /// to check that.
Richard Smith9c254182015-07-19 21:41:12 +00003168 bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
Richard Smithd7329392015-04-21 21:46:32 +00003169 if (MacroOffset ||
3170 II->isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +00003171 (IsModule ? II->hasRevertedBuiltin() : II->getObjCOrBuiltinID()) ||
Richard Smithcf97cf62015-04-19 01:34:23 +00003172 II->hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +00003173 (NeedDecls && II->getFETokenInfo<void>()))
Richard Smithcf97cf62015-04-19 01:34:23 +00003174 return true;
3175
3176 return false;
3177 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003178
Douglas Gregore84a9da2009-04-20 20:36:09 +00003179public:
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00003180 typedef IdentifierInfo* key_type;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003181 typedef key_type key_type_ref;
Mike Stump11289f42009-09-09 15:08:12 +00003182
Sebastian Redl539c5062010-08-18 23:57:32 +00003183 typedef IdentID data_type;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003184 typedef data_type data_type_ref;
Mike Stump11289f42009-09-09 15:08:12 +00003185
Justin Bogner25463f12014-04-18 20:27:24 +00003186 typedef unsigned hash_value_type;
3187 typedef unsigned offset_type;
3188
Richard Smithd7329392015-04-21 21:46:32 +00003189 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
Richard Smith33e0f7e2015-07-22 02:08:40 +00003190 IdentifierResolver &IdResolver, bool IsModule,
3191 ASTWriter::RecordData *InterestingIdentifierOffsets)
Richard Smitha534a312015-07-21 23:54:07 +00003192 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
Richard Smith33e0f7e2015-07-22 02:08:40 +00003193 NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3194 InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
Douglas Gregore84a9da2009-04-20 20:36:09 +00003195
Richard Smithd79514e2016-02-05 19:03:40 +00003196 bool needDecls() const { return NeedDecls; }
3197
Justin Bogner25463f12014-04-18 20:27:24 +00003198 static hash_value_type ComputeHash(const IdentifierInfo* II) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +00003199 return llvm::HashString(II->getName());
Douglas Gregore84a9da2009-04-20 20:36:09 +00003200 }
Mike Stump11289f42009-09-09 15:08:12 +00003201
Richard Smith33e0f7e2015-07-22 02:08:40 +00003202 bool isInterestingIdentifier(const IdentifierInfo *II) {
3203 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3204 return isInterestingIdentifier(II, MacroOffset);
3205 }
Richard Smith9c254182015-07-19 21:41:12 +00003206 bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) {
3207 return isInterestingIdentifier(II, 0);
3208 }
3209
Mike Stump11289f42009-09-09 15:08:12 +00003210 std::pair<unsigned,unsigned>
Douglas Gregor935bc7a22011-10-27 09:33:13 +00003211 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003212 unsigned KeyLen = II->getLength() + 1;
Douglas Gregor1d583f22009-04-28 21:18:29 +00003213 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
Richard Smithd7329392015-04-21 21:46:32 +00003214 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3215 if (isInterestingIdentifier(II, MacroOffset)) {
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003216 DataLen += 2; // 2 bytes for builtin ID
3217 DataLen += 2; // 2 bytes for flags
Richard Smithd7329392015-04-21 21:46:32 +00003218 if (MacroOffset)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003219 DataLen += 4; // MacroDirectives offset.
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003220
Richard Smitha534a312015-07-21 23:54:07 +00003221 if (NeedDecls) {
3222 for (IdentifierResolver::iterator D = IdResolver.begin(II),
3223 DEnd = IdResolver.end();
3224 D != DEnd; ++D)
3225 DataLen += 4;
3226 }
Douglas Gregor1d583f22009-04-28 21:18:29 +00003227 }
Justin Bognere1c147c2014-03-28 22:03:19 +00003228 using namespace llvm::support;
3229 endian::Writer<little> LE(Out);
3230
Richard Smithdf8a8312015-03-13 04:05:01 +00003231 assert((uint16_t)DataLen == DataLen && (uint16_t)KeyLen == KeyLen);
Justin Bognere1c147c2014-03-28 22:03:19 +00003232 LE.write<uint16_t>(DataLen);
Douglas Gregorab4df582009-04-28 20:01:51 +00003233 // We emit the key length after the data length so that every
3234 // string is preceded by a 16-bit length. This matches the PTH
3235 // format for storing identifiers.
Justin Bognere1c147c2014-03-28 22:03:19 +00003236 LE.write<uint16_t>(KeyLen);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003237 return std::make_pair(KeyLen, DataLen);
3238 }
Mike Stump11289f42009-09-09 15:08:12 +00003239
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003240 void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
Douglas Gregore84a9da2009-04-20 20:36:09 +00003241 unsigned KeyLen) {
3242 // Record the location of the key data. This is used when generating
3243 // the mapping from persistent IDs to strings.
3244 Writer.SetIdentifierOffset(II, Out.tell());
Richard Smith33e0f7e2015-07-22 02:08:40 +00003245
3246 // Emit the offset of the key/data length information to the interesting
3247 // identifiers table if necessary.
3248 if (InterestingIdentifierOffsets && isInterestingIdentifier(II))
3249 InterestingIdentifierOffsets->push_back(Out.tell() - 4);
3250
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003251 Out.write(II->getNameStart(), KeyLen);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003252 }
Mike Stump11289f42009-09-09 15:08:12 +00003253
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00003254 void EmitData(raw_ostream& Out, IdentifierInfo* II,
Sebastian Redl539c5062010-08-18 23:57:32 +00003255 IdentID ID, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003256 using namespace llvm::support;
3257 endian::Writer<little> LE(Out);
Richard Smithcf97cf62015-04-19 01:34:23 +00003258
Richard Smithd7329392015-04-21 21:46:32 +00003259 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3260 if (!isInterestingIdentifier(II, MacroOffset)) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003261 LE.write<uint32_t>(ID << 1);
Douglas Gregor1d583f22009-04-28 21:18:29 +00003262 return;
3263 }
Douglas Gregorb9256522009-04-28 21:32:13 +00003264
Justin Bognere1c147c2014-03-28 22:03:19 +00003265 LE.write<uint32_t>((ID << 1) | 0x01);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003266 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3267 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
Justin Bognere1c147c2014-03-28 22:03:19 +00003268 LE.write<uint16_t>(Bits);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003269 Bits = 0;
Richard Smithd7329392015-04-21 21:46:32 +00003270 bool HadMacroDefinition = MacroOffset != 0;
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003271 Bits = (Bits << 1) | unsigned(HadMacroDefinition);
Daniel Dunbar91b640a2009-12-18 20:58:47 +00003272 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3273 Bits = (Bits << 1) | unsigned(II->isPoisoned());
Richard Smith9c254182015-07-19 21:41:12 +00003274 Bits = (Bits << 1) | unsigned(II->hasRevertedBuiltin());
Argyrios Kyrtzidis3084a612010-08-11 22:55:12 +00003275 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
Daniel Dunbar91b640a2009-12-18 20:58:47 +00003276 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
Justin Bognere1c147c2014-03-28 22:03:19 +00003277 LE.write<uint16_t>(Bits);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003278
Richard Smithd7329392015-04-21 21:46:32 +00003279 if (HadMacroDefinition)
3280 LE.write<uint32_t>(MacroOffset);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003281
Richard Smitha534a312015-07-21 23:54:07 +00003282 if (NeedDecls) {
3283 // Emit the declaration IDs in reverse order, because the
3284 // IdentifierResolver provides the declarations as they would be
3285 // visible (e.g., the function "stat" would come before the struct
3286 // "stat"), but the ASTReader adds declarations to the end of the list
3287 // (so we need to see the struct "stat" before the function "stat").
3288 // Only emit declarations that aren't from a chained PCH, though.
3289 SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II),
3290 IdResolver.end());
3291 for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(),
3292 DEnd = Decls.rend();
3293 D != DEnd; ++D)
3294 LE.write<uint32_t>(
3295 Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D)));
3296 }
Douglas Gregore84a9da2009-04-20 20:36:09 +00003297 }
3298};
3299} // end anonymous namespace
3300
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003301/// \brief Write the identifier table into the AST file.
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003302///
3303/// The identifier table consists of a blob containing string data
3304/// (the actual identifiers themselves) and a separate "offsets" index
3305/// that maps identifier IDs to locations within the blob.
Douglas Gregor935bc7a22011-10-27 09:33:13 +00003306void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3307 IdentifierResolver &IdResolver,
3308 bool IsModule) {
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003309 using namespace llvm;
3310
Richard Smith33e0f7e2015-07-22 02:08:40 +00003311 RecordData InterestingIdents;
3312
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003313 // Create and write out the blob that contains the identifier
3314 // strings.
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003315 {
Justin Bognerbb094f02014-04-18 19:57:06 +00003316 llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
Richard Smith33e0f7e2015-07-22 02:08:40 +00003317 ASTIdentifierTableTrait Trait(
3318 *this, PP, IdResolver, IsModule,
3319 (getLangOpts().CPlusPlus && IsModule) ? &InterestingIdents : nullptr);
Mike Stump11289f42009-09-09 15:08:12 +00003320
Douglas Gregore6648fb2009-04-28 20:33:11 +00003321 // Look for any identifiers that were named while processing the
3322 // headers, but are otherwise not needed. We add these to the hash
3323 // table to enable checking of the predefines buffer in the case
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003324 // where the user adds new macro definitions when building the AST
Douglas Gregore6648fb2009-04-28 20:33:11 +00003325 // file.
Chandler Carruth8440c982015-03-26 23:54:15 +00003326 SmallVector<const IdentifierInfo *, 128> IIs;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003327 for (const auto &ID : PP.getIdentifierTable())
3328 IIs.push_back(ID.second);
Chandler Carruth8440c982015-03-26 23:54:15 +00003329 // Sort the identifiers lexicographically before getting them references so
3330 // that their order is stable.
3331 std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
3332 for (const IdentifierInfo *II : IIs)
Richard Smith9c254182015-07-19 21:41:12 +00003333 if (Trait.isInterestingNonMacroIdentifier(II))
3334 getIdentifierRef(II);
Douglas Gregore6648fb2009-04-28 20:33:11 +00003335
Sebastian Redlff4a2952010-07-23 23:49:55 +00003336 // Create the on-disk hash table representation. We only store offsets
3337 // for identifiers that appear here for the first time.
3338 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
Chandler Carruth885e78c2015-03-24 21:18:10 +00003339 for (auto IdentIDPair : IdentifierIDs) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003340 auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
Chandler Carruth885e78c2015-03-24 21:18:10 +00003341 IdentID ID = IdentIDPair.second;
3342 assert(II && "NULL identifier in identifier table");
Vassil Vassilev262f41e2016-03-30 20:16:03 +00003343 // Write out identifiers if either the ID is local or the identifier has
3344 // changed since it was loaded.
3345 if (ID >= FirstIdentID || !Chain || !II->isFromAST()
3346 || II->hasChangedSinceDeserialization() ||
Richard Smithd79514e2016-02-05 19:03:40 +00003347 (Trait.needDecls() &&
3348 II->hasFETokenInfoChangedSinceDeserialization()))
Chandler Carruth885e78c2015-03-24 21:18:10 +00003349 Generator.insert(II, ID, Trait);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003350 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003351
Douglas Gregore84a9da2009-04-20 20:36:09 +00003352 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003353 SmallString<4096> IdentifierTable;
Douglas Gregora868bbd2009-04-21 22:25:48 +00003354 uint32_t BucketOffset;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003355 {
Justin Bognere1c147c2014-03-28 22:03:19 +00003356 using namespace llvm::support;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003357 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003358 // Make sure that no bucket is at offset 0
Justin Bognere1c147c2014-03-28 22:03:19 +00003359 endian::Writer<little>(Out).write<uint32_t>(0);
Douglas Gregora868bbd2009-04-21 22:25:48 +00003360 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003361 }
3362
3363 // Create a blob abbreviation
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003364 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00003365 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
Douglas Gregora868bbd2009-04-21 22:25:48 +00003366 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregore84a9da2009-04-20 20:36:09 +00003367 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregor8f45df52009-04-16 22:23:12 +00003368 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003369
3370 // Write the identifier table
Mehdi Amini57a41912015-09-10 01:46:39 +00003371 RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
Yaron Keren92e1b622015-03-18 10:17:07 +00003372 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003373 }
3374
3375 // Write the offsets table for identifier IDs.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003376 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00003377 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
Douglas Gregor0e149972009-04-25 19:10:14 +00003378 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
Douglas Gregor1ab036c2011-08-03 21:49:18 +00003379 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
Douglas Gregor0e149972009-04-25 19:10:14 +00003380 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3381 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
3382
Douglas Gregor8d7edce2013-02-08 21:30:59 +00003383#ifndef NDEBUG
3384 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3385 assert(IdentifierOffsets[I] && "Missing identifier offset?");
3386#endif
Mehdi Amini57a41912015-09-10 01:46:39 +00003387
3388 RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
3389 IdentifierOffsets.size(),
3390 FirstIdentID - NUM_PREDEF_IDENT_IDS};
Douglas Gregor0e149972009-04-25 19:10:14 +00003391 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00003392 bytes(IdentifierOffsets));
Richard Smith33e0f7e2015-07-22 02:08:40 +00003393
3394 // In C++, write the list of interesting identifiers (those that are
3395 // defined as macros, poisoned, or similar unusual things).
3396 if (!InterestingIdents.empty())
3397 Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003398}
3399
Douglas Gregorc5046832009-04-27 18:38:38 +00003400//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003401// DeclContext's Name Lookup Table Serialization
3402//===----------------------------------------------------------------------===//
3403
3404namespace {
3405// Trait used for the on-disk hash table used in the method pool.
3406class ASTDeclContextNameLookupTrait {
3407 ASTWriter &Writer;
Richard Smithd88a7f12015-09-01 20:35:42 +00003408 llvm::SmallVector<DeclID, 64> DeclIDs;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003409
3410public:
Richard Smitha06c7e62015-08-26 23:55:49 +00003411 typedef DeclarationNameKey key_type;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003412 typedef key_type key_type_ref;
3413
Richard Smithd88a7f12015-09-01 20:35:42 +00003414 /// A start and end index into DeclIDs, representing a sequence of decls.
3415 typedef std::pair<unsigned, unsigned> data_type;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003416 typedef const data_type& data_type_ref;
3417
Justin Bogner25463f12014-04-18 20:27:24 +00003418 typedef unsigned hash_value_type;
3419 typedef unsigned offset_type;
3420
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003421 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { }
3422
Richard Smithd88a7f12015-09-01 20:35:42 +00003423 template<typename Coll>
3424 data_type getData(const Coll &Decls) {
3425 unsigned Start = DeclIDs.size();
3426 for (NamedDecl *D : Decls) {
3427 DeclIDs.push_back(
3428 Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3429 }
3430 return std::make_pair(Start, DeclIDs.size());
3431 }
3432
3433 data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
3434 unsigned Start = DeclIDs.size();
3435 for (auto ID : FromReader)
3436 DeclIDs.push_back(ID);
3437 return std::make_pair(Start, DeclIDs.size());
3438 }
3439
3440 static bool EqualKey(key_type_ref a, key_type_ref b) {
3441 return a == b;
3442 }
3443
Richard Smitha06c7e62015-08-26 23:55:49 +00003444 hash_value_type ComputeHash(DeclarationNameKey Name) {
3445 return Name.getHash();
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003446 }
3447
Richard Smithd88a7f12015-09-01 20:35:42 +00003448 void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
3449 assert(Writer.hasChain() &&
3450 "have reference to loaded module file but no chain?");
3451
3452 using namespace llvm::support;
3453 endian::Writer<little>(Out)
3454 .write<uint32_t>(Writer.getChain()->getModuleFileID(F));
3455 }
3456
Richard Smitha06c7e62015-08-26 23:55:49 +00003457 std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
3458 DeclarationNameKey Name,
3459 data_type_ref Lookup) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003460 using namespace llvm::support;
3461 endian::Writer<little> LE(Out);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003462 unsigned KeyLen = 1;
Richard Smitha06c7e62015-08-26 23:55:49 +00003463 switch (Name.getKind()) {
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003464 case DeclarationName::Identifier:
3465 case DeclarationName::ObjCZeroArgSelector:
3466 case DeclarationName::ObjCOneArgSelector:
3467 case DeclarationName::ObjCMultiArgSelector:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003468 case DeclarationName::CXXLiteralOperatorName:
3469 KeyLen += 4;
3470 break;
3471 case DeclarationName::CXXOperatorName:
3472 KeyLen += 1;
3473 break;
Douglas Gregor3b65ed02011-08-02 18:32:54 +00003474 case DeclarationName::CXXConstructorName:
3475 case DeclarationName::CXXDestructorName:
3476 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003477 case DeclarationName::CXXUsingDirective:
3478 break;
3479 }
Justin Bognere1c147c2014-03-28 22:03:19 +00003480 LE.write<uint16_t>(KeyLen);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003481
Richard Smithf02662d2015-07-30 03:17:16 +00003482 // 4 bytes for each DeclID.
Richard Smithd88a7f12015-09-01 20:35:42 +00003483 unsigned DataLen = 4 * (Lookup.second - Lookup.first);
3484 assert(uint16_t(DataLen) == DataLen &&
3485 "too many decls for serialized lookup result");
Justin Bognere1c147c2014-03-28 22:03:19 +00003486 LE.write<uint16_t>(DataLen);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003487
3488 return std::make_pair(KeyLen, DataLen);
3489 }
3490
Richard Smitha06c7e62015-08-26 23:55:49 +00003491 void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003492 using namespace llvm::support;
3493 endian::Writer<little> LE(Out);
Richard Smitha06c7e62015-08-26 23:55:49 +00003494 LE.write<uint8_t>(Name.getKind());
3495 switch (Name.getKind()) {
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003496 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +00003497 case DeclarationName::CXXLiteralOperatorName:
3498 LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier()));
Benjamin Kramer53750b12012-09-19 13:40:40 +00003499 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003500 case DeclarationName::ObjCZeroArgSelector:
3501 case DeclarationName::ObjCOneArgSelector:
3502 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00003503 LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
Benjamin Kramer53750b12012-09-19 13:40:40 +00003504 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003505 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00003506 assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
Benjamin Kramer53750b12012-09-19 13:40:40 +00003507 "Invalid operator?");
Richard Smitha06c7e62015-08-26 23:55:49 +00003508 LE.write<uint8_t>(Name.getOperatorKind());
Benjamin Kramer53750b12012-09-19 13:40:40 +00003509 return;
Douglas Gregor3b65ed02011-08-02 18:32:54 +00003510 case DeclarationName::CXXConstructorName:
3511 case DeclarationName::CXXDestructorName:
3512 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003513 case DeclarationName::CXXUsingDirective:
Benjamin Kramer53750b12012-09-19 13:40:40 +00003514 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003515 }
Benjamin Kramer53750b12012-09-19 13:40:40 +00003516
3517 llvm_unreachable("Invalid name kind?");
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003518 }
3519
Richard Smitha06c7e62015-08-26 23:55:49 +00003520 void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
3521 unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003522 using namespace llvm::support;
3523 endian::Writer<little> LE(Out);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003524 uint64_t Start = Out.tell(); (void)Start;
Richard Smithd88a7f12015-09-01 20:35:42 +00003525 for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
3526 LE.write<uint32_t>(DeclIDs[I]);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003527 assert(Out.tell() - Start == DataLen && "Data length is wrong");
3528 }
3529};
3530} // end anonymous namespace
3531
Chandler Carruthe972c362015-03-26 03:11:40 +00003532bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
3533 DeclContext *DC) {
3534 return Result.hasExternalDecls() && DC->NeedToReconcileExternalVisibleStorage;
3535}
3536
3537bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
3538 DeclContext *DC) {
3539 for (auto *D : Result.getLookupResult())
3540 if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
3541 return false;
3542
3543 return true;
3544}
3545
Richard Smithd88a7f12015-09-01 20:35:42 +00003546void
Chandler Carruthe972c362015-03-26 03:11:40 +00003547ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
Richard Smithcd45dbc2014-04-19 03:48:30 +00003548 llvm::SmallVectorImpl<char> &LookupTable) {
Chandler Carruthe972c362015-03-26 03:11:40 +00003549 assert(!ConstDC->HasLazyLocalLexicalLookups &&
3550 !ConstDC->HasLazyExternalLexicalLookups &&
Richard Smith9e2341d2015-03-23 03:25:59 +00003551 "must call buildLookups first");
Richard Smithcd45dbc2014-04-19 03:48:30 +00003552
Chandler Carruthe972c362015-03-26 03:11:40 +00003553 // FIXME: We need to build the lookups table, which is logically const.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003554 auto *DC = const_cast<DeclContext*>(ConstDC);
Chandler Carruthe972c362015-03-26 03:11:40 +00003555 assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
3556
3557 // Create the on-disk hash table representation.
Richard Smithd88a7f12015-09-01 20:35:42 +00003558 MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait,
3559 ASTDeclContextNameLookupTrait> Generator;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003560 ASTDeclContextNameLookupTrait Trait(*this);
3561
Chandler Carruthe972c362015-03-26 03:11:40 +00003562 // The first step is to collect the declaration names which we need to
3563 // serialize into the name lookup table, and to collect them in a stable
3564 // order.
3565 SmallVector<DeclarationName, 16> Names;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003566
Chandler Carruthe972c362015-03-26 03:11:40 +00003567 // We also build up small sets of the constructor and conversion function
3568 // names which are visible.
3569 llvm::SmallSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003570
Chandler Carruthe972c362015-03-26 03:11:40 +00003571 for (auto &Lookup : *DC->buildLookup()) {
3572 auto &Name = Lookup.first;
3573 auto &Result = Lookup.second;
3574
Douglas Gregor7dd37e52015-11-03 01:20:54 +00003575 // If there are no local declarations in our lookup result, we
3576 // don't need to write an entry for the name at all. If we can't
3577 // write out a lookup set without performing more deserialization,
3578 // just skip this entry.
3579 if (isLookupResultExternal(Result, DC) &&
Chandler Carruthe972c362015-03-26 03:11:40 +00003580 isLookupResultEntirelyExternal(Result, DC))
3581 continue;
3582
3583 // We also skip empty results. If any of the results could be external and
3584 // the currently available results are empty, then all of the results are
3585 // external and we skip it above. So the only way we get here with an empty
3586 // results is when no results could have been external *and* we have
3587 // external results.
3588 //
3589 // FIXME: While we might want to start emitting on-disk entries for negative
3590 // lookups into a decl context as an optimization, today we *have* to skip
3591 // them because there are names with empty lookup results in decl contexts
3592 // which we can't emit in any stable ordering: we lookup constructors and
3593 // conversion functions in the enclosing namespace scope creating empty
3594 // results for them. This in almost certainly a bug in Clang's name lookup,
3595 // but that is likely to be hard or impossible to fix and so we tolerate it
3596 // here by omitting lookups with empty results.
3597 if (Lookup.second.getLookupResult().empty())
3598 continue;
3599
3600 switch (Lookup.first.getNameKind()) {
3601 default:
3602 Names.push_back(Lookup.first);
3603 break;
3604
Richard Smithcd45dbc2014-04-19 03:48:30 +00003605 case DeclarationName::CXXConstructorName:
Chandler Carruthe972c362015-03-26 03:11:40 +00003606 assert(isa<CXXRecordDecl>(DC) &&
3607 "Cannot have a constructor name outside of a class!");
3608 ConstructorNameSet.insert(Name);
3609 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003610
3611 case DeclarationName::CXXConversionFunctionName:
Chandler Carruthe972c362015-03-26 03:11:40 +00003612 assert(isa<CXXRecordDecl>(DC) &&
3613 "Cannot have a conversion function name outside of a class!");
3614 ConversionNameSet.insert(Name);
Rafael Espindolac606b3e2015-03-25 04:43:15 +00003615 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003616 }
Chandler Carruth75c9f132015-03-25 00:34:51 +00003617 }
Chandler Carruth75c9f132015-03-25 00:34:51 +00003618
Chandler Carruthe972c362015-03-26 03:11:40 +00003619 // Sort the names into a stable order.
3620 std::sort(Names.begin(), Names.end());
3621
Chandler Carruthffbf7052015-03-26 22:27:09 +00003622 if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
Chandler Carruthe972c362015-03-26 03:11:40 +00003623 // We need to establish an ordering of constructor and conversion function
Chandler Carruthffbf7052015-03-26 22:27:09 +00003624 // names, and they don't have an intrinsic ordering.
Chandler Carruthe972c362015-03-26 03:11:40 +00003625
Chandler Carruthffbf7052015-03-26 22:27:09 +00003626 // First we try the easy case by forming the current context's constructor
3627 // name and adding that name first. This is a very useful optimization to
3628 // avoid walking the lexical declarations in many cases, and it also
3629 // handles the only case where a constructor name can come from some other
3630 // lexical context -- when that name is an implicit constructor merged from
3631 // another declaration in the redecl chain. Any non-implicit constructor or
3632 // conversion function which doesn't occur in all the lexical contexts
3633 // would be an ODR violation.
3634 auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
3635 Context->getCanonicalType(Context->getRecordType(D)));
3636 if (ConstructorNameSet.erase(ImplicitCtorName))
3637 Names.push_back(ImplicitCtorName);
Chandler Carruthe972c362015-03-26 03:11:40 +00003638
Chandler Carruthffbf7052015-03-26 22:27:09 +00003639 // If we still have constructors or conversion functions, we walk all the
3640 // names in the decl and add the constructors and conversion functions
3641 // which are visible in the order they lexically occur within the context.
3642 if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
3643 for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
3644 if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
3645 auto Name = ChildND->getDeclName();
3646 switch (Name.getNameKind()) {
3647 default:
3648 continue;
3649
3650 case DeclarationName::CXXConstructorName:
3651 if (ConstructorNameSet.erase(Name))
3652 Names.push_back(Name);
3653 break;
3654
3655 case DeclarationName::CXXConversionFunctionName:
3656 if (ConversionNameSet.erase(Name))
3657 Names.push_back(Name);
3658 break;
3659 }
3660
3661 if (ConstructorNameSet.empty() && ConversionNameSet.empty())
3662 break;
Chandler Carruthe972c362015-03-26 03:11:40 +00003663 }
3664
Chandler Carruthe972c362015-03-26 03:11:40 +00003665 assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
3666 "constructors by walking all the "
3667 "lexical members of the context.");
3668 assert(ConversionNameSet.empty() && "Failed to find all of the visible "
3669 "conversion functions by walking all "
3670 "the lexical members of the context.");
Richard Smith961eae52014-03-25 01:14:22 +00003671 }
3672
Chandler Carruthe972c362015-03-26 03:11:40 +00003673 // Next we need to do a lookup with each name into this decl context to fully
3674 // populate any results from external sources. We don't actually use the
3675 // results of these lookups because we only want to use the results after all
3676 // results have been loaded and the pointers into them will be stable.
3677 for (auto &Name : Names)
3678 DC->lookup(Name);
3679
3680 // Now we need to insert the results for each name into the hash table. For
3681 // constructor names and conversion function names, we actually need to merge
3682 // all of the results for them into one list of results each and insert
3683 // those.
3684 SmallVector<NamedDecl *, 8> ConstructorDecls;
3685 SmallVector<NamedDecl *, 8> ConversionDecls;
3686
3687 // Now loop over the names, either inserting them or appending for the two
3688 // special cases.
3689 for (auto &Name : Names) {
3690 DeclContext::lookup_result Result = DC->noload_lookup(Name);
3691
3692 switch (Name.getNameKind()) {
3693 default:
Richard Smithd88a7f12015-09-01 20:35:42 +00003694 Generator.insert(Name, Trait.getData(Result), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00003695 break;
3696
3697 case DeclarationName::CXXConstructorName:
3698 ConstructorDecls.append(Result.begin(), Result.end());
3699 break;
3700
3701 case DeclarationName::CXXConversionFunctionName:
3702 ConversionDecls.append(Result.begin(), Result.end());
3703 break;
3704 }
3705 }
3706
3707 // Handle our two special cases if we ended up having any. We arbitrarily use
3708 // the first declaration's name here because the name itself isn't part of
3709 // the key, only the kind of name is used.
3710 if (!ConstructorDecls.empty())
3711 Generator.insert(ConstructorDecls.front()->getDeclName(),
Richard Smithd88a7f12015-09-01 20:35:42 +00003712 Trait.getData(ConstructorDecls), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00003713 if (!ConversionDecls.empty())
3714 Generator.insert(ConversionDecls.front()->getDeclName(),
Richard Smithd88a7f12015-09-01 20:35:42 +00003715 Trait.getData(ConversionDecls), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00003716
Richard Smithd88a7f12015-09-01 20:35:42 +00003717 // Create the on-disk hash table. Also emit the existing imported and
3718 // merged table if there is one.
3719 auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr;
3720 Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr);
Richard Smith961eae52014-03-25 01:14:22 +00003721}
3722
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003723/// \brief Write the block containing all of the declaration IDs
3724/// visible from the given DeclContext.
3725///
3726/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
Sebastian Redla4071b42010-08-24 00:50:09 +00003727/// bitstream, or 0 if no block was written.
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003728uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
3729 DeclContext *DC) {
Richard Smith5fc18a92015-07-12 23:43:21 +00003730 // If we imported a key declaration of this namespace, write the visible
3731 // lookup results as an update record for it rather than including them
3732 // on this declaration. We will only look at key declarations on reload.
3733 if (isa<NamespaceDecl>(DC) && Chain &&
3734 Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) {
3735 // Only do this once, for the first local declaration of the namespace.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003736 for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
Richard Smith5fc18a92015-07-12 23:43:21 +00003737 Prev = Prev->getPreviousDecl())
3738 if (!Prev->isFromASTFile())
3739 return 0;
3740
3741 // Note that we need to emit an update record for the primary context.
3742 UpdatedDeclContexts.insert(DC->getPrimaryContext());
3743
3744 // Make sure all visible decls are written. They will be recorded later. We
3745 // do this using a side data structure so we can sort the names into
3746 // a deterministic order.
3747 StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup();
3748 SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16>
3749 LookupResults;
3750 if (Map) {
3751 LookupResults.reserve(Map->size());
3752 for (auto &Entry : *Map)
3753 LookupResults.push_back(
3754 std::make_pair(Entry.first, Entry.second.getLookupResult()));
3755 }
3756
3757 std::sort(LookupResults.begin(), LookupResults.end(), llvm::less_first());
3758 for (auto &NameAndResult : LookupResults) {
3759 DeclarationName Name = NameAndResult.first;
3760 DeclContext::lookup_result Result = NameAndResult.second;
3761 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
3762 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
3763 // We have to work around a name lookup bug here where negative lookup
3764 // results for these names get cached in namespace lookup tables (these
3765 // names should never be looked up in a namespace).
3766 assert(Result.empty() && "Cannot have a constructor or conversion "
3767 "function name in a namespace!");
3768 continue;
3769 }
3770
3771 for (NamedDecl *ND : Result)
3772 if (!ND->isFromASTFile())
3773 GetDeclRef(ND);
3774 }
3775
3776 return 0;
3777 }
3778
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003779 if (DC->getPrimaryContext() != DC)
3780 return 0;
3781
Chandler Carruthe972c362015-03-26 03:11:40 +00003782 // Skip contexts which don't support name lookup.
3783 if (!DC->isLookupContext())
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003784 return 0;
3785
3786 // If not in C++, we perform name lookup for the translation unit via the
3787 // IdentifierInfo chains, don't bother to build a visible-declarations table.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003788 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003789 return 0;
3790
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003791 // Serialize the contents of the mapping used for lookup. Note that,
3792 // although we have two very different code paths, the serialized
3793 // representation is the same for both cases: a declaration name,
3794 // followed by a size, followed by references to the visible
3795 // declarations that have that name.
3796 uint64_t Offset = Stream.GetCurrentBitNo();
Richard Smithf634c902012-03-16 06:12:59 +00003797 StoredDeclsMap *Map = DC->buildLookup();
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003798 if (!Map || Map->empty())
3799 return 0;
3800
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003801 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003802 SmallString<4096> LookupTable;
Richard Smithd88a7f12015-09-01 20:35:42 +00003803 GenerateNameLookupTable(DC, LookupTable);
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003804
3805 // Write the lookup table
Mehdi Amini57a41912015-09-10 01:46:39 +00003806 RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003807 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
Yaron Keren92e1b622015-03-18 10:17:07 +00003808 LookupTable);
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003809 ++NumVisibleDeclContexts;
3810 return Offset;
3811}
3812
Sebastian Redla4071b42010-08-24 00:50:09 +00003813/// \brief Write an UPDATE_VISIBLE block for the given context.
3814///
3815/// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
3816/// DeclContext in a dependent AST file. As such, they only exist for the TU
Richard Smithf634c902012-03-16 06:12:59 +00003817/// (in C++), for namespaces, and for classes with forward-declared unscoped
3818/// enumeration members (in C++11).
Sebastian Redla4071b42010-08-24 00:50:09 +00003819void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
Richard Smith961eae52014-03-25 01:14:22 +00003820 StoredDeclsMap *Map = DC->getLookupPtr();
Sebastian Redla4071b42010-08-24 00:50:09 +00003821 if (!Map || Map->empty())
3822 return;
3823
Sebastian Redla4071b42010-08-24 00:50:09 +00003824 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003825 SmallString<4096> LookupTable;
Richard Smithd88a7f12015-09-01 20:35:42 +00003826 GenerateNameLookupTable(DC, LookupTable);
Sebastian Redla4071b42010-08-24 00:50:09 +00003827
Richard Smith5fc18a92015-07-12 23:43:21 +00003828 // If we're updating a namespace, select a key declaration as the key for the
3829 // update record; those are the only ones that will be checked on reload.
3830 if (isa<NamespaceDecl>(DC))
3831 DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
3832
Sebastian Redla4071b42010-08-24 00:50:09 +00003833 // Write the lookup table
Mehdi Amini57a41912015-09-10 01:46:39 +00003834 RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))};
Yaron Keren92e1b622015-03-18 10:17:07 +00003835 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
Sebastian Redla4071b42010-08-24 00:50:09 +00003836}
3837
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003838/// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
3839void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
Mehdi Amini57a41912015-09-10 01:46:39 +00003840 RecordData::value_type Record[] = {Opts.fp_contract};
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003841 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
3842}
3843
3844/// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
3845void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003846 if (!SemaRef.Context.getLangOpts().OpenCL)
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003847 return;
3848
3849 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
3850 RecordData Record;
3851#define OPENCLEXT(nm) Record.push_back(Opts.nm);
3852#include "clang/Basic/OpenCLExtensions.def"
3853 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
3854}
3855
Douglas Gregor404cdde2012-01-27 01:47:08 +00003856void ASTWriter::WriteObjCCategories() {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003857 SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
Douglas Gregor404cdde2012-01-27 01:47:08 +00003858 RecordData Categories;
3859
3860 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
3861 unsigned Size = 0;
3862 unsigned StartIndex = Categories.size();
3863
3864 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
3865
3866 // Allocate space for the size.
3867 Categories.push_back(0);
3868
3869 // Add the categories.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003870 for (ObjCInterfaceDecl::known_categories_iterator
3871 Cat = Class->known_categories_begin(),
3872 CatEnd = Class->known_categories_end();
3873 Cat != CatEnd; ++Cat, ++Size) {
3874 assert(getDeclID(*Cat) != 0 && "Bogus category");
3875 AddDeclRef(*Cat, Categories);
Douglas Gregor404cdde2012-01-27 01:47:08 +00003876 }
3877
3878 // Update the size.
3879 Categories[StartIndex] = Size;
3880
3881 // Record this interface -> category map.
3882 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
3883 CategoriesMap.push_back(CatInfo);
3884 }
3885
3886 // Sort the categories map by the definition ID, since the reader will be
3887 // performing binary searches on this information.
3888 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
3889
3890 // Emit the categories map.
3891 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003892
3893 auto *Abbrev = new BitCodeAbbrev();
Douglas Gregor404cdde2012-01-27 01:47:08 +00003894 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
3895 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
3896 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3897 unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00003898
3899 RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
3900 Stream.EmitRecordWithBlob(AbbrevID, Record,
3901 reinterpret_cast<char *>(CategoriesMap.data()),
Douglas Gregor404cdde2012-01-27 01:47:08 +00003902 CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
Mehdi Amini57a41912015-09-10 01:46:39 +00003903
Douglas Gregor404cdde2012-01-27 01:47:08 +00003904 // Emit the category lists.
3905 Stream.EmitRecord(OBJC_CATEGORIES, Categories);
3906}
3907
Richard Smithe40f2ba2013-08-07 21:41:30 +00003908void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
3909 Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
3910
3911 if (LPTMap.empty())
3912 return;
3913
3914 RecordData Record;
Chandler Carruth52cee4d2015-03-26 09:08:15 +00003915 for (auto LPTMapEntry : LPTMap) {
3916 const FunctionDecl *FD = LPTMapEntry.first;
3917 LateParsedTemplate *LPT = LPTMapEntry.second;
3918 AddDeclRef(FD, Record);
Richard Smithe40f2ba2013-08-07 21:41:30 +00003919 AddDeclRef(LPT->D, Record);
3920 Record.push_back(LPT->Toks.size());
3921
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003922 for (const auto &Tok : LPT->Toks) {
3923 AddToken(Tok, Record);
Richard Smithe40f2ba2013-08-07 21:41:30 +00003924 }
3925 }
3926 Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
3927}
3928
Dario Domizioli13a0a382014-05-23 12:13:25 +00003929/// \brief Write the state of 'pragma clang optimize' at the end of the module.
3930void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
3931 RecordData Record;
3932 SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
3933 AddSourceLocation(PragmaLoc, Record);
3934 Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
3935}
3936
Nico Weber779355f2016-03-02 23:22:00 +00003937/// \brief Write the state of 'pragma ms_struct' at the end of the module.
3938void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
3939 RecordData Record;
3940 Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF);
3941 Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
3942}
3943
Nico Weber42932312016-03-03 00:17:35 +00003944/// \brief Write the state of 'pragma pointers_to_members' at the end of the
3945//module.
3946void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
3947 RecordData Record;
3948 Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod);
3949 AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record);
3950 Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
3951}
3952
Douglas Gregor8f64ca12015-12-08 22:43:32 +00003953void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
3954 ModuleFileExtensionWriter &Writer) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003955 // Enter the extension block.
3956 Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
3957
3958 // Emit the metadata record abbreviation.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003959 auto *Abv = new llvm::BitCodeAbbrev();
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003960 Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
3961 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3962 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3963 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3964 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3965 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
3966 unsigned Abbrev = Stream.EmitAbbrev(Abv);
3967
3968 // Emit the metadata record.
3969 RecordData Record;
3970 auto Metadata = Writer.getExtension()->getExtensionMetadata();
3971 Record.push_back(EXTENSION_METADATA);
3972 Record.push_back(Metadata.MajorVersion);
3973 Record.push_back(Metadata.MinorVersion);
3974 Record.push_back(Metadata.BlockName.size());
3975 Record.push_back(Metadata.UserInfo.size());
3976 SmallString<64> Buffer;
3977 Buffer += Metadata.BlockName;
3978 Buffer += Metadata.UserInfo;
3979 Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
3980
3981 // Emit the contents of the extension block.
Douglas Gregor8f64ca12015-12-08 22:43:32 +00003982 Writer.writeExtensionContents(SemaRef, Stream);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003983
3984 // Exit the extension block.
3985 Stream.ExitBlock();
3986}
3987
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003988//===----------------------------------------------------------------------===//
Douglas Gregorc5046832009-04-27 18:38:38 +00003989// General Serialization Routines
3990//===----------------------------------------------------------------------===//
3991
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00003992/// \brief Write a record containing the given attributes.
Alexander Kornienko20f6fc62012-07-09 10:04:07 +00003993void ASTWriter::WriteAttributes(ArrayRef<const Attr*> Attrs,
3994 RecordDataImpl &Record) {
Argyrios Kyrtzidis9beef8e2010-10-18 19:20:11 +00003995 Record.push_back(Attrs.size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003996 for (const auto *A : Attrs) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003997 Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
Argyrios Kyrtzidis309b4c42011-09-13 16:05:58 +00003998 AddSourceRange(A->getRange(), Record);
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00003999
Alexis Huntdcfba7b2010-08-18 23:23:40 +00004000#include "clang/Serialization/AttrPCHWrite.inc"
Daniel Dunbarfc6507e2010-05-27 02:25:39 +00004001
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00004002 }
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00004003}
4004
John McCallf413f5e2013-05-03 00:10:13 +00004005void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
4006 AddSourceLocation(Tok.getLocation(), Record);
4007 Record.push_back(Tok.getLength());
4008
4009 // FIXME: When reading literal tokens, reconstruct the literal pointer
4010 // if it is needed.
4011 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
4012 // FIXME: Should translate token kind to a stable encoding.
4013 Record.push_back(Tok.getKind());
4014 // FIXME: Should translate token flags to a stable encoding.
4015 Record.push_back(Tok.getFlags());
4016}
4017
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004018void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00004019 Record.push_back(Str.size());
4020 Record.insert(Record.end(), Str.begin(), Str.end());
4021}
4022
Richard Smith7ed1bc92014-12-05 22:42:13 +00004023bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
Richard Smith54cc3c22014-12-11 20:50:24 +00004024 assert(Context && "should have context when outputting path");
Richard Smith7ed1bc92014-12-05 22:42:13 +00004025
Richard Smith54cc3c22014-12-11 20:50:24 +00004026 bool Changed =
4027 cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004028
4029 // Remove a prefix to make the path relative, if relevant.
4030 const char *PathBegin = Path.data();
4031 const char *PathPtr =
4032 adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
4033 if (PathPtr != PathBegin) {
4034 Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
4035 Changed = true;
4036 }
4037
4038 return Changed;
4039}
4040
4041void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
4042 SmallString<128> FilePath(Path);
4043 PreparePathForOutput(FilePath);
4044 AddString(FilePath, Record);
4045}
4046
Mehdi Amini57a41912015-09-10 01:46:39 +00004047void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
Richard Smith7ed1bc92014-12-05 22:42:13 +00004048 StringRef Path) {
4049 SmallString<128> FilePath(Path);
4050 PreparePathForOutput(FilePath);
4051 Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
4052}
4053
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004054void ASTWriter::AddVersionTuple(const VersionTuple &Version,
4055 RecordDataImpl &Record) {
4056 Record.push_back(Version.getMajor());
David Blaikie05785d12013-02-20 22:23:23 +00004057 if (Optional<unsigned> Minor = Version.getMinor())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004058 Record.push_back(*Minor + 1);
4059 else
4060 Record.push_back(0);
David Blaikie05785d12013-02-20 22:23:23 +00004061 if (Optional<unsigned> Subminor = Version.getSubminor())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004062 Record.push_back(*Subminor + 1);
4063 else
4064 Record.push_back(0);
4065}
4066
Douglas Gregore84a9da2009-04-20 20:36:09 +00004067/// \brief Note that the identifier II occurs at the given offset
4068/// within the identifier table.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004069void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Sebastian Redl539c5062010-08-18 23:57:32 +00004070 IdentID ID = IdentifierIDs[II];
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00004071 // Only store offsets new to this AST file. Other identifier names are looked
Sebastian Redlff4a2952010-07-23 23:49:55 +00004072 // up earlier in the chain and thus don't need an offset.
4073 if (ID >= FirstIdentID)
4074 IdentifierOffsets[ID - FirstIdentID] = Offset;
Douglas Gregore84a9da2009-04-20 20:36:09 +00004075}
4076
Douglas Gregor95c13f52009-04-25 17:48:32 +00004077/// \brief Note that the selector Sel occurs at the given offset
4078/// within the method pool/selector table.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004079void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
Douglas Gregor95c13f52009-04-25 17:48:32 +00004080 unsigned ID = SelectorIDs[Sel];
4081 assert(ID && "Unknown selector");
Sebastian Redld95a56e2010-08-04 18:21:41 +00004082 // Don't record offsets for selectors that are also available in a different
4083 // file.
4084 if (ID < FirstSelectorID)
4085 return;
4086 SelectorOffsets[ID - FirstSelectorID] = Offset;
Douglas Gregor95c13f52009-04-25 17:48:32 +00004087}
4088
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004089ASTWriter::ASTWriter(
4090 llvm::BitstreamWriter &Stream,
4091 ArrayRef<llvm::IntrusiveRefCntPtr<ModuleFileExtension>> Extensions,
4092 bool IncludeTimestamps)
Richard Smith01b2cb42014-07-26 06:37:51 +00004093 : Stream(Stream), Context(nullptr), PP(nullptr), Chain(nullptr),
Richard Smithe75ee0f2015-08-17 07:13:32 +00004094 WritingModule(nullptr), IncludeTimestamps(IncludeTimestamps),
4095 WritingAST(false), DoneWritingDeclsAndTypes(false),
4096 ASTHasCompilerErrors(false), FirstDeclID(NUM_PREDEF_DECL_IDS),
4097 NextDeclID(FirstDeclID), FirstTypeID(NUM_PREDEF_TYPE_IDS),
4098 NextTypeID(FirstTypeID), FirstIdentID(NUM_PREDEF_IDENT_IDS),
4099 NextIdentID(FirstIdentID), FirstMacroID(NUM_PREDEF_MACRO_IDS),
4100 NextMacroID(FirstMacroID), FirstSubmoduleID(NUM_PREDEF_SUBMODULE_IDS),
Richard Smith01b2cb42014-07-26 06:37:51 +00004101 NextSubmoduleID(FirstSubmoduleID),
4102 FirstSelectorID(NUM_PREDEF_SELECTOR_IDS), NextSelectorID(FirstSelectorID),
4103 CollectedStmts(&StmtsToEmit), NumStatements(0), NumMacros(0),
4104 NumLexicalDeclContexts(0), NumVisibleDeclContexts(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00004105 NextCXXBaseSpecifiersID(1), NextCXXCtorInitializersID(1),
Richard Smithe75ee0f2015-08-17 07:13:32 +00004106 TypeExtQualAbbrev(0), TypeFunctionProtoAbbrev(0), DeclParmVarAbbrev(0),
Richard Smith01b2cb42014-07-26 06:37:51 +00004107 DeclContextLexicalAbbrev(0), DeclContextVisibleLookupAbbrev(0),
Richard Smitha27c26e2014-07-27 04:19:32 +00004108 UpdateVisibleAbbrev(0), DeclRecordAbbrev(0), DeclTypedefAbbrev(0),
Richard Smith01b2cb42014-07-26 06:37:51 +00004109 DeclVarAbbrev(0), DeclFieldAbbrev(0), DeclEnumAbbrev(0),
Richard Smitha27c26e2014-07-27 04:19:32 +00004110 DeclObjCIvarAbbrev(0), DeclCXXMethodAbbrev(0), DeclRefExprAbbrev(0),
4111 CharacterLiteralAbbrev(0), IntegerLiteralAbbrev(0),
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004112 ExprImplicitCastAbbrev(0) {
4113 for (const auto &Ext : Extensions) {
4114 if (auto Writer = Ext->createExtensionWriter(*this))
4115 ModuleFileExtensionWriters.push_back(std::move(Writer));
4116 }
4117}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004118
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004119ASTWriter::~ASTWriter() {
Reid Kleckner588c9372014-02-19 23:44:52 +00004120 llvm::DeleteContainerSeconds(FileDeclIDs);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004121}
4122
Richard Smithb3761912015-02-05 23:08:52 +00004123const LangOptions &ASTWriter::getLangOpts() const {
4124 assert(WritingAST && "can't determine lang opts when not writing AST");
4125 return Context->getLangOpts();
4126}
4127
Richard Smithe75ee0f2015-08-17 07:13:32 +00004128time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const {
4129 return IncludeTimestamps ? E->getModificationTime() : 0;
4130}
4131
Adrian Prantladbd2b12015-09-22 23:26:31 +00004132uint64_t ASTWriter::WriteAST(Sema &SemaRef, const std::string &OutputFile,
4133 Module *WritingModule, StringRef isysroot,
4134 bool hasErrors) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00004135 WritingAST = true;
Adrian Prantladbd2b12015-09-22 23:26:31 +00004136
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00004137 ASTHasCompilerErrors = hasErrors;
4138
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004139 // Emit the file header.
Douglas Gregor8f45df52009-04-16 22:23:12 +00004140 Stream.Emit((unsigned)'C', 8);
4141 Stream.Emit((unsigned)'P', 8);
4142 Stream.Emit((unsigned)'C', 8);
4143 Stream.Emit((unsigned)'H', 8);
Mike Stump11289f42009-09-09 15:08:12 +00004144
Chris Lattner28fa4e62009-04-26 22:26:21 +00004145 WriteBlockInfoBlock();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004146
Douglas Gregoreda8e122011-08-09 15:13:55 +00004147 Context = &SemaRef.Context;
Douglas Gregora28bcdd2011-12-01 02:07:58 +00004148 PP = &SemaRef.PP;
Douglas Gregora89c5ac2011-12-06 01:10:29 +00004149 this->WritingModule = WritingModule;
Adrian Prantladbd2b12015-09-22 23:26:31 +00004150 ASTFileSignature Signature =
4151 WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
Craig Toppera13603a2014-05-22 05:54:18 +00004152 Context = nullptr;
4153 PP = nullptr;
4154 this->WritingModule = nullptr;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004155 this->BaseDirectory.clear();
Craig Toppera13603a2014-05-22 05:54:18 +00004156
Douglas Gregor2fd3d402011-09-17 00:05:03 +00004157 WritingAST = false;
Adrian Prantladbd2b12015-09-22 23:26:31 +00004158 return Signature;
Sebastian Redl143413f2010-07-12 22:02:52 +00004159}
4160
Douglas Gregora94a1542011-07-27 21:45:57 +00004161template<typename Vector>
4162static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4163 ASTWriter::RecordData &Record) {
Craig Toppera13603a2014-05-22 05:54:18 +00004164 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4165 I != E; ++I) {
Douglas Gregora94a1542011-07-27 21:45:57 +00004166 Writer.AddDeclRef(*I, Record);
4167 }
4168}
4169
Adrian Prantladbd2b12015-09-22 23:26:31 +00004170uint64_t ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
4171 const std::string &OutputFile,
4172 Module *WritingModule) {
Sebastian Redl143413f2010-07-12 22:02:52 +00004173 using namespace llvm;
4174
Craig Toppera13603a2014-05-22 05:54:18 +00004175 bool isModule = WritingModule != nullptr;
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004176
Douglas Gregorcf68c582011-12-01 22:20:10 +00004177 // Make sure that the AST reader knows to finalize itself.
4178 if (Chain)
4179 Chain->finalizeForWriting();
4180
Sebastian Redl143413f2010-07-12 22:02:52 +00004181 ASTContext &Context = SemaRef.Context;
4182 Preprocessor &PP = SemaRef.PP;
4183
Douglas Gregordab42432011-08-12 00:15:20 +00004184 // Set up predefined declaration IDs.
Richard Smith5fc18a92015-07-12 23:43:21 +00004185 auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
4186 if (D) {
4187 assert(D->isCanonicalDecl() && "predefined decl is not canonical");
4188 DeclIDs[D] = ID;
Richard Smith5fc18a92015-07-12 23:43:21 +00004189 }
4190 };
4191 RegisterPredefDecl(Context.getTranslationUnitDecl(),
4192 PREDEF_DECL_TRANSLATION_UNIT_ID);
4193 RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
4194 RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
4195 RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
4196 RegisterPredefDecl(Context.ObjCProtocolClassDecl,
4197 PREDEF_DECL_OBJC_PROTOCOL_ID);
4198 RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
4199 RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
4200 RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
4201 PREDEF_DECL_OBJC_INSTANCETYPE_ID);
4202 RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
Richard Smith9b88a4c2015-07-27 05:40:23 +00004203 RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
Charles Davisc7d5c942015-09-17 20:55:33 +00004204 RegisterPredefDecl(Context.BuiltinMSVaListDecl,
4205 PREDEF_DECL_BUILTIN_MS_VA_LIST_ID);
Richard Smith5fc18a92015-07-12 23:43:21 +00004206 RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
David Majnemerd9b1a4f2015-11-04 03:40:30 +00004207 RegisterPredefDecl(Context.MakeIntegerSeqDecl,
4208 PREDEF_DECL_MAKE_INTEGER_SEQ_ID);
Quentin Colombet043406b2016-02-03 22:41:00 +00004209 RegisterPredefDecl(Context.CFConstantStringTypeDecl,
4210 PREDEF_DECL_CF_CONSTANT_STRING_ID);
Ben Langmuirf5416742016-02-04 00:55:24 +00004211 RegisterPredefDecl(Context.CFConstantStringTagDecl,
4212 PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID);
Meador Inge5d3fb222012-06-16 03:34:49 +00004213
Chris Lattner0c797362009-09-08 18:19:27 +00004214 // Build a record containing all of the tentative definitions in this file, in
Sebastian Redl35351a92010-01-31 22:27:38 +00004215 // TentativeDefinitions order. Generally, this record will be empty for
Chris Lattner0c797362009-09-08 18:19:27 +00004216 // headers.
Douglas Gregord4df8652009-04-22 22:02:47 +00004217 RecordData TentativeDefinitions;
Douglas Gregora94a1542011-07-27 21:45:57 +00004218 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
Douglas Gregoreb08bd42011-07-27 20:58:46 +00004219
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00004220 // Build a record containing all of the file scoped decls in this file.
4221 RecordData UnusedFileScopedDecls;
Argyrios Kyrtzidis59852362013-03-14 04:45:00 +00004222 if (!isModule)
4223 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
4224 UnusedFileScopedDecls);
Sebastian Redl08aca90252010-08-05 18:21:25 +00004225
Douglas Gregor851443c2011-08-12 01:39:19 +00004226 // Build a record containing all of the delegating constructors we still need
4227 // to resolve.
Alexis Hunt27a761d2011-05-04 23:29:54 +00004228 RecordData DelegatingCtorDecls;
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004229 if (!isModule)
4230 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
Alexis Hunt27a761d2011-05-04 23:29:54 +00004231
Douglas Gregor851443c2011-08-12 01:39:19 +00004232 // Write the set of weak, undeclared identifiers. We always write the
4233 // entire table, since later PCH files in a PCH chain are only interested in
4234 // the results at the end of the chain.
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004235 RecordData WeakUndeclaredIdentifiers;
Chandler Carruthf85d9822015-03-26 08:32:49 +00004236 for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) {
4237 IdentifierInfo *II = WeakUndeclaredIdentifier.first;
4238 WeakInfo &WI = WeakUndeclaredIdentifier.second;
4239 AddIdentifierRef(II, WeakUndeclaredIdentifiers);
4240 AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
4241 AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
4242 WeakUndeclaredIdentifiers.push_back(WI.getUsed());
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004243 }
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00004244
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004245 // Build a record containing all of the ext_vector declarations.
4246 RecordData ExtVectorDecls;
Douglas Gregorb7098a32011-07-28 00:39:29 +00004247 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004248
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004249 // Build a record containing all of the VTable uses information.
4250 RecordData VTableUses;
Argyrios Kyrtzidisedee67f2010-08-03 17:29:52 +00004251 if (!SemaRef.VTableUses.empty()) {
Argyrios Kyrtzidisedee67f2010-08-03 17:29:52 +00004252 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4253 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4254 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4255 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4256 }
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004257 }
4258
Nico Weber72889432014-09-06 01:25:55 +00004259 // Build a record containing all of the UnusedLocalTypedefNameCandidates.
4260 RecordData UnusedLocalTypedefNameCandidates;
4261 for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4262 AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
4263
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004264 // Build a record containing all of pending implicit instantiations.
Chandler Carruth54080172010-08-25 08:44:16 +00004265 RecordData PendingInstantiations;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004266 for (const auto &I : SemaRef.PendingInstantiations) {
4267 AddDeclRef(I.first, PendingInstantiations);
4268 AddSourceLocation(I.second, PendingInstantiations);
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004269 }
4270 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4271 "There are local ones at end of translation unit!");
4272
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004273 // Build a record containing some declaration references.
4274 RecordData SemaDeclRefs;
4275 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
4276 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4277 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
4278 }
4279
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004280 RecordData CUDASpecialDeclRefs;
4281 if (Context.getcudaConfigureCallDecl()) {
4282 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4283 }
4284
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004285 // Build a record containing all of the known namespaces.
4286 RecordData KnownNamespaces;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004287 for (const auto &I : SemaRef.KnownNamespaces) {
4288 if (!I.second)
4289 AddDeclRef(I.first, KnownNamespaces);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004290 }
Douglas Gregor112b9072012-10-18 05:31:06 +00004291
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004292 // Build a record of all used, undefined objects that require definitions.
4293 RecordData UndefinedButUsed;
Nick Lewyckyf0f56162013-01-31 03:23:57 +00004294
4295 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004296 SemaRef.getUndefinedButUsed(Undefined);
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004297 for (const auto &I : Undefined) {
4298 AddDeclRef(I.first, UndefinedButUsed);
4299 AddSourceLocation(I.second, UndefinedButUsed);
Nick Lewycky8334af82013-01-26 00:35:08 +00004300 }
4301
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00004302 // Build a record containing all delete-expressions that we would like to
4303 // analyze later in AST.
4304 RecordData DeleteExprsToAnalyze;
4305
4306 for (const auto &DeleteExprsInfo :
4307 SemaRef.getMismatchingDeleteExpressions()) {
4308 AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
4309 DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
4310 for (const auto &DeleteLoc : DeleteExprsInfo.second) {
4311 AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
4312 DeleteExprsToAnalyze.push_back(DeleteLoc.second);
4313 }
4314 }
4315
Douglas Gregor112b9072012-10-18 05:31:06 +00004316 // Write the control block
Adrian Prantladbd2b12015-09-22 23:26:31 +00004317 uint64_t Signature = WriteControlBlock(PP, Context, isysroot, OutputFile);
Douglas Gregor112b9072012-10-18 05:31:06 +00004318
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00004319 // Write the remaining AST contents.
Sebastian Redl539c5062010-08-18 23:57:32 +00004320 Stream.EnterSubblock(AST_BLOCK_ID, 5);
Douglas Gregor851443c2011-08-12 01:39:19 +00004321
Argyrios Kyrtzidis39605402012-12-13 21:38:23 +00004322 // This is so that older clang versions, before the introduction
4323 // of the control block, can read and reject the newer PCH format.
Mehdi Amini57a41912015-09-10 01:46:39 +00004324 {
4325 RecordData Record = {VERSION_MAJOR};
4326 Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4327 }
Argyrios Kyrtzidis39605402012-12-13 21:38:23 +00004328
Douglas Gregor851443c2011-08-12 01:39:19 +00004329 // Create a lexical update block containing all of the declarations in the
4330 // translation unit that do not come from other AST files.
4331 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00004332 SmallVector<uint32_t, 128> NewGlobalKindDeclPairs;
4333 for (const auto *D : TU->noload_decls()) {
4334 if (!D->isFromASTFile()) {
4335 NewGlobalKindDeclPairs.push_back(D->getKind());
4336 NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
4337 }
Douglas Gregor851443c2011-08-12 01:39:19 +00004338 }
4339
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004340 auto *Abv = new llvm::BitCodeAbbrev();
Douglas Gregor851443c2011-08-12 01:39:19 +00004341 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4342 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4343 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv);
Mehdi Amini57a41912015-09-10 01:46:39 +00004344 {
4345 RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
4346 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4347 bytes(NewGlobalKindDeclPairs));
4348 }
4349
Douglas Gregor851443c2011-08-12 01:39:19 +00004350 // And a visible updates block for the translation unit.
4351 Abv = new llvm::BitCodeAbbrev();
4352 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4353 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
Douglas Gregor851443c2011-08-12 01:39:19 +00004354 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4355 UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv);
4356 WriteDeclContextVisibleUpdate(TU);
Richard Smithf19e1272015-03-07 00:04:49 +00004357
4358 // If we have any extern "C" names, write out a visible update for them.
4359 if (Context.ExternCContext)
4360 WriteDeclContextVisibleUpdate(Context.ExternCContext);
Douglas Gregor851443c2011-08-12 01:39:19 +00004361
4362 // If the translation unit has an anonymous namespace, and we don't already
4363 // have an update block for it, write it as an update block.
Richard Smith6ef42932014-03-20 21:02:00 +00004364 // FIXME: Why do we not do this if there's already an update block?
Douglas Gregor851443c2011-08-12 01:39:19 +00004365 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4366 ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
Richard Smith6ef42932014-03-20 21:02:00 +00004367 if (Record.empty())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004368 Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
Douglas Gregor851443c2011-08-12 01:39:19 +00004369 }
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004370
Richard Smith5652c0f2014-03-21 01:48:23 +00004371 // Add update records for all mangling numbers and static local numbers.
4372 // These aren't really update records, but this is a convenient way of
4373 // tagging this rare extra data onto the declarations.
4374 for (const auto &Number : Context.MangleNumbers)
4375 if (!Number.first->isFromASTFile())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004376 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4377 Number.second));
Richard Smith5652c0f2014-03-21 01:48:23 +00004378 for (const auto &Number : Context.StaticLocalNumbers)
4379 if (!Number.first->isFromASTFile())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004380 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4381 Number.second));
Richard Smith5652c0f2014-03-21 01:48:23 +00004382
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004383 // Make sure visible decls, added to DeclContexts previously loaded from
4384 // an AST file, are registered for serialization.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004385 for (const auto *I : UpdatingVisibleDecls) {
4386 GetDeclRef(I);
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004387 }
4388
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +00004389 // Make sure all decls associated with an identifier are registered for
Richard Smith79bf9202015-08-24 03:33:22 +00004390 // serialization, if we're storing decls with identifiers.
4391 if (!WritingModule || !getLangOpts().CPlusPlus) {
4392 llvm::SmallVector<const IdentifierInfo*, 256> IIs;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004393 for (const auto &ID : PP.getIdentifierTable()) {
4394 const IdentifierInfo *II = ID.second;
Richard Smith79bf9202015-08-24 03:33:22 +00004395 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
4396 IIs.push_back(II);
4397 }
4398 // Sort the identifiers to visit based on their name.
4399 std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
4400 for (const IdentifierInfo *II : IIs) {
4401 for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4402 DEnd = SemaRef.IdResolver.end();
4403 D != DEnd; ++D) {
4404 GetDeclRef(*D);
4405 }
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +00004406 }
4407 }
4408
Douglas Gregor5204bde2011-08-02 16:26:37 +00004409 // Form the record of special types.
4410 RecordData SpecialTypes;
Douglas Gregor5204bde2011-08-02 16:26:37 +00004411 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
Douglas Gregor5204bde2011-08-02 16:26:37 +00004412 AddTypeRef(Context.getFILEType(), SpecialTypes);
4413 AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4414 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4415 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4416 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
Douglas Gregor5204bde2011-08-02 16:26:37 +00004417 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00004418 AddTypeRef(Context.getucontext_tType(), SpecialTypes);
Douglas Gregora28bcdd2011-12-01 02:07:58 +00004419
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004420 if (Chain) {
4421 // Write the mapping information describing our module dependencies and how
4422 // each of those modules were mapped into our own offset/ID space, so that
4423 // the reader can build the appropriate mapping to its own offset/ID space.
4424 // The map consists solely of a blob with the following format:
4425 // *(module-name-len:i16 module-name:len*i8
4426 // source-location-offset:i32
4427 // identifier-id:i32
4428 // preprocessed-entity-id:i32
4429 // macro-definition-id:i32
Douglas Gregor253eefe2011-12-01 00:59:36 +00004430 // submodule-id:i32
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004431 // selector-id:i32
4432 // declaration-id:i32
4433 // c++-base-specifiers-id:i32
4434 // type-id:i32)
4435 //
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004436 auto *Abbrev = new BitCodeAbbrev();
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004437 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4438 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4439 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(Abbrev);
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004440 SmallString<2048> Buffer;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004441 {
4442 llvm::raw_svector_ostream Out(Buffer);
Ben Langmuir785180e2014-10-20 16:27:30 +00004443 for (ModuleFile *M : Chain->ModuleMgr) {
Justin Bognere1c147c2014-03-28 22:03:19 +00004444 using namespace llvm::support;
4445 endian::Writer<little> LE(Out);
Ben Langmuir785180e2014-10-20 16:27:30 +00004446 StringRef FileName = M->FileName;
Justin Bognere1c147c2014-03-28 22:03:19 +00004447 LE.write<uint16_t>(FileName.size());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004448 Out.write(FileName.data(), FileName.size());
Ben Langmuirfe971d92014-08-16 04:54:18 +00004449
Ben Langmuir785180e2014-10-20 16:27:30 +00004450 // Note: if a base ID was uint max, it would not be possible to load
4451 // another module after it or have more than one entity inside it.
4452 uint32_t None = std::numeric_limits<uint32_t>::max();
4453
4454 auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) {
4455 assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
4456 if (ShouldWrite)
4457 LE.write<uint32_t>(BaseID);
4458 else
4459 LE.write<uint32_t>(None);
4460 };
4461
Ben Langmuirfe971d92014-08-16 04:54:18 +00004462 // These values should be unique within a chain, since they will be read
4463 // as keys into ContinuousRangeMaps.
Ben Langmuir785180e2014-10-20 16:27:30 +00004464 writeBaseIDOrNone(M->SLocEntryBaseOffset, M->LocalNumSLocEntries);
4465 writeBaseIDOrNone(M->BaseIdentifierID, M->LocalNumIdentifiers);
4466 writeBaseIDOrNone(M->BaseMacroID, M->LocalNumMacros);
4467 writeBaseIDOrNone(M->BasePreprocessedEntityID,
4468 M->NumPreprocessedEntities);
4469 writeBaseIDOrNone(M->BaseSubmoduleID, M->LocalNumSubmodules);
4470 writeBaseIDOrNone(M->BaseSelectorID, M->LocalNumSelectors);
4471 writeBaseIDOrNone(M->BaseDeclID, M->LocalNumDecls);
4472 writeBaseIDOrNone(M->BaseTypeIndex, M->LocalNumTypes);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004473 }
4474 }
Mehdi Amini57a41912015-09-10 01:46:39 +00004475 RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004476 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4477 Buffer.data(), Buffer.size());
4478 }
Richard Smithb9eab6d2014-03-20 19:44:17 +00004479
Richard Smithb9eab6d2014-03-20 19:44:17 +00004480 RecordData DeclUpdatesOffsetsRecord;
4481
Richard Smith59442b42014-03-20 20:07:19 +00004482 // Keep writing types, declarations, and declaration update records
4483 // until we've emitted all of them.
Richard Smith01b2cb42014-07-26 06:37:51 +00004484 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
4485 WriteTypeAbbrevs();
4486 WriteDeclAbbrevs();
Richard Smith59442b42014-03-20 20:07:19 +00004487 do {
4488 WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
4489 while (!DeclTypesToEmit.empty()) {
4490 DeclOrType DOT = DeclTypesToEmit.front();
4491 DeclTypesToEmit.pop();
4492 if (DOT.isType())
4493 WriteType(DOT.getType());
4494 else
4495 WriteDecl(Context, DOT.getDecl());
4496 }
4497 } while (!DeclUpdates.empty());
Richard Smithb9eab6d2014-03-20 19:44:17 +00004498 Stream.ExitBlock();
4499
Richard Smithb9eab6d2014-03-20 19:44:17 +00004500 DoneWritingDeclsAndTypes = true;
4501
4502 // These things can only be done once we've written out decls and types.
4503 WriteTypeDeclOffsets();
Richard Smith5652c0f2014-03-21 01:48:23 +00004504 if (!DeclUpdatesOffsetsRecord.empty())
4505 Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
Richard Smithb9eab6d2014-03-20 19:44:17 +00004506 WriteCXXBaseSpecifiersOffsets();
Richard Smithc2bb8182015-03-24 06:36:48 +00004507 WriteCXXCtorInitializersOffsets();
Richard Smithb9eab6d2014-03-20 19:44:17 +00004508 WriteFileDeclIDsMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00004509 WriteSourceManagerBlock(Context.getSourceManager(), PP);
Richard Smithb9eab6d2014-03-20 19:44:17 +00004510 WriteComments();
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004511 WritePreprocessor(PP, isModule);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004512 WriteHeaderSearch(PP.getHeaderSearchInfo());
Sebastian Redla19a67f2010-08-03 21:58:15 +00004513 WriteSelectors(SemaRef);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00004514 WriteReferencedSelectorsPool(SemaRef);
Richard Smith9c254182015-07-19 21:41:12 +00004515 WriteLateParsedTemplates(SemaRef);
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004516 WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
Peter Collingbourne5df20e02011-02-15 19:46:30 +00004517 WriteFPPragmaOptions(SemaRef.getFPOptions());
4518 WriteOpenCLExtensions(SemaRef);
Argyrios Kyrtzidis0f06b982013-03-27 17:17:23 +00004519 WritePragmaDiagnosticMappings(Context.getDiagnostics(), isModule);
Douglas Gregor652d82a2009-04-18 05:55:16 +00004520
Douglas Gregora89c5ac2011-12-06 01:10:29 +00004521 // If we're emitting a module, write out the submodule information.
4522 if (WritingModule)
4523 WriteSubmodules(WritingModule);
4524
Douglas Gregor5204bde2011-08-02 16:26:37 +00004525 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
4526
Douglas Gregord4df8652009-04-22 22:02:47 +00004527 // Write the record containing external, unnamed definitions.
Ben Langmuir332aafe2014-01-31 01:06:56 +00004528 if (!EagerlyDeserializedDecls.empty())
4529 Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
Douglas Gregord4df8652009-04-22 22:02:47 +00004530
4531 // Write the record containing tentative definitions.
4532 if (!TentativeDefinitions.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004533 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregoracfc76c2009-04-22 22:18:58 +00004534
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00004535 // Write the record containing unused file scoped decls.
4536 if (!UnusedFileScopedDecls.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004537 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00004538
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004539 // Write the record containing weak undeclared identifiers.
4540 if (!WeakUndeclaredIdentifiers.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004541 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004542 WeakUndeclaredIdentifiers);
4543
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004544 // Write the record containing ext_vector type names.
4545 if (!ExtVectorDecls.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004546 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
Mike Stump11289f42009-09-09 15:08:12 +00004547
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004548 // Write the record containing VTable uses information.
4549 if (!VTableUses.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004550 Stream.EmitRecord(VTABLE_USES, VTableUses);
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004551
Nico Weber72889432014-09-06 01:25:55 +00004552 // Write the record containing potentially unused local typedefs.
4553 if (!UnusedLocalTypedefNameCandidates.empty())
4554 Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
4555 UnusedLocalTypedefNameCandidates);
4556
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004557 // Write the record containing pending implicit instantiations.
Chandler Carruth54080172010-08-25 08:44:16 +00004558 if (!PendingInstantiations.empty())
4559 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004560
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004561 // Write the record containing declaration references of Sema.
4562 if (!SemaDeclRefs.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004563 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004564
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004565 // Write the record containing CUDA-specific declaration references.
4566 if (!CUDASpecialDeclRefs.empty())
4567 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
Alexis Hunt27a761d2011-05-04 23:29:54 +00004568
4569 // Write the delegating constructors.
4570 if (!DelegatingCtorDecls.empty())
4571 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004572
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004573 // Write the known namespaces.
4574 if (!KnownNamespaces.empty())
4575 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
Nick Lewycky8334af82013-01-26 00:35:08 +00004576
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004577 // Write the undefined internal functions and variables, and inline functions.
4578 if (!UndefinedButUsed.empty())
4579 Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00004580
4581 if (!DeleteExprsToAnalyze.empty())
4582 Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
4583
Douglas Gregor851443c2011-08-12 01:39:19 +00004584 // Write the visible updates to DeclContexts.
Richard Smithcd45dbc2014-04-19 03:48:30 +00004585 for (auto *DC : UpdatedDeclContexts)
4586 WriteDeclContextVisibleUpdate(DC);
Douglas Gregor851443c2011-08-12 01:39:19 +00004587
Douglas Gregor959bb062011-12-03 01:15:29 +00004588 if (!WritingModule) {
4589 // Write the submodules that were imported, if any.
Aaron Ballman4f45b712014-03-21 15:22:56 +00004590 struct ModuleInfo {
4591 uint64_t ID;
4592 Module *M;
4593 ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
4594 };
Richard Smith56be7542014-03-21 00:33:59 +00004595 llvm::SmallVector<ModuleInfo, 64> Imports;
Aaron Ballmanbbc31212014-03-14 20:59:21 +00004596 for (const auto *I : Context.local_imports()) {
Douglas Gregor959bb062011-12-03 01:15:29 +00004597 assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
Aaron Ballman4f45b712014-03-21 15:22:56 +00004598 Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
4599 I->getImportedModule()));
Douglas Gregor959bb062011-12-03 01:15:29 +00004600 }
Richard Smith56be7542014-03-21 00:33:59 +00004601
4602 if (!Imports.empty()) {
4603 auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
4604 return A.ID < B.ID;
4605 };
Ben Langmuir5f95c8f2014-09-08 20:36:26 +00004606 auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
4607 return A.ID == B.ID;
4608 };
Richard Smith56be7542014-03-21 00:33:59 +00004609
4610 // Sort and deduplicate module IDs.
4611 std::sort(Imports.begin(), Imports.end(), Cmp);
Ben Langmuir5f95c8f2014-09-08 20:36:26 +00004612 Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
Richard Smith56be7542014-03-21 00:33:59 +00004613 Imports.end());
4614
4615 RecordData ImportedModules;
4616 for (const auto &Import : Imports) {
4617 ImportedModules.push_back(Import.ID);
4618 // FIXME: If the module has macros imported then later has declarations
4619 // imported, this location won't be the right one as a location for the
4620 // declaration imports.
Richard Smith10434f32015-05-02 02:08:26 +00004621 AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
Richard Smith56be7542014-03-21 00:33:59 +00004622 }
4623
Douglas Gregor959bb062011-12-03 01:15:29 +00004624 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
4625 }
Douglas Gregor0a839132011-12-03 00:59:55 +00004626 }
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004627
Douglas Gregor404cdde2012-01-27 01:47:08 +00004628 WriteObjCCategories();
Nico Weber779355f2016-03-02 23:22:00 +00004629 if(!WritingModule) {
Dario Domizioli13a0a382014-05-23 12:13:25 +00004630 WriteOptimizePragmaOptions(SemaRef);
Nico Weber779355f2016-03-02 23:22:00 +00004631 WriteMSStructPragmaOptions(SemaRef);
Nico Weber42932312016-03-03 00:17:35 +00004632 WriteMSPointersToMembersPragmaOptions(SemaRef);
Nico Weber779355f2016-03-02 23:22:00 +00004633 }
Richard Smithe40f2ba2013-08-07 21:41:30 +00004634
Douglas Gregor08f01292009-04-17 22:13:46 +00004635 // Some simple statistics
Mehdi Amini57a41912015-09-10 01:46:39 +00004636 RecordData::value_type Record[] = {
4637 NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts};
Sebastian Redl539c5062010-08-18 23:57:32 +00004638 Stream.EmitRecord(STATISTICS, Record);
Douglas Gregor8f45df52009-04-16 22:23:12 +00004639 Stream.ExitBlock();
Adrian Prantladbd2b12015-09-22 23:26:31 +00004640
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004641 // Write the module file extension blocks.
4642 for (const auto &ExtWriter : ModuleFileExtensionWriters)
Douglas Gregor8f64ca12015-12-08 22:43:32 +00004643 WriteModuleFileExtension(SemaRef, *ExtWriter);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004644
Adrian Prantladbd2b12015-09-22 23:26:31 +00004645 return Signature;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004646}
4647
Richard Smithb9eab6d2014-03-20 19:44:17 +00004648void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00004649 if (DeclUpdates.empty())
4650 return;
4651
Richard Smith59442b42014-03-20 20:07:19 +00004652 DeclUpdateMap LocalUpdates;
4653 LocalUpdates.swap(DeclUpdates);
4654
Richard Smith6ef42932014-03-20 21:02:00 +00004655 for (auto &DeclUpdate : LocalUpdates) {
4656 const Decl *D = DeclUpdate.first;
Argyrios Kyrtzidis3ba70b82010-10-24 17:26:46 +00004657
Richard Smithd28ac5b2014-03-22 23:33:22 +00004658 bool HasUpdatedBody = false;
Richard Smith6ef42932014-03-20 21:02:00 +00004659 RecordData Record;
4660 for (auto &Update : DeclUpdate.second) {
4661 DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
4662
4663 Record.push_back(Kind);
4664 switch (Kind) {
4665 case UPD_CXX_ADDED_IMPLICIT_MEMBER:
4666 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4667 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
Richard Smithcd45dbc2014-04-19 03:48:30 +00004668 assert(Update.getDecl() && "no decl to add?");
Richard Smith6ef42932014-03-20 21:02:00 +00004669 Record.push_back(GetDeclRef(Update.getDecl()));
4670 break;
4671
Richard Smith4d235792014-08-07 18:53:08 +00004672 case UPD_CXX_ADDED_FUNCTION_DEFINITION:
Richard Smithd28ac5b2014-03-22 23:33:22 +00004673 // An updated body is emitted last, so that the reader doesn't need
4674 // to skip over the lazy body to reach statements for other records.
4675 Record.pop_back();
4676 HasUpdatedBody = true;
4677 break;
4678
Richard Smith4d235792014-08-07 18:53:08 +00004679 case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
4680 AddSourceLocation(Update.getLoc(), Record);
4681 break;
4682
John McCall32791cc2016-01-06 22:34:54 +00004683 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT:
4684 AddStmt(const_cast<Expr*>(
4685 cast<ParmVarDecl>(Update.getDecl())->getDefaultArg()));
4686 break;
4687
Richard Smithcd45dbc2014-04-19 03:48:30 +00004688 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
4689 auto *RD = cast<CXXRecordDecl>(D);
Chandler Carruth8a3d24d2015-03-26 04:27:10 +00004690 UpdatedDeclContexts.insert(RD->getPrimaryContext());
Richard Smithcd45dbc2014-04-19 03:48:30 +00004691 AddCXXDefinitionData(RD, Record);
4692 Record.push_back(WriteDeclContextLexicalBlock(
4693 *Context, const_cast<CXXRecordDecl *>(RD)));
4694
4695 // This state is sometimes updated by template instantiation, when we
4696 // switch from the specialization referring to the template declaration
4697 // to it referring to the template definition.
4698 if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
4699 Record.push_back(MSInfo->getTemplateSpecializationKind());
4700 AddSourceLocation(MSInfo->getPointOfInstantiation(), Record);
4701 } else {
4702 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
4703 Record.push_back(Spec->getTemplateSpecializationKind());
4704 AddSourceLocation(Spec->getPointOfInstantiation(), Record);
Richard Smithdf352052014-05-22 20:59:29 +00004705
4706 // The instantiation might have been resolved to a partial
4707 // specialization. If so, record which one.
4708 auto From = Spec->getInstantiatedFrom();
4709 if (auto PartialSpec =
4710 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
4711 Record.push_back(true);
4712 AddDeclRef(PartialSpec, Record);
4713 AddTemplateArgumentList(&Spec->getTemplateInstantiationArgs(),
4714 Record);
4715 } else {
4716 Record.push_back(false);
4717 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00004718 }
4719 Record.push_back(RD->getTagKind());
4720 AddSourceLocation(RD->getLocation(), Record);
4721 AddSourceLocation(RD->getLocStart(), Record);
4722 AddSourceLocation(RD->getRBraceLoc(), Record);
4723
4724 // Instantiation may change attributes; write them all out afresh.
4725 Record.push_back(D->hasAttrs());
4726 if (Record.back())
Craig Topper8c2a2a02014-08-30 16:55:39 +00004727 WriteAttributes(llvm::makeArrayRef(D->getAttrs().begin(),
4728 D->getAttrs().size()), Record);
Richard Smithcd45dbc2014-04-19 03:48:30 +00004729
4730 // FIXME: Ensure we don't get here for explicit instantiations.
4731 break;
4732 }
4733
Richard Smithf8134002015-03-10 01:41:22 +00004734 case UPD_CXX_RESOLVED_DTOR_DELETE:
4735 AddDeclRef(Update.getDecl(), Record);
4736 break;
4737
Richard Smith564417a2014-03-20 21:47:22 +00004738 case UPD_CXX_RESOLVED_EXCEPTION_SPEC:
4739 addExceptionSpec(
4740 *this,
4741 cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>(),
4742 Record);
4743 break;
4744
Richard Smith6ef42932014-03-20 21:02:00 +00004745 case UPD_CXX_DEDUCED_RETURN_TYPE:
4746 Record.push_back(GetOrCreateTypeID(Update.getType()));
4747 break;
4748
4749 case UPD_DECL_MARKED_USED:
4750 break;
Richard Smith5652c0f2014-03-21 01:48:23 +00004751
4752 case UPD_MANGLING_NUMBER:
4753 case UPD_STATIC_LOCAL_NUMBER:
4754 Record.push_back(Update.getNumber());
4755 break;
Richard Smith65ebb4a2015-03-26 04:09:53 +00004756
Alexey Bataev97720002014-11-11 04:05:39 +00004757 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
4758 AddSourceRange(D->getAttr<OMPThreadPrivateDeclAttr>()->getRange(),
4759 Record);
4760 break;
Richard Smith65ebb4a2015-03-26 04:09:53 +00004761
4762 case UPD_DECL_EXPORTED:
Richard Smith4caa4492015-05-15 02:34:32 +00004763 Record.push_back(getSubmoduleID(Update.getModule()));
Richard Smith65ebb4a2015-03-26 04:09:53 +00004764 break;
Alex Denisovfde64952015-06-26 05:28:36 +00004765
4766 case UPD_ADDED_ATTR_TO_RECORD:
4767 WriteAttributes(llvm::makeArrayRef(Update.getAttr()), Record);
4768 break;
Richard Smith6ef42932014-03-20 21:02:00 +00004769 }
4770 }
4771
Richard Smithd28ac5b2014-03-22 23:33:22 +00004772 if (HasUpdatedBody) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004773 const auto *Def = cast<FunctionDecl>(D);
Richard Smith4d235792014-08-07 18:53:08 +00004774 Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
Richard Smithd28ac5b2014-03-22 23:33:22 +00004775 Record.push_back(Def->isInlined());
4776 AddSourceLocation(Def->getInnerLocStart(), Record);
4777 AddFunctionDefinition(Def, Record);
4778 }
4779
Richard Smithcd45dbc2014-04-19 03:48:30 +00004780 OffsetsRecord.push_back(GetDeclRef(D));
4781 OffsetsRecord.push_back(Stream.GetCurrentBitNo());
4782
Richard Smith6ef42932014-03-20 21:02:00 +00004783 Stream.EmitRecord(DECL_UPDATES, Record);
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00004784
Richard Smithc2bb8182015-03-24 06:36:48 +00004785 FlushPendingAfterDecl();
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00004786 }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00004787}
4788
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004789void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
Richard Smithb22a1d12016-03-27 20:13:24 +00004790 uint32_t Raw = Loc.getRawEncoding();
4791 Record.push_back((Raw << 1) | (Raw >> 31));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004792}
4793
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004794void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
Chris Lattnerca025db2010-05-07 21:43:38 +00004795 AddSourceLocation(Range.getBegin(), Record);
4796 AddSourceLocation(Range.getEnd(), Record);
4797}
4798
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004799void ASTWriter::AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004800 Record.push_back(Value.getBitWidth());
Benjamin Kramer25f9ea62010-09-06 23:43:28 +00004801 const uint64_t *Words = Value.getRawData();
4802 Record.append(Words, Words + Value.getNumWords());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004803}
4804
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004805void ASTWriter::AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record) {
Douglas Gregor1daeb692009-04-13 18:14:40 +00004806 Record.push_back(Value.isUnsigned());
4807 AddAPInt(Value, Record);
4808}
4809
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004810void ASTWriter::AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record) {
Douglas Gregore0a3a512009-04-14 21:55:33 +00004811 AddAPInt(Value.bitcastToAPInt(), Record);
4812}
4813
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004814void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
Douglas Gregor4621c6a2009-04-22 18:49:13 +00004815 Record.push_back(getIdentifierRef(II));
4816}
4817
Sebastian Redl539c5062010-08-18 23:57:32 +00004818IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
Craig Toppera13603a2014-05-22 05:54:18 +00004819 if (!II)
Douglas Gregor4621c6a2009-04-22 18:49:13 +00004820 return 0;
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00004821
Sebastian Redl539c5062010-08-18 23:57:32 +00004822 IdentID &ID = IdentifierIDs[II];
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00004823 if (ID == 0)
Sebastian Redlff4a2952010-07-23 23:49:55 +00004824 ID = NextIdentID++;
Douglas Gregor4621c6a2009-04-22 18:49:13 +00004825 return ID;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004826}
4827
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004828MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004829 // Don't emit builtin macros like __LINE__ to the AST file unless they
4830 // have been redefined by the header (in which case they are not
4831 // isBuiltinMacro).
Craig Toppera13603a2014-05-22 05:54:18 +00004832 if (!MI || MI->isBuiltinMacro())
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004833 return 0;
4834
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004835 MacroID &ID = MacroIDs[MI];
4836 if (ID == 0) {
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004837 ID = NextMacroID++;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004838 MacroInfoToEmitData Info = { Name, MI, ID };
4839 MacroInfosToEmit.push_back(Info);
4840 }
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004841 return ID;
4842}
4843
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004844MacroID ASTWriter::getMacroID(MacroInfo *MI) {
Craig Toppera13603a2014-05-22 05:54:18 +00004845 if (!MI || MI->isBuiltinMacro())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004846 return 0;
4847
4848 assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
4849 return MacroIDs[MI];
4850}
4851
4852uint64_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
Richard Smithd7329392015-04-21 21:46:32 +00004853 return IdentMacroDirectivesOffsetMap.lookup(Name);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004854}
4855
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004856void ASTWriter::AddSelectorRef(const Selector SelRef, RecordDataImpl &Record) {
Sebastian Redl834bb972010-08-04 17:20:04 +00004857 Record.push_back(getSelectorRef(SelRef));
4858}
4859
Sebastian Redl539c5062010-08-18 23:57:32 +00004860SelectorID ASTWriter::getSelectorRef(Selector Sel) {
Craig Toppera13603a2014-05-22 05:54:18 +00004861 if (Sel.getAsOpaquePtr() == nullptr) {
Sebastian Redl834bb972010-08-04 17:20:04 +00004862 return 0;
Steve Naroff2ddea052009-04-23 10:39:46 +00004863 }
4864
Douglas Gregor8d7edce2013-02-08 21:30:59 +00004865 SelectorID SID = SelectorIDs[Sel];
Sebastian Redld95a56e2010-08-04 18:21:41 +00004866 if (SID == 0 && Chain) {
4867 // This might trigger a ReadSelector callback, which will set the ID for
4868 // this selector.
4869 Chain->LoadSelector(Sel);
Douglas Gregor8d7edce2013-02-08 21:30:59 +00004870 SID = SelectorIDs[Sel];
Sebastian Redld95a56e2010-08-04 18:21:41 +00004871 }
Steve Naroff2ddea052009-04-23 10:39:46 +00004872 if (SID == 0) {
Sebastian Redld95a56e2010-08-04 18:21:41 +00004873 SID = NextSelectorID++;
Douglas Gregor8d7edce2013-02-08 21:30:59 +00004874 SelectorIDs[Sel] = SID;
Steve Naroff2ddea052009-04-23 10:39:46 +00004875 }
Sebastian Redl834bb972010-08-04 17:20:04 +00004876 return SID;
Steve Naroff2ddea052009-04-23 10:39:46 +00004877}
4878
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004879void ASTWriter::AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record) {
Chris Lattnercba86142010-05-10 00:25:06 +00004880 AddDeclRef(Temp->getDestructor(), Record);
4881}
4882
Richard Smithc2bb8182015-03-24 06:36:48 +00004883void ASTWriter::AddCXXCtorInitializersRef(ArrayRef<CXXCtorInitializer *> Inits,
4884 RecordDataImpl &Record) {
4885 assert(!Inits.empty() && "Empty ctor initializer sets are not recorded");
4886 CXXCtorInitializersToWrite.push_back(
4887 QueuedCXXCtorInitializers(NextCXXCtorInitializersID, Inits));
4888 Record.push_back(NextCXXCtorInitializersID++);
4889}
4890
Douglas Gregord4c5ed02010-10-29 22:39:52 +00004891void ASTWriter::AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases,
Richard Smithc2bb8182015-03-24 06:36:48 +00004892 CXXBaseSpecifier const *BasesEnd,
Douglas Gregord4c5ed02010-10-29 22:39:52 +00004893 RecordDataImpl &Record) {
4894 assert(Bases != BasesEnd && "Empty base-specifier sets are not recorded");
4895 CXXBaseSpecifiersToWrite.push_back(
4896 QueuedCXXBaseSpecifiers(NextCXXBaseSpecifiersID,
4897 Bases, BasesEnd));
4898 Record.push_back(NextCXXBaseSpecifiersID++);
4899}
4900
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004901void ASTWriter::AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004902 const TemplateArgumentLocInfo &Arg,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004903 RecordDataImpl &Record) {
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004904 switch (Kind) {
John McCall0ad16662009-10-29 08:12:44 +00004905 case TemplateArgument::Expression:
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004906 AddStmt(Arg.getAsExpr());
John McCall0ad16662009-10-29 08:12:44 +00004907 break;
4908 case TemplateArgument::Type:
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004909 AddTypeSourceInfo(Arg.getAsTypeSourceInfo(), Record);
John McCall0ad16662009-10-29 08:12:44 +00004910 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004911 case TemplateArgument::Template:
Douglas Gregor9d802122011-03-02 17:09:35 +00004912 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00004913 AddSourceLocation(Arg.getTemplateNameLoc(), Record);
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004914 break;
4915 case TemplateArgument::TemplateExpansion:
Douglas Gregor9d802122011-03-02 17:09:35 +00004916 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004917 AddSourceLocation(Arg.getTemplateNameLoc(), Record);
Douglas Gregoreb29d182011-01-05 17:40:24 +00004918 AddSourceLocation(Arg.getTemplateEllipsisLoc(), Record);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004919 break;
John McCall0ad16662009-10-29 08:12:44 +00004920 case TemplateArgument::Null:
4921 case TemplateArgument::Integral:
4922 case TemplateArgument::Declaration:
Eli Friedmanb826a002012-09-26 02:36:12 +00004923 case TemplateArgument::NullPtr:
John McCall0ad16662009-10-29 08:12:44 +00004924 case TemplateArgument::Pack:
Eli Friedmanb826a002012-09-26 02:36:12 +00004925 // FIXME: Is this right?
John McCall0ad16662009-10-29 08:12:44 +00004926 break;
4927 }
4928}
4929
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004930void ASTWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004931 RecordDataImpl &Record) {
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004932 AddTemplateArgument(Arg.getArgument(), Record);
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00004933
4934 if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
4935 bool InfoHasSameExpr
4936 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
4937 Record.push_back(InfoHasSameExpr);
4938 if (InfoHasSameExpr)
4939 return; // Avoid storing the same expr twice.
4940 }
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004941 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo(),
4942 Record);
4943}
4944
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004945void ASTWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo,
4946 RecordDataImpl &Record) {
Craig Toppera13603a2014-05-22 05:54:18 +00004947 if (!TInfo) {
John McCall8f115c62009-10-16 21:56:05 +00004948 AddTypeRef(QualType(), Record);
4949 return;
4950 }
4951
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004952 AddTypeLoc(TInfo->getTypeLoc(), Record);
4953}
4954
4955void ASTWriter::AddTypeLoc(TypeLoc TL, RecordDataImpl &Record) {
4956 AddTypeRef(TL.getType(), Record);
4957
John McCall8f115c62009-10-16 21:56:05 +00004958 TypeLocWriter TLW(*this, Record);
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004959 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00004960 TLW.Visit(TL);
John McCall8f115c62009-10-16 21:56:05 +00004961}
4962
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004963void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
Argyrios Kyrtzidis9ab44ea2010-08-20 16:04:14 +00004964 Record.push_back(GetOrCreateTypeID(T));
4965}
4966
Richard Smith2095ffe2015-03-16 20:11:03 +00004967TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
Richard Smith1fa5d642013-05-11 05:45:24 +00004968 assert(Context);
Richard Smith2095ffe2015-03-16 20:11:03 +00004969 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
4970 if (T.isNull())
4971 return TypeIdx();
4972 assert(!T.getLocalFastQualifiers());
4973
4974 TypeIdx &Idx = TypeIdxs[T];
4975 if (Idx.getIndex() == 0) {
4976 if (DoneWritingDeclsAndTypes) {
4977 assert(0 && "New type seen after serializing all the types to emit!");
4978 return TypeIdx();
4979 }
4980
4981 // We haven't seen this type before. Assign it a new ID and put it
4982 // into the queue of types to emit.
4983 Idx = TypeIdx(NextTypeID++);
4984 DeclTypesToEmit.push(T);
4985 }
4986 return Idx;
4987 });
Argyrios Kyrtzidis082e4612010-08-20 16:04:20 +00004988}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004989
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00004990TypeID ASTWriter::getTypeID(QualType T) const {
Richard Smith1fa5d642013-05-11 05:45:24 +00004991 assert(Context);
Richard Smith2095ffe2015-03-16 20:11:03 +00004992 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
4993 if (T.isNull())
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004994 return TypeIdx();
Richard Smith2095ffe2015-03-16 20:11:03 +00004995 assert(!T.getLocalFastQualifiers());
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004996
Richard Smith2095ffe2015-03-16 20:11:03 +00004997 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
4998 assert(I != TypeIdxs.end() && "Type not emitted!");
4999 return I->second;
5000 });
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005001}
5002
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005003void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005004 Record.push_back(GetDeclRef(D));
5005}
5006
Sebastian Redl539c5062010-08-18 23:57:32 +00005007DeclID ASTWriter::GetDeclRef(const Decl *D) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005008 assert(WritingAST && "Cannot request a declaration ID before AST writing");
Craig Toppera13603a2014-05-22 05:54:18 +00005009
5010 if (!D) {
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005011 return 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005012 }
Douglas Gregorb3163e52012-01-05 22:33:30 +00005013
5014 // If D comes from an AST file, its declaration ID is already known and
5015 // fixed.
5016 if (D->isFromASTFile())
5017 return D->getGlobalID();
5018
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005019 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
Sebastian Redl539c5062010-08-18 23:57:32 +00005020 DeclID &ID = DeclIDs[D];
Mike Stump11289f42009-09-09 15:08:12 +00005021 if (ID == 0) {
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005022 if (DoneWritingDeclsAndTypes) {
5023 assert(0 && "New decl seen after serializing all the decls to emit!");
5024 return 0;
5025 }
5026
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005027 // We haven't seen this declaration before. Give it a new ID and
5028 // enqueue it in the list of declarations to emit.
Sebastian Redlff4a2952010-07-23 23:49:55 +00005029 ID = NextDeclID++;
Douglas Gregor12bfa382009-10-17 00:13:19 +00005030 DeclTypesToEmit.push(const_cast<Decl *>(D));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005031 }
5032
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005033 return ID;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005034}
5035
Sebastian Redl539c5062010-08-18 23:57:32 +00005036DeclID ASTWriter::getDeclID(const Decl *D) {
Craig Toppera13603a2014-05-22 05:54:18 +00005037 if (!D)
Douglas Gregore84a9da2009-04-20 20:36:09 +00005038 return 0;
5039
Douglas Gregorb3163e52012-01-05 22:33:30 +00005040 // If D comes from an AST file, its declaration ID is already known and
5041 // fixed.
5042 if (D->isFromASTFile())
5043 return D->getGlobalID();
5044
Douglas Gregore84a9da2009-04-20 20:36:09 +00005045 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
5046 return DeclIDs[D];
5047}
5048
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005049void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005050 assert(ID);
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005051 assert(D);
5052
5053 SourceLocation Loc = D->getLocation();
5054 if (Loc.isInvalid())
5055 return;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005056
5057 // We only keep track of the file-level declarations of each file.
5058 if (!D->getLexicalDeclContext()->isFileContext())
5059 return;
Argyrios Kyrtzidise1bc99e2012-02-24 19:45:46 +00005060 // FIXME: ParmVarDecls that are part of a function type of a parameter of
5061 // a function/objc method, should not have TU as lexical context.
Argyrios Kyrtzidisffe055a82012-02-24 01:12:38 +00005062 if (isa<ParmVarDecl>(D))
5063 return;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005064
5065 SourceManager &SM = Context->getSourceManager();
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005066 SourceLocation FileLoc = SM.getFileLoc(Loc);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005067 assert(SM.isLocalSourceLocation(FileLoc));
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005068 FileID FID;
5069 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00005070 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005071 if (FID.isInvalid())
5072 return;
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00005073 assert(SM.getSLocEntry(FID).isFile());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005074
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00005075 DeclIDInFileInfo *&Info = FileDeclIDs[FID];
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005076 if (!Info)
5077 Info = new DeclIDInFileInfo();
5078
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005079 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005080 LocDeclIDsTy &Decls = Info->DeclIDs;
5081
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005082 if (Decls.empty() || Decls.back().first <= Offset) {
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005083 Decls.push_back(LocDecl);
5084 return;
5085 }
5086
Benjamin Kramer45025c02013-08-24 13:22:59 +00005087 LocDeclIDsTy::iterator I =
5088 std::upper_bound(Decls.begin(), Decls.end(), LocDecl, llvm::less_first());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005089
5090 Decls.insert(I, LocDecl);
5091}
5092
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005093void ASTWriter::AddDeclarationName(DeclarationName Name, RecordDataImpl &Record) {
Chris Lattner258172e2009-04-27 07:35:58 +00005094 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005095 Record.push_back(Name.getNameKind());
5096 switch (Name.getNameKind()) {
5097 case DeclarationName::Identifier:
5098 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
5099 break;
5100
5101 case DeclarationName::ObjCZeroArgSelector:
5102 case DeclarationName::ObjCOneArgSelector:
5103 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff2ddea052009-04-23 10:39:46 +00005104 AddSelectorRef(Name.getObjCSelector(), Record);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005105 break;
5106
5107 case DeclarationName::CXXConstructorName:
5108 case DeclarationName::CXXDestructorName:
5109 case DeclarationName::CXXConversionFunctionName:
5110 AddTypeRef(Name.getCXXNameType(), Record);
5111 break;
5112
5113 case DeclarationName::CXXOperatorName:
5114 Record.push_back(Name.getCXXOverloadedOperator());
5115 break;
5116
Alexis Hunt3d221f22009-11-29 07:34:05 +00005117 case DeclarationName::CXXLiteralOperatorName:
5118 AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record);
5119 break;
5120
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005121 case DeclarationName::CXXUsingDirective:
5122 // No extra data to emit
5123 break;
5124 }
5125}
Chris Lattnerca025db2010-05-07 21:43:38 +00005126
Richard Smithd08aeb62014-08-28 01:33:39 +00005127unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
5128 assert(needsAnonymousDeclarationNumber(D) &&
5129 "expected an anonymous declaration");
5130
5131 // Number the anonymous declarations within this context, if we've not
5132 // already done so.
5133 auto It = AnonymousDeclarationNumbers.find(D);
5134 if (It == AnonymousDeclarationNumbers.end()) {
Richard Smith2b560572015-02-07 03:11:11 +00005135 auto *DC = D->getLexicalDeclContext();
5136 numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
5137 AnonymousDeclarationNumbers[ND] = Number;
5138 });
Richard Smithd08aeb62014-08-28 01:33:39 +00005139
5140 It = AnonymousDeclarationNumbers.find(D);
5141 assert(It != AnonymousDeclarationNumbers.end() &&
5142 "declaration not found within its lexical context");
5143 }
5144
5145 return It->second;
5146}
5147
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005148void ASTWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005149 DeclarationName Name, RecordDataImpl &Record) {
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005150 switch (Name.getNameKind()) {
5151 case DeclarationName::CXXConstructorName:
5152 case DeclarationName::CXXDestructorName:
5153 case DeclarationName::CXXConversionFunctionName:
5154 AddTypeSourceInfo(DNLoc.NamedType.TInfo, Record);
5155 break;
5156
5157 case DeclarationName::CXXOperatorName:
5158 AddSourceLocation(
5159 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.BeginOpNameLoc),
5160 Record);
5161 AddSourceLocation(
5162 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc),
5163 Record);
5164 break;
5165
5166 case DeclarationName::CXXLiteralOperatorName:
5167 AddSourceLocation(
5168 SourceLocation::getFromRawEncoding(DNLoc.CXXLiteralOperatorName.OpNameLoc),
5169 Record);
5170 break;
5171
5172 case DeclarationName::Identifier:
5173 case DeclarationName::ObjCZeroArgSelector:
5174 case DeclarationName::ObjCOneArgSelector:
5175 case DeclarationName::ObjCMultiArgSelector:
5176 case DeclarationName::CXXUsingDirective:
5177 break;
5178 }
5179}
5180
5181void ASTWriter::AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005182 RecordDataImpl &Record) {
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005183 AddDeclarationName(NameInfo.getName(), Record);
5184 AddSourceLocation(NameInfo.getLoc(), Record);
5185 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName(), Record);
5186}
5187
5188void ASTWriter::AddQualifierInfo(const QualifierInfo &Info,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005189 RecordDataImpl &Record) {
Douglas Gregor14454802011-02-25 02:25:35 +00005190 AddNestedNameSpecifierLoc(Info.QualifierLoc, Record);
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005191 Record.push_back(Info.NumTemplParamLists);
5192 for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i)
5193 AddTemplateParameterList(Info.TemplParamLists[i], Record);
5194}
5195
Sebastian Redl55c0ad52010-08-18 23:56:21 +00005196void ASTWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005197 RecordDataImpl &Record) {
Chris Lattnerca025db2010-05-07 21:43:38 +00005198 // Nested name specifiers usually aren't too long. I think that 8 would
Chris Lattner57540c52011-04-15 05:22:18 +00005199 // typically accommodate the vast majority.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005200 SmallVector<NestedNameSpecifier *, 8> NestedNames;
Chris Lattnerca025db2010-05-07 21:43:38 +00005201
5202 // Push each of the NNS's onto a stack for serialization in reverse order.
5203 while (NNS) {
5204 NestedNames.push_back(NNS);
5205 NNS = NNS->getPrefix();
5206 }
5207
5208 Record.push_back(NestedNames.size());
5209 while(!NestedNames.empty()) {
5210 NNS = NestedNames.pop_back_val();
5211 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
5212 Record.push_back(Kind);
5213 switch (Kind) {
5214 case NestedNameSpecifier::Identifier:
5215 AddIdentifierRef(NNS->getAsIdentifier(), Record);
5216 break;
5217
5218 case NestedNameSpecifier::Namespace:
5219 AddDeclRef(NNS->getAsNamespace(), Record);
5220 break;
5221
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005222 case NestedNameSpecifier::NamespaceAlias:
5223 AddDeclRef(NNS->getAsNamespaceAlias(), Record);
5224 break;
5225
Chris Lattnerca025db2010-05-07 21:43:38 +00005226 case NestedNameSpecifier::TypeSpec:
5227 case NestedNameSpecifier::TypeSpecWithTemplate:
5228 AddTypeRef(QualType(NNS->getAsType(), 0), Record);
5229 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5230 break;
5231
5232 case NestedNameSpecifier::Global:
5233 // Don't need to write an associated value.
5234 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00005235
5236 case NestedNameSpecifier::Super:
5237 AddDeclRef(NNS->getAsRecordDecl(), Record);
5238 break;
Chris Lattnerca025db2010-05-07 21:43:38 +00005239 }
5240 }
5241}
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005242
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005243void ASTWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
5244 RecordDataImpl &Record) {
5245 // Nested name specifiers usually aren't too long. I think that 8 would
Chris Lattner57540c52011-04-15 05:22:18 +00005246 // typically accommodate the vast majority.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005247 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005248
5249 // Push each of the nested-name-specifiers's onto a stack for
5250 // serialization in reverse order.
5251 while (NNS) {
5252 NestedNames.push_back(NNS);
5253 NNS = NNS.getPrefix();
5254 }
5255
5256 Record.push_back(NestedNames.size());
5257 while(!NestedNames.empty()) {
5258 NNS = NestedNames.pop_back_val();
5259 NestedNameSpecifier::SpecifierKind Kind
5260 = NNS.getNestedNameSpecifier()->getKind();
5261 Record.push_back(Kind);
5262 switch (Kind) {
5263 case NestedNameSpecifier::Identifier:
5264 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier(), Record);
5265 AddSourceRange(NNS.getLocalSourceRange(), Record);
5266 break;
5267
5268 case NestedNameSpecifier::Namespace:
5269 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace(), Record);
5270 AddSourceRange(NNS.getLocalSourceRange(), Record);
5271 break;
5272
5273 case NestedNameSpecifier::NamespaceAlias:
5274 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias(), Record);
5275 AddSourceRange(NNS.getLocalSourceRange(), Record);
5276 break;
5277
5278 case NestedNameSpecifier::TypeSpec:
5279 case NestedNameSpecifier::TypeSpecWithTemplate:
5280 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5281 AddTypeLoc(NNS.getTypeLoc(), Record);
5282 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
5283 break;
5284
5285 case NestedNameSpecifier::Global:
5286 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
5287 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00005288
5289 case NestedNameSpecifier::Super:
5290 AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl(), Record);
5291 AddSourceRange(NNS.getLocalSourceRange(), Record);
5292 break;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005293 }
5294 }
5295}
5296
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005297void ASTWriter::AddTemplateName(TemplateName Name, RecordDataImpl &Record) {
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005298 TemplateName::NameKind Kind = Name.getKind();
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005299 Record.push_back(Kind);
5300 switch (Kind) {
5301 case TemplateName::Template:
5302 AddDeclRef(Name.getAsTemplateDecl(), Record);
5303 break;
5304
5305 case TemplateName::OverloadedTemplate: {
5306 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
5307 Record.push_back(OvT->size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005308 for (const auto &I : *OvT)
5309 AddDeclRef(I, Record);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005310 break;
5311 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005312
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005313 case TemplateName::QualifiedTemplate: {
5314 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
5315 AddNestedNameSpecifier(QualT->getQualifier(), Record);
5316 Record.push_back(QualT->hasTemplateKeyword());
5317 AddDeclRef(QualT->getTemplateDecl(), Record);
5318 break;
5319 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005320
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005321 case TemplateName::DependentTemplate: {
5322 DependentTemplateName *DepT = Name.getAsDependentTemplateName();
5323 AddNestedNameSpecifier(DepT->getQualifier(), Record);
5324 Record.push_back(DepT->isIdentifier());
5325 if (DepT->isIdentifier())
5326 AddIdentifierRef(DepT->getIdentifier(), Record);
5327 else
5328 Record.push_back(DepT->getOperator());
5329 break;
5330 }
John McCalld9dfe3a2011-06-30 08:33:18 +00005331
5332 case TemplateName::SubstTemplateTemplateParm: {
5333 SubstTemplateTemplateParmStorage *subst
5334 = Name.getAsSubstTemplateTemplateParm();
5335 AddDeclRef(subst->getParameter(), Record);
5336 AddTemplateName(subst->getReplacement(), Record);
5337 break;
5338 }
Douglas Gregor5590be02011-01-15 06:45:20 +00005339
5340 case TemplateName::SubstTemplateTemplateParmPack: {
5341 SubstTemplateTemplateParmPackStorage *SubstPack
5342 = Name.getAsSubstTemplateTemplateParmPack();
5343 AddDeclRef(SubstPack->getParameterPack(), Record);
5344 AddTemplateArgument(SubstPack->getArgumentPack(), Record);
5345 break;
5346 }
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005347 }
5348}
5349
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005350void ASTWriter::AddTemplateArgument(const TemplateArgument &Arg,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005351 RecordDataImpl &Record) {
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005352 Record.push_back(Arg.getKind());
5353 switch (Arg.getKind()) {
5354 case TemplateArgument::Null:
5355 break;
5356 case TemplateArgument::Type:
5357 AddTypeRef(Arg.getAsType(), Record);
5358 break;
5359 case TemplateArgument::Declaration:
5360 AddDeclRef(Arg.getAsDecl(), Record);
David Blaikie952a9b12014-10-17 18:00:12 +00005361 AddTypeRef(Arg.getParamTypeForDecl(), Record);
Eli Friedmanb826a002012-09-26 02:36:12 +00005362 break;
5363 case TemplateArgument::NullPtr:
5364 AddTypeRef(Arg.getNullPtrType(), Record);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005365 break;
5366 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005367 AddAPSInt(Arg.getAsIntegral(), Record);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005368 AddTypeRef(Arg.getIntegralType(), Record);
5369 break;
5370 case TemplateArgument::Template:
Douglas Gregore1d60df2011-01-14 23:41:42 +00005371 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
5372 break;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005373 case TemplateArgument::TemplateExpansion:
5374 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
David Blaikie05785d12013-02-20 22:23:23 +00005375 if (Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
Douglas Gregore1d60df2011-01-14 23:41:42 +00005376 Record.push_back(*NumExpansions + 1);
5377 else
5378 Record.push_back(0);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005379 break;
5380 case TemplateArgument::Expression:
5381 AddStmt(Arg.getAsExpr());
5382 break;
5383 case TemplateArgument::Pack:
5384 Record.push_back(Arg.pack_size());
Aaron Ballman2a89e852014-07-15 21:32:31 +00005385 for (const auto &P : Arg.pack_elements())
5386 AddTemplateArgument(P, Record);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005387 break;
5388 }
5389}
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005390
5391void
Sebastian Redl55c0ad52010-08-18 23:56:21 +00005392ASTWriter::AddTemplateParameterList(const TemplateParameterList *TemplateParams,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005393 RecordDataImpl &Record) {
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005394 assert(TemplateParams && "No TemplateParams!");
5395 AddSourceLocation(TemplateParams->getTemplateLoc(), Record);
5396 AddSourceLocation(TemplateParams->getLAngleLoc(), Record);
5397 AddSourceLocation(TemplateParams->getRAngleLoc(), Record);
5398 Record.push_back(TemplateParams->size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005399 for (const auto &P : *TemplateParams)
5400 AddDeclRef(P, Record);
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005401}
5402
5403/// \brief Emit a template argument list.
5404void
Sebastian Redl55c0ad52010-08-18 23:56:21 +00005405ASTWriter::AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005406 RecordDataImpl &Record) {
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005407 assert(TemplateArgs && "No TemplateArgs!");
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005408 Record.push_back(TemplateArgs->size());
5409 for (int i=0, e = TemplateArgs->size(); i != e; ++i)
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005410 AddTemplateArgument(TemplateArgs->get(i), Record);
5411}
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005412
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005413void
5414ASTWriter::AddASTTemplateArgumentListInfo
5415(const ASTTemplateArgumentListInfo *ASTTemplArgList, RecordDataImpl &Record) {
5416 assert(ASTTemplArgList && "No ASTTemplArgList!");
5417 AddSourceLocation(ASTTemplArgList->LAngleLoc, Record);
5418 AddSourceLocation(ASTTemplArgList->RAngleLoc, Record);
5419 Record.push_back(ASTTemplArgList->NumTemplateArgs);
5420 const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
5421 for (int i=0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
5422 AddTemplateArgumentLoc(TemplArgs[i], Record);
5423}
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005424
5425void
Argyrios Kyrtzidis0f05fb92012-11-28 03:56:16 +00005426ASTWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set, RecordDataImpl &Record) {
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005427 Record.push_back(Set.size());
Argyrios Kyrtzidis0f05fb92012-11-28 03:56:16 +00005428 for (ASTUnresolvedSet::const_iterator
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005429 I = Set.begin(), E = Set.end(); I != E; ++I) {
5430 AddDeclRef(I.getDecl(), Record);
5431 Record.push_back(I.getAccess());
5432 }
5433}
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005434
Sebastian Redl55c0ad52010-08-18 23:56:21 +00005435void ASTWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005436 RecordDataImpl &Record) {
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005437 Record.push_back(Base.isVirtual());
5438 Record.push_back(Base.isBaseOfClass());
5439 Record.push_back(Base.getAccessSpecifierAsWritten());
Sebastian Redl08905022011-02-05 19:23:19 +00005440 Record.push_back(Base.getInheritConstructors());
Nick Lewycky19b9f952010-07-26 16:56:01 +00005441 AddTypeSourceInfo(Base.getTypeSourceInfo(), Record);
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005442 AddSourceRange(Base.getSourceRange(), Record);
Douglas Gregor752a5952011-01-03 22:36:02 +00005443 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
5444 : SourceLocation(),
5445 Record);
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005446}
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00005447
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005448void ASTWriter::FlushCXXBaseSpecifiers() {
5449 RecordData Record;
Richard Smithc2bb8182015-03-24 06:36:48 +00005450 unsigned N = CXXBaseSpecifiersToWrite.size();
5451 for (unsigned I = 0; I != N; ++I) {
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005452 Record.clear();
5453
5454 // Record the offset of this base-specifier set.
Douglas Gregorc27b2872011-08-04 00:01:48 +00005455 unsigned Index = CXXBaseSpecifiersToWrite[I].ID - 1;
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005456 if (Index == CXXBaseSpecifiersOffsets.size())
5457 CXXBaseSpecifiersOffsets.push_back(Stream.GetCurrentBitNo());
5458 else {
5459 if (Index > CXXBaseSpecifiersOffsets.size())
5460 CXXBaseSpecifiersOffsets.resize(Index + 1);
5461 CXXBaseSpecifiersOffsets[Index] = Stream.GetCurrentBitNo();
5462 }
5463
5464 const CXXBaseSpecifier *B = CXXBaseSpecifiersToWrite[I].Bases,
5465 *BEnd = CXXBaseSpecifiersToWrite[I].BasesEnd;
5466 Record.push_back(BEnd - B);
5467 for (; B != BEnd; ++B)
5468 AddCXXBaseSpecifier(*B, Record);
5469 Stream.EmitRecord(serialization::DECL_CXX_BASE_SPECIFIERS, Record);
Douglas Gregord5853042010-10-30 04:28:16 +00005470
5471 // Flush any expressions that were written as part of the base specifiers.
5472 FlushStmts();
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005473 }
5474
Richard Smithc2bb8182015-03-24 06:36:48 +00005475 assert(N == CXXBaseSpecifiersToWrite.size() &&
5476 "added more base specifiers while writing base specifiers");
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005477 CXXBaseSpecifiersToWrite.clear();
5478}
5479
Alexis Hunt1d792652011-01-08 20:30:50 +00005480void ASTWriter::AddCXXCtorInitializers(
5481 const CXXCtorInitializer * const *CtorInitializers,
5482 unsigned NumCtorInitializers,
5483 RecordDataImpl &Record) {
5484 Record.push_back(NumCtorInitializers);
5485 for (unsigned i=0; i != NumCtorInitializers; ++i) {
5486 const CXXCtorInitializer *Init = CtorInitializers[i];
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005487
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005488 if (Init->isBaseInitializer()) {
Alexis Hunt37a477f2011-05-04 01:19:08 +00005489 Record.push_back(CTOR_INITIALIZER_BASE);
Douglas Gregord73f3dd2011-11-01 01:16:03 +00005490 AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005491 Record.push_back(Init->isBaseVirtual());
Alexis Hunt37a477f2011-05-04 01:19:08 +00005492 } else if (Init->isDelegatingInitializer()) {
5493 Record.push_back(CTOR_INITIALIZER_DELEGATING);
Douglas Gregord73f3dd2011-11-01 01:16:03 +00005494 AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
Alexis Hunt37a477f2011-05-04 01:19:08 +00005495 } else if (Init->isMemberInitializer()){
5496 Record.push_back(CTOR_INITIALIZER_MEMBER);
5497 AddDeclRef(Init->getMember(), Record);
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005498 } else {
Alexis Hunt37a477f2011-05-04 01:19:08 +00005499 Record.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
5500 AddDeclRef(Init->getIndirectMember(), Record);
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005501 }
Francois Pichetd583da02010-12-04 09:14:42 +00005502
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005503 AddSourceLocation(Init->getMemberLocation(), Record);
5504 AddStmt(Init->getInit());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005505 AddSourceLocation(Init->getLParenLoc(), Record);
5506 AddSourceLocation(Init->getRParenLoc(), Record);
5507 Record.push_back(Init->isWritten());
5508 if (Init->isWritten()) {
5509 Record.push_back(Init->getSourceOrder());
5510 } else {
5511 Record.push_back(Init->getNumArrayIndices());
5512 for (unsigned i=0, e=Init->getNumArrayIndices(); i != e; ++i)
5513 AddDeclRef(Init->getArrayIndex(i), Record);
5514 }
5515 }
5516}
5517
Richard Smithc2bb8182015-03-24 06:36:48 +00005518void ASTWriter::FlushCXXCtorInitializers() {
5519 RecordData Record;
5520
5521 unsigned N = CXXCtorInitializersToWrite.size();
Daniel Jasperc77b0a12015-03-24 08:06:38 +00005522 (void)N; // Silence unused warning in non-assert builds.
Richard Smithc2bb8182015-03-24 06:36:48 +00005523 for (auto &Init : CXXCtorInitializersToWrite) {
5524 Record.clear();
5525
5526 // Record the offset of this mem-initializer list.
5527 unsigned Index = Init.ID - 1;
5528 if (Index == CXXCtorInitializersOffsets.size())
5529 CXXCtorInitializersOffsets.push_back(Stream.GetCurrentBitNo());
5530 else {
5531 if (Index > CXXCtorInitializersOffsets.size())
5532 CXXCtorInitializersOffsets.resize(Index + 1);
5533 CXXCtorInitializersOffsets[Index] = Stream.GetCurrentBitNo();
5534 }
5535
5536 AddCXXCtorInitializers(Init.Inits.data(), Init.Inits.size(), Record);
5537 Stream.EmitRecord(serialization::DECL_CXX_CTOR_INITIALIZERS, Record);
5538
5539 // Flush any expressions that were written as part of the initializers.
5540 FlushStmts();
5541 }
5542
5543 assert(N == CXXCtorInitializersToWrite.size() &&
5544 "added more ctor initializers while writing ctor initializers");
5545 CXXCtorInitializersToWrite.clear();
5546}
5547
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005548void ASTWriter::AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record) {
Richard Smith053f6c62014-05-16 23:01:30 +00005549 auto &Data = D->data();
Douglas Gregor99ae8062012-02-14 17:54:36 +00005550 Record.push_back(Data.IsLambda);
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005551 Record.push_back(Data.UserDeclaredConstructor);
Richard Smith328aae52012-11-30 05:11:39 +00005552 Record.push_back(Data.UserDeclaredSpecialMembers);
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005553 Record.push_back(Data.Aggregate);
5554 Record.push_back(Data.PlainOldData);
5555 Record.push_back(Data.Empty);
5556 Record.push_back(Data.Polymorphic);
5557 Record.push_back(Data.Abstract);
Chandler Carruth583edf82011-04-30 10:07:30 +00005558 Record.push_back(Data.IsStandardLayout);
Chandler Carruthb1963742011-04-30 09:17:45 +00005559 Record.push_back(Data.HasNoNonEmptyBases);
5560 Record.push_back(Data.HasPrivateFields);
5561 Record.push_back(Data.HasProtectedFields);
5562 Record.push_back(Data.HasPublicFields);
Douglas Gregor61226d32011-05-13 01:05:07 +00005563 Record.push_back(Data.HasMutableFields);
Richard Smithab44d5b2013-12-10 08:25:00 +00005564 Record.push_back(Data.HasVariantMembers);
Richard Smith561fb152012-02-25 07:33:38 +00005565 Record.push_back(Data.HasOnlyCMembers);
Richard Smithe2648ba2012-05-07 01:07:30 +00005566 Record.push_back(Data.HasInClassInitializer);
Richard Smith593f9932012-12-08 02:01:17 +00005567 Record.push_back(Data.HasUninitializedReferenceMember);
Nico Weber6a6376b2016-02-19 01:52:46 +00005568 Record.push_back(Data.HasUninitializedFields);
Richard Smith6b02d462012-12-08 08:32:28 +00005569 Record.push_back(Data.NeedOverloadResolutionForMoveConstructor);
5570 Record.push_back(Data.NeedOverloadResolutionForMoveAssignment);
5571 Record.push_back(Data.NeedOverloadResolutionForDestructor);
5572 Record.push_back(Data.DefaultedMoveConstructorIsDeleted);
5573 Record.push_back(Data.DefaultedMoveAssignmentIsDeleted);
5574 Record.push_back(Data.DefaultedDestructorIsDeleted);
Richard Smith328aae52012-11-30 05:11:39 +00005575 Record.push_back(Data.HasTrivialSpecialMembers);
Richard Smithb45a6f72014-04-17 20:33:01 +00005576 Record.push_back(Data.DeclaredNonTrivialSpecialMembers);
Richard Smith328aae52012-11-30 05:11:39 +00005577 Record.push_back(Data.HasIrrelevantDestructor);
Richard Smith111af8d2011-08-10 18:11:37 +00005578 Record.push_back(Data.HasConstexprNonCopyMoveConstructor);
Nico Weber72c57f42016-02-24 20:58:14 +00005579 Record.push_back(Data.HasDefaultedDefaultConstructor);
Richard Smith561fb152012-02-25 07:33:38 +00005580 Record.push_back(Data.DefaultedDefaultConstructorIsConstexpr);
Richard Smith561fb152012-02-25 07:33:38 +00005581 Record.push_back(Data.HasConstexprDefaultConstructor);
Chandler Carruthe71d0622011-04-24 02:49:34 +00005582 Record.push_back(Data.HasNonLiteralTypeFieldsOrBases);
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005583 Record.push_back(Data.ComputedVisibleConversions);
Alexis Huntea6f0322011-05-11 22:34:38 +00005584 Record.push_back(Data.UserProvidedDefaultConstructor);
Richard Smith328aae52012-11-30 05:11:39 +00005585 Record.push_back(Data.DeclaredSpecialMembers);
Richard Smith1c33fe82012-11-28 06:23:12 +00005586 Record.push_back(Data.ImplicitCopyConstructorHasConstParam);
5587 Record.push_back(Data.ImplicitCopyAssignmentHasConstParam);
5588 Record.push_back(Data.HasDeclaredCopyConstructorWithConstParam);
5589 Record.push_back(Data.HasDeclaredCopyAssignmentWithConstParam);
Richard Smith561fb152012-02-25 07:33:38 +00005590 // IsLambda bit is already saved.
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005591
5592 Record.push_back(Data.NumBases);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005593 if (Data.NumBases > 0)
5594 AddCXXBaseSpecifiersRef(Data.getBases(), Data.getBases() + Data.NumBases,
5595 Record);
5596
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005597 // FIXME: Make VBases lazily computed when needed to avoid storing them.
5598 Record.push_back(Data.NumVBases);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005599 if (Data.NumVBases > 0)
5600 AddCXXBaseSpecifiersRef(Data.getVBases(), Data.getVBases() + Data.NumVBases,
5601 Record);
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005602
Richard Smitha4ba74c2013-08-30 04:46:40 +00005603 AddUnresolvedSet(Data.Conversions.get(*Context), Record);
5604 AddUnresolvedSet(Data.VisibleConversions.get(*Context), Record);
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005605 // Data.Definition is the owning decl, no need to write it.
Richard Smith68ad0e72013-06-26 02:41:25 +00005606 AddDeclRef(D->getFirstFriend(), Record);
Douglas Gregor99ae8062012-02-14 17:54:36 +00005607
5608 // Add lambda-specific data.
5609 if (Data.IsLambda) {
Richard Smith053f6c62014-05-16 23:01:30 +00005610 auto &Lambda = D->getLambdaData();
Douglas Gregor680e9e02012-02-21 19:11:17 +00005611 Record.push_back(Lambda.Dependent);
Faisal Valic1a6dc42013-10-23 16:10:50 +00005612 Record.push_back(Lambda.IsGenericLambda);
5613 Record.push_back(Lambda.CaptureDefault);
Douglas Gregor99ae8062012-02-14 17:54:36 +00005614 Record.push_back(Lambda.NumCaptures);
5615 Record.push_back(Lambda.NumExplicitCaptures);
Douglas Gregor63798542012-02-20 19:44:39 +00005616 Record.push_back(Lambda.ManglingNumber);
Douglas Gregor7fcbd902012-02-21 00:37:24 +00005617 AddDeclRef(Lambda.ContextDecl, Record);
Eli Friedmand564afb2012-09-19 01:18:11 +00005618 AddTypeSourceInfo(Lambda.MethodTyInfo, Record);
Douglas Gregor99ae8062012-02-14 17:54:36 +00005619 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00005620 const LambdaCapture &Capture = Lambda.Captures[I];
Douglas Gregor99ae8062012-02-14 17:54:36 +00005621 AddSourceLocation(Capture.getLocation(), Record);
5622 Record.push_back(Capture.isImplicit());
Richard Smithba71c082013-05-16 06:20:58 +00005623 Record.push_back(Capture.getCaptureKind());
5624 switch (Capture.getCaptureKind()) {
Faisal Validc6b5962016-03-21 09:25:37 +00005625 case LCK_StarThis:
Richard Smithba71c082013-05-16 06:20:58 +00005626 case LCK_This:
Alexey Bataev39c81e22014-08-28 04:28:19 +00005627 case LCK_VLAType:
Richard Smithba71c082013-05-16 06:20:58 +00005628 break;
5629 case LCK_ByCopy:
Richard Smithbb13c9a2013-09-28 04:02:39 +00005630 case LCK_ByRef:
Richard Smithba71c082013-05-16 06:20:58 +00005631 VarDecl *Var =
Craig Toppera13603a2014-05-22 05:54:18 +00005632 Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
Richard Smithba71c082013-05-16 06:20:58 +00005633 AddDeclRef(Var, Record);
5634 AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
5635 : SourceLocation(),
5636 Record);
5637 break;
5638 }
Douglas Gregor99ae8062012-02-14 17:54:36 +00005639 }
5640 }
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005641}
5642
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005643void ASTWriter::ReaderInitialized(ASTReader *Reader) {
Sebastian Redl07a89a82010-07-30 00:29:29 +00005644 assert(Reader && "Cannot remove chain");
Douglas Gregordf0c1512011-08-18 04:12:04 +00005645 assert((!Chain || Chain == Reader) && "Cannot replace chain");
Sebastian Redl07a89a82010-07-30 00:29:29 +00005646 assert(FirstDeclID == NextDeclID &&
5647 FirstTypeID == NextTypeID &&
5648 FirstIdentID == NextIdentID &&
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005649 FirstMacroID == NextMacroID &&
Douglas Gregor253eefe2011-12-01 00:59:36 +00005650 FirstSubmoduleID == NextSubmoduleID &&
Sebastian Redld95a56e2010-08-04 18:21:41 +00005651 FirstSelectorID == NextSelectorID &&
Sebastian Redl07a89a82010-07-30 00:29:29 +00005652 "Setting chain after writing has started.");
Douglas Gregor925296b2011-07-19 16:10:42 +00005653
Sebastian Redl07a89a82010-07-30 00:29:29 +00005654 Chain = Reader;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005655
Richard Smith7f330cd2015-03-18 01:42:29 +00005656 // Note, this will get called multiple times, once one the reader starts up
5657 // and again each time it's done reading a PCH or module.
Douglas Gregordf0c1512011-08-18 04:12:04 +00005658 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
5659 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
5660 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005661 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
Douglas Gregor253eefe2011-12-01 00:59:36 +00005662 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
Douglas Gregordf0c1512011-08-18 04:12:04 +00005663 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005664 NextDeclID = FirstDeclID;
5665 NextTypeID = FirstTypeID;
5666 NextIdentID = FirstIdentID;
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005667 NextMacroID = FirstMacroID;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005668 NextSelectorID = FirstSelectorID;
Douglas Gregor253eefe2011-12-01 00:59:36 +00005669 NextSubmoduleID = FirstSubmoduleID;
Sebastian Redl07a89a82010-07-30 00:29:29 +00005670}
5671
Sebastian Redl539c5062010-08-18 23:57:32 +00005672void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005673 // Always keep the highest ID. See \p TypeRead() for more information.
5674 IdentID &StoredID = IdentifierIDs[II];
5675 if (ID > StoredID)
5676 StoredID = ID;
Sebastian Redlff4a2952010-07-23 23:49:55 +00005677}
5678
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005679void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005680 // Always keep the highest ID. See \p TypeRead() for more information.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005681 MacroID &StoredID = MacroIDs[MI];
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005682 if (ID > StoredID)
5683 StoredID = ID;
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005684}
5685
Argyrios Kyrtzidisbb5c7eae2010-08-20 16:03:59 +00005686void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005687 // Always take the highest-numbered type index. This copes with an interesting
5688 // case for chained AST writing where we schedule writing the type and then,
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005689 // later, deserialize the type from another AST. In this case, we want to
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005690 // keep the higher-numbered entry so that we can properly write it out to
5691 // the AST file.
5692 TypeIdx &StoredIdx = TypeIdxs[T];
5693 if (Idx.getIndex() >= StoredIdx.getIndex())
5694 StoredIdx = Idx;
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00005695}
5696
Sebastian Redl539c5062010-08-18 23:57:32 +00005697void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005698 // Always keep the highest ID. See \p TypeRead() for more information.
5699 SelectorID &StoredID = SelectorIDs[S];
5700 if (ID > StoredID)
5701 StoredID = ID;
Sebastian Redl834bb972010-08-04 17:20:04 +00005702}
Douglas Gregor91096292010-10-02 19:29:26 +00005703
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00005704void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
Richard Smith66a81862015-05-04 02:25:31 +00005705 MacroDefinitionRecord *MD) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00005706 assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
Douglas Gregor91096292010-10-02 19:29:26 +00005707 MacroDefinitions[MD] = ID;
5708}
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005709
Douglas Gregore37a85a2011-12-02 17:30:13 +00005710void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
5711 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
5712 SubmoduleIDs[Mod] = ID;
5713}
5714
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005715void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
John McCallf937c022011-10-07 06:10:15 +00005716 assert(D->isCompleteDefinition());
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005717 assert(!WritingAST && "Already writing the AST!");
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005718 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005719 // We are interested when a PCH decl is modified.
Douglas Gregorb3722e22011-09-09 23:01:35 +00005720 if (RD->isFromASTFile()) {
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005721 // A forward reference was mutated into a definition. Rewrite it.
5722 // FIXME: This happens during template instantiation, should we
5723 // have created a new definition decl instead ?
Richard Smithcd45dbc2014-04-19 03:48:30 +00005724 assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
5725 "completed a tag from another module but not by instantiation?");
5726 DeclUpdates[RD].push_back(
5727 DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION));
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005728 }
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005729 }
5730}
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005731
Richard Smithf983f7f2015-10-13 00:23:25 +00005732static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) {
5733 if (D->isFromASTFile())
5734 return true;
5735
5736 // If we've not loaded any modules, this can't be imported.
5737 if (!Chain || !Chain->getModuleManager().size())
5738 return false;
5739
5740 // The predefined __va_list_tag struct is imported if we imported any decls.
5741 // FIXME: This is a gross hack.
5742 return D == D->getASTContext().getVaListTagDecl();
5743}
5744
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005745void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
Vassil Vassilev632eac32016-03-16 11:17:04 +00005746 // TU is handled elsewhere.
5747 if (isa<TranslationUnitDecl>(DC))
5748 return;
5749
5750 // Namespaces are handled elsewhere, except for template instantiations of
5751 // FunctionTemplateDecls in namespaces. We are interested in cases where the
5752 // local instantiations are added to an imported context. Only happens when
5753 // adding ADL lookup candidates, for example templated friends.
5754 if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None &&
5755 !isa<FunctionTemplateDecl>(D))
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005756 return;
5757
Richard Smithf983f7f2015-10-13 00:23:25 +00005758 // We're only interested in cases where a local declaration is added to an
5759 // imported context.
5760 if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC)))
5761 return;
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005762
Richard Smith0f4e2c42015-08-06 04:23:48 +00005763 assert(DC == DC->getPrimaryContext() && "added to non-primary context");
Douglas Gregor9f782892013-01-21 15:25:38 +00005764 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
Richard Smithe9a8bc32014-09-30 00:45:29 +00005765 assert(!WritingAST && "Already writing the AST!");
Richard Smithf983f7f2015-10-13 00:23:25 +00005766 if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) {
5767 // We're adding a visible declaration to a predefined decl context. Ensure
5768 // that we write out all of its lookup results so we don't get a nasty
5769 // surprise when we try to emit its lookup table.
5770 for (auto *Child : DC->decls())
5771 UpdatingVisibleDecls.push_back(Child);
5772 }
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005773 UpdatingVisibleDecls.push_back(D);
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005774}
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005775
5776void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
5777 assert(D->isImplicit());
Richard Smithf983f7f2015-10-13 00:23:25 +00005778
5779 // We're only interested in cases where a local declaration is added to an
5780 // imported context.
5781 if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD))
5782 return;
5783
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005784 if (!isa<CXXMethodDecl>(D))
Richard Smithf983f7f2015-10-13 00:23:25 +00005785 return;
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005786
5787 // A decl coming from PCH was modified.
John McCallf937c022011-10-07 06:10:15 +00005788 assert(RD->isCompleteDefinition());
Richard Smithe9a8bc32014-09-30 00:45:29 +00005789 assert(!WritingAST && "Already writing the AST!");
Aaron Ballman4f45b712014-03-21 15:22:56 +00005790 DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005791}
Argyrios Kyrtzidis402dbbb2010-10-28 07:38:42 +00005792
Richard Smith564417a2014-03-20 21:47:22 +00005793void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005794 assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
5795 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00005796 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005797 // If we don't already know the exception specification for this redecl
5798 // chain, add an update record for it.
5799 if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
5800 ->getType()
5801 ->castAs<FunctionProtoType>()
5802 ->getExceptionSpecType()))
5803 DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
5804 });
Richard Smith564417a2014-03-20 21:47:22 +00005805}
5806
Richard Smith1fa5d642013-05-11 05:45:24 +00005807void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
5808 assert(!WritingAST && "Already writing the AST!");
Richard Smith9e2341d2015-03-23 03:25:59 +00005809 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00005810 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005811 DeclUpdates[D].push_back(
5812 DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
5813 });
Richard Smith1fa5d642013-05-11 05:45:24 +00005814}
5815
Richard Smithf8134002015-03-10 01:41:22 +00005816void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
5817 const FunctionDecl *Delete) {
5818 assert(!WritingAST && "Already writing the AST!");
5819 assert(Delete && "Not given an operator delete");
Richard Smith9e2341d2015-03-23 03:25:59 +00005820 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00005821 Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005822 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete));
5823 });
Richard Smithf8134002015-03-10 01:41:22 +00005824}
5825
Sebastian Redlab238a72011-04-24 16:28:06 +00005826void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005827 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005828 if (!D->isFromASTFile())
Sebastian Redlab238a72011-04-24 16:28:06 +00005829 return; // Declaration not imported from PCH.
5830
Richard Smith4d235792014-08-07 18:53:08 +00005831 // Implicit function decl from a PCH was defined.
5832 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
Sebastian Redlab238a72011-04-24 16:28:06 +00005833}
5834
Richard Smithd28ac5b2014-03-22 23:33:22 +00005835void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
5836 assert(!WritingAST && "Already writing the AST!");
5837 if (!D->isFromASTFile())
5838 return;
5839
Richard Smith9e2341d2015-03-23 03:25:59 +00005840 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
Richard Smithd28ac5b2014-03-22 23:33:22 +00005841}
5842
Sebastian Redl2ac2c722011-04-29 08:19:30 +00005843void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005844 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005845 if (!D->isFromASTFile())
Sebastian Redl2ac2c722011-04-29 08:19:30 +00005846 return;
5847
5848 // Since the actual instantiation is delayed, this really means that we need
5849 // to update the instantiation location.
Richard Smith6ef42932014-03-20 21:02:00 +00005850 DeclUpdates[D].push_back(
Aaron Ballman4f45b712014-03-21 15:22:56 +00005851 DeclUpdate(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER,
5852 D->getMemberSpecializationInfo()->getPointOfInstantiation()));
Sebastian Redl2ac2c722011-04-29 08:19:30 +00005853}
5854
John McCall32791cc2016-01-06 22:34:54 +00005855void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) {
5856 assert(!WritingAST && "Already writing the AST!");
5857 if (!D->isFromASTFile())
5858 return;
5859
5860 DeclUpdates[D].push_back(
5861 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D));
5862}
5863
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00005864void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
5865 const ObjCInterfaceDecl *IFD) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005866 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005867 if (!IFD->isFromASTFile())
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00005868 return; // Declaration not imported from PCH.
Douglas Gregor404cdde2012-01-27 01:47:08 +00005869
5870 assert(IFD->getDefinition() && "Category on a class without a definition?");
5871 ObjCClassesWithCategories.insert(
5872 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00005873}
Argyrios Kyrtzidisb97a4022011-11-12 21:07:46 +00005874
Eli Friedman276dd182013-09-05 00:02:25 +00005875void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
5876 assert(!WritingAST && "Already writing the AST!");
5877 if (!D->isFromASTFile())
5878 return;
5879
Aaron Ballman4f45b712014-03-21 15:22:56 +00005880 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
Eli Friedman276dd182013-09-05 00:02:25 +00005881}
Alexey Bataev97720002014-11-11 04:05:39 +00005882
5883void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
5884 assert(!WritingAST && "Already writing the AST!");
5885 if (!D->isFromASTFile())
5886 return;
5887
5888 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE));
5889}
Richard Smith65ebb4a2015-03-26 04:09:53 +00005890
Richard Smith4caa4492015-05-15 02:34:32 +00005891void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
Richard Smith65ebb4a2015-03-26 04:09:53 +00005892 assert(!WritingAST && "Already writing the AST!");
5893 assert(D->isHidden() && "expected a hidden declaration");
Richard Smith4caa4492015-05-15 02:34:32 +00005894 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M));
Richard Smith65ebb4a2015-03-26 04:09:53 +00005895}
Alex Denisovfde64952015-06-26 05:28:36 +00005896
5897void ASTWriter::AddedAttributeToRecord(const Attr *Attr,
5898 const RecordDecl *Record) {
5899 assert(!WritingAST && "Already writing the AST!");
5900 if (!Record->isFromASTFile())
5901 return;
5902 DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr));
5903}