blob: 72b2bf6d1689d24ff40750515733f0d4e92cc5c3 [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"
Argyrios Kyrtzidis4bd97102010-08-20 16:03:52 +000015#include "ASTCommon.h"
Richard Smithd88a7f12015-09-01 20:35:42 +000016#include "ASTReaderInternals.h"
17#include "MultiOnDiskHashTable.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclContextInternals.h"
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +000021#include "clang/AST/DeclFriend.h"
Richard Smith961eae52014-03-25 01:14:22 +000022#include "clang/AST/DeclLookups.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/AST/DeclTemplate.h"
Douglas Gregorfeb84b02009-04-14 21:18:50 +000024#include "clang/AST/Expr.h"
John McCallbfd822c2010-08-24 07:32:53 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000026#include "clang/AST/Type.h"
John McCall8f115c62009-10-16 21:56:05 +000027#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000028#include "clang/Basic/DiagnosticOptions.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000029#include "clang/Basic/FileManager.h"
Chris Lattner226efd32010-11-23 19:19:34 +000030#include "clang/Basic/FileSystemStatCache.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000031#include "clang/Basic/SourceManager.h"
Douglas Gregor4c7626e2009-04-13 16:31:14 +000032#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregorbfbde532009-04-10 21:16:55 +000033#include "clang/Basic/TargetInfo.h"
Douglas Gregorcb177f12012-10-16 23:40:58 +000034#include "clang/Basic/TargetOptions.h"
Douglas Gregor7b71e632009-04-27 22:23:34 +000035#include "clang/Basic/Version.h"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000036#include "clang/Basic/VersionTuple.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "clang/Lex/HeaderSearch.h"
38#include "clang/Lex/HeaderSearchOptions.h"
39#include "clang/Lex/MacroInfo.h"
40#include "clang/Lex/PreprocessingRecord.h"
41#include "clang/Lex/Preprocessor.h"
42#include "clang/Lex/PreprocessorOptions.h"
43#include "clang/Sema/IdentifierResolver.h"
44#include "clang/Sema/Sema.h"
45#include "clang/Serialization/ASTReader.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000046#include "clang/Serialization/ModuleFileExtension.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"
Douglas Gregora7f71a92009-04-10 03:52:48 +000055#include "llvm/Support/MemoryBuffer.h"
Justin Bognerbb094f02014-04-18 19:57:06 +000056#include "llvm/Support/OnDiskHashTable.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000057#include "llvm/Support/Path.h"
Ben Langmuir487ea142014-10-23 18:05:36 +000058#include "llvm/Support/Process.h"
Douglas Gregor925296b2011-07-19 16:10:42 +000059#include <algorithm>
Chris Lattner225dd6c2009-04-11 18:40:46 +000060#include <cstdio>
Douglas Gregor09b69892011-02-10 17:09:37 +000061#include <string.h>
Douglas Gregor925296b2011-07-19 16:10:42 +000062#include <utility>
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +000063
Douglas Gregoref84c4b2009-04-09 22:27:44 +000064using namespace clang;
Sebastian Redl539c5062010-08-18 23:57:32 +000065using namespace clang::serialization;
Douglas Gregoref84c4b2009-04-09 22:27:44 +000066
Sebastian Redl3df5a082010-07-30 17:03:48 +000067template <typename T, typename Allocator>
Reid Kleckner012665e2015-05-21 00:13:09 +000068static StringRef bytes(const std::vector<T, Allocator> &v) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000069 if (v.empty()) return StringRef();
70 return StringRef(reinterpret_cast<const char*>(&v[0]),
Benjamin Kramerd47a12a2011-04-24 17:44:50 +000071 sizeof(T) * v.size());
Sebastian Redl3df5a082010-07-30 17:03:48 +000072}
Benjamin Kramerd47a12a2011-04-24 17:44:50 +000073
74template <typename T>
Reid Kleckner012665e2015-05-21 00:13:09 +000075static StringRef bytes(const SmallVectorImpl<T> &v) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000076 return StringRef(reinterpret_cast<const char*>(v.data()),
Benjamin Kramerd47a12a2011-04-24 17:44:50 +000077 sizeof(T) * v.size());
Sebastian Redl3df5a082010-07-30 17:03:48 +000078}
79
Douglas Gregoref84c4b2009-04-09 22:27:44 +000080//===----------------------------------------------------------------------===//
81// Type serialization
82//===----------------------------------------------------------------------===//
Chris Lattner7099dbc2009-04-27 06:16:06 +000083
Richard Smith290d8012016-04-06 17:06:00 +000084namespace clang {
Sebastian Redl42a0f6a2010-08-18 23:56:27 +000085 class ASTTypeWriter {
Sebastian Redl55c0ad52010-08-18 23:56:21 +000086 ASTWriter &Writer;
Richard Smith69c82bf2016-04-01 22:52:03 +000087 ASTRecordWriter Record;
Douglas Gregoref84c4b2009-04-09 22:27:44 +000088
Douglas Gregoref84c4b2009-04-09 22:27:44 +000089 /// \brief Type code that corresponds to the record generated.
Sebastian Redl539c5062010-08-18 23:57:32 +000090 TypeCode Code;
Richard Smith01b2cb42014-07-26 06:37:51 +000091 /// \brief Abbreviation to use for the record, if any.
92 unsigned AbbrevToUse;
Douglas Gregoref84c4b2009-04-09 22:27:44 +000093
Richard Smith290d8012016-04-06 17:06:00 +000094 public:
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +000095 ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
Richard Smith290d8012016-04-06 17:06:00 +000096 : Writer(Writer), Record(Writer, Record), Code((TypeCode)0), AbbrevToUse(0) { }
97
98 uint64_t Emit() {
99 return Record.Emit(Code, AbbrevToUse);
100 }
101
102 void Visit(QualType T) {
103 if (T.hasLocalNonFastQualifiers()) {
104 Qualifiers Qs = T.getLocalQualifiers();
105 Record.AddTypeRef(T.getLocalUnqualifiedType());
106 Record.push_back(Qs.getAsOpaqueValue());
107 Code = TYPE_EXT_QUAL;
108 AbbrevToUse = Writer.TypeExtQualAbbrev;
109 } else {
110 switch (T->getTypeClass()) {
111 // For all of the concrete, non-dependent types, call the
112 // appropriate visitor function.
113#define TYPE(Class, Base) \
114 case Type::Class: Visit##Class##Type(cast<Class##Type>(T)); break;
115#define ABSTRACT_TYPE(Class, Base)
116#include "clang/AST/TypeNodes.def"
117 }
118 }
119 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000120
121 void VisitArrayType(const ArrayType *T);
122 void VisitFunctionType(const FunctionType *T);
123 void VisitTagType(const TagType *T);
124
125#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
126#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000127#include "clang/AST/TypeNodes.def"
128 };
Richard Smith290d8012016-04-06 17:06:00 +0000129} // end namespace clang
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000130
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000131void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
David Blaikie83d382b2011-09-23 05:06:16 +0000132 llvm_unreachable("Built-in types are never serialized");
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000133}
134
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000135void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000136 Record.AddTypeRef(T->getElementType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000137 Code = TYPE_COMPLEX;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000138}
139
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000140void ASTTypeWriter::VisitPointerType(const PointerType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000141 Record.AddTypeRef(T->getPointeeType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000142 Code = TYPE_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000143}
144
Reid Kleckner8a365022013-06-24 17:51:48 +0000145void ASTTypeWriter::VisitDecayedType(const DecayedType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000146 Record.AddTypeRef(T->getOriginalType());
Reid Kleckner8a365022013-06-24 17:51:48 +0000147 Code = TYPE_DECAYED;
148}
149
Reid Kleckner0503a872013-12-05 01:23:43 +0000150void ASTTypeWriter::VisitAdjustedType(const AdjustedType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000151 Record.AddTypeRef(T->getOriginalType());
152 Record.AddTypeRef(T->getAdjustedType());
Reid Kleckner0503a872013-12-05 01:23:43 +0000153 Code = TYPE_ADJUSTED;
154}
155
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000156void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000157 Record.AddTypeRef(T->getPointeeType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000158 Code = TYPE_BLOCK_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000159}
160
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000161void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000162 Record.AddTypeRef(T->getPointeeTypeAsWritten());
Richard Smith0f538462011-04-12 10:38:03 +0000163 Record.push_back(T->isSpelledAsLValue());
Sebastian Redl539c5062010-08-18 23:57:32 +0000164 Code = TYPE_LVALUE_REFERENCE;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000165}
166
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000167void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000168 Record.AddTypeRef(T->getPointeeTypeAsWritten());
Sebastian Redl539c5062010-08-18 23:57:32 +0000169 Code = TYPE_RVALUE_REFERENCE;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000170}
171
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000172void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000173 Record.AddTypeRef(T->getPointeeType());
174 Record.AddTypeRef(QualType(T->getClass(), 0));
Sebastian Redl539c5062010-08-18 23:57:32 +0000175 Code = TYPE_MEMBER_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000176}
177
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000178void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000179 Record.AddTypeRef(T->getElementType());
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000180 Record.push_back(T->getSizeModifier()); // FIXME: stable values
John McCall8ccfcb52009-09-24 19:53:00 +0000181 Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000182}
183
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000184void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000185 VisitArrayType(T);
Richard Smith69c82bf2016-04-01 22:52:03 +0000186 Record.AddAPInt(T->getSize());
Sebastian Redl539c5062010-08-18 23:57:32 +0000187 Code = TYPE_CONSTANT_ARRAY;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000188}
189
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000190void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000191 VisitArrayType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000192 Code = TYPE_INCOMPLETE_ARRAY;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000193}
194
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000195void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000196 VisitArrayType(T);
Richard Smith69c82bf2016-04-01 22:52:03 +0000197 Record.AddSourceLocation(T->getLBracketLoc());
198 Record.AddSourceLocation(T->getRBracketLoc());
Richard Smith290d8012016-04-06 17:06:00 +0000199 Record.AddStmt(T->getSizeExpr());
Sebastian Redl539c5062010-08-18 23:57:32 +0000200 Code = TYPE_VARIABLE_ARRAY;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000201}
202
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000203void ASTTypeWriter::VisitVectorType(const VectorType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000204 Record.AddTypeRef(T->getElementType());
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000205 Record.push_back(T->getNumElements());
Bob Wilsonaeb56442010-11-10 21:56:12 +0000206 Record.push_back(T->getVectorKind());
Sebastian Redl539c5062010-08-18 23:57:32 +0000207 Code = TYPE_VECTOR;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000208}
209
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000210void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000211 VisitVectorType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000212 Code = TYPE_EXT_VECTOR;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000213}
214
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000215void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000216 Record.AddTypeRef(T->getReturnType());
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000217 FunctionType::ExtInfo C = T->getExtInfo();
218 Record.push_back(C.getNoReturn());
Eli Friedmanc5b20b52011-04-09 08:18:08 +0000219 Record.push_back(C.getHasRegParm());
Rafael Espindola49b85ab2010-03-30 22:15:11 +0000220 Record.push_back(C.getRegParm());
Douglas Gregor8c940862010-01-18 17:14:39 +0000221 // FIXME: need to stabilize encoding of calling convention...
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000222 Record.push_back(C.getCC());
John McCall31168b02011-06-15 23:02:42 +0000223 Record.push_back(C.getProducesResult());
Richard Smith01b2cb42014-07-26 06:37:51 +0000224
225 if (C.getHasRegParm() || C.getRegParm() || C.getProducesResult())
226 AbbrevToUse = 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000227}
228
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000229void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000230 VisitFunctionType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000231 Code = TYPE_FUNCTION_NO_PROTO;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000232}
233
Richard Smith290d8012016-04-06 17:06:00 +0000234static void addExceptionSpec(const FunctionProtoType *T,
235 ASTRecordWriter &Record) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000236 Record.push_back(T->getExceptionSpecType());
237 if (T->getExceptionSpecType() == EST_Dynamic) {
238 Record.push_back(T->getNumExceptions());
239 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
Richard Smith69c82bf2016-04-01 22:52:03 +0000240 Record.AddTypeRef(T->getExceptionType(I));
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000241 } else if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
Richard Smith290d8012016-04-06 17:06:00 +0000242 Record.AddStmt(T->getNoexceptExpr());
Richard Smith8b987a92012-04-21 17:47:47 +0000243 } else if (T->getExceptionSpecType() == EST_Uninstantiated) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000244 Record.AddDeclRef(T->getExceptionSpecDecl());
245 Record.AddDeclRef(T->getExceptionSpecTemplate());
Richard Smithd3b5c9082012-07-27 04:22:15 +0000246 } else if (T->getExceptionSpecType() == EST_Unevaluated) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000247 Record.AddDeclRef(T->getExceptionSpecDecl());
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000248 }
Richard Smith564417a2014-03-20 21:47:22 +0000249}
250
251void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
252 VisitFunctionType(T);
Richard Smith01b2cb42014-07-26 06:37:51 +0000253
Richard Smith564417a2014-03-20 21:47:22 +0000254 Record.push_back(T->isVariadic());
255 Record.push_back(T->hasTrailingReturn());
256 Record.push_back(T->getTypeQuals());
257 Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
Richard Smith290d8012016-04-06 17:06:00 +0000258 addExceptionSpec(T, Record);
Richard Smith01b2cb42014-07-26 06:37:51 +0000259
260 Record.push_back(T->getNumParams());
261 for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
Richard Smith69c82bf2016-04-01 22:52:03 +0000262 Record.AddTypeRef(T->getParamType(I));
Richard Smith01b2cb42014-07-26 06:37:51 +0000263
John McCall18afab72016-03-01 00:49:02 +0000264 if (T->hasExtParameterInfos()) {
265 for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
266 Record.push_back(T->getExtParameterInfo(I).getOpaqueValue());
267 }
268
Richard Smith01b2cb42014-07-26 06:37:51 +0000269 if (T->isVariadic() || T->hasTrailingReturn() || T->getTypeQuals() ||
John McCall18afab72016-03-01 00:49:02 +0000270 T->getRefQualifier() || T->getExceptionSpecType() != EST_None ||
271 T->hasExtParameterInfos())
Richard Smith01b2cb42014-07-26 06:37:51 +0000272 AbbrevToUse = 0;
273
Sebastian Redl539c5062010-08-18 23:57:32 +0000274 Code = TYPE_FUNCTION_PROTO;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000275}
276
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000277void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000278 Record.AddDeclRef(T->getDecl());
Sebastian Redl539c5062010-08-18 23:57:32 +0000279 Code = TYPE_UNRESOLVED_USING;
John McCallb96ec562009-12-04 22:46:56 +0000280}
John McCallb96ec562009-12-04 22:46:56 +0000281
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000282void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000283 Record.AddDeclRef(T->getDecl());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +0000284 assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
Richard Smith69c82bf2016-04-01 22:52:03 +0000285 Record.AddTypeRef(T->getCanonicalTypeInternal());
Sebastian Redl539c5062010-08-18 23:57:32 +0000286 Code = TYPE_TYPEDEF;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000287}
288
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000289void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
Richard Smith290d8012016-04-06 17:06:00 +0000290 Record.AddStmt(T->getUnderlyingExpr());
Sebastian Redl539c5062010-08-18 23:57:32 +0000291 Code = TYPE_TYPEOF_EXPR;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000292}
293
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000294void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000295 Record.AddTypeRef(T->getUnderlyingType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000296 Code = TYPE_TYPEOF;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000297}
298
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000299void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000300 Record.AddTypeRef(T->getUnderlyingType());
Richard Smith290d8012016-04-06 17:06:00 +0000301 Record.AddStmt(T->getUnderlyingExpr());
Sebastian Redl539c5062010-08-18 23:57:32 +0000302 Code = TYPE_DECLTYPE;
Anders Carlsson81df7b82009-06-24 19:06:50 +0000303}
304
Alexis Hunte852b102011-05-24 22:41:36 +0000305void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000306 Record.AddTypeRef(T->getBaseType());
307 Record.AddTypeRef(T->getUnderlyingType());
Alexis Hunte852b102011-05-24 22:41:36 +0000308 Record.push_back(T->getUTTKind());
309 Code = TYPE_UNARY_TRANSFORM;
310}
311
Richard Smith30482bc2011-02-20 03:19:35 +0000312void ASTTypeWriter::VisitAutoType(const AutoType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000313 Record.AddTypeRef(T->getDeducedType());
Richard Smithe301ba22015-11-11 02:02:15 +0000314 Record.push_back((unsigned)T->getKeyword());
Richard Smith27d807c2013-04-30 13:56:41 +0000315 if (T->getDeducedType().isNull())
316 Record.push_back(T->isDependentType());
Richard Smith30482bc2011-02-20 03:19:35 +0000317 Code = TYPE_AUTO;
318}
319
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000320void ASTTypeWriter::VisitTagType(const TagType *T) {
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +0000321 Record.push_back(T->isDependentType());
Richard Smith69c82bf2016-04-01 22:52:03 +0000322 Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +0000323 assert(!T->isBeingDefined() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000324 "Cannot serialize in the middle of a type definition");
325}
326
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000327void ASTTypeWriter::VisitRecordType(const RecordType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000328 VisitTagType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000329 Code = TYPE_RECORD;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000330}
331
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000332void ASTTypeWriter::VisitEnumType(const EnumType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000333 VisitTagType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000334 Code = TYPE_ENUM;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000335}
336
John McCall81904512011-01-06 01:58:22 +0000337void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000338 Record.AddTypeRef(T->getModifiedType());
339 Record.AddTypeRef(T->getEquivalentType());
John McCall81904512011-01-06 01:58:22 +0000340 Record.push_back(T->getAttrKind());
341 Code = TYPE_ATTRIBUTED;
342}
343
Mike Stump11289f42009-09-09 15:08:12 +0000344void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000345ASTTypeWriter::VisitSubstTemplateTypeParmType(
John McCallcebee162009-10-18 09:09:24 +0000346 const SubstTemplateTypeParmType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000347 Record.AddTypeRef(QualType(T->getReplacedParameter(), 0));
348 Record.AddTypeRef(T->getReplacementType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000349 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
John McCallcebee162009-10-18 09:09:24 +0000350}
351
352void
Douglas Gregorada4b792011-01-14 02:55:32 +0000353ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
354 const SubstTemplateTypeParmPackType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000355 Record.AddTypeRef(QualType(T->getReplacedParameter(), 0));
356 Record.AddTemplateArgument(T->getArgumentPack());
Douglas Gregorada4b792011-01-14 02:55:32 +0000357 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK;
358}
359
360void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000361ASTTypeWriter::VisitTemplateSpecializationType(
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000362 const TemplateSpecializationType *T) {
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +0000363 Record.push_back(T->isDependentType());
Richard Smith69c82bf2016-04-01 22:52:03 +0000364 Record.AddTemplateName(T->getTemplateName());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000365 Record.push_back(T->getNumArgs());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +0000366 for (const auto &ArgI : *T)
Richard Smith69c82bf2016-04-01 22:52:03 +0000367 Record.AddTemplateArgument(ArgI);
368 Record.AddTypeRef(T->isTypeAlias() ? T->getAliasedType()
369 : T->isCanonicalUnqualified()
370 ? QualType()
371 : T->getCanonicalTypeInternal());
Sebastian Redl539c5062010-08-18 23:57:32 +0000372 Code = TYPE_TEMPLATE_SPECIALIZATION;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000373}
374
375void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000376ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
Argyrios Kyrtzidis4a57bd02010-06-30 08:49:25 +0000377 VisitArrayType(T);
Richard Smith290d8012016-04-06 17:06:00 +0000378 Record.AddStmt(T->getSizeExpr());
Richard Smith69c82bf2016-04-01 22:52:03 +0000379 Record.AddSourceRange(T->getBracketsRange());
Sebastian Redl539c5062010-08-18 23:57:32 +0000380 Code = TYPE_DEPENDENT_SIZED_ARRAY;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000381}
382
383void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000384ASTTypeWriter::VisitDependentSizedExtVectorType(
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000385 const DependentSizedExtVectorType *T) {
386 // FIXME: Serialize this type (C++ only)
David Blaikie83d382b2011-09-23 05:06:16 +0000387 llvm_unreachable("Cannot serialize dependent sized extended vector types");
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000388}
389
390void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000391ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000392 Record.push_back(T->getDepth());
393 Record.push_back(T->getIndex());
394 Record.push_back(T->isParameterPack());
Richard Smith69c82bf2016-04-01 22:52:03 +0000395 Record.AddDeclRef(T->getDecl());
Sebastian Redl539c5062010-08-18 23:57:32 +0000396 Code = TYPE_TEMPLATE_TYPE_PARM;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000397}
398
399void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000400ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
Argyrios Kyrtzidisbfcacee2010-06-24 08:57:31 +0000401 Record.push_back(T->getKeyword());
Richard Smith69c82bf2016-04-01 22:52:03 +0000402 Record.AddNestedNameSpecifier(T->getQualifier());
403 Record.AddIdentifierRef(T->getIdentifier());
404 Record.AddTypeRef(
405 T->isCanonicalUnqualified() ? QualType() : T->getCanonicalTypeInternal());
Sebastian Redl539c5062010-08-18 23:57:32 +0000406 Code = TYPE_DEPENDENT_NAME;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000407}
408
409void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000410ASTTypeWriter::VisitDependentTemplateSpecializationType(
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000411 const DependentTemplateSpecializationType *T) {
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +0000412 Record.push_back(T->getKeyword());
Richard Smith69c82bf2016-04-01 22:52:03 +0000413 Record.AddNestedNameSpecifier(T->getQualifier());
414 Record.AddIdentifierRef(T->getIdentifier());
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +0000415 Record.push_back(T->getNumArgs());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +0000416 for (const auto &I : *T)
Richard Smith69c82bf2016-04-01 22:52:03 +0000417 Record.AddTemplateArgument(I);
Sebastian Redl539c5062010-08-18 23:57:32 +0000418 Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000419}
420
Douglas Gregord2fa7662010-12-20 02:24:11 +0000421void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000422 Record.AddTypeRef(T->getPattern());
David Blaikie05785d12013-02-20 22:23:23 +0000423 if (Optional<unsigned> NumExpansions = T->getNumExpansions())
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000424 Record.push_back(*NumExpansions + 1);
425 else
426 Record.push_back(0);
Douglas Gregord2fa7662010-12-20 02:24:11 +0000427 Code = TYPE_PACK_EXPANSION;
428}
429
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000430void ASTTypeWriter::VisitParenType(const ParenType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000431 Record.AddTypeRef(T->getInnerType());
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000432 Code = TYPE_PAREN;
433}
434
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000435void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000436 Record.push_back(T->getKeyword());
Richard Smith69c82bf2016-04-01 22:52:03 +0000437 Record.AddNestedNameSpecifier(T->getQualifier());
438 Record.AddTypeRef(T->getNamedType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000439 Code = TYPE_ELABORATED;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000440}
441
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000442void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000443 Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
444 Record.AddTypeRef(T->getInjectedSpecializationType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000445 Code = TYPE_INJECTED_CLASS_NAME;
John McCalle78aac42010-03-10 03:28:59 +0000446}
447
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000448void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000449 Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
Sebastian Redl539c5062010-08-18 23:57:32 +0000450 Code = TYPE_OBJC_INTERFACE;
John McCall8b07ec22010-05-15 11:32:37 +0000451}
452
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000453void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000454 Record.AddTypeRef(T->getBaseType());
Douglas Gregore83b9562015-07-07 03:57:53 +0000455 Record.push_back(T->getTypeArgsAsWritten().size());
456 for (auto TypeArg : T->getTypeArgsAsWritten())
Richard Smith69c82bf2016-04-01 22:52:03 +0000457 Record.AddTypeRef(TypeArg);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000458 Record.push_back(T->getNumProtocols());
Aaron Ballman1683f7b2014-03-17 15:55:30 +0000459 for (const auto *I : T->quals())
Richard Smith69c82bf2016-04-01 22:52:03 +0000460 Record.AddDeclRef(I);
Douglas Gregorab209d82015-07-07 03:58:42 +0000461 Record.push_back(T->isKindOfTypeAsWritten());
Sebastian Redl539c5062010-08-18 23:57:32 +0000462 Code = TYPE_OBJC_OBJECT;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000463}
464
Steve Narofffb4330f2009-06-17 22:40:22 +0000465void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000466ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000467 Record.AddTypeRef(T->getPointeeType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000468 Code = TYPE_OBJC_OBJECT_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000469}
470
Eli Friedman0dfb8892011-10-06 23:00:33 +0000471void
472ASTTypeWriter::VisitAtomicType(const AtomicType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000473 Record.AddTypeRef(T->getValueType());
Eli Friedman0dfb8892011-10-06 23:00:33 +0000474 Code = TYPE_ATOMIC;
475}
476
Xiuli Pan9c14e282016-01-09 12:53:17 +0000477void
478ASTTypeWriter::VisitPipeType(const PipeType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000479 Record.AddTypeRef(T->getElementType());
Xiuli Pan9c14e282016-01-09 12:53:17 +0000480 Code = TYPE_PIPE;
481}
482
John McCall8f115c62009-10-16 21:56:05 +0000483namespace {
484
485class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
Richard Smith290d8012016-04-06 17:06:00 +0000486 ASTRecordWriter &Record;
John McCall8f115c62009-10-16 21:56:05 +0000487
488public:
Richard Smith290d8012016-04-06 17:06:00 +0000489 TypeLocWriter(ASTRecordWriter &Record)
490 : Record(Record) { }
John McCall8f115c62009-10-16 21:56:05 +0000491
John McCall17001972009-10-18 01:05:36 +0000492#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCall8f115c62009-10-16 21:56:05 +0000493#define TYPELOC(CLASS, PARENT) \
John McCall17001972009-10-18 01:05:36 +0000494 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +0000495#include "clang/AST/TypeLocNodes.def"
496
John McCall17001972009-10-18 01:05:36 +0000497 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
498 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +0000499};
500
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +0000501} // end anonymous namespace
John McCall8f115c62009-10-16 21:56:05 +0000502
John McCall17001972009-10-18 01:05:36 +0000503void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
504 // nothing to do
John McCall8f115c62009-10-16 21:56:05 +0000505}
John McCall17001972009-10-18 01:05:36 +0000506void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000507 Record.AddSourceLocation(TL.getBuiltinLoc());
Douglas Gregorc9b7a592010-01-18 18:04:31 +0000508 if (TL.needsExtraLocalData()) {
509 Record.push_back(TL.getWrittenTypeSpec());
510 Record.push_back(TL.getWrittenSignSpec());
511 Record.push_back(TL.getWrittenWidthSpec());
512 Record.push_back(TL.hasModeAttr());
513 }
John McCall8f115c62009-10-16 21:56:05 +0000514}
John McCall17001972009-10-18 01:05:36 +0000515void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000516 Record.AddSourceLocation(TL.getNameLoc());
John McCall8f115c62009-10-16 21:56:05 +0000517}
John McCall17001972009-10-18 01:05:36 +0000518void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000519 Record.AddSourceLocation(TL.getStarLoc());
John McCall8f115c62009-10-16 21:56:05 +0000520}
Reid Kleckner8a365022013-06-24 17:51:48 +0000521void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
522 // nothing to do
523}
Reid Kleckner0503a872013-12-05 01:23:43 +0000524void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
525 // nothing to do
526}
John McCall17001972009-10-18 01:05:36 +0000527void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000528 Record.AddSourceLocation(TL.getCaretLoc());
John McCall8f115c62009-10-16 21:56:05 +0000529}
John McCall17001972009-10-18 01:05:36 +0000530void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000531 Record.AddSourceLocation(TL.getAmpLoc());
John McCall8f115c62009-10-16 21:56:05 +0000532}
John McCall17001972009-10-18 01:05:36 +0000533void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000534 Record.AddSourceLocation(TL.getAmpAmpLoc());
John McCall8f115c62009-10-16 21:56:05 +0000535}
John McCall17001972009-10-18 01:05:36 +0000536void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000537 Record.AddSourceLocation(TL.getStarLoc());
538 Record.AddTypeSourceInfo(TL.getClassTInfo());
John McCall8f115c62009-10-16 21:56:05 +0000539}
John McCall17001972009-10-18 01:05:36 +0000540void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000541 Record.AddSourceLocation(TL.getLBracketLoc());
542 Record.AddSourceLocation(TL.getRBracketLoc());
John McCall17001972009-10-18 01:05:36 +0000543 Record.push_back(TL.getSizeExpr() ? 1 : 0);
544 if (TL.getSizeExpr())
Richard Smith290d8012016-04-06 17:06:00 +0000545 Record.AddStmt(TL.getSizeExpr());
John McCall8f115c62009-10-16 21:56:05 +0000546}
John McCall17001972009-10-18 01:05:36 +0000547void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
548 VisitArrayTypeLoc(TL);
549}
550void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
551 VisitArrayTypeLoc(TL);
552}
553void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
554 VisitArrayTypeLoc(TL);
555}
556void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
557 DependentSizedArrayTypeLoc TL) {
558 VisitArrayTypeLoc(TL);
559}
560void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
561 DependentSizedExtVectorTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000562 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000563}
564void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000565 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000566}
567void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000568 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000569}
570void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000571 Record.AddSourceLocation(TL.getLocalRangeBegin());
572 Record.AddSourceLocation(TL.getLParenLoc());
573 Record.AddSourceLocation(TL.getRParenLoc());
574 Record.AddSourceLocation(TL.getLocalRangeEnd());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +0000575 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000576 Record.AddDeclRef(TL.getParam(i));
John McCall17001972009-10-18 01:05:36 +0000577}
578void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
579 VisitFunctionTypeLoc(TL);
580}
581void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
582 VisitFunctionTypeLoc(TL);
583}
John McCallb96ec562009-12-04 22:46:56 +0000584void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000585 Record.AddSourceLocation(TL.getNameLoc());
John McCallb96ec562009-12-04 22:46:56 +0000586}
John McCall17001972009-10-18 01:05:36 +0000587void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000588 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000589}
590void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000591 Record.AddSourceLocation(TL.getTypeofLoc());
592 Record.AddSourceLocation(TL.getLParenLoc());
593 Record.AddSourceLocation(TL.getRParenLoc());
John McCall17001972009-10-18 01:05:36 +0000594}
595void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000596 Record.AddSourceLocation(TL.getTypeofLoc());
597 Record.AddSourceLocation(TL.getLParenLoc());
598 Record.AddSourceLocation(TL.getRParenLoc());
599 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
John McCall17001972009-10-18 01:05:36 +0000600}
601void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000602 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000603}
Alexis Hunte852b102011-05-24 22:41:36 +0000604void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000605 Record.AddSourceLocation(TL.getKWLoc());
606 Record.AddSourceLocation(TL.getLParenLoc());
607 Record.AddSourceLocation(TL.getRParenLoc());
608 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
Alexis Hunte852b102011-05-24 22:41:36 +0000609}
Richard Smith30482bc2011-02-20 03:19:35 +0000610void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000611 Record.AddSourceLocation(TL.getNameLoc());
Richard Smith30482bc2011-02-20 03:19:35 +0000612}
John McCall17001972009-10-18 01:05:36 +0000613void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000614 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000615}
616void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000617 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000618}
John McCall81904512011-01-06 01:58:22 +0000619void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000620 Record.AddSourceLocation(TL.getAttrNameLoc());
John McCall81904512011-01-06 01:58:22 +0000621 if (TL.hasAttrOperand()) {
622 SourceRange range = TL.getAttrOperandParensRange();
Richard Smith69c82bf2016-04-01 22:52:03 +0000623 Record.AddSourceLocation(range.getBegin());
624 Record.AddSourceLocation(range.getEnd());
John McCall81904512011-01-06 01:58:22 +0000625 }
626 if (TL.hasAttrExprOperand()) {
627 Expr *operand = TL.getAttrExprOperand();
628 Record.push_back(operand ? 1 : 0);
Richard Smith290d8012016-04-06 17:06:00 +0000629 if (operand) Record.AddStmt(operand);
John McCall81904512011-01-06 01:58:22 +0000630 } else if (TL.hasAttrEnumOperand()) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000631 Record.AddSourceLocation(TL.getAttrEnumOperandLoc());
John McCall81904512011-01-06 01:58:22 +0000632 }
633}
John McCall17001972009-10-18 01:05:36 +0000634void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000635 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000636}
John McCallcebee162009-10-18 09:09:24 +0000637void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
638 SubstTemplateTypeParmTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000639 Record.AddSourceLocation(TL.getNameLoc());
John McCallcebee162009-10-18 09:09:24 +0000640}
Douglas Gregorada4b792011-01-14 02:55:32 +0000641void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
642 SubstTemplateTypeParmPackTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000643 Record.AddSourceLocation(TL.getNameLoc());
Douglas Gregorada4b792011-01-14 02:55:32 +0000644}
John McCall17001972009-10-18 01:05:36 +0000645void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
646 TemplateSpecializationTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000647 Record.AddSourceLocation(TL.getTemplateKeywordLoc());
648 Record.AddSourceLocation(TL.getTemplateNameLoc());
649 Record.AddSourceLocation(TL.getLAngleLoc());
650 Record.AddSourceLocation(TL.getRAngleLoc());
John McCall0ad16662009-10-29 08:12:44 +0000651 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000652 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
653 TL.getArgLoc(i).getLocInfo());
John McCall17001972009-10-18 01:05:36 +0000654}
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000655void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000656 Record.AddSourceLocation(TL.getLParenLoc());
657 Record.AddSourceLocation(TL.getRParenLoc());
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000658}
Abramo Bagnara6150c882010-05-11 21:36:43 +0000659void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000660 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
661 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
John McCall17001972009-10-18 01:05:36 +0000662}
John McCalle78aac42010-03-10 03:28:59 +0000663void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000664 Record.AddSourceLocation(TL.getNameLoc());
John McCalle78aac42010-03-10 03:28:59 +0000665}
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +0000666void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000667 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
668 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
669 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000670}
John McCallc392f372010-06-11 00:33:02 +0000671void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
672 DependentTemplateSpecializationTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000673 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
674 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
675 Record.AddSourceLocation(TL.getTemplateKeywordLoc());
676 Record.AddSourceLocation(TL.getTemplateNameLoc());
677 Record.AddSourceLocation(TL.getLAngleLoc());
678 Record.AddSourceLocation(TL.getRAngleLoc());
John McCallc392f372010-06-11 00:33:02 +0000679 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
Richard Smith69c82bf2016-04-01 22:52:03 +0000680 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
681 TL.getArgLoc(I).getLocInfo());
John McCallc392f372010-06-11 00:33:02 +0000682}
Douglas Gregord2fa7662010-12-20 02:24:11 +0000683void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000684 Record.AddSourceLocation(TL.getEllipsisLoc());
Douglas Gregord2fa7662010-12-20 02:24:11 +0000685}
John McCall17001972009-10-18 01:05:36 +0000686void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000687 Record.AddSourceLocation(TL.getNameLoc());
John McCall8b07ec22010-05-15 11:32:37 +0000688}
689void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
690 Record.push_back(TL.hasBaseTypeAsWritten());
Richard Smith69c82bf2016-04-01 22:52:03 +0000691 Record.AddSourceLocation(TL.getTypeArgsLAngleLoc());
692 Record.AddSourceLocation(TL.getTypeArgsRAngleLoc());
Douglas Gregore9d95f12015-07-07 03:57:35 +0000693 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000694 Record.AddTypeSourceInfo(TL.getTypeArgTInfo(i));
695 Record.AddSourceLocation(TL.getProtocolLAngleLoc());
696 Record.AddSourceLocation(TL.getProtocolRAngleLoc());
John McCall17001972009-10-18 01:05:36 +0000697 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000698 Record.AddSourceLocation(TL.getProtocolLoc(i));
John McCall8f115c62009-10-16 21:56:05 +0000699}
John McCallfc93cf92009-10-22 22:37:11 +0000700void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000701 Record.AddSourceLocation(TL.getStarLoc());
John McCallfc93cf92009-10-22 22:37:11 +0000702}
Eli Friedman0dfb8892011-10-06 23:00:33 +0000703void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000704 Record.AddSourceLocation(TL.getKWLoc());
705 Record.AddSourceLocation(TL.getLParenLoc());
706 Record.AddSourceLocation(TL.getRParenLoc());
Eli Friedman0dfb8892011-10-06 23:00:33 +0000707}
Xiuli Pan9c14e282016-01-09 12:53:17 +0000708void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000709 Record.AddSourceLocation(TL.getKWLoc());
Xiuli Pan9c14e282016-01-09 12:53:17 +0000710}
John McCall8f115c62009-10-16 21:56:05 +0000711
Richard Smith01b2cb42014-07-26 06:37:51 +0000712void ASTWriter::WriteTypeAbbrevs() {
713 using namespace llvm;
714
715 BitCodeAbbrev *Abv;
716
717 // Abbreviation for TYPE_EXT_QUAL
718 Abv = new BitCodeAbbrev();
719 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
720 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
721 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals
722 TypeExtQualAbbrev = Stream.EmitAbbrev(Abv);
723
724 // Abbreviation for TYPE_FUNCTION_PROTO
725 Abv = new BitCodeAbbrev();
726 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_FUNCTION_PROTO));
727 // FunctionType
728 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ReturnType
729 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NoReturn
730 Abv->Add(BitCodeAbbrevOp(0)); // HasRegParm
731 Abv->Add(BitCodeAbbrevOp(0)); // RegParm
732 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // CC
733 Abv->Add(BitCodeAbbrevOp(0)); // ProducesResult
734 // FunctionProtoType
735 Abv->Add(BitCodeAbbrevOp(0)); // IsVariadic
736 Abv->Add(BitCodeAbbrevOp(0)); // HasTrailingReturn
737 Abv->Add(BitCodeAbbrevOp(0)); // TypeQuals
738 Abv->Add(BitCodeAbbrevOp(0)); // RefQualifier
739 Abv->Add(BitCodeAbbrevOp(EST_None)); // ExceptionSpec
740 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // NumParams
741 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
742 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Params
743 TypeFunctionProtoAbbrev = Stream.EmitAbbrev(Abv);
744}
745
Chris Lattner19cea4e2009-04-22 05:57:30 +0000746//===----------------------------------------------------------------------===//
Sebastian Redl55c0ad52010-08-18 23:56:21 +0000747// ASTWriter Implementation
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000748//===----------------------------------------------------------------------===//
749
Chris Lattner28fa4e62009-04-26 22:26:21 +0000750static void EmitBlockID(unsigned ID, const char *Name,
751 llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000752 ASTWriter::RecordDataImpl &Record) {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000753 Record.clear();
754 Record.push_back(ID);
755 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
756
757 // Emit the block name if present.
Craig Toppera13603a2014-05-22 05:54:18 +0000758 if (!Name || Name[0] == 0)
759 return;
Chris Lattner28fa4e62009-04-26 22:26:21 +0000760 Record.clear();
761 while (*Name)
762 Record.push_back(*Name++);
763 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
764}
765
766static void EmitRecordID(unsigned ID, const char *Name,
767 llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000768 ASTWriter::RecordDataImpl &Record) {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000769 Record.clear();
770 Record.push_back(ID);
771 while (*Name)
772 Record.push_back(*Name++);
773 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000774}
775
776static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000777 ASTWriter::RecordDataImpl &Record) {
Sebastian Redl539c5062010-08-18 23:57:32 +0000778#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
Chris Lattnerccac3a62009-04-27 00:49:53 +0000779 RECORD(STMT_STOP);
780 RECORD(STMT_NULL_PTR);
Richard Smith01b2cb42014-07-26 06:37:51 +0000781 RECORD(STMT_REF_PTR);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000782 RECORD(STMT_NULL);
783 RECORD(STMT_COMPOUND);
784 RECORD(STMT_CASE);
785 RECORD(STMT_DEFAULT);
786 RECORD(STMT_LABEL);
Richard Smithc202b282012-04-14 00:33:13 +0000787 RECORD(STMT_ATTRIBUTED);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000788 RECORD(STMT_IF);
789 RECORD(STMT_SWITCH);
790 RECORD(STMT_WHILE);
791 RECORD(STMT_DO);
792 RECORD(STMT_FOR);
793 RECORD(STMT_GOTO);
794 RECORD(STMT_INDIRECT_GOTO);
795 RECORD(STMT_CONTINUE);
796 RECORD(STMT_BREAK);
797 RECORD(STMT_RETURN);
798 RECORD(STMT_DECL);
Chad Rosierde70e0e2012-08-25 00:11:56 +0000799 RECORD(STMT_GCCASM);
Chad Rosiere30d4992012-08-24 23:51:02 +0000800 RECORD(STMT_MSASM);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000801 RECORD(EXPR_PREDEFINED);
802 RECORD(EXPR_DECL_REF);
803 RECORD(EXPR_INTEGER_LITERAL);
804 RECORD(EXPR_FLOATING_LITERAL);
805 RECORD(EXPR_IMAGINARY_LITERAL);
806 RECORD(EXPR_STRING_LITERAL);
807 RECORD(EXPR_CHARACTER_LITERAL);
808 RECORD(EXPR_PAREN);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000809 RECORD(EXPR_PAREN_LIST);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000810 RECORD(EXPR_UNARY_OPERATOR);
811 RECORD(EXPR_SIZEOF_ALIGN_OF);
812 RECORD(EXPR_ARRAY_SUBSCRIPT);
813 RECORD(EXPR_CALL);
814 RECORD(EXPR_MEMBER);
815 RECORD(EXPR_BINARY_OPERATOR);
816 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
817 RECORD(EXPR_CONDITIONAL_OPERATOR);
818 RECORD(EXPR_IMPLICIT_CAST);
819 RECORD(EXPR_CSTYLE_CAST);
820 RECORD(EXPR_COMPOUND_LITERAL);
821 RECORD(EXPR_EXT_VECTOR_ELEMENT);
822 RECORD(EXPR_INIT_LIST);
823 RECORD(EXPR_DESIGNATED_INIT);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000824 RECORD(EXPR_DESIGNATED_INIT_UPDATE);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000825 RECORD(EXPR_IMPLICIT_VALUE_INIT);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000826 RECORD(EXPR_NO_INIT);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000827 RECORD(EXPR_VA_ARG);
828 RECORD(EXPR_ADDR_LABEL);
829 RECORD(EXPR_STMT);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000830 RECORD(EXPR_CHOOSE);
831 RECORD(EXPR_GNU_NULL);
832 RECORD(EXPR_SHUFFLE_VECTOR);
833 RECORD(EXPR_BLOCK);
Peter Collingbourne91147592011-04-15 00:35:48 +0000834 RECORD(EXPR_GENERIC_SELECTION);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000835 RECORD(EXPR_OBJC_STRING_LITERAL);
Patrick Beard0caa3942012-04-19 00:25:12 +0000836 RECORD(EXPR_OBJC_BOXED_EXPRESSION);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000837 RECORD(EXPR_OBJC_ARRAY_LITERAL);
838 RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000839 RECORD(EXPR_OBJC_ENCODE);
840 RECORD(EXPR_OBJC_SELECTOR_EXPR);
841 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
842 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
843 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
844 RECORD(EXPR_OBJC_KVC_REF_EXPR);
845 RECORD(EXPR_OBJC_MESSAGE_EXPR);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000846 RECORD(STMT_OBJC_FOR_COLLECTION);
847 RECORD(STMT_OBJC_CATCH);
848 RECORD(STMT_OBJC_FINALLY);
849 RECORD(STMT_OBJC_AT_TRY);
850 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
851 RECORD(STMT_OBJC_AT_THROW);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000852 RECORD(EXPR_OBJC_BOOL_LITERAL);
Richard Smith01b2cb42014-07-26 06:37:51 +0000853 RECORD(STMT_CXX_CATCH);
854 RECORD(STMT_CXX_TRY);
855 RECORD(STMT_CXX_FOR_RANGE);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000856 RECORD(EXPR_CXX_OPERATOR_CALL);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000857 RECORD(EXPR_CXX_MEMBER_CALL);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000858 RECORD(EXPR_CXX_CONSTRUCT);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000859 RECORD(EXPR_CXX_TEMPORARY_OBJECT);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000860 RECORD(EXPR_CXX_STATIC_CAST);
861 RECORD(EXPR_CXX_DYNAMIC_CAST);
862 RECORD(EXPR_CXX_REINTERPRET_CAST);
863 RECORD(EXPR_CXX_CONST_CAST);
864 RECORD(EXPR_CXX_FUNCTIONAL_CAST);
Richard Smithc67fdd42012-03-07 08:35:16 +0000865 RECORD(EXPR_USER_DEFINED_LITERAL);
Richard Smithcc1b96d2013-06-12 22:31:48 +0000866 RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000867 RECORD(EXPR_CXX_BOOL_LITERAL);
868 RECORD(EXPR_CXX_NULL_PTR_LITERAL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000869 RECORD(EXPR_CXX_TYPEID_EXPR);
870 RECORD(EXPR_CXX_TYPEID_TYPE);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000871 RECORD(EXPR_CXX_THIS);
872 RECORD(EXPR_CXX_THROW);
873 RECORD(EXPR_CXX_DEFAULT_ARG);
Richard Smith01b2cb42014-07-26 06:37:51 +0000874 RECORD(EXPR_CXX_DEFAULT_INIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000875 RECORD(EXPR_CXX_BIND_TEMPORARY);
876 RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
877 RECORD(EXPR_CXX_NEW);
878 RECORD(EXPR_CXX_DELETE);
879 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
880 RECORD(EXPR_EXPR_WITH_CLEANUPS);
881 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
882 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
883 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
884 RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
885 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
Richard Smith01b2cb42014-07-26 06:37:51 +0000886 RECORD(EXPR_CXX_EXPRESSION_TRAIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000887 RECORD(EXPR_CXX_NOEXCEPT);
888 RECORD(EXPR_OPAQUE_VALUE);
Richard Smith01b2cb42014-07-26 06:37:51 +0000889 RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR);
890 RECORD(EXPR_TYPE_TRAIT);
891 RECORD(EXPR_ARRAY_TYPE_TRAIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000892 RECORD(EXPR_PACK_EXPANSION);
893 RECORD(EXPR_SIZEOF_PACK);
Richard Smith01b2cb42014-07-26 06:37:51 +0000894 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000895 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
Richard Smith01b2cb42014-07-26 06:37:51 +0000896 RECORD(EXPR_FUNCTION_PARM_PACK);
897 RECORD(EXPR_MATERIALIZE_TEMPORARY);
Peter Collingbourne41f85462011-02-09 21:07:24 +0000898 RECORD(EXPR_CUDA_KERNEL_CALL);
Richard Smith01b2cb42014-07-26 06:37:51 +0000899 RECORD(EXPR_CXX_UUIDOF_EXPR);
900 RECORD(EXPR_CXX_UUIDOF_TYPE);
901 RECORD(EXPR_LAMBDA);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000902#undef RECORD
Chris Lattner28fa4e62009-04-26 22:26:21 +0000903}
Mike Stump11289f42009-09-09 15:08:12 +0000904
Sebastian Redl55c0ad52010-08-18 23:56:21 +0000905void ASTWriter::WriteBlockInfoBlock() {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000906 RecordData Record;
907 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
Mike Stump11289f42009-09-09 15:08:12 +0000908
Sebastian Redl539c5062010-08-18 23:57:32 +0000909#define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
910#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
Mike Stump11289f42009-09-09 15:08:12 +0000911
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000912 // Control Block.
913 BLOCK(CONTROL_BLOCK);
914 RECORD(METADATA);
Ben Langmuir487ea142014-10-23 18:05:36 +0000915 RECORD(SIGNATURE);
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000916 RECORD(MODULE_NAME);
Richard Smithfa715652015-08-31 22:43:10 +0000917 RECORD(MODULE_DIRECTORY);
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000918 RECORD(MODULE_MAP_FILE);
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000919 RECORD(IMPORTS);
Douglas Gregorfad10d82012-10-18 18:36:53 +0000920 RECORD(ORIGINAL_FILE);
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000921 RECORD(ORIGINAL_PCH_DIR);
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +0000922 RECORD(ORIGINAL_FILE_ID);
Douglas Gregor3120d2c2012-10-22 18:42:04 +0000923 RECORD(INPUT_FILE_OFFSETS);
Richard Smith0516b182015-09-08 19:40:14 +0000924
925 BLOCK(OPTIONS_BLOCK);
926 RECORD(LANGUAGE_OPTIONS);
927 RECORD(TARGET_OPTIONS);
Douglas Gregor8263ffb2012-10-24 15:17:15 +0000928 RECORD(DIAGNOSTIC_OPTIONS);
Douglas Gregorc6317db2012-10-24 15:49:58 +0000929 RECORD(FILE_SYSTEM_OPTIONS);
Douglas Gregor2d302362012-10-24 16:50:34 +0000930 RECORD(HEADER_SEARCH_OPTIONS);
Douglas Gregorb6af6c22012-10-24 20:05:57 +0000931 RECORD(PREPROCESSOR_OPTIONS);
932
Douglas Gregor108cb222012-10-19 00:45:00 +0000933 BLOCK(INPUT_FILES_BLOCK);
934 RECORD(INPUT_FILE);
935
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000936 // AST Top-Level Block.
937 BLOCK(AST_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000938 RECORD(TYPE_OFFSET);
939 RECORD(DECL_OFFSET);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000940 RECORD(IDENTIFIER_OFFSET);
941 RECORD(IDENTIFIER_TABLE);
Ben Langmuir332aafe2014-01-31 01:06:56 +0000942 RECORD(EAGERLY_DESERIALIZED_DECLS);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000943 RECORD(SPECIAL_TYPES);
944 RECORD(STATISTICS);
945 RECORD(TENTATIVE_DEFINITIONS);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000946 RECORD(SELECTOR_OFFSETS);
947 RECORD(METHOD_POOL);
948 RECORD(PP_COUNTER_VALUE);
Douglas Gregor258ae542009-04-27 06:38:32 +0000949 RECORD(SOURCE_LOCATION_OFFSETS);
950 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor61cac2b2009-04-27 20:06:05 +0000951 RECORD(EXT_VECTOR_DECLS);
Richard Smithfa715652015-08-31 22:43:10 +0000952 RECORD(UNUSED_FILESCOPED_DECLS);
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +0000953 RECORD(PPD_ENTITIES_OFFSETS);
Richard Smithfa715652015-08-31 22:43:10 +0000954 RECORD(VTABLE_USES);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +0000955 RECORD(REFERENCED_SELECTOR_POOL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000956 RECORD(TU_UPDATE_LEXICAL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000957 RECORD(SEMA_DECL_REFS);
958 RECORD(WEAK_UNDECLARED_IDENTIFIERS);
959 RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000960 RECORD(UPDATE_VISIBLE);
961 RECORD(DECL_UPDATE_OFFSETS);
962 RECORD(DECL_UPDATES);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000963 RECORD(DIAG_PRAGMA_MAPPINGS);
Peter Collingbourne5df20e02011-02-15 19:46:30 +0000964 RECORD(CUDA_SPECIAL_DECL_REFS);
Douglas Gregor09b69892011-02-10 17:09:37 +0000965 RECORD(HEADER_SEARCH_TABLE);
Peter Collingbourne5df20e02011-02-15 19:46:30 +0000966 RECORD(FP_PRAGMA_OPTIONS);
967 RECORD(OPENCL_EXTENSIONS);
Alexis Hunt27a761d2011-05-04 23:29:54 +0000968 RECORD(DELEGATING_CTORS);
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000969 RECORD(KNOWN_NAMESPACES);
Douglas Gregor78d0b572011-08-04 16:39:39 +0000970 RECORD(MODULE_OFFSET_MAP);
971 RECORD(SOURCE_MANAGER_LINE_TABLE);
Douglas Gregor404cdde2012-01-27 01:47:08 +0000972 RECORD(OBJC_CATEGORIES_MAP);
Douglas Gregor66e4add2011-12-19 21:09:25 +0000973 RECORD(FILE_SORTED_DECLS);
974 RECORD(IMPORTED_MODULES);
Douglas Gregor404cdde2012-01-27 01:47:08 +0000975 RECORD(OBJC_CATEGORIES);
Douglas Gregorcb28f9d2012-10-09 23:05:51 +0000976 RECORD(MACRO_OFFSET);
Richard Smithfa715652015-08-31 22:43:10 +0000977 RECORD(INTERESTING_IDENTIFIERS);
978 RECORD(UNDEFINED_BUT_USED);
Richard Smithe40f2ba2013-08-07 21:41:30 +0000979 RECORD(LATE_PARSED_TEMPLATE);
Dario Domizioli13a0a382014-05-23 12:13:25 +0000980 RECORD(OPTIMIZE_PRAGMA_OPTIONS);
Nico Weber779355f2016-03-02 23:22:00 +0000981 RECORD(MSSTRUCT_PRAGMA_OPTIONS);
Nico Weber42932312016-03-03 00:17:35 +0000982 RECORD(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS);
Richard Smithfa715652015-08-31 22:43:10 +0000983 RECORD(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES);
Richard Smithfa715652015-08-31 22:43:10 +0000984 RECORD(DELETE_EXPRS_TO_ANALYZE);
Douglas Gregor358cd442012-01-15 16:58:34 +0000985
Chris Lattner28fa4e62009-04-26 22:26:21 +0000986 // SourceManager Block.
Chris Lattner64031982009-04-27 00:40:25 +0000987 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000988 RECORD(SM_SLOC_FILE_ENTRY);
989 RECORD(SM_SLOC_BUFFER_ENTRY);
990 RECORD(SM_SLOC_BUFFER_BLOB);
Richard Smithaada85c2016-02-06 02:06:43 +0000991 RECORD(SM_SLOC_BUFFER_BLOB_COMPRESSED);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +0000992 RECORD(SM_SLOC_EXPANSION_ENTRY);
Mike Stump11289f42009-09-09 15:08:12 +0000993
Chris Lattner28fa4e62009-04-26 22:26:21 +0000994 // Preprocessor Block.
Chris Lattner64031982009-04-27 00:40:25 +0000995 BLOCK(PREPROCESSOR_BLOCK);
Richard Smithec216502015-02-13 19:48:37 +0000996 RECORD(PP_MACRO_DIRECTIVE_HISTORY);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000997 RECORD(PP_MACRO_FUNCTION_LIKE);
Richard Smithd7329392015-04-21 21:46:32 +0000998 RECORD(PP_MACRO_OBJECT_LIKE);
999 RECORD(PP_MODULE_MACRO);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001000 RECORD(PP_TOKEN);
Richard Smithec216502015-02-13 19:48:37 +00001001
Richard Smithfa715652015-08-31 22:43:10 +00001002 // Submodule Block.
1003 BLOCK(SUBMODULE_BLOCK);
1004 RECORD(SUBMODULE_METADATA);
1005 RECORD(SUBMODULE_DEFINITION);
1006 RECORD(SUBMODULE_UMBRELLA_HEADER);
1007 RECORD(SUBMODULE_HEADER);
1008 RECORD(SUBMODULE_TOPHEADER);
1009 RECORD(SUBMODULE_UMBRELLA_DIR);
1010 RECORD(SUBMODULE_IMPORTS);
1011 RECORD(SUBMODULE_EXPORTS);
1012 RECORD(SUBMODULE_REQUIRES);
1013 RECORD(SUBMODULE_EXCLUDED_HEADER);
1014 RECORD(SUBMODULE_LINK_LIBRARY);
1015 RECORD(SUBMODULE_CONFIG_MACRO);
1016 RECORD(SUBMODULE_CONFLICT);
1017 RECORD(SUBMODULE_PRIVATE_HEADER);
1018 RECORD(SUBMODULE_TEXTUAL_HEADER);
1019 RECORD(SUBMODULE_PRIVATE_TEXTUAL_HEADER);
Richard Smithdc1f0422016-07-20 19:10:16 +00001020 RECORD(SUBMODULE_INITIALIZERS);
Richard Smithfa715652015-08-31 22:43:10 +00001021
1022 // Comments Block.
1023 BLOCK(COMMENTS_BLOCK);
1024 RECORD(COMMENTS_RAW_COMMENT);
1025
Douglas Gregor12bfa382009-10-17 00:13:19 +00001026 // Decls and Types block.
1027 BLOCK(DECLTYPES_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001028 RECORD(TYPE_EXT_QUAL);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001029 RECORD(TYPE_COMPLEX);
1030 RECORD(TYPE_POINTER);
1031 RECORD(TYPE_BLOCK_POINTER);
1032 RECORD(TYPE_LVALUE_REFERENCE);
1033 RECORD(TYPE_RVALUE_REFERENCE);
1034 RECORD(TYPE_MEMBER_POINTER);
1035 RECORD(TYPE_CONSTANT_ARRAY);
1036 RECORD(TYPE_INCOMPLETE_ARRAY);
1037 RECORD(TYPE_VARIABLE_ARRAY);
1038 RECORD(TYPE_VECTOR);
1039 RECORD(TYPE_EXT_VECTOR);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001040 RECORD(TYPE_FUNCTION_NO_PROTO);
Richard Smithf1b4b8b2014-07-27 04:29:04 +00001041 RECORD(TYPE_FUNCTION_PROTO);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001042 RECORD(TYPE_TYPEDEF);
1043 RECORD(TYPE_TYPEOF_EXPR);
1044 RECORD(TYPE_TYPEOF);
1045 RECORD(TYPE_RECORD);
1046 RECORD(TYPE_ENUM);
1047 RECORD(TYPE_OBJC_INTERFACE);
Steve Narofffb4330f2009-06-17 22:40:22 +00001048 RECORD(TYPE_OBJC_OBJECT_POINTER);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001049 RECORD(TYPE_DECLTYPE);
1050 RECORD(TYPE_ELABORATED);
1051 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
1052 RECORD(TYPE_UNRESOLVED_USING);
1053 RECORD(TYPE_INJECTED_CLASS_NAME);
1054 RECORD(TYPE_OBJC_OBJECT);
1055 RECORD(TYPE_TEMPLATE_TYPE_PARM);
1056 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
1057 RECORD(TYPE_DEPENDENT_NAME);
1058 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
1059 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
1060 RECORD(TYPE_PAREN);
1061 RECORD(TYPE_PACK_EXPANSION);
1062 RECORD(TYPE_ATTRIBUTED);
1063 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
Richard Smithf1b4b8b2014-07-27 04:29:04 +00001064 RECORD(TYPE_AUTO);
1065 RECORD(TYPE_UNARY_TRANSFORM);
Eli Friedman0dfb8892011-10-06 23:00:33 +00001066 RECORD(TYPE_ATOMIC);
Richard Smithf1b4b8b2014-07-27 04:29:04 +00001067 RECORD(TYPE_DECAYED);
1068 RECORD(TYPE_ADJUSTED);
Richard Smithd61d4ac2015-08-22 20:13:39 +00001069 RECORD(LOCAL_REDECLARATIONS);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001070 RECORD(DECL_TYPEDEF);
Richard Smith01b2cb42014-07-26 06:37:51 +00001071 RECORD(DECL_TYPEALIAS);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001072 RECORD(DECL_ENUM);
1073 RECORD(DECL_RECORD);
1074 RECORD(DECL_ENUM_CONSTANT);
1075 RECORD(DECL_FUNCTION);
1076 RECORD(DECL_OBJC_METHOD);
1077 RECORD(DECL_OBJC_INTERFACE);
1078 RECORD(DECL_OBJC_PROTOCOL);
1079 RECORD(DECL_OBJC_IVAR);
1080 RECORD(DECL_OBJC_AT_DEFS_FIELD);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001081 RECORD(DECL_OBJC_CATEGORY);
1082 RECORD(DECL_OBJC_CATEGORY_IMPL);
1083 RECORD(DECL_OBJC_IMPLEMENTATION);
1084 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
1085 RECORD(DECL_OBJC_PROPERTY);
1086 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001087 RECORD(DECL_FIELD);
John McCall5e77d762013-04-16 07:28:30 +00001088 RECORD(DECL_MS_PROPERTY);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001089 RECORD(DECL_VAR);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001090 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001091 RECORD(DECL_PARM_VAR);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001092 RECORD(DECL_FILE_SCOPE_ASM);
1093 RECORD(DECL_BLOCK);
1094 RECORD(DECL_CONTEXT_LEXICAL);
1095 RECORD(DECL_CONTEXT_VISIBLE);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001096 RECORD(DECL_NAMESPACE);
1097 RECORD(DECL_NAMESPACE_ALIAS);
1098 RECORD(DECL_USING);
1099 RECORD(DECL_USING_SHADOW);
1100 RECORD(DECL_USING_DIRECTIVE);
1101 RECORD(DECL_UNRESOLVED_USING_VALUE);
1102 RECORD(DECL_UNRESOLVED_USING_TYPENAME);
1103 RECORD(DECL_LINKAGE_SPEC);
1104 RECORD(DECL_CXX_RECORD);
1105 RECORD(DECL_CXX_METHOD);
1106 RECORD(DECL_CXX_CONSTRUCTOR);
Richard Smith5179eb72016-06-28 19:03:57 +00001107 RECORD(DECL_CXX_INHERITED_CONSTRUCTOR);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001108 RECORD(DECL_CXX_DESTRUCTOR);
1109 RECORD(DECL_CXX_CONVERSION);
1110 RECORD(DECL_ACCESS_SPEC);
1111 RECORD(DECL_FRIEND);
1112 RECORD(DECL_FRIEND_TEMPLATE);
1113 RECORD(DECL_CLASS_TEMPLATE);
1114 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
1115 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001116 RECORD(DECL_VAR_TEMPLATE);
1117 RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
1118 RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001119 RECORD(DECL_FUNCTION_TEMPLATE);
1120 RECORD(DECL_TEMPLATE_TYPE_PARM);
1121 RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
1122 RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
Richard Smithefc884a2016-04-13 07:41:35 +00001123 RECORD(DECL_TYPE_ALIAS_TEMPLATE);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001124 RECORD(DECL_STATIC_ASSERT);
1125 RECORD(DECL_CXX_BASE_SPECIFIERS);
Richard Smithefc884a2016-04-13 07:41:35 +00001126 RECORD(DECL_CXX_CTOR_INITIALIZERS);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001127 RECORD(DECL_INDIRECTFIELD);
1128 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
Richard Smithefc884a2016-04-13 07:41:35 +00001129 RECORD(DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK);
1130 RECORD(DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION);
1131 RECORD(DECL_IMPORT);
1132 RECORD(DECL_OMP_THREADPRIVATE);
1133 RECORD(DECL_EMPTY);
1134 RECORD(DECL_OBJC_TYPE_PARAM);
1135 RECORD(DECL_OMP_CAPTUREDEXPR);
1136 RECORD(DECL_PRAGMA_COMMENT);
1137 RECORD(DECL_PRAGMA_DETECT_MISMATCH);
1138 RECORD(DECL_OMP_DECLARE_REDUCTION);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001139
Douglas Gregor03412ba2011-06-03 02:27:19 +00001140 // Statements and Exprs can occur in the Decls and Types block.
1141 AddStmtsExprs(Stream, Record);
1142
Douglas Gregor92a96f52011-02-08 21:58:10 +00001143 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001144 RECORD(PPD_MACRO_EXPANSION);
Douglas Gregor92a96f52011-02-08 21:58:10 +00001145 RECORD(PPD_MACRO_DEFINITION);
1146 RECORD(PPD_INCLUSION_DIRECTIVE);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00001147
1148 // Decls and Types block.
1149 BLOCK(EXTENSION_BLOCK);
1150 RECORD(EXTENSION_METADATA);
1151
Chris Lattner28fa4e62009-04-26 22:26:21 +00001152#undef RECORD
1153#undef BLOCK
1154 Stream.ExitBlock();
1155}
1156
Richard Smith54cc3c22014-12-11 20:50:24 +00001157/// \brief Prepares a path for being written to an AST file by converting it
1158/// to an absolute path and removing nested './'s.
1159///
1160/// \return \c true if the path was changed.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001161static bool cleanPathForOutput(FileManager &FileMgr,
1162 SmallVectorImpl<char> &Path) {
Argyrios Kyrtzidis403cbcb2015-07-31 01:39:23 +00001163 bool Changed = FileMgr.makeAbsolutePath(Path);
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +00001164 return Changed | llvm::sys::path::remove_dots(Path);
Richard Smith54cc3c22014-12-11 20:50:24 +00001165}
1166
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001167/// \brief Adjusts the given filename to only write out the portion of the
1168/// filename that is not part of the system root directory.
Mike Stump11289f42009-09-09 15:08:12 +00001169///
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001170/// \param Filename the file name to adjust.
1171///
Richard Smith7ed1bc92014-12-05 22:42:13 +00001172/// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
1173/// the returned filename will be adjusted by this root directory.
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001174///
1175/// \returns either the original filename (if it needs no adjustment) or the
1176/// adjusted filename (which points into the @p Filename parameter).
Mike Stump11289f42009-09-09 15:08:12 +00001177static const char *
Richard Smith7ed1bc92014-12-05 22:42:13 +00001178adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001179 assert(Filename && "No file name to adjust?");
Mike Stump11289f42009-09-09 15:08:12 +00001180
Richard Smith7ed1bc92014-12-05 22:42:13 +00001181 if (BaseDir.empty())
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001182 return Filename;
Mike Stump11289f42009-09-09 15:08:12 +00001183
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001184 // Verify that the filename and the system root have the same prefix.
1185 unsigned Pos = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001186 for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
1187 if (Filename[Pos] != BaseDir[Pos])
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001188 return Filename; // Prefixes don't match.
Mike Stump11289f42009-09-09 15:08:12 +00001189
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001190 // We hit the end of the filename before we hit the end of the system root.
1191 if (!Filename[Pos])
1192 return Filename;
Mike Stump11289f42009-09-09 15:08:12 +00001193
Richard Smith7ed1bc92014-12-05 22:42:13 +00001194 // If there's not a path separator at the end of the base directory nor
1195 // immediately after it, then this isn't within the base directory.
1196 if (!llvm::sys::path::is_separator(Filename[Pos])) {
1197 if (!llvm::sys::path::is_separator(BaseDir.back()))
1198 return Filename;
1199 } else {
1200 // If the file name has a '/' at the current position, skip over the '/'.
1201 // We distinguish relative paths from absolute paths by the
1202 // absence of '/' at the beginning of relative paths.
1203 //
1204 // FIXME: This is wrong. We distinguish them by asking if the path is
1205 // absolute, which isn't the same thing. And there might be multiple '/'s
1206 // in a row. Use a better mechanism to indicate whether we have emitted an
1207 // absolute or relative path.
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001208 ++Pos;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001209 }
Mike Stump11289f42009-09-09 15:08:12 +00001210
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001211 return Filename + Pos;
1212}
Chris Lattner28fa4e62009-04-26 22:26:21 +00001213
Ben Langmuir487ea142014-10-23 18:05:36 +00001214static ASTFileSignature getSignature() {
1215 while (1) {
1216 if (ASTFileSignature S = llvm::sys::Process::GetRandomNumber())
1217 return S;
1218 // Rely on GetRandomNumber to eventually return non-zero...
1219 }
1220}
1221
Douglas Gregor112b9072012-10-18 05:31:06 +00001222/// \brief Write the control block.
Adrian Prantladbd2b12015-09-22 23:26:31 +00001223uint64_t ASTWriter::WriteControlBlock(Preprocessor &PP,
1224 ASTContext &Context,
1225 StringRef isysroot,
1226 const std::string &OutputFile) {
1227 ASTFileSignature Signature = 0;
1228
Douglas Gregorbfbde532009-04-10 21:16:55 +00001229 using namespace llvm;
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001230 Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001231 RecordData Record;
1232
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001233 // Metadata
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001234 auto *MetadataAbbrev = new BitCodeAbbrev();
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001235 MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1236 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1237 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1238 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1239 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1240 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
Richard Smithe75ee0f2015-08-17 07:13:32 +00001241 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001242 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1243 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1244 unsigned MetadataAbbrevCode = Stream.EmitAbbrev(MetadataAbbrev);
Richard Smith7ed1bc92014-12-05 22:42:13 +00001245 assert((!WritingModule || isysroot.empty()) &&
1246 "writing module as a relocatable PCH?");
Mehdi Amini57a41912015-09-10 01:46:39 +00001247 {
1248 RecordData::value_type Record[] = {METADATA, VERSION_MAJOR, VERSION_MINOR,
1249 CLANG_VERSION_MAJOR, CLANG_VERSION_MINOR,
1250 !isysroot.empty(), IncludeTimestamps,
1251 ASTHasCompilerErrors};
1252 Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1253 getClangFullRepositoryVersion());
1254 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001255 if (WritingModule) {
Chandler Carruth885e78c2015-03-24 21:18:10 +00001256 // For implicit modules we output a signature that we can use to ensure
1257 // duplicate module builds don't collide in the cache as their output order
1258 // is non-deterministic.
1259 // FIXME: Remove this when output is deterministic.
1260 if (Context.getLangOpts().ImplicitModules) {
Adrian Prantladbd2b12015-09-22 23:26:31 +00001261 Signature = getSignature();
1262 RecordData::value_type Record[] = {Signature};
Chandler Carruth885e78c2015-03-24 21:18:10 +00001263 Stream.EmitRecord(SIGNATURE, Record);
1264 }
1265
Richard Smith7ed1bc92014-12-05 22:42:13 +00001266 // Module name
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001267 auto *Abbrev = new BitCodeAbbrev();
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001268 Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1269 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1270 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00001271 RecordData::value_type Record[] = {MODULE_NAME};
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001272 Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1273 }
1274
Richard Smith7ed1bc92014-12-05 22:42:13 +00001275 if (WritingModule && WritingModule->Directory) {
Richard Smith7ed1bc92014-12-05 22:42:13 +00001276 SmallString<128> BaseDir(WritingModule->Directory->getName());
Richard Smith54cc3c22014-12-11 20:50:24 +00001277 cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
Richard Smithf7b41372015-08-13 23:47:44 +00001278
1279 // If the home of the module is the current working directory, then we
1280 // want to pick up the cwd of the build process loading the module, not
1281 // our cwd, when we load this module.
1282 if (!PP.getHeaderSearchInfo()
1283 .getHeaderSearchOpts()
1284 .ModuleMapFileHomeIsCwd ||
1285 WritingModule->Directory->getName() != StringRef(".")) {
1286 // Module directory.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001287 auto *Abbrev = new BitCodeAbbrev();
Richard Smithf7b41372015-08-13 23:47:44 +00001288 Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1289 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
1290 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1291
Mehdi Amini57a41912015-09-10 01:46:39 +00001292 RecordData::value_type Record[] = {MODULE_DIRECTORY};
Richard Smithf7b41372015-08-13 23:47:44 +00001293 Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
1294 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001295
1296 // Write out all other paths relative to the base directory if possible.
1297 BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1298 } else if (!isysroot.empty()) {
1299 // Write out paths relative to the sysroot if possible.
1300 BaseDirectory = isysroot;
1301 }
1302
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001303 // Module map file
1304 if (WritingModule) {
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001305 Record.clear();
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001306
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001307 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
1308
1309 // Primary module map file.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001310 AddPath(Map.getModuleMapFileForUniquing(WritingModule)->getName(), Record);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001311
1312 // Additional module map files.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001313 if (auto *AdditionalModMaps =
1314 Map.getAdditionalModuleMapFiles(WritingModule)) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001315 Record.push_back(AdditionalModMaps->size());
1316 for (const FileEntry *F : *AdditionalModMaps)
Richard Smith7ed1bc92014-12-05 22:42:13 +00001317 AddPath(F->getName(), Record);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001318 } else {
1319 Record.push_back(0);
1320 }
1321
1322 Stream.EmitRecord(MODULE_MAP_FILE, Record);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001323 }
1324
Douglas Gregor112b9072012-10-18 05:31:06 +00001325 // Imports
Douglas Gregor29cc6422011-08-17 21:07:30 +00001326 if (Chain) {
Douglas Gregor29cc6422011-08-17 21:07:30 +00001327 serialization::ModuleManager &Mgr = Chain->getModuleManager();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001328 Record.clear();
Douglas Gregordf0c1512011-08-18 04:12:04 +00001329
Richard Smith7f330cd2015-03-18 01:42:29 +00001330 for (auto *M : Mgr) {
Douglas Gregordf0c1512011-08-18 04:12:04 +00001331 // Skip modules that weren't directly imported.
Richard Smith7f330cd2015-03-18 01:42:29 +00001332 if (!M->isDirectlyImported())
Douglas Gregordf0c1512011-08-18 04:12:04 +00001333 continue;
1334
Richard Smith7f330cd2015-03-18 01:42:29 +00001335 Record.push_back((unsigned)M->Kind); // FIXME: Stable encoding
1336 AddSourceLocation(M->ImportLoc, Record);
1337 Record.push_back(M->File->getSize());
Richard Smithe75ee0f2015-08-17 07:13:32 +00001338 Record.push_back(getTimestampForOutput(M->File));
Richard Smith7f330cd2015-03-18 01:42:29 +00001339 Record.push_back(M->Signature);
1340 AddPath(M->FileName, Record);
Douglas Gregordf0c1512011-08-18 04:12:04 +00001341 }
Douglas Gregor29cc6422011-08-17 21:07:30 +00001342 Stream.EmitRecord(IMPORTS, Record);
1343 }
Mike Stump11289f42009-09-09 15:08:12 +00001344
Richard Smith0516b182015-09-08 19:40:14 +00001345 // Write the options block.
1346 Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
1347
Douglas Gregor112b9072012-10-18 05:31:06 +00001348 // Language options.
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001349 Record.clear();
Douglas Gregor112b9072012-10-18 05:31:06 +00001350 const LangOptions &LangOpts = Context.getLangOpts();
1351#define LANGOPT(Name, Bits, Default, Description) \
1352 Record.push_back(LangOpts.Name);
1353#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1354 Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001355#include "clang/Basic/LangOptions.def"
1356#define SANITIZER(NAME, ID) \
1357 Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
Will Dietzf54319c2013-01-18 11:30:38 +00001358#include "clang/Basic/Sanitizers.def"
Douglas Gregor112b9072012-10-18 05:31:06 +00001359
Ben Langmuircd98cb72015-06-23 18:20:18 +00001360 Record.push_back(LangOpts.ModuleFeatures.size());
1361 for (StringRef Feature : LangOpts.ModuleFeatures)
1362 AddString(Feature, Record);
1363
Douglas Gregor112b9072012-10-18 05:31:06 +00001364 Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1365 AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
Ben Langmuird4a667a2015-06-23 18:20:23 +00001366
1367 AddString(LangOpts.CurrentModule, Record);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001368
1369 // Comment options.
1370 Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001371 for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1372 AddString(I, Record);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001373 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00001374 Record.push_back(LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001375
Samuel Antaoee8fb302016-01-06 13:42:12 +00001376 // OpenMP offloading options.
1377 Record.push_back(LangOpts.OMPTargetTriples.size());
1378 for (auto &T : LangOpts.OMPTargetTriples)
1379 AddString(T.getTriple(), Record);
1380
1381 AddString(LangOpts.OMPHostIRFile, Record);
1382
Douglas Gregor112b9072012-10-18 05:31:06 +00001383 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1384
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001385 // Target options.
1386 Record.clear();
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001387 const TargetInfo &Target = Context.getTargetInfo();
1388 const TargetOptions &TargetOpts = Target.getTargetOpts();
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001389 AddString(TargetOpts.Triple, Record);
1390 AddString(TargetOpts.CPU, Record);
1391 AddString(TargetOpts.ABI, Record);
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001392 Record.push_back(TargetOpts.FeaturesAsWritten.size());
1393 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1394 AddString(TargetOpts.FeaturesAsWritten[I], Record);
1395 }
1396 Record.push_back(TargetOpts.Features.size());
1397 for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1398 AddString(TargetOpts.Features[I], Record);
1399 }
1400 Stream.EmitRecord(TARGET_OPTIONS, Record);
1401
Douglas Gregor8263ffb2012-10-24 15:17:15 +00001402 // Diagnostic options.
1403 Record.clear();
1404 const DiagnosticOptions &DiagOpts
1405 = Context.getDiagnostics().getDiagnosticOptions();
1406#define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1407#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1408 Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1409#include "clang/Basic/DiagnosticOptions.def"
1410 Record.push_back(DiagOpts.Warnings.size());
1411 for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1412 AddString(DiagOpts.Warnings[I], Record);
Richard Smith3be1cb22014-08-07 00:24:21 +00001413 Record.push_back(DiagOpts.Remarks.size());
1414 for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1415 AddString(DiagOpts.Remarks[I], Record);
Douglas Gregor8263ffb2012-10-24 15:17:15 +00001416 // Note: we don't serialize the log or serialization file names, because they
1417 // are generally transient files and will almost always be overridden.
1418 Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1419
Douglas Gregorc6317db2012-10-24 15:49:58 +00001420 // File system options.
1421 Record.clear();
Yaron Keren8dec46c2015-08-26 08:10:22 +00001422 const FileSystemOptions &FSOpts =
1423 Context.getSourceManager().getFileManager().getFileSystemOpts();
Douglas Gregorc6317db2012-10-24 15:49:58 +00001424 AddString(FSOpts.WorkingDir, Record);
1425 Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1426
Douglas Gregor2d302362012-10-24 16:50:34 +00001427 // Header search options.
1428 Record.clear();
1429 const HeaderSearchOptions &HSOpts
1430 = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1431 AddString(HSOpts.Sysroot, Record);
1432
1433 // Include entries.
1434 Record.push_back(HSOpts.UserEntries.size());
1435 for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1436 const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1437 AddString(Entry.Path, Record);
1438 Record.push_back(static_cast<unsigned>(Entry.Group));
Douglas Gregor2d302362012-10-24 16:50:34 +00001439 Record.push_back(Entry.IsFramework);
1440 Record.push_back(Entry.IgnoreSysRoot);
Douglas Gregor2d302362012-10-24 16:50:34 +00001441 }
1442
1443 // System header prefixes.
1444 Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1445 for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1446 AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1447 Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1448 }
1449
1450 AddString(HSOpts.ResourceDir, Record);
1451 AddString(HSOpts.ModuleCachePath, Record);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00001452 AddString(HSOpts.ModuleUserBuildPath, Record);
Douglas Gregor2d302362012-10-24 16:50:34 +00001453 Record.push_back(HSOpts.DisableModuleHash);
1454 Record.push_back(HSOpts.UseBuiltinIncludes);
1455 Record.push_back(HSOpts.UseStandardSystemIncludes);
1456 Record.push_back(HSOpts.UseStandardCXXIncludes);
1457 Record.push_back(HSOpts.UseLibcxx);
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00001458 // Write out the specific module cache path that contains the module files.
1459 AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
Douglas Gregor2d302362012-10-24 16:50:34 +00001460 Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1461
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001462 // Preprocessor options.
1463 Record.clear();
1464 const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1465
1466 // Macro definitions.
1467 Record.push_back(PPOpts.Macros.size());
1468 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1469 AddString(PPOpts.Macros[I].first, Record);
1470 Record.push_back(PPOpts.Macros[I].second);
1471 }
1472
1473 // Includes
1474 Record.push_back(PPOpts.Includes.size());
1475 for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1476 AddString(PPOpts.Includes[I], Record);
1477
1478 // Macro includes
1479 Record.push_back(PPOpts.MacroIncludes.size());
1480 for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1481 AddString(PPOpts.MacroIncludes[I], Record);
1482
Douglas Gregorb6368752012-10-24 23:41:50 +00001483 Record.push_back(PPOpts.UsePredefines);
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00001484 // Detailed record is important since it is used for the module cache hash.
1485 Record.push_back(PPOpts.DetailedRecord);
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001486 AddString(PPOpts.ImplicitPCHInclude, Record);
1487 AddString(PPOpts.ImplicitPTHInclude, Record);
1488 Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1489 Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1490
Richard Smith0516b182015-09-08 19:40:14 +00001491 // Leave the options block.
1492 Stream.ExitBlock();
1493
Douglas Gregora3b20262011-05-06 21:43:30 +00001494 // Original file name and file ID
Douglas Gregor45fe0362009-05-12 01:31:05 +00001495 SourceManager &SM = Context.getSourceManager();
1496 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001497 auto *FileAbbrev = new BitCodeAbbrev();
Douglas Gregorfad10d82012-10-18 18:36:53 +00001498 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1499 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
Douglas Gregor45fe0362009-05-12 01:31:05 +00001500 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1501 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
1502
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001503 Record.clear();
Douglas Gregorfad10d82012-10-18 18:36:53 +00001504 Record.push_back(ORIGINAL_FILE);
Douglas Gregora3b20262011-05-06 21:43:30 +00001505 Record.push_back(SM.getMainFileID().getOpaqueValue());
Richard Smith7ed1bc92014-12-05 22:42:13 +00001506 EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
Douglas Gregor45fe0362009-05-12 01:31:05 +00001507 }
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00001508
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +00001509 Record.clear();
1510 Record.push_back(SM.getMainFileID().getOpaqueValue());
1511 Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1512
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001513 // Original PCH directory
1514 if (!OutputFile.empty() && OutputFile != "-") {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001515 auto *Abbrev = new BitCodeAbbrev();
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001516 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1517 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1518 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1519
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001520 SmallString<128> OutputPath(OutputFile);
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001521
Argyrios Kyrtzidisc56419e2015-07-31 00:58:32 +00001522 SM.getFileManager().makeAbsolutePath(OutputPath);
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001523 StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1524
Mehdi Amini57a41912015-09-10 01:46:39 +00001525 RecordData::value_type Record[] = {ORIGINAL_PCH_DIR};
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001526 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1527 }
1528
Douglas Gregor49491f72013-03-15 22:15:07 +00001529 WriteInputFiles(Context.SourceMgr,
1530 PP.getHeaderSearchInfo().getHeaderSearchOpts(),
Douglas Gregora3dd9002013-07-22 20:48:33 +00001531 PP.getLangOpts().Modules);
Douglas Gregor72be3902012-10-19 00:38:02 +00001532 Stream.ExitBlock();
Adrian Prantladbd2b12015-09-22 23:26:31 +00001533 return Signature;
Douglas Gregor72be3902012-10-19 00:38:02 +00001534}
1535
Douglas Gregor49491f72013-03-15 22:15:07 +00001536namespace {
1537 /// \brief An input file.
1538 struct InputFileEntry {
1539 const FileEntry *File;
1540 bool IsSystemFile;
Richard Smitha8cfffa2015-11-26 02:04:16 +00001541 bool IsTransient;
Douglas Gregor49491f72013-03-15 22:15:07 +00001542 bool BufferOverridden;
1543 };
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001544} // end anonymous namespace
Douglas Gregor49491f72013-03-15 22:15:07 +00001545
1546void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1547 HeaderSearchOptions &HSOpts,
Douglas Gregora3dd9002013-07-22 20:48:33 +00001548 bool Modules) {
Douglas Gregor72be3902012-10-19 00:38:02 +00001549 using namespace llvm;
1550 Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
Mehdi Amini57a41912015-09-10 01:46:39 +00001551
Douglas Gregor72be3902012-10-19 00:38:02 +00001552 // Create input-file abbreviation.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001553 auto *IFAbbrev = new BitCodeAbbrev();
Douglas Gregor72be3902012-10-19 00:38:02 +00001554 IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001555 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
Douglas Gregor72be3902012-10-19 00:38:02 +00001556 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1557 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001558 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
Richard Smitha8cfffa2015-11-26 02:04:16 +00001559 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
Douglas Gregor72be3902012-10-19 00:38:02 +00001560 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1561 unsigned IFAbbrevCode = Stream.EmitAbbrev(IFAbbrev);
1562
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001563 // Get all ContentCache objects for files, sorted by whether the file is a
1564 // system one or not. System files go at the back, users files at the front.
Douglas Gregor49491f72013-03-15 22:15:07 +00001565 std::deque<InputFileEntry> SortedFiles;
Douglas Gregor72be3902012-10-19 00:38:02 +00001566 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1567 // Get this source location entry.
1568 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
NAKAMURA Takumideca50f2012-10-19 01:53:57 +00001569 assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
Douglas Gregor72be3902012-10-19 00:38:02 +00001570
1571 // We only care about file entries that were not overridden.
1572 if (!SLoc->isFile())
1573 continue;
1574 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001575 if (!Cache->OrigEntry)
Douglas Gregor72be3902012-10-19 00:38:02 +00001576 continue;
1577
Douglas Gregor49491f72013-03-15 22:15:07 +00001578 InputFileEntry Entry;
1579 Entry.File = Cache->OrigEntry;
1580 Entry.IsSystemFile = Cache->IsSystemFile;
Richard Smitha8cfffa2015-11-26 02:04:16 +00001581 Entry.IsTransient = Cache->IsTransient;
Douglas Gregor49491f72013-03-15 22:15:07 +00001582 Entry.BufferOverridden = Cache->BufferOverridden;
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001583 if (Cache->IsSystemFile)
Douglas Gregor49491f72013-03-15 22:15:07 +00001584 SortedFiles.push_back(Entry);
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001585 else
Douglas Gregor49491f72013-03-15 22:15:07 +00001586 SortedFiles.push_front(Entry);
1587 }
1588
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001589 unsigned UserFilesNum = 0;
1590 // Write out all of the input files.
Richard Smithec216502015-02-13 19:48:37 +00001591 std::vector<uint64_t> InputFileOffsets;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001592 for (const auto &Entry : SortedFiles) {
Douglas Gregor49491f72013-03-15 22:15:07 +00001593 uint32_t &InputFileID = InputFileIDs[Entry.File];
Argyrios Kyrtzidise65856f2012-12-11 07:48:08 +00001594 if (InputFileID != 0)
1595 continue; // already recorded this file.
1596
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001597 // Record this entry's offset.
1598 InputFileOffsets.push_back(Stream.GetCurrentBitNo());
Argyrios Kyrtzidise65856f2012-12-11 07:48:08 +00001599
1600 InputFileID = InputFileOffsets.size();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001601
Douglas Gregor49491f72013-03-15 22:15:07 +00001602 if (!Entry.IsSystemFile)
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001603 ++UserFilesNum;
1604
Douglas Gregor72be3902012-10-19 00:38:02 +00001605 // Emit size/modification time for this file.
Mehdi Amini57a41912015-09-10 01:46:39 +00001606 // And whether this file was overridden.
1607 RecordData::value_type Record[] = {
Richard Smitha8cfffa2015-11-26 02:04:16 +00001608 INPUT_FILE,
1609 InputFileOffsets.size(),
1610 (uint64_t)Entry.File->getSize(),
1611 (uint64_t)getTimestampForOutput(Entry.File),
1612 Entry.BufferOverridden,
1613 Entry.IsTransient};
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001614
Richard Smith7ed1bc92014-12-05 22:42:13 +00001615 EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
1616 }
Douglas Gregor49491f72013-03-15 22:15:07 +00001617
Douglas Gregor112b9072012-10-18 05:31:06 +00001618 Stream.ExitBlock();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001619
1620 // Create input file offsets abbreviation.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001621 auto *OffsetsAbbrev = new BitCodeAbbrev();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001622 OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1623 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001624 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1625 // input files
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001626 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
1627 unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(OffsetsAbbrev);
1628
1629 // Write input file offsets.
Mehdi Amini57a41912015-09-10 01:46:39 +00001630 RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
1631 InputFileOffsets.size(), UserFilesNum};
Reid Kleckner012665e2015-05-21 00:13:09 +00001632 Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
Douglas Gregor55abb232009-04-10 20:39:37 +00001633}
1634
Douglas Gregora7f71a92009-04-10 03:52:48 +00001635//===----------------------------------------------------------------------===//
1636// Source Manager Serialization
1637//===----------------------------------------------------------------------===//
1638
1639/// \brief Create an abbreviation for the SLocEntry that refers to a
1640/// file.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001641static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001642 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001643
1644 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00001645 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001646 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1647 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1648 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1649 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregorb41ca8f2010-03-21 22:49:54 +00001650 // FileEntry fields.
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001651 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001652 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00001653 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1654 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
Douglas Gregor8f45df52009-04-16 22:23:12 +00001655 return Stream.EmitAbbrev(Abbrev);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001656}
1657
1658/// \brief Create an abbreviation for the SLocEntry that refers to a
1659/// buffer.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001660static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001661 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001662
1663 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00001664 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001665 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1666 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1667 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1668 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1669 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregor8f45df52009-04-16 22:23:12 +00001670 return Stream.EmitAbbrev(Abbrev);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001671}
1672
1673/// \brief Create an abbreviation for the SLocEntry that refers to a
1674/// buffer's blob.
Richard Smithaada85c2016-02-06 02:06:43 +00001675static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
1676 bool Compressed) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001677 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001678
1679 auto *Abbrev = new BitCodeAbbrev();
Richard Smithaada85c2016-02-06 02:06:43 +00001680 Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED
1681 : SM_SLOC_BUFFER_BLOB));
1682 if (Compressed)
1683 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
Douglas Gregora7f71a92009-04-10 03:52:48 +00001684 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregor8f45df52009-04-16 22:23:12 +00001685 return Stream.EmitAbbrev(Abbrev);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001686}
1687
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001688/// \brief Create an abbreviation for the SLocEntry that refers to a macro
1689/// expansion.
1690static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001691 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001692
1693 auto *Abbrev = new BitCodeAbbrev();
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001694 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001695 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1696 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1697 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1698 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregor83243272009-04-15 18:05:10 +00001699 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregor8f45df52009-04-16 22:23:12 +00001700 return Stream.EmitAbbrev(Abbrev);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001701}
1702
Douglas Gregor09b69892011-02-10 17:09:37 +00001703namespace {
1704 // Trait used for the on-disk hash table of header search information.
1705 class HeaderFileInfoTrait {
1706 ASTWriter &Writer;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001707 const HeaderSearch &HS;
Douglas Gregor09b69892011-02-10 17:09:37 +00001708
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001709 // Keep track of the framework names we've used during serialization.
1710 SmallVector<char, 128> FrameworkStringData;
1711 llvm::StringMap<unsigned> FrameworkNameOffset;
1712
Douglas Gregor09b69892011-02-10 17:09:37 +00001713 public:
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001714 HeaderFileInfoTrait(ASTWriter &Writer, const HeaderSearch &HS)
1715 : Writer(Writer), HS(HS) { }
Douglas Gregor09b69892011-02-10 17:09:37 +00001716
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001717 struct key_type {
1718 const FileEntry *FE;
1719 const char *Filename;
1720 };
1721 typedef const key_type &key_type_ref;
Douglas Gregor09b69892011-02-10 17:09:37 +00001722
1723 typedef HeaderFileInfo data_type;
1724 typedef const data_type &data_type_ref;
Justin Bogner25463f12014-04-18 20:27:24 +00001725 typedef unsigned hash_value_type;
1726 typedef unsigned offset_type;
Douglas Gregor09b69892011-02-10 17:09:37 +00001727
Richard Smithe75ee0f2015-08-17 07:13:32 +00001728 hash_value_type ComputeHash(key_type_ref key) {
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001729 // The hash is based only on size/time of the file, so that the reader can
1730 // match even when symlinking or excess path elements ("foo/../", "../")
1731 // change the form of the name. However, complete path is still the key.
1732 return llvm::hash_combine(key.FE->getSize(),
Richard Smithe75ee0f2015-08-17 07:13:32 +00001733 Writer.getTimestampForOutput(key.FE));
Douglas Gregor09b69892011-02-10 17:09:37 +00001734 }
1735
1736 std::pair<unsigned,unsigned>
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001737 EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001738 using namespace llvm::support;
Richard Smith386bb072015-08-18 23:42:23 +00001739 endian::Writer<little> LE(Out);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001740 unsigned KeyLen = strlen(key.Filename) + 1 + 8 + 8;
Richard Smith386bb072015-08-18 23:42:23 +00001741 LE.write<uint16_t>(KeyLen);
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001742 unsigned DataLen = 1 + 2 + 4 + 4;
Richard Smith386bb072015-08-18 23:42:23 +00001743 for (auto ModInfo : HS.getModuleMap().findAllModulesForHeader(key.FE))
1744 if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
1745 DataLen += 4;
1746 LE.write<uint8_t>(DataLen);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001747 return std::make_pair(KeyLen, DataLen);
Douglas Gregor09b69892011-02-10 17:09:37 +00001748 }
1749
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001750 void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001751 using namespace llvm::support;
1752 endian::Writer<little> LE(Out);
1753 LE.write<uint64_t>(key.FE->getSize());
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001754 KeyLen -= 8;
Richard Smithe75ee0f2015-08-17 07:13:32 +00001755 LE.write<uint64_t>(Writer.getTimestampForOutput(key.FE));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001756 KeyLen -= 8;
1757 Out.write(key.Filename, KeyLen);
Douglas Gregor09b69892011-02-10 17:09:37 +00001758 }
1759
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001760 void EmitData(raw_ostream &Out, key_type_ref key,
Douglas Gregor09b69892011-02-10 17:09:37 +00001761 data_type_ref Data, unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001762 using namespace llvm::support;
1763 endian::Writer<little> LE(Out);
Douglas Gregor09b69892011-02-10 17:09:37 +00001764 uint64_t Start = Out.tell(); (void)Start;
1765
Richard Smith386bb072015-08-18 23:42:23 +00001766 unsigned char Flags = (Data.isImport << 4)
1767 | (Data.isPragmaOnce << 3)
1768 | (Data.DirInfo << 1)
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001769 | Data.IndexHeaderMapHeader;
Justin Bognere1c147c2014-03-28 22:03:19 +00001770 LE.write<uint8_t>(Flags);
1771 LE.write<uint16_t>(Data.NumIncludes);
Douglas Gregor09b69892011-02-10 17:09:37 +00001772
1773 if (!Data.ControllingMacro)
Justin Bognere1c147c2014-03-28 22:03:19 +00001774 LE.write<uint32_t>(Data.ControllingMacroID);
Douglas Gregor09b69892011-02-10 17:09:37 +00001775 else
Justin Bognere1c147c2014-03-28 22:03:19 +00001776 LE.write<uint32_t>(Writer.getIdentifierRef(Data.ControllingMacro));
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001777
1778 unsigned Offset = 0;
1779 if (!Data.Framework.empty()) {
1780 // If this header refers into a framework, save the framework name.
1781 llvm::StringMap<unsigned>::iterator Pos
1782 = FrameworkNameOffset.find(Data.Framework);
1783 if (Pos == FrameworkNameOffset.end()) {
1784 Offset = FrameworkStringData.size() + 1;
1785 FrameworkStringData.append(Data.Framework.begin(),
1786 Data.Framework.end());
1787 FrameworkStringData.push_back(0);
1788
1789 FrameworkNameOffset[Data.Framework] = Offset;
1790 } else
1791 Offset = Pos->second;
1792 }
Justin Bognere1c147c2014-03-28 22:03:19 +00001793 LE.write<uint32_t>(Offset);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001794
Richard Smith386bb072015-08-18 23:42:23 +00001795 // FIXME: If the header is excluded, we should write out some
1796 // record of that fact.
1797 for (auto ModInfo : HS.getModuleMap().findAllModulesForHeader(key.FE)) {
1798 if (uint32_t ModID =
1799 Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule())) {
1800 uint32_t Value = (ModID << 2) | (unsigned)ModInfo.getRole();
1801 assert((Value >> 2) == ModID && "overflow in header module info");
1802 LE.write<uint32_t>(Value);
1803 }
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001804 }
1805
Douglas Gregor09b69892011-02-10 17:09:37 +00001806 assert(Out.tell() - Start == DataLen && "Wrong data length");
1807 }
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001808
1809 const char *strings_begin() const { return FrameworkStringData.begin(); }
1810 const char *strings_end() const { return FrameworkStringData.end(); }
Douglas Gregor09b69892011-02-10 17:09:37 +00001811 };
1812} // end anonymous namespace
1813
1814/// \brief Write the header search block for the list of files that
1815///
1816/// \param HS The header search structure to save.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001817void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001818 SmallVector<const FileEntry *, 16> FilesByUID;
Douglas Gregor09b69892011-02-10 17:09:37 +00001819 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
1820
1821 if (FilesByUID.size() > HS.header_file_size())
1822 FilesByUID.resize(HS.header_file_size());
1823
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001824 HeaderFileInfoTrait GeneratorTrait(*this, HS);
Justin Bognerbb094f02014-04-18 19:57:06 +00001825 llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001826 SmallVector<const char *, 4> SavedStrings;
Douglas Gregor09b69892011-02-10 17:09:37 +00001827 unsigned NumHeaderSearchEntries = 0;
1828 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1829 const FileEntry *File = FilesByUID[UID];
1830 if (!File)
1831 continue;
1832
Richard Smith386bb072015-08-18 23:42:23 +00001833 // Get the file info. This will load info from the external source if
1834 // necessary. Skip emitting this file if we have no information on it
1835 // as a header file (in which case HFI will be null) or if it hasn't
1836 // changed since it was loaded. Also skip it if it's for a modular header
1837 // from a different module; in that case, we rely on the module(s)
1838 // containing the header to provide this information.
Richard Smithd8879c82015-08-24 21:59:32 +00001839 const HeaderFileInfo *HFI =
1840 HS.getExistingFileInfo(File, /*WantExternal*/!Chain);
1841 if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001842 continue;
Douglas Gregor09b69892011-02-10 17:09:37 +00001843
Richard Smith7ed1bc92014-12-05 22:42:13 +00001844 // Massage the file path into an appropriate form.
Douglas Gregor09b69892011-02-10 17:09:37 +00001845 const char *Filename = File->getName();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001846 SmallString<128> FilenameTmp(Filename);
1847 if (PreparePathForOutput(FilenameTmp)) {
1848 // If we performed any translation on the file name at all, we need to
1849 // save this string, since the generator will refer to it later.
1850 Filename = strdup(FilenameTmp.c_str());
Douglas Gregor09b69892011-02-10 17:09:37 +00001851 SavedStrings.push_back(Filename);
1852 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001853
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001854 HeaderFileInfoTrait::key_type key = { File, Filename };
Richard Smith386bb072015-08-18 23:42:23 +00001855 Generator.insert(key, *HFI, GeneratorTrait);
Douglas Gregor09b69892011-02-10 17:09:37 +00001856 ++NumHeaderSearchEntries;
1857 }
1858
1859 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001860 SmallString<4096> TableData;
Douglas Gregor09b69892011-02-10 17:09:37 +00001861 uint32_t BucketOffset;
1862 {
Justin Bognere1c147c2014-03-28 22:03:19 +00001863 using namespace llvm::support;
Douglas Gregor09b69892011-02-10 17:09:37 +00001864 llvm::raw_svector_ostream Out(TableData);
1865 // Make sure that no bucket is at offset 0
Justin Bognere1c147c2014-03-28 22:03:19 +00001866 endian::Writer<little>(Out).write<uint32_t>(0);
Douglas Gregor09b69892011-02-10 17:09:37 +00001867 BucketOffset = Generator.Emit(Out, GeneratorTrait);
1868 }
1869
1870 // Create a blob abbreviation
1871 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001872
1873 auto *Abbrev = new BitCodeAbbrev();
Douglas Gregor09b69892011-02-10 17:09:37 +00001874 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1875 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1876 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001877 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor09b69892011-02-10 17:09:37 +00001878 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1879 unsigned TableAbbrev = Stream.EmitAbbrev(Abbrev);
1880
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001881 // Write the header search table
Mehdi Amini57a41912015-09-10 01:46:39 +00001882 RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
1883 NumHeaderSearchEntries, TableData.size()};
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001884 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
Yaron Keren92e1b622015-03-18 10:17:07 +00001885 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
Douglas Gregor09b69892011-02-10 17:09:37 +00001886
1887 // Free all of the strings we had to duplicate.
1888 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
David Greenebae0e352013-01-15 22:09:43 +00001889 free(const_cast<char *>(SavedStrings[I]));
Douglas Gregor09b69892011-02-10 17:09:37 +00001890}
1891
Douglas Gregora7f71a92009-04-10 03:52:48 +00001892/// \brief Writes the block containing the serialized form of the
1893/// source manager.
1894///
1895/// TODO: We should probably use an on-disk hash table (stored in a
1896/// blob), indexed based on the file name, so that we only create
1897/// entries for files that we actually need. In the common case (no
1898/// errors), we probably won't have to create file entries for any of
1899/// the files in the AST.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00001900void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001901 const Preprocessor &PP) {
Douglas Gregor258ae542009-04-27 06:38:32 +00001902 RecordData Record;
1903
Chris Lattner0910e3b2009-04-10 17:16:57 +00001904 // Enter the source manager block.
Richard Smithaada85c2016-02-06 02:06:43 +00001905 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001906
1907 // Abbreviations for the various kinds of source-location entries.
Chris Lattnerc4976c732009-04-27 19:03:22 +00001908 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
1909 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
Richard Smithaada85c2016-02-06 02:06:43 +00001910 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
1911 unsigned SLocBufferBlobCompressedAbbrv =
1912 CreateSLocBufferBlobAbbrev(Stream, true);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001913 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001914
Douglas Gregor258ae542009-04-27 06:38:32 +00001915 // Write out the source location entry table. We skip the first
1916 // entry, which is always the same dummy entry.
Chris Lattner12d61d32009-04-27 19:01:47 +00001917 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor258ae542009-04-27 06:38:32 +00001918 RecordData PreloadSLocs;
Douglas Gregor925296b2011-07-19 16:10:42 +00001919 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
1920 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
Sebastian Redl5c415f32010-07-22 17:01:13 +00001921 I != N; ++I) {
Douglas Gregor8655e882009-10-16 22:46:09 +00001922 // Get this source location entry.
Douglas Gregor925296b2011-07-19 16:10:42 +00001923 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00001924 FileID FID = FileID::get(I);
1925 assert(&SourceMgr.getSLocEntry(FID) == SLoc);
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00001926
Douglas Gregor258ae542009-04-27 06:38:32 +00001927 // Record the offset of this source-location entry.
1928 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
1929
1930 // Figure out which record code to use.
1931 unsigned Code;
1932 if (SLoc->isFile()) {
Douglas Gregor9dc32122011-11-16 20:05:18 +00001933 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1934 if (Cache->OrigEntry) {
Sebastian Redl539c5062010-08-18 23:57:32 +00001935 Code = SM_SLOC_FILE_ENTRY;
Argyrios Kyrtzidis92dd4662011-06-02 20:01:46 +00001936 } else
Sebastian Redl539c5062010-08-18 23:57:32 +00001937 Code = SM_SLOC_BUFFER_ENTRY;
Douglas Gregor258ae542009-04-27 06:38:32 +00001938 } else
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001939 Code = SM_SLOC_EXPANSION_ENTRY;
Douglas Gregor258ae542009-04-27 06:38:32 +00001940 Record.clear();
1941 Record.push_back(Code);
1942
Douglas Gregor925296b2011-07-19 16:10:42 +00001943 // Starting offset of this entry within this module, so skip the dummy.
1944 Record.push_back(SLoc->getOffset() - 2);
Douglas Gregor258ae542009-04-27 06:38:32 +00001945 if (SLoc->isFile()) {
1946 const SrcMgr::FileInfo &File = SLoc->getFile();
Richard Smithb22a1d12016-03-27 20:13:24 +00001947 AddSourceLocation(File.getIncludeLoc(), Record);
Douglas Gregor258ae542009-04-27 06:38:32 +00001948 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
1949 Record.push_back(File.hasLineDirectives());
1950
1951 const SrcMgr::ContentCache *Content = File.getContentCache();
Richard Smithaada85c2016-02-06 02:06:43 +00001952 bool EmitBlob = false;
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001953 if (Content->OrigEntry) {
1954 assert(Content->OrigEntry == Content->ContentsEntry &&
Douglas Gregor9dc32122011-11-16 20:05:18 +00001955 "Writing to AST an overridden file is not supported");
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001956
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001957 // The source location entry is a file. Emit input file ID.
1958 assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
1959 Record.push_back(InputFileIDs[Content->OrigEntry]);
Mike Stump11289f42009-09-09 15:08:12 +00001960
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001961 Record.push_back(File.NumCreatedFIDs);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00001962
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00001963 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00001964 if (FDI != FileDeclIDs.end()) {
1965 Record.push_back(FDI->second->FirstDeclIndex);
1966 Record.push_back(FDI->second->DeclIDs.size());
1967 } else {
1968 Record.push_back(0);
1969 Record.push_back(0);
1970 }
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001971
1972 Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
1973
Richard Smithaada85c2016-02-06 02:06:43 +00001974 if (Content->BufferOverridden || Content->IsTransient)
1975 EmitBlob = true;
Douglas Gregor258ae542009-04-27 06:38:32 +00001976 } else {
1977 // The source location entry is a buffer. The blob associated
1978 // with this entry contains the contents of the buffer.
1979
1980 // We add one to the size so that we capture the trailing NULL
1981 // that is required by llvm::MemoryBuffer::getMemBuffer (on
1982 // the reader side).
Douglas Gregor874cc622010-03-16 00:35:39 +00001983 const llvm::MemoryBuffer *Buffer
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001984 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
Douglas Gregor258ae542009-04-27 06:38:32 +00001985 const char *Name = Buffer->getBufferIdentifier();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001986 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001987 StringRef(Name, strlen(Name) + 1));
Richard Smithaada85c2016-02-06 02:06:43 +00001988 EmitBlob = true;
Douglas Gregor258ae542009-04-27 06:38:32 +00001989
Douglas Gregor925296b2011-07-19 16:10:42 +00001990 if (strcmp(Name, "<built-in>") == 0) {
1991 PreloadSLocs.push_back(SLocEntryOffsets.size());
1992 }
Douglas Gregor258ae542009-04-27 06:38:32 +00001993 }
Richard Smithaada85c2016-02-06 02:06:43 +00001994
1995 if (EmitBlob) {
1996 // Include the implicit terminating null character in the on-disk buffer
1997 // if we're writing it uncompressed.
1998 const llvm::MemoryBuffer *Buffer =
1999 Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
2000 StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
2001
2002 // Compress the buffer if possible. We expect that almost all PCM
2003 // consumers will not want its contents.
2004 SmallString<0> CompressedBuffer;
2005 if (llvm::zlib::compress(Blob.drop_back(1), CompressedBuffer) ==
2006 llvm::zlib::StatusOK) {
2007 RecordData::value_type Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED,
2008 Blob.size() - 1};
2009 Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
2010 CompressedBuffer);
2011 } else {
2012 RecordData::value_type Record[] = {SM_SLOC_BUFFER_BLOB};
2013 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob);
2014 }
2015 }
Douglas Gregor258ae542009-04-27 06:38:32 +00002016 } else {
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00002017 // The source location entry is a macro expansion.
Chandler Carruthee4c1d12011-07-26 04:56:51 +00002018 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
Richard Smithb22a1d12016-03-27 20:13:24 +00002019 AddSourceLocation(Expansion.getSpellingLoc(), Record);
2020 AddSourceLocation(Expansion.getExpansionLocStart(), Record);
2021 AddSourceLocation(Expansion.isMacroArgExpansion()
2022 ? SourceLocation()
2023 : Expansion.getExpansionLocEnd(),
2024 Record);
Douglas Gregor258ae542009-04-27 06:38:32 +00002025
2026 // Compute the token length for this macro expansion.
Douglas Gregor925296b2011-07-19 16:10:42 +00002027 unsigned NextOffset = SourceMgr.getNextLocalOffset();
Douglas Gregor8655e882009-10-16 22:46:09 +00002028 if (I + 1 != N)
Douglas Gregor925296b2011-07-19 16:10:42 +00002029 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
Douglas Gregor258ae542009-04-27 06:38:32 +00002030 Record.push_back(NextOffset - SLoc->getOffset() - 1);
Mehdi Amini5ae4a852015-09-09 20:35:37 +00002031 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
Douglas Gregor258ae542009-04-27 06:38:32 +00002032 }
2033 }
2034
Douglas Gregor8f45df52009-04-16 22:23:12 +00002035 Stream.ExitBlock();
Douglas Gregor258ae542009-04-27 06:38:32 +00002036
2037 if (SLocEntryOffsets.empty())
2038 return;
2039
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002040 // Write the source-location offsets table into the AST block. This
Douglas Gregor258ae542009-04-27 06:38:32 +00002041 // table is used for lazily loading source-location information.
2042 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002043
2044 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00002045 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
Douglas Gregor258ae542009-04-27 06:38:32 +00002046 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
Douglas Gregor925296b2011-07-19 16:10:42 +00002047 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
Douglas Gregor258ae542009-04-27 06:38:32 +00002048 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
2049 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00002050 {
2051 RecordData::value_type Record[] = {
2052 SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
2053 SourceMgr.getNextLocalOffset() - 1 /* skip dummy */};
2054 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
2055 bytes(SLocEntryOffsets));
2056 }
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002057 // Write the source location entry preloads array, telling the AST
Douglas Gregor258ae542009-04-27 06:38:32 +00002058 // reader which source locations entries it should load eagerly.
Sebastian Redl539c5062010-08-18 23:57:32 +00002059 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregor925296b2011-07-19 16:10:42 +00002060
2061 // Write the line table. It depends on remapping working, so it must come
2062 // after the source location offsets.
2063 if (SourceMgr.hasLineTable()) {
2064 LineTableInfo &LineTable = SourceMgr.getLineTable();
2065
2066 Record.clear();
Richard Smith63078492015-09-01 07:41:55 +00002067
2068 // Emit the needed file names.
2069 llvm::DenseMap<int, int> FilenameMap;
2070 for (const auto &L : LineTable) {
2071 if (L.first.ID < 0)
2072 continue;
2073 for (auto &LE : L.second) {
2074 if (FilenameMap.insert(std::make_pair(LE.FilenameID,
2075 FilenameMap.size())).second)
2076 AddPath(LineTable.getFilename(LE.FilenameID), Record);
2077 }
2078 }
2079 Record.push_back(0);
Douglas Gregor925296b2011-07-19 16:10:42 +00002080
2081 // Emit the line entries
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002082 for (const auto &L : LineTable) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002083 // Only emit entries for local files.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002084 if (L.first.ID < 0)
Douglas Gregor925296b2011-07-19 16:10:42 +00002085 continue;
2086
2087 // Emit the file ID
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002088 Record.push_back(L.first.ID);
Douglas Gregor925296b2011-07-19 16:10:42 +00002089
2090 // Emit the line entries
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002091 Record.push_back(L.second.size());
2092 for (const auto &LE : L.second) {
2093 Record.push_back(LE.FileOffset);
2094 Record.push_back(LE.LineNo);
2095 Record.push_back(FilenameMap[LE.FilenameID]);
2096 Record.push_back((unsigned)LE.FileKind);
2097 Record.push_back(LE.IncludeOffset);
Douglas Gregor925296b2011-07-19 16:10:42 +00002098 }
2099 }
Richard Smith63078492015-09-01 07:41:55 +00002100
Douglas Gregor925296b2011-07-19 16:10:42 +00002101 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
2102 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00002103}
2104
Douglas Gregorc5046832009-04-27 18:38:38 +00002105//===----------------------------------------------------------------------===//
2106// Preprocessor Serialization
2107//===----------------------------------------------------------------------===//
2108
Argyrios Kyrtzidis0aef0f02013-03-15 22:43:10 +00002109static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
2110 const Preprocessor &PP) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002111 if (MacroInfo *MI = MD->getMacroInfo())
2112 if (MI->isBuiltinMacro())
2113 return true;
Argyrios Kyrtzidis0aef0f02013-03-15 22:43:10 +00002114
2115 if (IsModule) {
2116 SourceLocation Loc = MD->getLocation();
2117 if (Loc.isInvalid())
2118 return true;
2119 if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
2120 return true;
2121 }
2122
2123 return false;
2124}
2125
Chris Lattnereeffaef2009-04-10 17:15:23 +00002126/// \brief Writes the block containing the serialized form of the
2127/// preprocessor.
2128///
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00002129void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002130 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
2131 if (PPRec)
2132 WritePreprocessorDetail(*PPRec);
2133
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002134 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00002135 RecordData ModuleMacroRecord;
Chris Lattner0910e3b2009-04-10 17:16:57 +00002136
Chris Lattner0af3ba12009-04-13 01:29:17 +00002137 // If the preprocessor __COUNTER__ value has been bumped, remember it.
2138 if (PP.getCounterValue() != 0) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002139 RecordData::value_type Record[] = {PP.getCounterValue()};
Sebastian Redl539c5062010-08-18 23:57:32 +00002140 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
Douglas Gregoreda6a892009-04-26 00:07:37 +00002141 }
2142
2143 // Enter the preprocessor block.
Douglas Gregor796d76a2010-10-20 22:00:55 +00002144 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
Mike Stump11289f42009-09-09 15:08:12 +00002145
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002146 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
Richard Smithb5aaf5a2015-09-01 02:35:58 +00002147 // FIXME: Include a location for the use, and say which one was used.
Douglas Gregoreda6a892009-04-26 00:07:37 +00002148 if (PP.SawDateOrTime())
Richard Smithb5aaf5a2015-09-01 02:35:58 +00002149 PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
Douglas Gregor796d76a2010-10-20 22:00:55 +00002150
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002151 // Loop over all the macro directives that are live at the end of the file,
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002152 // emitting each to the PP section.
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002153
Richard Smithee977932015-05-01 21:22:17 +00002154 // Construct the list of identifiers with macro directives that need to be
2155 // serialized.
2156 SmallVector<const IdentifierInfo *, 128> MacroIdentifiers;
2157 for (auto &Id : PP.getIdentifierTable())
2158 if (Id.second->hadMacroDefinition() &&
2159 (!Id.second->isFromAST() ||
2160 Id.second->hasChangedSinceDeserialization()))
2161 MacroIdentifiers.push_back(Id.second);
Douglas Gregor2e5571d2011-02-10 18:20:09 +00002162 // Sort the set of macro definitions that need to be serialized by the
2163 // name of the macro, to provide a stable ordering.
Richard Smithee977932015-05-01 21:22:17 +00002164 std::sort(MacroIdentifiers.begin(), MacroIdentifiers.end(),
2165 llvm::less_ptr<IdentifierInfo>());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002166
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002167 // Emit the macro directives as a list and associate the offset with the
2168 // identifier they belong to.
Richard Smithee977932015-05-01 21:22:17 +00002169 for (const IdentifierInfo *Name : MacroIdentifiers) {
2170 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name);
Richard Smithd7329392015-04-21 21:46:32 +00002171 auto StartOffset = Stream.GetCurrentBitNo();
2172
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002173 // Emit the macro directives in reverse source order.
2174 for (; MD; MD = MD->getPrevious()) {
Richard Smithd7329392015-04-21 21:46:32 +00002175 // Once we hit an ignored macro, we're done: the rest of the chain
2176 // will all be ignored macros.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002177 if (shouldIgnoreMacro(MD, IsModule, PP))
Richard Smithd7329392015-04-21 21:46:32 +00002178 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002179
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002180 AddSourceLocation(MD->getLocation(), Record);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002181 Record.push_back(MD->getKind());
Richard Smithdaa69e02014-07-25 04:40:03 +00002182 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
Richard Smith3981b172015-04-30 02:16:23 +00002183 Record.push_back(getMacroRef(DefMD->getInfo(), Name));
Richard Smith713369b2015-04-23 20:40:50 +00002184 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002185 Record.push_back(VisMD->isPublic());
2186 }
Richard Smithb8b2ed62015-04-23 18:18:26 +00002187 }
Richard Smithd7329392015-04-21 21:46:32 +00002188
Richard Smithb8b2ed62015-04-23 18:18:26 +00002189 // Write out any exported module macros.
Richard Smithee977932015-05-01 21:22:17 +00002190 bool EmittedModuleMacros = false;
Manman Ren33d80292016-05-31 18:19:32 +00002191 // We write out exported module macros for PCH as well.
2192 auto Leafs = PP.getLeafModuleMacros(Name);
2193 SmallVector<ModuleMacro*, 8> Worklist(Leafs.begin(), Leafs.end());
2194 llvm::DenseMap<ModuleMacro*, unsigned> Visits;
2195 while (!Worklist.empty()) {
2196 auto *Macro = Worklist.pop_back_val();
Richard Smithd7329392015-04-21 21:46:32 +00002197
Manman Ren33d80292016-05-31 18:19:32 +00002198 // Emit a record indicating this submodule exports this macro.
2199 ModuleMacroRecord.push_back(
2200 getSubmoduleID(Macro->getOwningModule()));
2201 ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
2202 for (auto *M : Macro->overrides())
2203 ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
Richard Smithd7329392015-04-21 21:46:32 +00002204
Manman Ren33d80292016-05-31 18:19:32 +00002205 Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2206 ModuleMacroRecord.clear();
Richard Smithd7329392015-04-21 21:46:32 +00002207
Manman Ren33d80292016-05-31 18:19:32 +00002208 // Enqueue overridden macros once we've visited all their ancestors.
2209 for (auto *M : Macro->overrides())
2210 if (++Visits[M] == M->getNumOverridingMacros())
2211 Worklist.push_back(M);
Richard Smithee977932015-05-01 21:22:17 +00002212
Manman Ren33d80292016-05-31 18:19:32 +00002213 EmittedModuleMacros = true;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002214 }
Richard Smithd7329392015-04-21 21:46:32 +00002215
Richard Smithee977932015-05-01 21:22:17 +00002216 if (Record.empty() && !EmittedModuleMacros)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002217 continue;
2218
Richard Smithd7329392015-04-21 21:46:32 +00002219 IdentMacroDirectivesOffsetMap[Name] = StartOffset;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002220 Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2221 Record.clear();
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002222 }
Alexander Kornienko1d26c022012-09-25 17:18:14 +00002223
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002224 /// \brief Offsets of each of the macros into the bitstream, indexed by
2225 /// the local macro ID
2226 ///
2227 /// For each identifier that is associated with a macro, this map
2228 /// provides the offset into the bitstream where that macro is
2229 /// defined.
2230 std::vector<uint32_t> MacroOffsets;
2231
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002232 for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2233 const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2234 MacroInfo *MI = MacroInfosToEmit[I].MI;
2235 MacroID ID = MacroInfosToEmit[I].ID;
Douglas Gregoreb114da2010-10-01 01:03:07 +00002236
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002237 if (ID < FirstMacroID) {
2238 assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2239 continue;
Chris Lattner2199f5b2009-04-10 18:08:30 +00002240 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002241
2242 // Record the local offset of this macro.
2243 unsigned Index = ID - FirstMacroID;
2244 if (Index == MacroOffsets.size())
2245 MacroOffsets.push_back(Stream.GetCurrentBitNo());
2246 else {
2247 if (Index > MacroOffsets.size())
2248 MacroOffsets.resize(Index + 1);
2249
2250 MacroOffsets[Index] = Stream.GetCurrentBitNo();
2251 }
2252
2253 AddIdentifierRef(Name, Record);
2254 Record.push_back(inferSubmoduleIDFromLocation(MI->getDefinitionLoc()));
2255 AddSourceLocation(MI->getDefinitionLoc(), Record);
2256 AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2257 Record.push_back(MI->isUsed());
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00002258 Record.push_back(MI->isUsedForHeaderGuard());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002259 unsigned Code;
2260 if (MI->isObjectLike()) {
2261 Code = PP_MACRO_OBJECT_LIKE;
2262 } else {
2263 Code = PP_MACRO_FUNCTION_LIKE;
2264
2265 Record.push_back(MI->isC99Varargs());
2266 Record.push_back(MI->isGNUVarargs());
2267 Record.push_back(MI->hasCommaPasting());
2268 Record.push_back(MI->getNumArgs());
Daniel Marjamakie4770da2015-05-29 09:15:24 +00002269 for (const IdentifierInfo *Arg : MI->args())
2270 AddIdentifierRef(Arg, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002271 }
2272
2273 // If we have a detailed preprocessing record, record the macro definition
2274 // ID that corresponds to this macro.
2275 if (PPRec)
2276 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2277
2278 Stream.EmitRecord(Code, Record);
2279 Record.clear();
2280
2281 // Emit the tokens array.
2282 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2283 // Note that we know that the preprocessor does not have any annotation
2284 // tokens in it because they are created by the parser, and thus can't
2285 // be in a macro definition.
2286 const Token &Tok = MI->getReplacementToken(TokNo);
John McCallf413f5e2013-05-03 00:10:13 +00002287 AddToken(Tok, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002288 Stream.EmitRecord(PP_TOKEN, Record);
2289 Record.clear();
2290 }
2291 ++NumMacros;
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002292 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002293
Douglas Gregor92a96f52011-02-08 21:58:10 +00002294 Stream.ExitBlock();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002295
2296 // Write the offsets table for macro IDs.
2297 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002298
Richard Smith13090a22015-04-10 02:02:24 +00002299 auto *Abbrev = new BitCodeAbbrev();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002300 Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2301 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2302 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2303 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2304
2305 unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00002306 {
2307 RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
2308 FirstMacroID - NUM_PREDEF_MACRO_IDS};
2309 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
2310 }
Douglas Gregor92a96f52011-02-08 21:58:10 +00002311}
2312
2313void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
Argyrios Kyrtzidis7f448362011-09-19 20:40:42 +00002314 if (PPRec.local_begin() == PPRec.local_end())
Douglas Gregor92a96f52011-02-08 21:58:10 +00002315 return;
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002316
Argyrios Kyrtzidis64f63812011-09-19 20:40:25 +00002317 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002318
Douglas Gregor92a96f52011-02-08 21:58:10 +00002319 // Enter the preprocessor block.
2320 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002321
Douglas Gregoraae92242010-03-19 21:51:54 +00002322 // If the preprocessor has a preprocessing record, emit it.
2323 unsigned NumPreprocessingRecords = 0;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002324 using namespace llvm;
2325
2326 // Set up the abbreviation for
2327 unsigned InclusionAbbrev = 0;
2328 {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002329 auto *Abbrev = new BitCodeAbbrev();
Douglas Gregor92a96f52011-02-08 21:58:10 +00002330 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
Douglas Gregor92a96f52011-02-08 21:58:10 +00002331 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2332 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2333 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
Argyrios Kyrtzidisf590e092012-10-02 16:10:46 +00002334 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
Douglas Gregor92a96f52011-02-08 21:58:10 +00002335 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2336 InclusionAbbrev = Stream.EmitAbbrev(Abbrev);
2337 }
2338
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002339 unsigned FirstPreprocessorEntityID
2340 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
2341 + NUM_PREDEF_PP_ENTITY_IDS;
2342 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002343 RecordData Record;
Argyrios Kyrtzidis7f448362011-09-19 20:40:42 +00002344 for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2345 EEnd = PPRec.local_end();
Douglas Gregor0d4b4312011-08-04 17:06:18 +00002346 E != EEnd;
2347 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
Douglas Gregor92a96f52011-02-08 21:58:10 +00002348 Record.clear();
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002349
Richard Smith66a81862015-05-04 02:25:31 +00002350 PreprocessedEntityOffsets.push_back(
2351 PPEntityOffset((*E)->getSourceRange(), Stream.GetCurrentBitNo()));
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002352
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002353 if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002354 // Record this macro definition's ID.
2355 MacroDefinitions[MD] = NextPreprocessorEntityID;
Richard Smith66a81862015-05-04 02:25:31 +00002356
Douglas Gregor92a96f52011-02-08 21:58:10 +00002357 AddIdentifierRef(MD->getName(), Record);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002358 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2359 continue;
Douglas Gregoraae92242010-03-19 21:51:54 +00002360 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002361
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002362 if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
Argyrios Kyrtzidis80f78b92011-09-08 17:18:41 +00002363 Record.push_back(ME->isBuiltinMacro());
2364 if (ME->isBuiltinMacro())
2365 AddIdentifierRef(ME->getName(), Record);
2366 else
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002367 Record.push_back(MacroDefinitions[ME->getDefinition()]);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00002368 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002369 continue;
2370 }
2371
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002372 if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
Douglas Gregor92a96f52011-02-08 21:58:10 +00002373 Record.push_back(PPD_INCLUSION_DIRECTIVE);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002374 Record.push_back(ID->getFileName().size());
2375 Record.push_back(ID->wasInQuotes());
2376 Record.push_back(static_cast<unsigned>(ID->getKind()));
Argyrios Kyrtzidisf590e092012-10-02 16:10:46 +00002377 Record.push_back(ID->importedModule());
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002378 SmallString<64> Buffer;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002379 Buffer += ID->getFileName();
Argyrios Kyrtzidis8dbcfc32012-03-08 01:08:28 +00002380 // Check that the FileEntry is not null because it was not resolved and
2381 // we create a PCH even with compiler errors.
2382 if (ID->getFile())
2383 Buffer += ID->getFile()->getName();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00002384 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002385 continue;
2386 }
2387
2388 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2389 }
Douglas Gregor8f45df52009-04-16 22:23:12 +00002390 Stream.ExitBlock();
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002391
Douglas Gregoraae92242010-03-19 21:51:54 +00002392 // Write the offsets table for the preprocessing record.
2393 if (NumPreprocessingRecords > 0) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002394 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2395
Douglas Gregoraae92242010-03-19 21:51:54 +00002396 // Write the offsets table for identifier IDs.
2397 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002398
2399 auto *Abbrev = new BitCodeAbbrev();
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002400 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002401 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
Douglas Gregoraae92242010-03-19 21:51:54 +00002402 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002403 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002404
Mehdi Amini57a41912015-09-10 01:46:39 +00002405 RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
2406 FirstPreprocessorEntityID -
2407 NUM_PREDEF_PP_ENTITY_IDS};
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002408 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00002409 bytes(PreprocessedEntityOffsets));
Douglas Gregoraae92242010-03-19 21:51:54 +00002410 }
Chris Lattnereeffaef2009-04-10 17:15:23 +00002411}
2412
Richard Smith386bb072015-08-18 23:42:23 +00002413unsigned ASTWriter::getLocalOrImportedSubmoduleID(Module *Mod) {
Richard Smith080056b2015-08-18 21:53:42 +00002414 if (!Mod)
2415 return 0;
2416
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002417 llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
2418 if (Known != SubmoduleIDs.end())
2419 return Known->second;
Richard Smith386bb072015-08-18 23:42:23 +00002420
Richard Smithdc1f0422016-07-20 19:10:16 +00002421 auto *Top = Mod->getTopLevelModule();
2422 if (Top != WritingModule &&
2423 !Top->fullModuleNameIs(StringRef(getLangOpts().CurrentModule)))
Richard Smith386bb072015-08-18 23:42:23 +00002424 return 0;
2425
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002426 return SubmoduleIDs[Mod] = NextSubmoduleID++;
2427}
2428
Richard Smith386bb072015-08-18 23:42:23 +00002429unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2430 // FIXME: This can easily happen, if we have a reference to a submodule that
2431 // did not result in us loading a module file for that submodule. For
2432 // instance, a cross-top-level-module 'conflict' declaration will hit this.
2433 unsigned ID = getLocalOrImportedSubmoduleID(Mod);
2434 assert((ID || !Mod) &&
2435 "asked for module ID for non-local, non-imported module");
2436 return ID;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00002437}
2438
Douglas Gregor253eefe2011-12-01 00:59:36 +00002439/// \brief Compute the number of modules within the given tree (including the
2440/// given module).
2441static unsigned getNumberOfModules(Module *Mod) {
2442 unsigned ChildModules = 0;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002443 for (auto Sub = Mod->submodule_begin(), SubEnd = Mod->submodule_end();
Douglas Gregor253eefe2011-12-01 00:59:36 +00002444 Sub != SubEnd; ++Sub)
Douglas Gregoreb90e832012-01-04 23:32:19 +00002445 ChildModules += getNumberOfModules(*Sub);
Douglas Gregor253eefe2011-12-01 00:59:36 +00002446
2447 return ChildModules + 1;
2448}
2449
Douglas Gregorde3ef502011-11-30 23:21:26 +00002450void ASTWriter::WriteSubmodules(Module *WritingModule) {
Douglas Gregor69021972011-11-30 17:33:56 +00002451 // Enter the submodule description block.
Richard Smith202210b2014-10-24 20:23:01 +00002452 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
Douglas Gregor69021972011-11-30 17:33:56 +00002453
2454 // Write the abbreviations needed for the submodules block.
2455 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002456
2457 auto *Abbrev = new BitCodeAbbrev();
Douglas Gregor69021972011-11-30 17:33:56 +00002458 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002459 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
Douglas Gregor69021972011-11-30 17:33:56 +00002460 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
2461 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2462 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
Richard Smith9bca2982014-03-08 00:03:56 +00002463 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2464 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
Douglas Gregora686e1b2012-01-27 19:52:33 +00002465 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
Douglas Gregor73441092011-12-05 22:27:44 +00002466 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
Douglas Gregor73441092011-12-05 22:27:44 +00002467 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002468 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
Douglas Gregor69021972011-11-30 17:33:56 +00002469 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2470 unsigned DefinitionAbbrev = Stream.EmitAbbrev(Abbrev);
2471
2472 Abbrev = new BitCodeAbbrev();
Douglas Gregor524e33e2011-12-08 19:11:24 +00002473 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
Douglas Gregor69021972011-11-30 17:33:56 +00002474 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2475 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(Abbrev);
2476
2477 Abbrev = new BitCodeAbbrev();
2478 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2479 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2480 unsigned HeaderAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregor524e33e2011-12-08 19:11:24 +00002481
2482 Abbrev = new BitCodeAbbrev();
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +00002483 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2484 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2485 unsigned TopHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2486
2487 Abbrev = new BitCodeAbbrev();
Douglas Gregor524e33e2011-12-08 19:11:24 +00002488 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2489 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2490 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(Abbrev);
2491
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002492 Abbrev = new BitCodeAbbrev();
2493 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
Richard Smitha3feee22013-10-28 22:18:19 +00002494 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2495 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002496 unsigned RequiresAbbrev = Stream.EmitAbbrev(Abbrev);
2497
Douglas Gregor59527662012-10-15 06:28:11 +00002498 Abbrev = new BitCodeAbbrev();
2499 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2500 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2501 unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2502
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002503 Abbrev = new BitCodeAbbrev();
Richard Smith306d8922014-10-22 23:50:56 +00002504 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
2505 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2506 unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2507
2508 Abbrev = new BitCodeAbbrev();
Lawrence Crowlb53e5482013-06-20 21:14:14 +00002509 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2510 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2511 unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2512
2513 Abbrev = new BitCodeAbbrev();
Richard Smith202210b2014-10-24 20:23:01 +00002514 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
2515 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2516 unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2517
2518 Abbrev = new BitCodeAbbrev();
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002519 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2520 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2521 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2522 unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(Abbrev);
2523
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002524 Abbrev = new BitCodeAbbrev();
2525 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2526 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2527 unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(Abbrev);
2528
Douglas Gregorfb912652013-03-20 21:10:35 +00002529 Abbrev = new BitCodeAbbrev();
2530 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2531 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
2532 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
2533 unsigned ConflictAbbrev = Stream.EmitAbbrev(Abbrev);
2534
Douglas Gregor253eefe2011-12-01 00:59:36 +00002535 // Write the submodule metadata block.
Mehdi Amini57a41912015-09-10 01:46:39 +00002536 RecordData::value_type Record[] = {getNumberOfModules(WritingModule),
2537 FirstSubmoduleID -
2538 NUM_PREDEF_SUBMODULE_IDS};
Douglas Gregor253eefe2011-12-01 00:59:36 +00002539 Stream.EmitRecord(SUBMODULE_METADATA, Record);
2540
Douglas Gregor69021972011-11-30 17:33:56 +00002541 // Write all of the submodules.
Douglas Gregorde3ef502011-11-30 23:21:26 +00002542 std::queue<Module *> Q;
Douglas Gregor69021972011-11-30 17:33:56 +00002543 Q.push(WritingModule);
Douglas Gregor69021972011-11-30 17:33:56 +00002544 while (!Q.empty()) {
Douglas Gregorde3ef502011-11-30 23:21:26 +00002545 Module *Mod = Q.front();
Douglas Gregor69021972011-11-30 17:33:56 +00002546 Q.pop();
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002547 unsigned ID = getSubmoduleID(Mod);
Mehdi Amini57a41912015-09-10 01:46:39 +00002548
2549 uint64_t ParentID = 0;
Douglas Gregor69021972011-11-30 17:33:56 +00002550 if (Mod->Parent) {
2551 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
Mehdi Amini57a41912015-09-10 01:46:39 +00002552 ParentID = SubmoduleIDs[Mod->Parent];
Douglas Gregor69021972011-11-30 17:33:56 +00002553 }
Mehdi Amini57a41912015-09-10 01:46:39 +00002554
2555 // Emit the definition of the block.
2556 {
2557 RecordData::value_type Record[] = {
2558 SUBMODULE_DEFINITION, ID, ParentID, Mod->IsFramework, Mod->IsExplicit,
2559 Mod->IsSystem, Mod->IsExternC, Mod->InferSubmodules,
2560 Mod->InferExplicitSubmodules, Mod->InferExportWildcard,
2561 Mod->ConfigMacrosExhaustive};
2562 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2563 }
2564
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002565 // Emit the requirements.
Richard Smith080056b2015-08-18 21:53:42 +00002566 for (const auto &R : Mod->Requirements) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002567 RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.second};
Richard Smith080056b2015-08-18 21:53:42 +00002568 Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.first);
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002569 }
2570
Douglas Gregor69021972011-11-30 17:33:56 +00002571 // Emit the umbrella header, if there is one.
Richard Smith2b63d152015-05-16 02:28:53 +00002572 if (auto UmbrellaHeader = Mod->getUmbrellaHeader()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002573 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
Richard Smith2b63d152015-05-16 02:28:53 +00002574 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2575 UmbrellaHeader.NameAsWritten);
2576 } else if (auto UmbrellaDir = Mod->getUmbrellaDir()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002577 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
2578 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
Richard Smith2b63d152015-05-16 02:28:53 +00002579 UmbrellaDir.NameAsWritten);
Douglas Gregor69021972011-11-30 17:33:56 +00002580 }
Richard Smith306d8922014-10-22 23:50:56 +00002581
Douglas Gregor69021972011-11-30 17:33:56 +00002582 // Emit the headers.
Richard Smith202210b2014-10-24 20:23:01 +00002583 struct {
Richard Smith3c1a41a2014-12-02 00:08:08 +00002584 unsigned RecordKind;
Richard Smith202210b2014-10-24 20:23:01 +00002585 unsigned Abbrev;
Richard Smith3c1a41a2014-12-02 00:08:08 +00002586 Module::HeaderKind HeaderKind;
Richard Smith202210b2014-10-24 20:23:01 +00002587 } HeaderLists[] = {
Richard Smith3c1a41a2014-12-02 00:08:08 +00002588 {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
2589 {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
2590 {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
Richard Smith202210b2014-10-24 20:23:01 +00002591 {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
Richard Smith3c1a41a2014-12-02 00:08:08 +00002592 Module::HK_PrivateTextual},
2593 {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
Richard Smith202210b2014-10-24 20:23:01 +00002594 };
2595 for (auto &HL : HeaderLists) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002596 RecordData::value_type Record[] = {HL.RecordKind};
Richard Smith3c1a41a2014-12-02 00:08:08 +00002597 for (auto &H : Mod->Headers[HL.HeaderKind])
2598 Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
2599 }
2600
2601 // Emit the top headers.
2602 {
2603 auto TopHeaders = Mod->getTopHeaders(PP->getFileManager());
Mehdi Amini57a41912015-09-10 01:46:39 +00002604 RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
Richard Smith3c1a41a2014-12-02 00:08:08 +00002605 for (auto *H : TopHeaders)
2606 Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, H->getName());
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +00002607 }
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002608
2609 // Emit the imports.
2610 if (!Mod->Imports.empty()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002611 RecordData Record;
Richard Smith080056b2015-08-18 21:53:42 +00002612 for (auto *I : Mod->Imports)
2613 Record.push_back(getSubmoduleID(I));
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002614 Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2615 }
2616
Douglas Gregor24bb9232011-12-02 18:58:38 +00002617 // Emit the exports.
2618 if (!Mod->Exports.empty()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002619 RecordData Record;
Richard Smith080056b2015-08-18 21:53:42 +00002620 for (const auto &E : Mod->Exports) {
2621 // FIXME: This may fail; we don't require that all exported modules
2622 // are local or imported.
2623 Record.push_back(getSubmoduleID(E.getPointer()));
2624 Record.push_back(E.getInt());
Douglas Gregor24bb9232011-12-02 18:58:38 +00002625 }
2626 Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2627 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002628
Daniel Jasperba7f2f72013-09-24 09:14:14 +00002629 //FIXME: How do we emit the 'use'd modules? They may not be submodules.
2630 // Might be unnecessary as use declarations are only used to build the
2631 // module itself.
2632
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002633 // Emit the link libraries.
Richard Smith080056b2015-08-18 21:53:42 +00002634 for (const auto &LL : Mod->LinkLibraries) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002635 RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
2636 LL.IsFramework};
Richard Smith080056b2015-08-18 21:53:42 +00002637 Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002638 }
2639
Douglas Gregorfb912652013-03-20 21:10:35 +00002640 // Emit the conflicts.
Richard Smith080056b2015-08-18 21:53:42 +00002641 for (const auto &C : Mod->Conflicts) {
Richard Smith080056b2015-08-18 21:53:42 +00002642 // FIXME: This may fail; we don't require that all conflicting modules
2643 // are local or imported.
Mehdi Amini57a41912015-09-10 01:46:39 +00002644 RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
2645 getSubmoduleID(C.Other)};
Richard Smith080056b2015-08-18 21:53:42 +00002646 Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message);
Douglas Gregorfb912652013-03-20 21:10:35 +00002647 }
2648
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002649 // Emit the configuration macros.
Richard Smith080056b2015-08-18 21:53:42 +00002650 for (const auto &CM : Mod->ConfigMacros) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002651 RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
Richard Smith080056b2015-08-18 21:53:42 +00002652 Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM);
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002653 }
2654
Richard Smithdc1f0422016-07-20 19:10:16 +00002655 // Emit the initializers, if any.
2656 RecordData Inits;
2657 for (Decl *D : Context->getModuleInitializers(Mod))
2658 Inits.push_back(GetDeclRef(D));
2659 if (!Inits.empty())
2660 Stream.EmitRecord(SUBMODULE_INITIALIZERS, Inits);
2661
Douglas Gregor69021972011-11-30 17:33:56 +00002662 // Queue up the submodules of this module.
Richard Smith080056b2015-08-18 21:53:42 +00002663 for (auto *M : Mod->submodules())
2664 Q.push(M);
Douglas Gregor69021972011-11-30 17:33:56 +00002665 }
2666
2667 Stream.ExitBlock();
Richard Smith23d8d032015-05-14 00:45:20 +00002668
Richard Smith23d8d032015-05-14 00:45:20 +00002669 assert((NextSubmoduleID - FirstSubmoduleID ==
2670 getNumberOfModules(WritingModule)) &&
2671 "Wrong # of submodules; found a reference to a non-local, "
2672 "non-imported submodule?");
Douglas Gregor69021972011-11-30 17:33:56 +00002673}
2674
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002675serialization::SubmoduleID
2676ASTWriter::inferSubmoduleIDFromLocation(SourceLocation Loc) {
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002677 if (Loc.isInvalid() || !WritingModule)
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002678 return 0; // No submodule
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002679
2680 // Find the module that owns this location.
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002681 ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002682 Module *OwningMod
2683 = ModMap.inferModuleFromLocation(FullSourceLoc(Loc,PP->getSourceManager()));
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002684 if (!OwningMod)
2685 return 0;
2686
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002687 // Check whether this submodule is part of our own module.
2688 if (WritingModule != OwningMod && !OwningMod->isSubModuleOf(WritingModule))
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002689 return 0;
2690
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002691 return getSubmoduleID(OwningMod);
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002692}
2693
Argyrios Kyrtzidis0f06b982013-03-27 17:17:23 +00002694void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
2695 bool isModule) {
2696 // Make sure set diagnostic pragmas don't affect the translation unit that
2697 // imports the module.
2698 // FIXME: Make diagnostic pragma sections work properly with modules.
2699 if (isModule)
2700 return;
2701
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002702 llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
2703 DiagStateIDMap;
2704 unsigned CurrID = 0;
2705 DiagStateIDMap[&Diag.DiagStates.front()] = ++CurrID; // the command-line one.
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002706 RecordData Record;
David Blaikie9c902b52011-09-25 23:23:43 +00002707 for (DiagnosticsEngine::DiagStatePointsTy::const_iterator
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002708 I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end();
2709 I != E; ++I) {
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002710 const DiagnosticsEngine::DiagStatePoint &point = *I;
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002711 if (point.Loc.isInvalid())
2712 continue;
2713
Richard Smithb22a1d12016-03-27 20:13:24 +00002714 AddSourceLocation(point.Loc, Record);
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002715 unsigned &DiagStateID = DiagStateIDMap[point.State];
2716 Record.push_back(DiagStateID);
2717
2718 if (DiagStateID == 0) {
2719 DiagStateID = ++CurrID;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002720 for (const auto &I : *(point.State)) {
2721 if (I.second.isPragma()) {
2722 Record.push_back(I.first);
2723 Record.push_back((unsigned)I.second.getSeverity());
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002724 }
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002725 }
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002726 Record.push_back(-1); // mark the end of the diag/map pairs for this
2727 // location.
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002728 }
2729 }
2730
Argyrios Kyrtzidisb0ca9eb2010-11-05 22:20:49 +00002731 if (!Record.empty())
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002732 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
Argyrios Kyrtzidis452707c2010-11-05 22:10: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) {
Richard Smith290d8012016-04-06 17:06:00 +00002741 TypeIdx &IdxRef = TypeIdxs[T];
2742 if (IdxRef.getIndex() == 0) // we haven't seen this type before.
2743 IdxRef = TypeIdx(NextTypeID++);
2744 TypeIdx Idx = IdxRef;
Mike Stump11289f42009-09-09 15:08:12 +00002745
Douglas Gregor9b3932c2010-10-05 18:37:06 +00002746 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
Douglas Gregordc72caa2010-10-04 18:21:45 +00002747
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002748 RecordData Record;
Mike Stump11289f42009-09-09 15:08:12 +00002749
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002750 // Emit the type's representation.
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002751 ASTTypeWriter W(*this, Record);
Richard Smith290d8012016-04-06 17:06:00 +00002752 W.Visit(T);
2753 uint64_t Offset = W.Emit();
John McCall8ccfcb52009-09-24 19:53:00 +00002754
Richard Smith290d8012016-04-06 17:06:00 +00002755 // Record the offset for this type.
2756 unsigned Index = Idx.getIndex() - FirstTypeID;
2757 if (TypeOffsets.size() == Index)
2758 TypeOffsets.push_back(Offset);
2759 else if (TypeOffsets.size() < Index) {
2760 TypeOffsets.resize(Index + 1);
2761 TypeOffsets[Index] = Offset;
John McCall8ccfcb52009-09-24 19:53:00 +00002762 } else {
Richard Smith290d8012016-04-06 17:06:00 +00002763 llvm_unreachable("Types emitted in wrong order");
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002764 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002765}
2766
Douglas Gregorc5046832009-04-27 18:38:38 +00002767//===----------------------------------------------------------------------===//
2768// Declaration Serialization
2769//===----------------------------------------------------------------------===//
2770
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002771/// \brief Write the block containing all of the declaration IDs
2772/// lexically declared within the given DeclContext.
2773///
2774/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
2775/// bistream, or 0 if no block was written.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002776uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002777 DeclContext *DC) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002778 if (DC->decls_empty())
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002779 return 0;
2780
Douglas Gregor8f45df52009-04-16 22:23:12 +00002781 uint64_t Offset = Stream.GetCurrentBitNo();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002782 SmallVector<uint32_t, 128> KindDeclPairs;
2783 for (const auto *D : DC->decls()) {
2784 KindDeclPairs.push_back(D->getKind());
2785 KindDeclPairs.push_back(GetDeclRef(D));
2786 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002787
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002788 ++NumLexicalDeclContexts;
Mehdi Amini57a41912015-09-10 01:46:39 +00002789 RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
Richard Smith82f8fcd2015-08-06 22:07:25 +00002790 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
2791 bytes(KindDeclPairs));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002792 return Offset;
2793}
2794
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002795void ASTWriter::WriteTypeDeclOffsets() {
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002796 using namespace llvm;
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002797
2798 // Write the type offsets array
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002799 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00002800 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002801 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
Douglas Gregor5204bde2011-08-02 16:26:37 +00002802 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002803 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
2804 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00002805 {
2806 RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(),
2807 FirstTypeID - NUM_PREDEF_TYPE_IDS};
2808 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
2809 }
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002810
2811 // Write the declaration offsets array
2812 Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00002813 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002814 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
Douglas Gregorf7180622011-08-03 15:48:04 +00002815 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002816 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
2817 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00002818 {
2819 RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(),
2820 FirstDeclID - NUM_PREDEF_DECL_IDS};
2821 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
2822 }
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002823}
2824
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002825void ASTWriter::WriteFileDeclIDsMap() {
2826 using namespace llvm;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002827
Chandler Carruthb306d732015-03-27 00:31:20 +00002828 SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs(
2829 FileDeclIDs.begin(), FileDeclIDs.end());
2830 std::sort(SortedFileDeclIDs.begin(), SortedFileDeclIDs.end(),
2831 llvm::less_first());
2832
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002833 // Join the vectors of DeclIDs from all files.
Chandler Carruthb306d732015-03-27 00:31:20 +00002834 SmallVector<DeclID, 256> FileGroupedDeclIDs;
2835 for (auto &FileDeclEntry : SortedFileDeclIDs) {
2836 DeclIDInFileInfo &Info = *FileDeclEntry.second;
2837 Info.FirstDeclIndex = FileGroupedDeclIDs.size();
2838 for (auto &LocDeclEntry : Info.DeclIDs)
2839 FileGroupedDeclIDs.push_back(LocDeclEntry.second);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002840 }
2841
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002842 auto *Abbrev = new BitCodeAbbrev();
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002843 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002844 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002845 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2846 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00002847 RecordData::value_type Record[] = {FILE_SORTED_DECLS,
2848 FileGroupedDeclIDs.size()};
Reid Kleckner012665e2015-05-21 00:13:09 +00002849 Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002850}
2851
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002852void ASTWriter::WriteComments() {
2853 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +00002854 ArrayRef<RawComment *> RawComments = Context->Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002855 RecordData Record;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002856 for (const auto *I : RawComments) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002857 Record.clear();
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002858 AddSourceRange(I->getSourceRange(), Record);
2859 Record.push_back(I->getKind());
2860 Record.push_back(I->isTrailingComment());
2861 Record.push_back(I->isAlmostTrailingComment());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002862 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
2863 }
2864 Stream.ExitBlock();
2865}
2866
Douglas Gregorc5046832009-04-27 18:38:38 +00002867//===----------------------------------------------------------------------===//
2868// Global Method Pool and Selector Serialization
2869//===----------------------------------------------------------------------===//
2870
Douglas Gregore84a9da2009-04-20 20:36:09 +00002871namespace {
Douglas Gregorc78d3462009-04-24 21:10:55 +00002872// Trait used for the on-disk hash table used in the method pool.
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002873class ASTMethodPoolTrait {
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002874 ASTWriter &Writer;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002875
2876public:
2877 typedef Selector key_type;
2878 typedef key_type key_type_ref;
Mike Stump11289f42009-09-09 15:08:12 +00002879
Sebastian Redl834bb972010-08-04 17:20:04 +00002880 struct data_type {
Sebastian Redl539c5062010-08-18 23:57:32 +00002881 SelectorID ID;
Sebastian Redl834bb972010-08-04 17:20:04 +00002882 ObjCMethodList Instance, Factory;
2883 };
Douglas Gregorc78d3462009-04-24 21:10:55 +00002884 typedef const data_type& data_type_ref;
2885
Justin Bogner25463f12014-04-18 20:27:24 +00002886 typedef unsigned hash_value_type;
2887 typedef unsigned offset_type;
2888
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002889 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { }
Mike Stump11289f42009-09-09 15:08:12 +00002890
Justin Bogner25463f12014-04-18 20:27:24 +00002891 static hash_value_type ComputeHash(Selector Sel) {
Argyrios Kyrtzidis4bd97102010-08-20 16:03:52 +00002892 return serialization::ComputeHash(Sel);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002893 }
Mike Stump11289f42009-09-09 15:08:12 +00002894
2895 std::pair<unsigned,unsigned>
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002896 EmitKeyDataLength(raw_ostream& Out, Selector Sel,
Douglas Gregorc78d3462009-04-24 21:10:55 +00002897 data_type_ref Methods) {
Justin Bognere1c147c2014-03-28 22:03:19 +00002898 using namespace llvm::support;
2899 endian::Writer<little> LE(Out);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002900 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
Justin Bognere1c147c2014-03-28 22:03:19 +00002901 LE.write<uint16_t>(KeyLen);
Sebastian Redl834bb972010-08-04 17:20:04 +00002902 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
2903 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002904 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002905 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002906 DataLen += 4;
Sebastian Redl834bb972010-08-04 17:20:04 +00002907 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002908 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002909 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002910 DataLen += 4;
Justin Bognere1c147c2014-03-28 22:03:19 +00002911 LE.write<uint16_t>(DataLen);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002912 return std::make_pair(KeyLen, DataLen);
2913 }
Mike Stump11289f42009-09-09 15:08:12 +00002914
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002915 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00002916 using namespace llvm::support;
2917 endian::Writer<little> LE(Out);
Mike Stump11289f42009-09-09 15:08:12 +00002918 uint64_t Start = Out.tell();
Douglas Gregor95c13f52009-04-25 17:48:32 +00002919 assert((Start >> 32) == 0 && "Selector key offset too large");
2920 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002921 unsigned N = Sel.getNumArgs();
Justin Bognere1c147c2014-03-28 22:03:19 +00002922 LE.write<uint16_t>(N);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002923 if (N == 0)
2924 N = 1;
2925 for (unsigned I = 0; I != N; ++I)
Justin Bognere1c147c2014-03-28 22:03:19 +00002926 LE.write<uint32_t>(
2927 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
Douglas Gregorc78d3462009-04-24 21:10:55 +00002928 }
Mike Stump11289f42009-09-09 15:08:12 +00002929
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002930 void EmitData(raw_ostream& Out, key_type_ref,
Douglas Gregor4647cfa2009-04-24 21:49:02 +00002931 data_type_ref Methods, unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00002932 using namespace llvm::support;
2933 endian::Writer<little> LE(Out);
Douglas Gregor4647cfa2009-04-24 21:49:02 +00002934 uint64_t Start = Out.tell(); (void)Start;
Justin Bognere1c147c2014-03-28 22:03:19 +00002935 LE.write<uint32_t>(Methods.ID);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002936 unsigned NumInstanceMethods = 0;
Sebastian Redl834bb972010-08-04 17:20:04 +00002937 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002938 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002939 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002940 ++NumInstanceMethods;
2941
2942 unsigned NumFactoryMethods = 0;
Sebastian Redl834bb972010-08-04 17:20:04 +00002943 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002944 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002945 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002946 ++NumFactoryMethods;
2947
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002948 unsigned InstanceBits = Methods.Instance.getBits();
2949 assert(InstanceBits < 4);
Nico Weberff4b35e2014-12-27 22:14:15 +00002950 unsigned InstanceHasMoreThanOneDeclBit =
2951 Methods.Instance.hasMoreThanOneDecl();
2952 unsigned FullInstanceBits = (NumInstanceMethods << 3) |
2953 (InstanceHasMoreThanOneDeclBit << 2) |
2954 InstanceBits;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002955 unsigned FactoryBits = Methods.Factory.getBits();
2956 assert(FactoryBits < 4);
Nico Weberff4b35e2014-12-27 22:14:15 +00002957 unsigned FactoryHasMoreThanOneDeclBit =
2958 Methods.Factory.hasMoreThanOneDecl();
2959 unsigned FullFactoryBits = (NumFactoryMethods << 3) |
2960 (FactoryHasMoreThanOneDeclBit << 2) |
2961 FactoryBits;
2962 LE.write<uint16_t>(FullInstanceBits);
2963 LE.write<uint16_t>(FullFactoryBits);
Sebastian Redl834bb972010-08-04 17:20:04 +00002964 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002965 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002966 if (Method->getMethod())
2967 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
Sebastian Redl834bb972010-08-04 17:20:04 +00002968 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002969 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002970 if (Method->getMethod())
2971 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
Douglas Gregor4647cfa2009-04-24 21:49:02 +00002972
2973 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorc78d3462009-04-24 21:10:55 +00002974 }
2975};
2976} // end anonymous namespace
2977
Sebastian Redla19a67f2010-08-03 21:58:15 +00002978/// \brief Write ObjC data: selectors and the method pool.
Douglas Gregorc78d3462009-04-24 21:10:55 +00002979///
2980/// The method pool contains both instance and factory methods, stored
Sebastian Redla19a67f2010-08-03 21:58:15 +00002981/// in an on-disk hash table indexed by the selector. The hash table also
2982/// contains an empty entry for every other selector known to Sema.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002983void ASTWriter::WriteSelectors(Sema &SemaRef) {
Douglas Gregorc78d3462009-04-24 21:10:55 +00002984 using namespace llvm;
2985
Sebastian Redla19a67f2010-08-03 21:58:15 +00002986 // Do we have to do anything at all?
Sebastian Redl834bb972010-08-04 17:20:04 +00002987 if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
Sebastian Redla19a67f2010-08-03 21:58:15 +00002988 return;
Sebastian Redld95a56e2010-08-04 18:21:41 +00002989 unsigned NumTableEntries = 0;
Sebastian Redla19a67f2010-08-03 21:58:15 +00002990 // Create and write out the blob that contains selectors and the method pool.
Douglas Gregorc78d3462009-04-24 21:10:55 +00002991 {
Justin Bognerbb094f02014-04-18 19:57:06 +00002992 llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00002993 ASTMethodPoolTrait Trait(*this);
Mike Stump11289f42009-09-09 15:08:12 +00002994
Sebastian Redla19a67f2010-08-03 21:58:15 +00002995 // Create the on-disk hash table representation. We walk through every
2996 // selector we've seen and look it up in the method pool.
Sebastian Redld95a56e2010-08-04 18:21:41 +00002997 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
Chandler Carruthacbbeb92015-03-27 00:47:43 +00002998 for (auto &SelectorAndID : SelectorIDs) {
2999 Selector S = SelectorAndID.first;
3000 SelectorID ID = SelectorAndID.second;
Sebastian Redla19a67f2010-08-03 21:58:15 +00003001 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003002 ASTMethodPoolTrait::data_type Data = {
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003003 ID,
Sebastian Redl834bb972010-08-04 17:20:04 +00003004 ObjCMethodList(),
3005 ObjCMethodList()
3006 };
3007 if (F != SemaRef.MethodPool.end()) {
3008 Data.Instance = F->second.first;
3009 Data.Factory = F->second.second;
3010 }
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003011 // Only write this selector if it's not in an existing AST or something
Sebastian Redld95a56e2010-08-04 18:21:41 +00003012 // changed.
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003013 if (Chain && ID < FirstSelectorID) {
Sebastian Redld95a56e2010-08-04 18:21:41 +00003014 // Selector already exists. Did it change?
3015 bool changed = false;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003016 for (ObjCMethodList *M = &Data.Instance;
3017 !changed && M && M->getMethod(); M = M->getNext()) {
3018 if (!M->getMethod()->isFromASTFile())
Sebastian Redld95a56e2010-08-04 18:21:41 +00003019 changed = true;
3020 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003021 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003022 M = M->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003023 if (!M->getMethod()->isFromASTFile())
Sebastian Redld95a56e2010-08-04 18:21:41 +00003024 changed = true;
3025 }
3026 if (!changed)
3027 continue;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003028 } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
Sebastian Redl6e1a2a02010-08-04 21:22:45 +00003029 // A new method pool entry.
3030 ++NumTableEntries;
Sebastian Redld95a56e2010-08-04 18:21:41 +00003031 }
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003032 Generator.insert(S, Data, Trait);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003033 }
3034
Douglas Gregorc78d3462009-04-24 21:10:55 +00003035 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003036 SmallString<4096> MethodPool;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003037 uint32_t BucketOffset;
3038 {
Justin Bognere1c147c2014-03-28 22:03:19 +00003039 using namespace llvm::support;
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003040 ASTMethodPoolTrait Trait(*this);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003041 llvm::raw_svector_ostream Out(MethodPool);
3042 // Make sure that no bucket is at offset 0
Justin Bognere1c147c2014-03-28 22:03:19 +00003043 endian::Writer<little>(Out).write<uint32_t>(0);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003044 BucketOffset = Generator.Emit(Out, Trait);
3045 }
3046
3047 // Create a blob abbreviation
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003048 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00003049 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003050 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor95c13f52009-04-25 17:48:32 +00003051 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003052 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3053 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
3054
Douglas Gregor95c13f52009-04-25 17:48:32 +00003055 // Write the method pool
Mehdi Amini57a41912015-09-10 01:46:39 +00003056 {
3057 RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3058 NumTableEntries};
3059 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3060 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00003061
3062 // Create a blob abbreviation for the selector table offsets.
3063 Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00003064 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
Douglas Gregord4c5ed02010-10-29 22:39:52 +00003065 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
Douglas Gregor8f364fb2011-08-03 23:28:44 +00003066 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
Douglas Gregor95c13f52009-04-25 17:48:32 +00003067 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3068 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
3069
3070 // Write the selector offsets table.
Mehdi Amini57a41912015-09-10 01:46:39 +00003071 {
3072 RecordData::value_type Record[] = {
3073 SELECTOR_OFFSETS, SelectorOffsets.size(),
3074 FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3075 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3076 bytes(SelectorOffsets));
3077 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00003078 }
3079}
3080
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003081/// \brief Write the selectors referenced in @selector expression into AST file.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003082void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003083 using namespace llvm;
3084 if (SemaRef.ReferencedSelectors.empty())
3085 return;
Sebastian Redlada023c2010-08-04 20:40:17 +00003086
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003087 RecordData Record;
Richard Smithe64e7452016-04-18 21:54:58 +00003088 ASTRecordWriter Writer(*this, Record);
Sebastian Redlada023c2010-08-04 20:40:17 +00003089
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003090 // Note: this writes out all references even for a dependent AST. But it is
Sebastian Redl51c79d82010-08-04 22:21:29 +00003091 // very tricky to fix, and given that @selector shouldn't really appear in
3092 // headers, probably not worth it. It's not a correctness issue.
Chandler Carruth12c8f652015-03-27 00:55:05 +00003093 for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
3094 Selector Sel = SelectorAndLocation.first;
3095 SourceLocation Loc = SelectorAndLocation.second;
Richard Smithe64e7452016-04-18 21:54:58 +00003096 Writer.AddSelectorRef(Sel);
3097 Writer.AddSourceLocation(Loc);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003098 }
Richard Smithe64e7452016-04-18 21:54:58 +00003099 Writer.Emit(REFERENCED_SELECTOR_POOL);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003100}
3101
Douglas Gregorc5046832009-04-27 18:38:38 +00003102//===----------------------------------------------------------------------===//
3103// Identifier Table Serialization
3104//===----------------------------------------------------------------------===//
3105
Richard Smithb3761912015-02-05 23:08:52 +00003106/// Determine the declaration that should be put into the name lookup table to
3107/// represent the given declaration in this module. This is usually D itself,
3108/// but if D was imported and merged into a local declaration, we want the most
3109/// recent local declaration instead. The chosen declaration will be the most
3110/// recent declaration in any module that imports this one.
3111static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
3112 NamedDecl *D) {
3113 if (!LangOpts.Modules || !D->isFromASTFile())
3114 return D;
3115
3116 if (Decl *Redecl = D->getPreviousDecl()) {
3117 // For Redeclarable decls, a prior declaration might be local.
3118 for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
Richard Smithd49941b2016-04-26 23:40:43 +00003119 // If we find a local decl, we're done.
3120 if (!Redecl->isFromASTFile()) {
3121 // Exception: in very rare cases (for injected-class-names), not all
3122 // redeclarations are in the same semantic context. Skip ones in a
3123 // different context. They don't go in this lookup table at all.
3124 if (!Redecl->getDeclContext()->getRedeclContext()->Equals(
3125 D->getDeclContext()->getRedeclContext()))
3126 continue;
Richard Smithb3761912015-02-05 23:08:52 +00003127 return cast<NamedDecl>(Redecl);
Richard Smithd49941b2016-04-26 23:40:43 +00003128 }
3129
Richard Smithfe620d22015-03-05 23:24:12 +00003130 // If we find a decl from a (chained-)PCH stop since we won't find a
Richard Smithb3761912015-02-05 23:08:52 +00003131 // local one.
Richard Smithd49941b2016-04-26 23:40:43 +00003132 if (Redecl->getOwningModuleID() == 0)
Richard Smithb3761912015-02-05 23:08:52 +00003133 break;
3134 }
3135 } else if (Decl *First = D->getCanonicalDecl()) {
3136 // For Mergeable decls, the first decl might be local.
3137 if (!First->isFromASTFile())
3138 return cast<NamedDecl>(First);
3139 }
3140
3141 // All declarations are imported. Our most recent declaration will also be
3142 // the most recent one in anyone who imports us.
3143 return D;
3144}
3145
Douglas Gregorc78d3462009-04-24 21:10:55 +00003146namespace {
Richard Smithcf97cf62015-04-19 01:34:23 +00003147class ASTIdentifierTableTrait {
3148 ASTWriter &Writer;
3149 Preprocessor &PP;
3150 IdentifierResolver &IdResolver;
Richard Smith9c254182015-07-19 21:41:12 +00003151 bool IsModule;
Richard Smitha534a312015-07-21 23:54:07 +00003152 bool NeedDecls;
Richard Smith33e0f7e2015-07-22 02:08:40 +00003153 ASTWriter::RecordData *InterestingIdentifierOffsets;
Richard Smithcf97cf62015-04-19 01:34:23 +00003154
3155 /// \brief Determines whether this is an "interesting" identifier that needs a
3156 /// full IdentifierInfo structure written into the hash table. Notably, this
3157 /// doesn't check whether the name has macros defined; use PublicMacroIterator
3158 /// to check that.
Richard Smith9c254182015-07-19 21:41:12 +00003159 bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
Richard Smithd7329392015-04-21 21:46:32 +00003160 if (MacroOffset ||
3161 II->isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +00003162 (IsModule ? II->hasRevertedBuiltin() : II->getObjCOrBuiltinID()) ||
Richard Smithcf97cf62015-04-19 01:34:23 +00003163 II->hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +00003164 (NeedDecls && II->getFETokenInfo<void>()))
Richard Smithcf97cf62015-04-19 01:34:23 +00003165 return true;
3166
3167 return false;
3168 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003169
Douglas Gregore84a9da2009-04-20 20:36:09 +00003170public:
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00003171 typedef IdentifierInfo* key_type;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003172 typedef key_type key_type_ref;
Mike Stump11289f42009-09-09 15:08:12 +00003173
Sebastian Redl539c5062010-08-18 23:57:32 +00003174 typedef IdentID data_type;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003175 typedef data_type data_type_ref;
Mike Stump11289f42009-09-09 15:08:12 +00003176
Justin Bogner25463f12014-04-18 20:27:24 +00003177 typedef unsigned hash_value_type;
3178 typedef unsigned offset_type;
3179
Richard Smithd7329392015-04-21 21:46:32 +00003180 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
Richard Smith33e0f7e2015-07-22 02:08:40 +00003181 IdentifierResolver &IdResolver, bool IsModule,
3182 ASTWriter::RecordData *InterestingIdentifierOffsets)
Richard Smitha534a312015-07-21 23:54:07 +00003183 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
Richard Smith33e0f7e2015-07-22 02:08:40 +00003184 NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3185 InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
Douglas Gregore84a9da2009-04-20 20:36:09 +00003186
Richard Smithd79514e2016-02-05 19:03:40 +00003187 bool needDecls() const { return NeedDecls; }
3188
Justin Bogner25463f12014-04-18 20:27:24 +00003189 static hash_value_type ComputeHash(const IdentifierInfo* II) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +00003190 return llvm::HashString(II->getName());
Douglas Gregore84a9da2009-04-20 20:36:09 +00003191 }
Mike Stump11289f42009-09-09 15:08:12 +00003192
Richard Smith33e0f7e2015-07-22 02:08:40 +00003193 bool isInterestingIdentifier(const IdentifierInfo *II) {
3194 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3195 return isInterestingIdentifier(II, MacroOffset);
3196 }
Richard Smith9c254182015-07-19 21:41:12 +00003197 bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) {
3198 return isInterestingIdentifier(II, 0);
3199 }
3200
Mike Stump11289f42009-09-09 15:08:12 +00003201 std::pair<unsigned,unsigned>
Douglas Gregor935bc7a22011-10-27 09:33:13 +00003202 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003203 unsigned KeyLen = II->getLength() + 1;
Douglas Gregor1d583f22009-04-28 21:18:29 +00003204 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
Richard Smithd7329392015-04-21 21:46:32 +00003205 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3206 if (isInterestingIdentifier(II, MacroOffset)) {
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003207 DataLen += 2; // 2 bytes for builtin ID
3208 DataLen += 2; // 2 bytes for flags
Richard Smithd7329392015-04-21 21:46:32 +00003209 if (MacroOffset)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003210 DataLen += 4; // MacroDirectives offset.
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003211
Richard Smitha534a312015-07-21 23:54:07 +00003212 if (NeedDecls) {
3213 for (IdentifierResolver::iterator D = IdResolver.begin(II),
3214 DEnd = IdResolver.end();
3215 D != DEnd; ++D)
3216 DataLen += 4;
3217 }
Douglas Gregor1d583f22009-04-28 21:18:29 +00003218 }
Justin Bognere1c147c2014-03-28 22:03:19 +00003219 using namespace llvm::support;
3220 endian::Writer<little> LE(Out);
3221
Richard Smithdf8a8312015-03-13 04:05:01 +00003222 assert((uint16_t)DataLen == DataLen && (uint16_t)KeyLen == KeyLen);
Justin Bognere1c147c2014-03-28 22:03:19 +00003223 LE.write<uint16_t>(DataLen);
Douglas Gregorab4df582009-04-28 20:01:51 +00003224 // We emit the key length after the data length so that every
3225 // string is preceded by a 16-bit length. This matches the PTH
3226 // format for storing identifiers.
Justin Bognere1c147c2014-03-28 22:03:19 +00003227 LE.write<uint16_t>(KeyLen);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003228 return std::make_pair(KeyLen, DataLen);
3229 }
Mike Stump11289f42009-09-09 15:08:12 +00003230
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003231 void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
Douglas Gregore84a9da2009-04-20 20:36:09 +00003232 unsigned KeyLen) {
3233 // Record the location of the key data. This is used when generating
3234 // the mapping from persistent IDs to strings.
3235 Writer.SetIdentifierOffset(II, Out.tell());
Richard Smith33e0f7e2015-07-22 02:08:40 +00003236
3237 // Emit the offset of the key/data length information to the interesting
3238 // identifiers table if necessary.
3239 if (InterestingIdentifierOffsets && isInterestingIdentifier(II))
3240 InterestingIdentifierOffsets->push_back(Out.tell() - 4);
3241
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003242 Out.write(II->getNameStart(), KeyLen);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003243 }
Mike Stump11289f42009-09-09 15:08:12 +00003244
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00003245 void EmitData(raw_ostream& Out, IdentifierInfo* II,
Sebastian Redl539c5062010-08-18 23:57:32 +00003246 IdentID ID, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003247 using namespace llvm::support;
3248 endian::Writer<little> LE(Out);
Richard Smithcf97cf62015-04-19 01:34:23 +00003249
Richard Smithd7329392015-04-21 21:46:32 +00003250 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3251 if (!isInterestingIdentifier(II, MacroOffset)) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003252 LE.write<uint32_t>(ID << 1);
Douglas Gregor1d583f22009-04-28 21:18:29 +00003253 return;
3254 }
Douglas Gregorb9256522009-04-28 21:32:13 +00003255
Justin Bognere1c147c2014-03-28 22:03:19 +00003256 LE.write<uint32_t>((ID << 1) | 0x01);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003257 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3258 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
Justin Bognere1c147c2014-03-28 22:03:19 +00003259 LE.write<uint16_t>(Bits);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003260 Bits = 0;
Richard Smithd7329392015-04-21 21:46:32 +00003261 bool HadMacroDefinition = MacroOffset != 0;
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003262 Bits = (Bits << 1) | unsigned(HadMacroDefinition);
Daniel Dunbar91b640a2009-12-18 20:58:47 +00003263 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3264 Bits = (Bits << 1) | unsigned(II->isPoisoned());
Richard Smith9c254182015-07-19 21:41:12 +00003265 Bits = (Bits << 1) | unsigned(II->hasRevertedBuiltin());
Argyrios Kyrtzidis3084a612010-08-11 22:55:12 +00003266 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
Daniel Dunbar91b640a2009-12-18 20:58:47 +00003267 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
Justin Bognere1c147c2014-03-28 22:03:19 +00003268 LE.write<uint16_t>(Bits);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003269
Richard Smithd7329392015-04-21 21:46:32 +00003270 if (HadMacroDefinition)
3271 LE.write<uint32_t>(MacroOffset);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003272
Richard Smitha534a312015-07-21 23:54:07 +00003273 if (NeedDecls) {
3274 // Emit the declaration IDs in reverse order, because the
3275 // IdentifierResolver provides the declarations as they would be
3276 // visible (e.g., the function "stat" would come before the struct
3277 // "stat"), but the ASTReader adds declarations to the end of the list
3278 // (so we need to see the struct "stat" before the function "stat").
3279 // Only emit declarations that aren't from a chained PCH, though.
3280 SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II),
3281 IdResolver.end());
3282 for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(),
3283 DEnd = Decls.rend();
3284 D != DEnd; ++D)
3285 LE.write<uint32_t>(
3286 Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D)));
3287 }
Douglas Gregore84a9da2009-04-20 20:36:09 +00003288 }
3289};
3290} // end anonymous namespace
3291
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003292/// \brief Write the identifier table into the AST file.
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003293///
3294/// The identifier table consists of a blob containing string data
3295/// (the actual identifiers themselves) and a separate "offsets" index
3296/// that maps identifier IDs to locations within the blob.
Douglas Gregor935bc7a22011-10-27 09:33:13 +00003297void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3298 IdentifierResolver &IdResolver,
3299 bool IsModule) {
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003300 using namespace llvm;
3301
Richard Smith33e0f7e2015-07-22 02:08:40 +00003302 RecordData InterestingIdents;
3303
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003304 // Create and write out the blob that contains the identifier
3305 // strings.
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003306 {
Justin Bognerbb094f02014-04-18 19:57:06 +00003307 llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
Richard Smith33e0f7e2015-07-22 02:08:40 +00003308 ASTIdentifierTableTrait Trait(
3309 *this, PP, IdResolver, IsModule,
3310 (getLangOpts().CPlusPlus && IsModule) ? &InterestingIdents : nullptr);
Mike Stump11289f42009-09-09 15:08:12 +00003311
Douglas Gregore6648fb2009-04-28 20:33:11 +00003312 // Look for any identifiers that were named while processing the
3313 // headers, but are otherwise not needed. We add these to the hash
3314 // table to enable checking of the predefines buffer in the case
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003315 // where the user adds new macro definitions when building the AST
Douglas Gregore6648fb2009-04-28 20:33:11 +00003316 // file.
Chandler Carruth8440c982015-03-26 23:54:15 +00003317 SmallVector<const IdentifierInfo *, 128> IIs;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003318 for (const auto &ID : PP.getIdentifierTable())
3319 IIs.push_back(ID.second);
Chandler Carruth8440c982015-03-26 23:54:15 +00003320 // Sort the identifiers lexicographically before getting them references so
3321 // that their order is stable.
3322 std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
3323 for (const IdentifierInfo *II : IIs)
Richard Smith9c254182015-07-19 21:41:12 +00003324 if (Trait.isInterestingNonMacroIdentifier(II))
3325 getIdentifierRef(II);
Douglas Gregore6648fb2009-04-28 20:33:11 +00003326
Sebastian Redlff4a2952010-07-23 23:49:55 +00003327 // Create the on-disk hash table representation. We only store offsets
3328 // for identifiers that appear here for the first time.
3329 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
Chandler Carruth885e78c2015-03-24 21:18:10 +00003330 for (auto IdentIDPair : IdentifierIDs) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003331 auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
Chandler Carruth885e78c2015-03-24 21:18:10 +00003332 IdentID ID = IdentIDPair.second;
3333 assert(II && "NULL identifier in identifier table");
Vassil Vassilev262f41e2016-03-30 20:16:03 +00003334 // Write out identifiers if either the ID is local or the identifier has
3335 // changed since it was loaded.
3336 if (ID >= FirstIdentID || !Chain || !II->isFromAST()
3337 || II->hasChangedSinceDeserialization() ||
Richard Smithd79514e2016-02-05 19:03:40 +00003338 (Trait.needDecls() &&
3339 II->hasFETokenInfoChangedSinceDeserialization()))
Chandler Carruth885e78c2015-03-24 21:18:10 +00003340 Generator.insert(II, ID, Trait);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003341 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003342
Douglas Gregore84a9da2009-04-20 20:36:09 +00003343 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003344 SmallString<4096> IdentifierTable;
Douglas Gregora868bbd2009-04-21 22:25:48 +00003345 uint32_t BucketOffset;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003346 {
Justin Bognere1c147c2014-03-28 22:03:19 +00003347 using namespace llvm::support;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003348 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003349 // Make sure that no bucket is at offset 0
Justin Bognere1c147c2014-03-28 22:03:19 +00003350 endian::Writer<little>(Out).write<uint32_t>(0);
Douglas Gregora868bbd2009-04-21 22:25:48 +00003351 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003352 }
3353
3354 // Create a blob abbreviation
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003355 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00003356 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
Douglas Gregora868bbd2009-04-21 22:25:48 +00003357 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregore84a9da2009-04-20 20:36:09 +00003358 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregor8f45df52009-04-16 22:23:12 +00003359 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003360
3361 // Write the identifier table
Mehdi Amini57a41912015-09-10 01:46:39 +00003362 RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
Yaron Keren92e1b622015-03-18 10:17:07 +00003363 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003364 }
3365
3366 // Write the offsets table for identifier IDs.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003367 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00003368 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
Douglas Gregor0e149972009-04-25 19:10:14 +00003369 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
Douglas Gregor1ab036c2011-08-03 21:49:18 +00003370 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
Douglas Gregor0e149972009-04-25 19:10:14 +00003371 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3372 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
3373
Douglas Gregor8d7edce2013-02-08 21:30:59 +00003374#ifndef NDEBUG
3375 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3376 assert(IdentifierOffsets[I] && "Missing identifier offset?");
3377#endif
Mehdi Amini57a41912015-09-10 01:46:39 +00003378
3379 RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
3380 IdentifierOffsets.size(),
3381 FirstIdentID - NUM_PREDEF_IDENT_IDS};
Douglas Gregor0e149972009-04-25 19:10:14 +00003382 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00003383 bytes(IdentifierOffsets));
Richard Smith33e0f7e2015-07-22 02:08:40 +00003384
3385 // In C++, write the list of interesting identifiers (those that are
3386 // defined as macros, poisoned, or similar unusual things).
3387 if (!InterestingIdents.empty())
3388 Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003389}
3390
Douglas Gregorc5046832009-04-27 18:38:38 +00003391//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003392// DeclContext's Name Lookup Table Serialization
3393//===----------------------------------------------------------------------===//
3394
3395namespace {
3396// Trait used for the on-disk hash table used in the method pool.
3397class ASTDeclContextNameLookupTrait {
3398 ASTWriter &Writer;
Richard Smithd88a7f12015-09-01 20:35:42 +00003399 llvm::SmallVector<DeclID, 64> DeclIDs;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003400
3401public:
Richard Smitha06c7e62015-08-26 23:55:49 +00003402 typedef DeclarationNameKey key_type;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003403 typedef key_type key_type_ref;
3404
Richard Smithd88a7f12015-09-01 20:35:42 +00003405 /// A start and end index into DeclIDs, representing a sequence of decls.
3406 typedef std::pair<unsigned, unsigned> data_type;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003407 typedef const data_type& data_type_ref;
3408
Justin Bogner25463f12014-04-18 20:27:24 +00003409 typedef unsigned hash_value_type;
3410 typedef unsigned offset_type;
3411
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003412 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { }
3413
Richard Smithd88a7f12015-09-01 20:35:42 +00003414 template<typename Coll>
3415 data_type getData(const Coll &Decls) {
3416 unsigned Start = DeclIDs.size();
3417 for (NamedDecl *D : Decls) {
3418 DeclIDs.push_back(
3419 Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3420 }
3421 return std::make_pair(Start, DeclIDs.size());
3422 }
3423
3424 data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
3425 unsigned Start = DeclIDs.size();
3426 for (auto ID : FromReader)
3427 DeclIDs.push_back(ID);
3428 return std::make_pair(Start, DeclIDs.size());
3429 }
3430
3431 static bool EqualKey(key_type_ref a, key_type_ref b) {
3432 return a == b;
3433 }
3434
Richard Smitha06c7e62015-08-26 23:55:49 +00003435 hash_value_type ComputeHash(DeclarationNameKey Name) {
3436 return Name.getHash();
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003437 }
3438
Richard Smithd88a7f12015-09-01 20:35:42 +00003439 void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
3440 assert(Writer.hasChain() &&
3441 "have reference to loaded module file but no chain?");
3442
3443 using namespace llvm::support;
3444 endian::Writer<little>(Out)
3445 .write<uint32_t>(Writer.getChain()->getModuleFileID(F));
3446 }
3447
Richard Smitha06c7e62015-08-26 23:55:49 +00003448 std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
3449 DeclarationNameKey Name,
3450 data_type_ref Lookup) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003451 using namespace llvm::support;
3452 endian::Writer<little> LE(Out);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003453 unsigned KeyLen = 1;
Richard Smitha06c7e62015-08-26 23:55:49 +00003454 switch (Name.getKind()) {
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003455 case DeclarationName::Identifier:
3456 case DeclarationName::ObjCZeroArgSelector:
3457 case DeclarationName::ObjCOneArgSelector:
3458 case DeclarationName::ObjCMultiArgSelector:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003459 case DeclarationName::CXXLiteralOperatorName:
3460 KeyLen += 4;
3461 break;
3462 case DeclarationName::CXXOperatorName:
3463 KeyLen += 1;
3464 break;
Douglas Gregor3b65ed02011-08-02 18:32:54 +00003465 case DeclarationName::CXXConstructorName:
3466 case DeclarationName::CXXDestructorName:
3467 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003468 case DeclarationName::CXXUsingDirective:
3469 break;
3470 }
Justin Bognere1c147c2014-03-28 22:03:19 +00003471 LE.write<uint16_t>(KeyLen);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003472
Richard Smithf02662d2015-07-30 03:17:16 +00003473 // 4 bytes for each DeclID.
Richard Smithd88a7f12015-09-01 20:35:42 +00003474 unsigned DataLen = 4 * (Lookup.second - Lookup.first);
3475 assert(uint16_t(DataLen) == DataLen &&
3476 "too many decls for serialized lookup result");
Justin Bognere1c147c2014-03-28 22:03:19 +00003477 LE.write<uint16_t>(DataLen);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003478
3479 return std::make_pair(KeyLen, DataLen);
3480 }
3481
Richard Smitha06c7e62015-08-26 23:55:49 +00003482 void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003483 using namespace llvm::support;
3484 endian::Writer<little> LE(Out);
Richard Smitha06c7e62015-08-26 23:55:49 +00003485 LE.write<uint8_t>(Name.getKind());
3486 switch (Name.getKind()) {
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003487 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +00003488 case DeclarationName::CXXLiteralOperatorName:
3489 LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier()));
Benjamin Kramer53750b12012-09-19 13:40:40 +00003490 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003491 case DeclarationName::ObjCZeroArgSelector:
3492 case DeclarationName::ObjCOneArgSelector:
3493 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00003494 LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
Benjamin Kramer53750b12012-09-19 13:40:40 +00003495 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003496 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00003497 assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
Benjamin Kramer53750b12012-09-19 13:40:40 +00003498 "Invalid operator?");
Richard Smitha06c7e62015-08-26 23:55:49 +00003499 LE.write<uint8_t>(Name.getOperatorKind());
Benjamin Kramer53750b12012-09-19 13:40:40 +00003500 return;
Douglas Gregor3b65ed02011-08-02 18:32:54 +00003501 case DeclarationName::CXXConstructorName:
3502 case DeclarationName::CXXDestructorName:
3503 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003504 case DeclarationName::CXXUsingDirective:
Benjamin Kramer53750b12012-09-19 13:40:40 +00003505 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003506 }
Benjamin Kramer53750b12012-09-19 13:40:40 +00003507
3508 llvm_unreachable("Invalid name kind?");
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003509 }
3510
Richard Smitha06c7e62015-08-26 23:55:49 +00003511 void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
3512 unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003513 using namespace llvm::support;
3514 endian::Writer<little> LE(Out);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003515 uint64_t Start = Out.tell(); (void)Start;
Richard Smithd88a7f12015-09-01 20:35:42 +00003516 for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
3517 LE.write<uint32_t>(DeclIDs[I]);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003518 assert(Out.tell() - Start == DataLen && "Data length is wrong");
3519 }
3520};
3521} // end anonymous namespace
3522
Chandler Carruthe972c362015-03-26 03:11:40 +00003523bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
3524 DeclContext *DC) {
3525 return Result.hasExternalDecls() && DC->NeedToReconcileExternalVisibleStorage;
3526}
3527
3528bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
3529 DeclContext *DC) {
3530 for (auto *D : Result.getLookupResult())
3531 if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
3532 return false;
3533
3534 return true;
3535}
3536
Richard Smithd88a7f12015-09-01 20:35:42 +00003537void
Chandler Carruthe972c362015-03-26 03:11:40 +00003538ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
Richard Smithcd45dbc2014-04-19 03:48:30 +00003539 llvm::SmallVectorImpl<char> &LookupTable) {
Chandler Carruthe972c362015-03-26 03:11:40 +00003540 assert(!ConstDC->HasLazyLocalLexicalLookups &&
3541 !ConstDC->HasLazyExternalLexicalLookups &&
Richard Smith9e2341d2015-03-23 03:25:59 +00003542 "must call buildLookups first");
Richard Smithcd45dbc2014-04-19 03:48:30 +00003543
Chandler Carruthe972c362015-03-26 03:11:40 +00003544 // FIXME: We need to build the lookups table, which is logically const.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003545 auto *DC = const_cast<DeclContext*>(ConstDC);
Chandler Carruthe972c362015-03-26 03:11:40 +00003546 assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
3547
3548 // Create the on-disk hash table representation.
Richard Smithd88a7f12015-09-01 20:35:42 +00003549 MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait,
3550 ASTDeclContextNameLookupTrait> Generator;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003551 ASTDeclContextNameLookupTrait Trait(*this);
3552
Chandler Carruthe972c362015-03-26 03:11:40 +00003553 // The first step is to collect the declaration names which we need to
3554 // serialize into the name lookup table, and to collect them in a stable
3555 // order.
3556 SmallVector<DeclarationName, 16> Names;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003557
Chandler Carruthe972c362015-03-26 03:11:40 +00003558 // We also build up small sets of the constructor and conversion function
3559 // names which are visible.
3560 llvm::SmallSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003561
Chandler Carruthe972c362015-03-26 03:11:40 +00003562 for (auto &Lookup : *DC->buildLookup()) {
3563 auto &Name = Lookup.first;
3564 auto &Result = Lookup.second;
3565
Douglas Gregor7dd37e52015-11-03 01:20:54 +00003566 // If there are no local declarations in our lookup result, we
3567 // don't need to write an entry for the name at all. If we can't
3568 // write out a lookup set without performing more deserialization,
3569 // just skip this entry.
3570 if (isLookupResultExternal(Result, DC) &&
Chandler Carruthe972c362015-03-26 03:11:40 +00003571 isLookupResultEntirelyExternal(Result, DC))
3572 continue;
3573
3574 // We also skip empty results. If any of the results could be external and
3575 // the currently available results are empty, then all of the results are
3576 // external and we skip it above. So the only way we get here with an empty
3577 // results is when no results could have been external *and* we have
3578 // external results.
3579 //
3580 // FIXME: While we might want to start emitting on-disk entries for negative
3581 // lookups into a decl context as an optimization, today we *have* to skip
3582 // them because there are names with empty lookup results in decl contexts
3583 // which we can't emit in any stable ordering: we lookup constructors and
3584 // conversion functions in the enclosing namespace scope creating empty
3585 // results for them. This in almost certainly a bug in Clang's name lookup,
3586 // but that is likely to be hard or impossible to fix and so we tolerate it
3587 // here by omitting lookups with empty results.
3588 if (Lookup.second.getLookupResult().empty())
3589 continue;
3590
3591 switch (Lookup.first.getNameKind()) {
3592 default:
3593 Names.push_back(Lookup.first);
3594 break;
3595
Richard Smithcd45dbc2014-04-19 03:48:30 +00003596 case DeclarationName::CXXConstructorName:
Chandler Carruthe972c362015-03-26 03:11:40 +00003597 assert(isa<CXXRecordDecl>(DC) &&
3598 "Cannot have a constructor name outside of a class!");
3599 ConstructorNameSet.insert(Name);
3600 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003601
3602 case DeclarationName::CXXConversionFunctionName:
Chandler Carruthe972c362015-03-26 03:11:40 +00003603 assert(isa<CXXRecordDecl>(DC) &&
3604 "Cannot have a conversion function name outside of a class!");
3605 ConversionNameSet.insert(Name);
Rafael Espindolac606b3e2015-03-25 04:43:15 +00003606 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003607 }
Chandler Carruth75c9f132015-03-25 00:34:51 +00003608 }
Chandler Carruth75c9f132015-03-25 00:34:51 +00003609
Chandler Carruthe972c362015-03-26 03:11:40 +00003610 // Sort the names into a stable order.
3611 std::sort(Names.begin(), Names.end());
3612
Chandler Carruthffbf7052015-03-26 22:27:09 +00003613 if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
Chandler Carruthe972c362015-03-26 03:11:40 +00003614 // We need to establish an ordering of constructor and conversion function
Chandler Carruthffbf7052015-03-26 22:27:09 +00003615 // names, and they don't have an intrinsic ordering.
Chandler Carruthe972c362015-03-26 03:11:40 +00003616
Chandler Carruthffbf7052015-03-26 22:27:09 +00003617 // First we try the easy case by forming the current context's constructor
3618 // name and adding that name first. This is a very useful optimization to
3619 // avoid walking the lexical declarations in many cases, and it also
3620 // handles the only case where a constructor name can come from some other
3621 // lexical context -- when that name is an implicit constructor merged from
3622 // another declaration in the redecl chain. Any non-implicit constructor or
3623 // conversion function which doesn't occur in all the lexical contexts
3624 // would be an ODR violation.
3625 auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
3626 Context->getCanonicalType(Context->getRecordType(D)));
3627 if (ConstructorNameSet.erase(ImplicitCtorName))
3628 Names.push_back(ImplicitCtorName);
Chandler Carruthe972c362015-03-26 03:11:40 +00003629
Chandler Carruthffbf7052015-03-26 22:27:09 +00003630 // If we still have constructors or conversion functions, we walk all the
3631 // names in the decl and add the constructors and conversion functions
3632 // which are visible in the order they lexically occur within the context.
3633 if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
3634 for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
3635 if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
3636 auto Name = ChildND->getDeclName();
3637 switch (Name.getNameKind()) {
3638 default:
3639 continue;
3640
3641 case DeclarationName::CXXConstructorName:
3642 if (ConstructorNameSet.erase(Name))
3643 Names.push_back(Name);
3644 break;
3645
3646 case DeclarationName::CXXConversionFunctionName:
3647 if (ConversionNameSet.erase(Name))
3648 Names.push_back(Name);
3649 break;
3650 }
3651
3652 if (ConstructorNameSet.empty() && ConversionNameSet.empty())
3653 break;
Chandler Carruthe972c362015-03-26 03:11:40 +00003654 }
3655
Chandler Carruthe972c362015-03-26 03:11:40 +00003656 assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
3657 "constructors by walking all the "
3658 "lexical members of the context.");
3659 assert(ConversionNameSet.empty() && "Failed to find all of the visible "
3660 "conversion functions by walking all "
3661 "the lexical members of the context.");
Richard Smith961eae52014-03-25 01:14:22 +00003662 }
3663
Chandler Carruthe972c362015-03-26 03:11:40 +00003664 // Next we need to do a lookup with each name into this decl context to fully
3665 // populate any results from external sources. We don't actually use the
3666 // results of these lookups because we only want to use the results after all
3667 // results have been loaded and the pointers into them will be stable.
3668 for (auto &Name : Names)
3669 DC->lookup(Name);
3670
3671 // Now we need to insert the results for each name into the hash table. For
3672 // constructor names and conversion function names, we actually need to merge
3673 // all of the results for them into one list of results each and insert
3674 // those.
3675 SmallVector<NamedDecl *, 8> ConstructorDecls;
3676 SmallVector<NamedDecl *, 8> ConversionDecls;
3677
3678 // Now loop over the names, either inserting them or appending for the two
3679 // special cases.
3680 for (auto &Name : Names) {
3681 DeclContext::lookup_result Result = DC->noload_lookup(Name);
3682
3683 switch (Name.getNameKind()) {
3684 default:
Richard Smithd88a7f12015-09-01 20:35:42 +00003685 Generator.insert(Name, Trait.getData(Result), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00003686 break;
3687
3688 case DeclarationName::CXXConstructorName:
3689 ConstructorDecls.append(Result.begin(), Result.end());
3690 break;
3691
3692 case DeclarationName::CXXConversionFunctionName:
3693 ConversionDecls.append(Result.begin(), Result.end());
3694 break;
3695 }
3696 }
3697
3698 // Handle our two special cases if we ended up having any. We arbitrarily use
3699 // the first declaration's name here because the name itself isn't part of
3700 // the key, only the kind of name is used.
3701 if (!ConstructorDecls.empty())
3702 Generator.insert(ConstructorDecls.front()->getDeclName(),
Richard Smithd88a7f12015-09-01 20:35:42 +00003703 Trait.getData(ConstructorDecls), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00003704 if (!ConversionDecls.empty())
3705 Generator.insert(ConversionDecls.front()->getDeclName(),
Richard Smithd88a7f12015-09-01 20:35:42 +00003706 Trait.getData(ConversionDecls), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00003707
Richard Smithd88a7f12015-09-01 20:35:42 +00003708 // Create the on-disk hash table. Also emit the existing imported and
3709 // merged table if there is one.
3710 auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr;
3711 Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr);
Richard Smith961eae52014-03-25 01:14:22 +00003712}
3713
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003714/// \brief Write the block containing all of the declaration IDs
3715/// visible from the given DeclContext.
3716///
3717/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
Sebastian Redla4071b42010-08-24 00:50:09 +00003718/// bitstream, or 0 if no block was written.
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003719uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
3720 DeclContext *DC) {
Richard Smith5fc18a92015-07-12 23:43:21 +00003721 // If we imported a key declaration of this namespace, write the visible
3722 // lookup results as an update record for it rather than including them
3723 // on this declaration. We will only look at key declarations on reload.
3724 if (isa<NamespaceDecl>(DC) && Chain &&
3725 Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) {
3726 // Only do this once, for the first local declaration of the namespace.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003727 for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
Richard Smith5fc18a92015-07-12 23:43:21 +00003728 Prev = Prev->getPreviousDecl())
3729 if (!Prev->isFromASTFile())
3730 return 0;
3731
3732 // Note that we need to emit an update record for the primary context.
3733 UpdatedDeclContexts.insert(DC->getPrimaryContext());
3734
3735 // Make sure all visible decls are written. They will be recorded later. We
3736 // do this using a side data structure so we can sort the names into
3737 // a deterministic order.
3738 StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup();
3739 SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16>
3740 LookupResults;
3741 if (Map) {
3742 LookupResults.reserve(Map->size());
3743 for (auto &Entry : *Map)
3744 LookupResults.push_back(
3745 std::make_pair(Entry.first, Entry.second.getLookupResult()));
3746 }
3747
3748 std::sort(LookupResults.begin(), LookupResults.end(), llvm::less_first());
3749 for (auto &NameAndResult : LookupResults) {
3750 DeclarationName Name = NameAndResult.first;
3751 DeclContext::lookup_result Result = NameAndResult.second;
3752 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
3753 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
3754 // We have to work around a name lookup bug here where negative lookup
3755 // results for these names get cached in namespace lookup tables (these
3756 // names should never be looked up in a namespace).
3757 assert(Result.empty() && "Cannot have a constructor or conversion "
3758 "function name in a namespace!");
3759 continue;
3760 }
3761
3762 for (NamedDecl *ND : Result)
3763 if (!ND->isFromASTFile())
3764 GetDeclRef(ND);
3765 }
3766
3767 return 0;
3768 }
3769
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003770 if (DC->getPrimaryContext() != DC)
3771 return 0;
3772
Chandler Carruthe972c362015-03-26 03:11:40 +00003773 // Skip contexts which don't support name lookup.
3774 if (!DC->isLookupContext())
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003775 return 0;
3776
3777 // If not in C++, we perform name lookup for the translation unit via the
3778 // IdentifierInfo chains, don't bother to build a visible-declarations table.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003779 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003780 return 0;
3781
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003782 // Serialize the contents of the mapping used for lookup. Note that,
3783 // although we have two very different code paths, the serialized
3784 // representation is the same for both cases: a declaration name,
3785 // followed by a size, followed by references to the visible
3786 // declarations that have that name.
3787 uint64_t Offset = Stream.GetCurrentBitNo();
Richard Smithf634c902012-03-16 06:12:59 +00003788 StoredDeclsMap *Map = DC->buildLookup();
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003789 if (!Map || Map->empty())
3790 return 0;
3791
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003792 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003793 SmallString<4096> LookupTable;
Richard Smithd88a7f12015-09-01 20:35:42 +00003794 GenerateNameLookupTable(DC, LookupTable);
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003795
3796 // Write the lookup table
Mehdi Amini57a41912015-09-10 01:46:39 +00003797 RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003798 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
Yaron Keren92e1b622015-03-18 10:17:07 +00003799 LookupTable);
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003800 ++NumVisibleDeclContexts;
3801 return Offset;
3802}
3803
Sebastian Redla4071b42010-08-24 00:50:09 +00003804/// \brief Write an UPDATE_VISIBLE block for the given context.
3805///
3806/// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
3807/// DeclContext in a dependent AST file. As such, they only exist for the TU
Richard Smithf634c902012-03-16 06:12:59 +00003808/// (in C++), for namespaces, and for classes with forward-declared unscoped
3809/// enumeration members (in C++11).
Sebastian Redla4071b42010-08-24 00:50:09 +00003810void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
Richard Smith961eae52014-03-25 01:14:22 +00003811 StoredDeclsMap *Map = DC->getLookupPtr();
Sebastian Redla4071b42010-08-24 00:50:09 +00003812 if (!Map || Map->empty())
3813 return;
3814
Sebastian Redla4071b42010-08-24 00:50:09 +00003815 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003816 SmallString<4096> LookupTable;
Richard Smithd88a7f12015-09-01 20:35:42 +00003817 GenerateNameLookupTable(DC, LookupTable);
Sebastian Redla4071b42010-08-24 00:50:09 +00003818
Richard Smith5fc18a92015-07-12 23:43:21 +00003819 // If we're updating a namespace, select a key declaration as the key for the
3820 // update record; those are the only ones that will be checked on reload.
3821 if (isa<NamespaceDecl>(DC))
3822 DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
3823
Sebastian Redla4071b42010-08-24 00:50:09 +00003824 // Write the lookup table
Mehdi Amini57a41912015-09-10 01:46:39 +00003825 RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))};
Yaron Keren92e1b622015-03-18 10:17:07 +00003826 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
Sebastian Redla4071b42010-08-24 00:50:09 +00003827}
3828
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003829/// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
3830void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
Mehdi Amini57a41912015-09-10 01:46:39 +00003831 RecordData::value_type Record[] = {Opts.fp_contract};
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003832 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
3833}
3834
3835/// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
3836void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003837 if (!SemaRef.Context.getLangOpts().OpenCL)
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003838 return;
3839
3840 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
3841 RecordData Record;
3842#define OPENCLEXT(nm) Record.push_back(Opts.nm);
3843#include "clang/Basic/OpenCLExtensions.def"
3844 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
3845}
3846
Douglas Gregor404cdde2012-01-27 01:47:08 +00003847void ASTWriter::WriteObjCCategories() {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003848 SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
Douglas Gregor404cdde2012-01-27 01:47:08 +00003849 RecordData Categories;
3850
3851 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
3852 unsigned Size = 0;
3853 unsigned StartIndex = Categories.size();
3854
3855 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
3856
3857 // Allocate space for the size.
3858 Categories.push_back(0);
3859
3860 // Add the categories.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003861 for (ObjCInterfaceDecl::known_categories_iterator
3862 Cat = Class->known_categories_begin(),
3863 CatEnd = Class->known_categories_end();
3864 Cat != CatEnd; ++Cat, ++Size) {
3865 assert(getDeclID(*Cat) != 0 && "Bogus category");
3866 AddDeclRef(*Cat, Categories);
Douglas Gregor404cdde2012-01-27 01:47:08 +00003867 }
3868
3869 // Update the size.
3870 Categories[StartIndex] = Size;
3871
3872 // Record this interface -> category map.
3873 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
3874 CategoriesMap.push_back(CatInfo);
3875 }
3876
3877 // Sort the categories map by the definition ID, since the reader will be
3878 // performing binary searches on this information.
3879 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
3880
3881 // Emit the categories map.
3882 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003883
3884 auto *Abbrev = new BitCodeAbbrev();
Douglas Gregor404cdde2012-01-27 01:47:08 +00003885 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
3886 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
3887 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3888 unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00003889
3890 RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
3891 Stream.EmitRecordWithBlob(AbbrevID, Record,
3892 reinterpret_cast<char *>(CategoriesMap.data()),
Douglas Gregor404cdde2012-01-27 01:47:08 +00003893 CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
Mehdi Amini57a41912015-09-10 01:46:39 +00003894
Douglas Gregor404cdde2012-01-27 01:47:08 +00003895 // Emit the category lists.
3896 Stream.EmitRecord(OBJC_CATEGORIES, Categories);
3897}
3898
Richard Smithe40f2ba2013-08-07 21:41:30 +00003899void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
3900 Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
3901
3902 if (LPTMap.empty())
3903 return;
3904
3905 RecordData Record;
Chandler Carruth52cee4d2015-03-26 09:08:15 +00003906 for (auto LPTMapEntry : LPTMap) {
3907 const FunctionDecl *FD = LPTMapEntry.first;
3908 LateParsedTemplate *LPT = LPTMapEntry.second;
3909 AddDeclRef(FD, Record);
Richard Smithe40f2ba2013-08-07 21:41:30 +00003910 AddDeclRef(LPT->D, Record);
3911 Record.push_back(LPT->Toks.size());
3912
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003913 for (const auto &Tok : LPT->Toks) {
3914 AddToken(Tok, Record);
Richard Smithe40f2ba2013-08-07 21:41:30 +00003915 }
3916 }
3917 Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
3918}
3919
Dario Domizioli13a0a382014-05-23 12:13:25 +00003920/// \brief Write the state of 'pragma clang optimize' at the end of the module.
3921void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
3922 RecordData Record;
3923 SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
3924 AddSourceLocation(PragmaLoc, Record);
3925 Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
3926}
3927
Nico Weber779355f2016-03-02 23:22:00 +00003928/// \brief Write the state of 'pragma ms_struct' at the end of the module.
3929void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
3930 RecordData Record;
3931 Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF);
3932 Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
3933}
3934
Nico Weber42932312016-03-03 00:17:35 +00003935/// \brief Write the state of 'pragma pointers_to_members' at the end of the
3936//module.
3937void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
3938 RecordData Record;
3939 Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod);
3940 AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record);
3941 Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
3942}
3943
Douglas Gregor8f64ca12015-12-08 22:43:32 +00003944void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
3945 ModuleFileExtensionWriter &Writer) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003946 // Enter the extension block.
3947 Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
3948
3949 // Emit the metadata record abbreviation.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003950 auto *Abv = new llvm::BitCodeAbbrev();
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003951 Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
3952 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3953 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3954 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3955 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3956 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
3957 unsigned Abbrev = Stream.EmitAbbrev(Abv);
3958
3959 // Emit the metadata record.
3960 RecordData Record;
3961 auto Metadata = Writer.getExtension()->getExtensionMetadata();
3962 Record.push_back(EXTENSION_METADATA);
3963 Record.push_back(Metadata.MajorVersion);
3964 Record.push_back(Metadata.MinorVersion);
3965 Record.push_back(Metadata.BlockName.size());
3966 Record.push_back(Metadata.UserInfo.size());
3967 SmallString<64> Buffer;
3968 Buffer += Metadata.BlockName;
3969 Buffer += Metadata.UserInfo;
3970 Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
3971
3972 // Emit the contents of the extension block.
Douglas Gregor8f64ca12015-12-08 22:43:32 +00003973 Writer.writeExtensionContents(SemaRef, Stream);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003974
3975 // Exit the extension block.
3976 Stream.ExitBlock();
3977}
3978
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003979//===----------------------------------------------------------------------===//
Douglas Gregorc5046832009-04-27 18:38:38 +00003980// General Serialization Routines
3981//===----------------------------------------------------------------------===//
3982
Richard Smith69c82bf2016-04-01 22:52:03 +00003983/// \brief Emit the list of attributes to the specified record.
Richard Smith290d8012016-04-06 17:06:00 +00003984void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) {
3985 auto &Record = *this;
Argyrios Kyrtzidis9beef8e2010-10-18 19:20:11 +00003986 Record.push_back(Attrs.size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003987 for (const auto *A : Attrs) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003988 Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
Richard Smith290d8012016-04-06 17:06:00 +00003989 Record.AddSourceRange(A->getRange());
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00003990
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003991#include "clang/Serialization/AttrPCHWrite.inc"
Daniel Dunbarfc6507e2010-05-27 02:25:39 +00003992
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00003993 }
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00003994}
3995
John McCallf413f5e2013-05-03 00:10:13 +00003996void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
3997 AddSourceLocation(Tok.getLocation(), Record);
3998 Record.push_back(Tok.getLength());
3999
4000 // FIXME: When reading literal tokens, reconstruct the literal pointer
4001 // if it is needed.
4002 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
4003 // FIXME: Should translate token kind to a stable encoding.
4004 Record.push_back(Tok.getKind());
4005 // FIXME: Should translate token flags to a stable encoding.
4006 Record.push_back(Tok.getFlags());
4007}
4008
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004009void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00004010 Record.push_back(Str.size());
4011 Record.insert(Record.end(), Str.begin(), Str.end());
4012}
4013
Richard Smith7ed1bc92014-12-05 22:42:13 +00004014bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
Richard Smith54cc3c22014-12-11 20:50:24 +00004015 assert(Context && "should have context when outputting path");
Richard Smith7ed1bc92014-12-05 22:42:13 +00004016
Richard Smith54cc3c22014-12-11 20:50:24 +00004017 bool Changed =
4018 cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004019
4020 // Remove a prefix to make the path relative, if relevant.
4021 const char *PathBegin = Path.data();
4022 const char *PathPtr =
4023 adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
4024 if (PathPtr != PathBegin) {
4025 Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
4026 Changed = true;
4027 }
4028
4029 return Changed;
4030}
4031
4032void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
4033 SmallString<128> FilePath(Path);
4034 PreparePathForOutput(FilePath);
4035 AddString(FilePath, Record);
4036}
4037
Mehdi Amini57a41912015-09-10 01:46:39 +00004038void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
Richard Smith7ed1bc92014-12-05 22:42:13 +00004039 StringRef Path) {
4040 SmallString<128> FilePath(Path);
4041 PreparePathForOutput(FilePath);
4042 Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
4043}
4044
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004045void ASTWriter::AddVersionTuple(const VersionTuple &Version,
4046 RecordDataImpl &Record) {
4047 Record.push_back(Version.getMajor());
David Blaikie05785d12013-02-20 22:23:23 +00004048 if (Optional<unsigned> Minor = Version.getMinor())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004049 Record.push_back(*Minor + 1);
4050 else
4051 Record.push_back(0);
David Blaikie05785d12013-02-20 22:23:23 +00004052 if (Optional<unsigned> Subminor = Version.getSubminor())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004053 Record.push_back(*Subminor + 1);
4054 else
4055 Record.push_back(0);
4056}
4057
Douglas Gregore84a9da2009-04-20 20:36:09 +00004058/// \brief Note that the identifier II occurs at the given offset
4059/// within the identifier table.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004060void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Sebastian Redl539c5062010-08-18 23:57:32 +00004061 IdentID ID = IdentifierIDs[II];
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00004062 // Only store offsets new to this AST file. Other identifier names are looked
Sebastian Redlff4a2952010-07-23 23:49:55 +00004063 // up earlier in the chain and thus don't need an offset.
4064 if (ID >= FirstIdentID)
4065 IdentifierOffsets[ID - FirstIdentID] = Offset;
Douglas Gregore84a9da2009-04-20 20:36:09 +00004066}
4067
Douglas Gregor95c13f52009-04-25 17:48:32 +00004068/// \brief Note that the selector Sel occurs at the given offset
4069/// within the method pool/selector table.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004070void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
Douglas Gregor95c13f52009-04-25 17:48:32 +00004071 unsigned ID = SelectorIDs[Sel];
4072 assert(ID && "Unknown selector");
Sebastian Redld95a56e2010-08-04 18:21:41 +00004073 // Don't record offsets for selectors that are also available in a different
4074 // file.
4075 if (ID < FirstSelectorID)
4076 return;
4077 SelectorOffsets[ID - FirstSelectorID] = Offset;
Douglas Gregor95c13f52009-04-25 17:48:32 +00004078}
4079
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004080ASTWriter::ASTWriter(
4081 llvm::BitstreamWriter &Stream,
4082 ArrayRef<llvm::IntrusiveRefCntPtr<ModuleFileExtension>> Extensions,
4083 bool IncludeTimestamps)
Richard Smith01b2cb42014-07-26 06:37:51 +00004084 : Stream(Stream), Context(nullptr), PP(nullptr), Chain(nullptr),
Richard Smithe75ee0f2015-08-17 07:13:32 +00004085 WritingModule(nullptr), IncludeTimestamps(IncludeTimestamps),
4086 WritingAST(false), DoneWritingDeclsAndTypes(false),
4087 ASTHasCompilerErrors(false), FirstDeclID(NUM_PREDEF_DECL_IDS),
4088 NextDeclID(FirstDeclID), FirstTypeID(NUM_PREDEF_TYPE_IDS),
4089 NextTypeID(FirstTypeID), FirstIdentID(NUM_PREDEF_IDENT_IDS),
4090 NextIdentID(FirstIdentID), FirstMacroID(NUM_PREDEF_MACRO_IDS),
4091 NextMacroID(FirstMacroID), FirstSubmoduleID(NUM_PREDEF_SUBMODULE_IDS),
Richard Smith01b2cb42014-07-26 06:37:51 +00004092 NextSubmoduleID(FirstSubmoduleID),
4093 FirstSelectorID(NUM_PREDEF_SELECTOR_IDS), NextSelectorID(FirstSelectorID),
Richard Smith290d8012016-04-06 17:06:00 +00004094 NumStatements(0), NumMacros(0),
Richard Smith01b2cb42014-07-26 06:37:51 +00004095 NumLexicalDeclContexts(0), NumVisibleDeclContexts(0),
Richard Smithe75ee0f2015-08-17 07:13:32 +00004096 TypeExtQualAbbrev(0), TypeFunctionProtoAbbrev(0), DeclParmVarAbbrev(0),
Richard Smith01b2cb42014-07-26 06:37:51 +00004097 DeclContextLexicalAbbrev(0), DeclContextVisibleLookupAbbrev(0),
Richard Smitha27c26e2014-07-27 04:19:32 +00004098 UpdateVisibleAbbrev(0), DeclRecordAbbrev(0), DeclTypedefAbbrev(0),
Richard Smith01b2cb42014-07-26 06:37:51 +00004099 DeclVarAbbrev(0), DeclFieldAbbrev(0), DeclEnumAbbrev(0),
Richard Smitha27c26e2014-07-27 04:19:32 +00004100 DeclObjCIvarAbbrev(0), DeclCXXMethodAbbrev(0), DeclRefExprAbbrev(0),
4101 CharacterLiteralAbbrev(0), IntegerLiteralAbbrev(0),
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004102 ExprImplicitCastAbbrev(0) {
4103 for (const auto &Ext : Extensions) {
4104 if (auto Writer = Ext->createExtensionWriter(*this))
4105 ModuleFileExtensionWriters.push_back(std::move(Writer));
4106 }
4107}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004108
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004109ASTWriter::~ASTWriter() {
Reid Kleckner588c9372014-02-19 23:44:52 +00004110 llvm::DeleteContainerSeconds(FileDeclIDs);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004111}
4112
Richard Smithb3761912015-02-05 23:08:52 +00004113const LangOptions &ASTWriter::getLangOpts() const {
4114 assert(WritingAST && "can't determine lang opts when not writing AST");
4115 return Context->getLangOpts();
4116}
4117
Richard Smithe75ee0f2015-08-17 07:13:32 +00004118time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const {
4119 return IncludeTimestamps ? E->getModificationTime() : 0;
4120}
4121
Adrian Prantladbd2b12015-09-22 23:26:31 +00004122uint64_t ASTWriter::WriteAST(Sema &SemaRef, const std::string &OutputFile,
4123 Module *WritingModule, StringRef isysroot,
4124 bool hasErrors) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00004125 WritingAST = true;
Adrian Prantladbd2b12015-09-22 23:26:31 +00004126
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00004127 ASTHasCompilerErrors = hasErrors;
4128
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004129 // Emit the file header.
Douglas Gregor8f45df52009-04-16 22:23:12 +00004130 Stream.Emit((unsigned)'C', 8);
4131 Stream.Emit((unsigned)'P', 8);
4132 Stream.Emit((unsigned)'C', 8);
4133 Stream.Emit((unsigned)'H', 8);
Mike Stump11289f42009-09-09 15:08:12 +00004134
Chris Lattner28fa4e62009-04-26 22:26:21 +00004135 WriteBlockInfoBlock();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004136
Douglas Gregoreda8e122011-08-09 15:13:55 +00004137 Context = &SemaRef.Context;
Douglas Gregora28bcdd2011-12-01 02:07:58 +00004138 PP = &SemaRef.PP;
Douglas Gregora89c5ac2011-12-06 01:10:29 +00004139 this->WritingModule = WritingModule;
Adrian Prantladbd2b12015-09-22 23:26:31 +00004140 ASTFileSignature Signature =
4141 WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
Craig Toppera13603a2014-05-22 05:54:18 +00004142 Context = nullptr;
4143 PP = nullptr;
4144 this->WritingModule = nullptr;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004145 this->BaseDirectory.clear();
Craig Toppera13603a2014-05-22 05:54:18 +00004146
Douglas Gregor2fd3d402011-09-17 00:05:03 +00004147 WritingAST = false;
Adrian Prantladbd2b12015-09-22 23:26:31 +00004148 return Signature;
Sebastian Redl143413f2010-07-12 22:02:52 +00004149}
4150
Douglas Gregora94a1542011-07-27 21:45:57 +00004151template<typename Vector>
4152static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4153 ASTWriter::RecordData &Record) {
Craig Toppera13603a2014-05-22 05:54:18 +00004154 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4155 I != E; ++I) {
Douglas Gregora94a1542011-07-27 21:45:57 +00004156 Writer.AddDeclRef(*I, Record);
4157 }
4158}
4159
Adrian Prantladbd2b12015-09-22 23:26:31 +00004160uint64_t ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
4161 const std::string &OutputFile,
4162 Module *WritingModule) {
Sebastian Redl143413f2010-07-12 22:02:52 +00004163 using namespace llvm;
4164
Craig Toppera13603a2014-05-22 05:54:18 +00004165 bool isModule = WritingModule != nullptr;
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004166
Douglas Gregorcf68c582011-12-01 22:20:10 +00004167 // Make sure that the AST reader knows to finalize itself.
4168 if (Chain)
4169 Chain->finalizeForWriting();
4170
Sebastian Redl143413f2010-07-12 22:02:52 +00004171 ASTContext &Context = SemaRef.Context;
4172 Preprocessor &PP = SemaRef.PP;
4173
Douglas Gregordab42432011-08-12 00:15:20 +00004174 // Set up predefined declaration IDs.
Richard Smith5fc18a92015-07-12 23:43:21 +00004175 auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
4176 if (D) {
4177 assert(D->isCanonicalDecl() && "predefined decl is not canonical");
4178 DeclIDs[D] = ID;
Richard Smith5fc18a92015-07-12 23:43:21 +00004179 }
4180 };
4181 RegisterPredefDecl(Context.getTranslationUnitDecl(),
4182 PREDEF_DECL_TRANSLATION_UNIT_ID);
4183 RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
4184 RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
4185 RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
4186 RegisterPredefDecl(Context.ObjCProtocolClassDecl,
4187 PREDEF_DECL_OBJC_PROTOCOL_ID);
4188 RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
4189 RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
4190 RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
4191 PREDEF_DECL_OBJC_INSTANCETYPE_ID);
4192 RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
Richard Smith9b88a4c2015-07-27 05:40:23 +00004193 RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
Charles Davisc7d5c942015-09-17 20:55:33 +00004194 RegisterPredefDecl(Context.BuiltinMSVaListDecl,
4195 PREDEF_DECL_BUILTIN_MS_VA_LIST_ID);
Richard Smith5fc18a92015-07-12 23:43:21 +00004196 RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
David Majnemerd9b1a4f2015-11-04 03:40:30 +00004197 RegisterPredefDecl(Context.MakeIntegerSeqDecl,
4198 PREDEF_DECL_MAKE_INTEGER_SEQ_ID);
Quentin Colombet043406b2016-02-03 22:41:00 +00004199 RegisterPredefDecl(Context.CFConstantStringTypeDecl,
4200 PREDEF_DECL_CF_CONSTANT_STRING_ID);
Ben Langmuirf5416742016-02-04 00:55:24 +00004201 RegisterPredefDecl(Context.CFConstantStringTagDecl,
4202 PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID);
Eric Fiselier6ad68552016-07-01 01:24:09 +00004203 RegisterPredefDecl(Context.TypePackElementDecl,
4204 PREDEF_DECL_TYPE_PACK_ELEMENT_ID);
Meador Inge5d3fb222012-06-16 03:34:49 +00004205
Chris Lattner0c797362009-09-08 18:19:27 +00004206 // Build a record containing all of the tentative definitions in this file, in
Sebastian Redl35351a92010-01-31 22:27:38 +00004207 // TentativeDefinitions order. Generally, this record will be empty for
Chris Lattner0c797362009-09-08 18:19:27 +00004208 // headers.
Douglas Gregord4df8652009-04-22 22:02:47 +00004209 RecordData TentativeDefinitions;
Douglas Gregora94a1542011-07-27 21:45:57 +00004210 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
Douglas Gregoreb08bd42011-07-27 20:58:46 +00004211
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00004212 // Build a record containing all of the file scoped decls in this file.
4213 RecordData UnusedFileScopedDecls;
Argyrios Kyrtzidis59852362013-03-14 04:45:00 +00004214 if (!isModule)
4215 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
4216 UnusedFileScopedDecls);
Sebastian Redl08aca90252010-08-05 18:21:25 +00004217
Douglas Gregor851443c2011-08-12 01:39:19 +00004218 // Build a record containing all of the delegating constructors we still need
4219 // to resolve.
Alexis Hunt27a761d2011-05-04 23:29:54 +00004220 RecordData DelegatingCtorDecls;
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004221 if (!isModule)
4222 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
Alexis Hunt27a761d2011-05-04 23:29:54 +00004223
Douglas Gregor851443c2011-08-12 01:39:19 +00004224 // Write the set of weak, undeclared identifiers. We always write the
4225 // entire table, since later PCH files in a PCH chain are only interested in
4226 // the results at the end of the chain.
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004227 RecordData WeakUndeclaredIdentifiers;
Chandler Carruthf85d9822015-03-26 08:32:49 +00004228 for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) {
4229 IdentifierInfo *II = WeakUndeclaredIdentifier.first;
4230 WeakInfo &WI = WeakUndeclaredIdentifier.second;
4231 AddIdentifierRef(II, WeakUndeclaredIdentifiers);
4232 AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
4233 AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
4234 WeakUndeclaredIdentifiers.push_back(WI.getUsed());
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004235 }
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00004236
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004237 // Build a record containing all of the ext_vector declarations.
4238 RecordData ExtVectorDecls;
Douglas Gregorb7098a32011-07-28 00:39:29 +00004239 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004240
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004241 // Build a record containing all of the VTable uses information.
4242 RecordData VTableUses;
Argyrios Kyrtzidisedee67f2010-08-03 17:29:52 +00004243 if (!SemaRef.VTableUses.empty()) {
Argyrios Kyrtzidisedee67f2010-08-03 17:29:52 +00004244 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4245 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4246 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4247 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4248 }
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004249 }
4250
Nico Weber72889432014-09-06 01:25:55 +00004251 // Build a record containing all of the UnusedLocalTypedefNameCandidates.
4252 RecordData UnusedLocalTypedefNameCandidates;
4253 for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4254 AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
4255
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004256 // Build a record containing all of pending implicit instantiations.
Chandler Carruth54080172010-08-25 08:44:16 +00004257 RecordData PendingInstantiations;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004258 for (const auto &I : SemaRef.PendingInstantiations) {
4259 AddDeclRef(I.first, PendingInstantiations);
4260 AddSourceLocation(I.second, PendingInstantiations);
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004261 }
4262 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4263 "There are local ones at end of translation unit!");
4264
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004265 // Build a record containing some declaration references.
4266 RecordData SemaDeclRefs;
4267 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
4268 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4269 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
4270 }
4271
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004272 RecordData CUDASpecialDeclRefs;
4273 if (Context.getcudaConfigureCallDecl()) {
4274 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4275 }
4276
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004277 // Build a record containing all of the known namespaces.
4278 RecordData KnownNamespaces;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004279 for (const auto &I : SemaRef.KnownNamespaces) {
4280 if (!I.second)
4281 AddDeclRef(I.first, KnownNamespaces);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004282 }
Douglas Gregor112b9072012-10-18 05:31:06 +00004283
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004284 // Build a record of all used, undefined objects that require definitions.
4285 RecordData UndefinedButUsed;
Nick Lewyckyf0f56162013-01-31 03:23:57 +00004286
4287 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004288 SemaRef.getUndefinedButUsed(Undefined);
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004289 for (const auto &I : Undefined) {
4290 AddDeclRef(I.first, UndefinedButUsed);
4291 AddSourceLocation(I.second, UndefinedButUsed);
Nick Lewycky8334af82013-01-26 00:35:08 +00004292 }
4293
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00004294 // Build a record containing all delete-expressions that we would like to
4295 // analyze later in AST.
4296 RecordData DeleteExprsToAnalyze;
4297
4298 for (const auto &DeleteExprsInfo :
4299 SemaRef.getMismatchingDeleteExpressions()) {
4300 AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
4301 DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
4302 for (const auto &DeleteLoc : DeleteExprsInfo.second) {
4303 AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
4304 DeleteExprsToAnalyze.push_back(DeleteLoc.second);
4305 }
4306 }
4307
Douglas Gregor112b9072012-10-18 05:31:06 +00004308 // Write the control block
Adrian Prantladbd2b12015-09-22 23:26:31 +00004309 uint64_t Signature = WriteControlBlock(PP, Context, isysroot, OutputFile);
Douglas Gregor112b9072012-10-18 05:31:06 +00004310
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00004311 // Write the remaining AST contents.
Sebastian Redl539c5062010-08-18 23:57:32 +00004312 Stream.EnterSubblock(AST_BLOCK_ID, 5);
Douglas Gregor851443c2011-08-12 01:39:19 +00004313
Argyrios Kyrtzidis39605402012-12-13 21:38:23 +00004314 // This is so that older clang versions, before the introduction
4315 // of the control block, can read and reject the newer PCH format.
Mehdi Amini57a41912015-09-10 01:46:39 +00004316 {
4317 RecordData Record = {VERSION_MAJOR};
4318 Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4319 }
Argyrios Kyrtzidis39605402012-12-13 21:38:23 +00004320
Douglas Gregor851443c2011-08-12 01:39:19 +00004321 // Create a lexical update block containing all of the declarations in the
4322 // translation unit that do not come from other AST files.
4323 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00004324 SmallVector<uint32_t, 128> NewGlobalKindDeclPairs;
4325 for (const auto *D : TU->noload_decls()) {
4326 if (!D->isFromASTFile()) {
4327 NewGlobalKindDeclPairs.push_back(D->getKind());
4328 NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
4329 }
Douglas Gregor851443c2011-08-12 01:39:19 +00004330 }
4331
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004332 auto *Abv = new llvm::BitCodeAbbrev();
Douglas Gregor851443c2011-08-12 01:39:19 +00004333 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4334 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4335 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv);
Mehdi Amini57a41912015-09-10 01:46:39 +00004336 {
4337 RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
4338 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4339 bytes(NewGlobalKindDeclPairs));
4340 }
4341
Douglas Gregor851443c2011-08-12 01:39:19 +00004342 // And a visible updates block for the translation unit.
4343 Abv = new llvm::BitCodeAbbrev();
4344 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4345 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
Douglas Gregor851443c2011-08-12 01:39:19 +00004346 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4347 UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv);
4348 WriteDeclContextVisibleUpdate(TU);
Richard Smithf19e1272015-03-07 00:04:49 +00004349
4350 // If we have any extern "C" names, write out a visible update for them.
4351 if (Context.ExternCContext)
4352 WriteDeclContextVisibleUpdate(Context.ExternCContext);
Douglas Gregor851443c2011-08-12 01:39:19 +00004353
4354 // If the translation unit has an anonymous namespace, and we don't already
4355 // have an update block for it, write it as an update block.
Richard Smith6ef42932014-03-20 21:02:00 +00004356 // FIXME: Why do we not do this if there's already an update block?
Douglas Gregor851443c2011-08-12 01:39:19 +00004357 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4358 ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
Richard Smith6ef42932014-03-20 21:02:00 +00004359 if (Record.empty())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004360 Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
Douglas Gregor851443c2011-08-12 01:39:19 +00004361 }
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004362
Richard Smith5652c0f2014-03-21 01:48:23 +00004363 // Add update records for all mangling numbers and static local numbers.
4364 // These aren't really update records, but this is a convenient way of
4365 // tagging this rare extra data onto the declarations.
4366 for (const auto &Number : Context.MangleNumbers)
4367 if (!Number.first->isFromASTFile())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004368 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4369 Number.second));
Richard Smith5652c0f2014-03-21 01:48:23 +00004370 for (const auto &Number : Context.StaticLocalNumbers)
4371 if (!Number.first->isFromASTFile())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004372 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4373 Number.second));
Richard Smith5652c0f2014-03-21 01:48:23 +00004374
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004375 // Make sure visible decls, added to DeclContexts previously loaded from
4376 // an AST file, are registered for serialization.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004377 for (const auto *I : UpdatingVisibleDecls) {
4378 GetDeclRef(I);
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004379 }
4380
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +00004381 // Make sure all decls associated with an identifier are registered for
Richard Smith79bf9202015-08-24 03:33:22 +00004382 // serialization, if we're storing decls with identifiers.
4383 if (!WritingModule || !getLangOpts().CPlusPlus) {
4384 llvm::SmallVector<const IdentifierInfo*, 256> IIs;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004385 for (const auto &ID : PP.getIdentifierTable()) {
4386 const IdentifierInfo *II = ID.second;
Richard Smith79bf9202015-08-24 03:33:22 +00004387 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
4388 IIs.push_back(II);
4389 }
4390 // Sort the identifiers to visit based on their name.
4391 std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
4392 for (const IdentifierInfo *II : IIs) {
4393 for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4394 DEnd = SemaRef.IdResolver.end();
4395 D != DEnd; ++D) {
4396 GetDeclRef(*D);
4397 }
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +00004398 }
4399 }
4400
Manman Rena0f31a02016-04-29 19:04:05 +00004401 // For method pool in the module, if it contains an entry for a selector,
4402 // the entry should be complete, containing everything introduced by that
4403 // module and all modules it imports. It's possible that the entry is out of
4404 // date, so we need to pull in the new content here.
4405
4406 // It's possible that updateOutOfDateSelector can update SelectorIDs. To be
4407 // safe, we copy all selectors out.
4408 llvm::SmallVector<Selector, 256> AllSelectors;
4409 for (auto &SelectorAndID : SelectorIDs)
4410 AllSelectors.push_back(SelectorAndID.first);
4411 for (auto &Selector : AllSelectors)
4412 SemaRef.updateOutOfDateSelector(Selector);
4413
Douglas Gregor5204bde2011-08-02 16:26:37 +00004414 // Form the record of special types.
4415 RecordData SpecialTypes;
Douglas Gregor5204bde2011-08-02 16:26:37 +00004416 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
Douglas Gregor5204bde2011-08-02 16:26:37 +00004417 AddTypeRef(Context.getFILEType(), SpecialTypes);
4418 AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4419 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4420 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4421 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
Douglas Gregor5204bde2011-08-02 16:26:37 +00004422 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00004423 AddTypeRef(Context.getucontext_tType(), SpecialTypes);
Douglas Gregora28bcdd2011-12-01 02:07:58 +00004424
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004425 if (Chain) {
4426 // Write the mapping information describing our module dependencies and how
4427 // each of those modules were mapped into our own offset/ID space, so that
4428 // the reader can build the appropriate mapping to its own offset/ID space.
4429 // The map consists solely of a blob with the following format:
4430 // *(module-name-len:i16 module-name:len*i8
4431 // source-location-offset:i32
4432 // identifier-id:i32
4433 // preprocessed-entity-id:i32
4434 // macro-definition-id:i32
Douglas Gregor253eefe2011-12-01 00:59:36 +00004435 // submodule-id:i32
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004436 // selector-id:i32
4437 // declaration-id:i32
4438 // c++-base-specifiers-id:i32
4439 // type-id:i32)
4440 //
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004441 auto *Abbrev = new BitCodeAbbrev();
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004442 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4443 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4444 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(Abbrev);
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004445 SmallString<2048> Buffer;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004446 {
4447 llvm::raw_svector_ostream Out(Buffer);
Ben Langmuir785180e2014-10-20 16:27:30 +00004448 for (ModuleFile *M : Chain->ModuleMgr) {
Justin Bognere1c147c2014-03-28 22:03:19 +00004449 using namespace llvm::support;
4450 endian::Writer<little> LE(Out);
Ben Langmuir785180e2014-10-20 16:27:30 +00004451 StringRef FileName = M->FileName;
Justin Bognere1c147c2014-03-28 22:03:19 +00004452 LE.write<uint16_t>(FileName.size());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004453 Out.write(FileName.data(), FileName.size());
Ben Langmuirfe971d92014-08-16 04:54:18 +00004454
Ben Langmuir785180e2014-10-20 16:27:30 +00004455 // Note: if a base ID was uint max, it would not be possible to load
4456 // another module after it or have more than one entity inside it.
4457 uint32_t None = std::numeric_limits<uint32_t>::max();
4458
4459 auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) {
4460 assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
4461 if (ShouldWrite)
4462 LE.write<uint32_t>(BaseID);
4463 else
4464 LE.write<uint32_t>(None);
4465 };
4466
Ben Langmuirfe971d92014-08-16 04:54:18 +00004467 // These values should be unique within a chain, since they will be read
4468 // as keys into ContinuousRangeMaps.
Ben Langmuir785180e2014-10-20 16:27:30 +00004469 writeBaseIDOrNone(M->SLocEntryBaseOffset, M->LocalNumSLocEntries);
4470 writeBaseIDOrNone(M->BaseIdentifierID, M->LocalNumIdentifiers);
4471 writeBaseIDOrNone(M->BaseMacroID, M->LocalNumMacros);
4472 writeBaseIDOrNone(M->BasePreprocessedEntityID,
4473 M->NumPreprocessedEntities);
4474 writeBaseIDOrNone(M->BaseSubmoduleID, M->LocalNumSubmodules);
4475 writeBaseIDOrNone(M->BaseSelectorID, M->LocalNumSelectors);
4476 writeBaseIDOrNone(M->BaseDeclID, M->LocalNumDecls);
4477 writeBaseIDOrNone(M->BaseTypeIndex, M->LocalNumTypes);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004478 }
4479 }
Mehdi Amini57a41912015-09-10 01:46:39 +00004480 RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004481 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4482 Buffer.data(), Buffer.size());
4483 }
Richard Smithb9eab6d2014-03-20 19:44:17 +00004484
Richard Smithb9eab6d2014-03-20 19:44:17 +00004485 RecordData DeclUpdatesOffsetsRecord;
4486
Richard Smith59442b42014-03-20 20:07:19 +00004487 // Keep writing types, declarations, and declaration update records
4488 // until we've emitted all of them.
Richard Smith01b2cb42014-07-26 06:37:51 +00004489 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
4490 WriteTypeAbbrevs();
4491 WriteDeclAbbrevs();
Richard Smith59442b42014-03-20 20:07:19 +00004492 do {
4493 WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
4494 while (!DeclTypesToEmit.empty()) {
4495 DeclOrType DOT = DeclTypesToEmit.front();
4496 DeclTypesToEmit.pop();
4497 if (DOT.isType())
4498 WriteType(DOT.getType());
4499 else
4500 WriteDecl(Context, DOT.getDecl());
4501 }
4502 } while (!DeclUpdates.empty());
Richard Smithb9eab6d2014-03-20 19:44:17 +00004503 Stream.ExitBlock();
4504
Richard Smithb9eab6d2014-03-20 19:44:17 +00004505 DoneWritingDeclsAndTypes = true;
4506
4507 // These things can only be done once we've written out decls and types.
4508 WriteTypeDeclOffsets();
Richard Smith5652c0f2014-03-21 01:48:23 +00004509 if (!DeclUpdatesOffsetsRecord.empty())
4510 Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
Richard Smithb9eab6d2014-03-20 19:44:17 +00004511 WriteFileDeclIDsMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00004512 WriteSourceManagerBlock(Context.getSourceManager(), PP);
Richard Smithb9eab6d2014-03-20 19:44:17 +00004513 WriteComments();
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004514 WritePreprocessor(PP, isModule);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004515 WriteHeaderSearch(PP.getHeaderSearchInfo());
Sebastian Redla19a67f2010-08-03 21:58:15 +00004516 WriteSelectors(SemaRef);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00004517 WriteReferencedSelectorsPool(SemaRef);
Richard Smith9c254182015-07-19 21:41:12 +00004518 WriteLateParsedTemplates(SemaRef);
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004519 WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
Peter Collingbourne5df20e02011-02-15 19:46:30 +00004520 WriteFPPragmaOptions(SemaRef.getFPOptions());
4521 WriteOpenCLExtensions(SemaRef);
Argyrios Kyrtzidis0f06b982013-03-27 17:17:23 +00004522 WritePragmaDiagnosticMappings(Context.getDiagnostics(), isModule);
Douglas Gregor652d82a2009-04-18 05:55:16 +00004523
Douglas Gregora89c5ac2011-12-06 01:10:29 +00004524 // If we're emitting a module, write out the submodule information.
4525 if (WritingModule)
4526 WriteSubmodules(WritingModule);
Richard Smithdc1f0422016-07-20 19:10:16 +00004527 else if (!getLangOpts().CurrentModule.empty()) {
4528 // If we're building a PCH in the implementation of a module, we may need
4529 // the description of the current module.
4530 //
4531 // FIXME: We may need other modules that we did not load from an AST file,
4532 // such as if a module declares a 'conflicts' on a different module.
4533 Module *M = PP.getHeaderSearchInfo().getModuleMap().findModule(
4534 getLangOpts().CurrentModule);
4535 if (M && !M->IsFromModuleFile)
4536 WriteSubmodules(M);
4537 }
Douglas Gregora89c5ac2011-12-06 01:10:29 +00004538
Douglas Gregor5204bde2011-08-02 16:26:37 +00004539 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
4540
Douglas Gregord4df8652009-04-22 22:02:47 +00004541 // Write the record containing external, unnamed definitions.
Ben Langmuir332aafe2014-01-31 01:06:56 +00004542 if (!EagerlyDeserializedDecls.empty())
4543 Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
Douglas Gregord4df8652009-04-22 22:02:47 +00004544
4545 // Write the record containing tentative definitions.
4546 if (!TentativeDefinitions.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004547 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregoracfc76c2009-04-22 22:18:58 +00004548
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00004549 // Write the record containing unused file scoped decls.
4550 if (!UnusedFileScopedDecls.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004551 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00004552
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004553 // Write the record containing weak undeclared identifiers.
4554 if (!WeakUndeclaredIdentifiers.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004555 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004556 WeakUndeclaredIdentifiers);
4557
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004558 // Write the record containing ext_vector type names.
4559 if (!ExtVectorDecls.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004560 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
Mike Stump11289f42009-09-09 15:08:12 +00004561
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004562 // Write the record containing VTable uses information.
4563 if (!VTableUses.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004564 Stream.EmitRecord(VTABLE_USES, VTableUses);
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004565
Nico Weber72889432014-09-06 01:25:55 +00004566 // Write the record containing potentially unused local typedefs.
4567 if (!UnusedLocalTypedefNameCandidates.empty())
4568 Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
4569 UnusedLocalTypedefNameCandidates);
4570
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004571 // Write the record containing pending implicit instantiations.
Chandler Carruth54080172010-08-25 08:44:16 +00004572 if (!PendingInstantiations.empty())
4573 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004574
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004575 // Write the record containing declaration references of Sema.
4576 if (!SemaDeclRefs.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004577 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004578
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004579 // Write the record containing CUDA-specific declaration references.
4580 if (!CUDASpecialDeclRefs.empty())
4581 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
Alexis Hunt27a761d2011-05-04 23:29:54 +00004582
4583 // Write the delegating constructors.
4584 if (!DelegatingCtorDecls.empty())
4585 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004586
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004587 // Write the known namespaces.
4588 if (!KnownNamespaces.empty())
4589 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
Nick Lewycky8334af82013-01-26 00:35:08 +00004590
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004591 // Write the undefined internal functions and variables, and inline functions.
4592 if (!UndefinedButUsed.empty())
4593 Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00004594
4595 if (!DeleteExprsToAnalyze.empty())
4596 Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
4597
Douglas Gregor851443c2011-08-12 01:39:19 +00004598 // Write the visible updates to DeclContexts.
Richard Smithcd45dbc2014-04-19 03:48:30 +00004599 for (auto *DC : UpdatedDeclContexts)
4600 WriteDeclContextVisibleUpdate(DC);
Douglas Gregor851443c2011-08-12 01:39:19 +00004601
Douglas Gregor959bb062011-12-03 01:15:29 +00004602 if (!WritingModule) {
4603 // Write the submodules that were imported, if any.
Aaron Ballman4f45b712014-03-21 15:22:56 +00004604 struct ModuleInfo {
4605 uint64_t ID;
4606 Module *M;
4607 ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
4608 };
Richard Smith56be7542014-03-21 00:33:59 +00004609 llvm::SmallVector<ModuleInfo, 64> Imports;
Aaron Ballmanbbc31212014-03-14 20:59:21 +00004610 for (const auto *I : Context.local_imports()) {
Douglas Gregor959bb062011-12-03 01:15:29 +00004611 assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
Aaron Ballman4f45b712014-03-21 15:22:56 +00004612 Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
4613 I->getImportedModule()));
Douglas Gregor959bb062011-12-03 01:15:29 +00004614 }
Richard Smith56be7542014-03-21 00:33:59 +00004615
4616 if (!Imports.empty()) {
4617 auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
4618 return A.ID < B.ID;
4619 };
Ben Langmuir5f95c8f2014-09-08 20:36:26 +00004620 auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
4621 return A.ID == B.ID;
4622 };
Richard Smith56be7542014-03-21 00:33:59 +00004623
4624 // Sort and deduplicate module IDs.
4625 std::sort(Imports.begin(), Imports.end(), Cmp);
Ben Langmuir5f95c8f2014-09-08 20:36:26 +00004626 Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
Richard Smith56be7542014-03-21 00:33:59 +00004627 Imports.end());
4628
4629 RecordData ImportedModules;
4630 for (const auto &Import : Imports) {
4631 ImportedModules.push_back(Import.ID);
4632 // FIXME: If the module has macros imported then later has declarations
4633 // imported, this location won't be the right one as a location for the
4634 // declaration imports.
Richard Smith10434f32015-05-02 02:08:26 +00004635 AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
Richard Smith56be7542014-03-21 00:33:59 +00004636 }
4637
Douglas Gregor959bb062011-12-03 01:15:29 +00004638 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
4639 }
Douglas Gregor0a839132011-12-03 00:59:55 +00004640 }
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004641
Douglas Gregor404cdde2012-01-27 01:47:08 +00004642 WriteObjCCategories();
Nico Weber779355f2016-03-02 23:22:00 +00004643 if(!WritingModule) {
Dario Domizioli13a0a382014-05-23 12:13:25 +00004644 WriteOptimizePragmaOptions(SemaRef);
Nico Weber779355f2016-03-02 23:22:00 +00004645 WriteMSStructPragmaOptions(SemaRef);
Nico Weber42932312016-03-03 00:17:35 +00004646 WriteMSPointersToMembersPragmaOptions(SemaRef);
Nico Weber779355f2016-03-02 23:22:00 +00004647 }
Richard Smithe40f2ba2013-08-07 21:41:30 +00004648
Douglas Gregor08f01292009-04-17 22:13:46 +00004649 // Some simple statistics
Mehdi Amini57a41912015-09-10 01:46:39 +00004650 RecordData::value_type Record[] = {
4651 NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts};
Sebastian Redl539c5062010-08-18 23:57:32 +00004652 Stream.EmitRecord(STATISTICS, Record);
Douglas Gregor8f45df52009-04-16 22:23:12 +00004653 Stream.ExitBlock();
Adrian Prantladbd2b12015-09-22 23:26:31 +00004654
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004655 // Write the module file extension blocks.
4656 for (const auto &ExtWriter : ModuleFileExtensionWriters)
Douglas Gregor8f64ca12015-12-08 22:43:32 +00004657 WriteModuleFileExtension(SemaRef, *ExtWriter);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004658
Adrian Prantladbd2b12015-09-22 23:26:31 +00004659 return Signature;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004660}
4661
Richard Smithb9eab6d2014-03-20 19:44:17 +00004662void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00004663 if (DeclUpdates.empty())
4664 return;
4665
Richard Smith59442b42014-03-20 20:07:19 +00004666 DeclUpdateMap LocalUpdates;
4667 LocalUpdates.swap(DeclUpdates);
4668
Richard Smith6ef42932014-03-20 21:02:00 +00004669 for (auto &DeclUpdate : LocalUpdates) {
4670 const Decl *D = DeclUpdate.first;
Argyrios Kyrtzidis3ba70b82010-10-24 17:26:46 +00004671
Richard Smithd28ac5b2014-03-22 23:33:22 +00004672 bool HasUpdatedBody = false;
Richard Smith69c82bf2016-04-01 22:52:03 +00004673 RecordData RecordData;
4674 ASTRecordWriter Record(*this, RecordData);
Richard Smith6ef42932014-03-20 21:02:00 +00004675 for (auto &Update : DeclUpdate.second) {
4676 DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
4677
Richard Smith69c82bf2016-04-01 22:52:03 +00004678 // An updated body is emitted last, so that the reader doesn't need
4679 // to skip over the lazy body to reach statements for other records.
4680 if (Kind == UPD_CXX_ADDED_FUNCTION_DEFINITION)
4681 HasUpdatedBody = true;
4682 else
4683 Record.push_back(Kind);
4684
Richard Smith6ef42932014-03-20 21:02:00 +00004685 switch (Kind) {
4686 case UPD_CXX_ADDED_IMPLICIT_MEMBER:
4687 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4688 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
Richard Smithcd45dbc2014-04-19 03:48:30 +00004689 assert(Update.getDecl() && "no decl to add?");
Richard Smith6ef42932014-03-20 21:02:00 +00004690 Record.push_back(GetDeclRef(Update.getDecl()));
4691 break;
4692
Richard Smith4d235792014-08-07 18:53:08 +00004693 case UPD_CXX_ADDED_FUNCTION_DEFINITION:
Richard Smithd28ac5b2014-03-22 23:33:22 +00004694 break;
4695
Richard Smith4d235792014-08-07 18:53:08 +00004696 case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
Richard Smith69c82bf2016-04-01 22:52:03 +00004697 Record.AddSourceLocation(Update.getLoc());
Richard Smith4d235792014-08-07 18:53:08 +00004698 break;
4699
John McCall32791cc2016-01-06 22:34:54 +00004700 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT:
Richard Smith290d8012016-04-06 17:06:00 +00004701 Record.AddStmt(const_cast<Expr *>(
4702 cast<ParmVarDecl>(Update.getDecl())->getDefaultArg()));
John McCall32791cc2016-01-06 22:34:54 +00004703 break;
4704
Richard Smith4b054b22016-08-24 21:25:37 +00004705 case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER:
4706 Record.AddStmt(
4707 cast<FieldDecl>(Update.getDecl())->getInClassInitializer());
4708 break;
4709
Richard Smithcd45dbc2014-04-19 03:48:30 +00004710 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
4711 auto *RD = cast<CXXRecordDecl>(D);
Chandler Carruth8a3d24d2015-03-26 04:27:10 +00004712 UpdatedDeclContexts.insert(RD->getPrimaryContext());
Richard Smith69c82bf2016-04-01 22:52:03 +00004713 Record.AddCXXDefinitionData(RD);
Richard Smith72e50fe2016-04-14 00:50:18 +00004714 Record.AddOffset(WriteDeclContextLexicalBlock(
Richard Smithcd45dbc2014-04-19 03:48:30 +00004715 *Context, const_cast<CXXRecordDecl *>(RD)));
4716
4717 // This state is sometimes updated by template instantiation, when we
4718 // switch from the specialization referring to the template declaration
4719 // to it referring to the template definition.
4720 if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
4721 Record.push_back(MSInfo->getTemplateSpecializationKind());
Richard Smith69c82bf2016-04-01 22:52:03 +00004722 Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
Richard Smithcd45dbc2014-04-19 03:48:30 +00004723 } else {
4724 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
4725 Record.push_back(Spec->getTemplateSpecializationKind());
Richard Smith69c82bf2016-04-01 22:52:03 +00004726 Record.AddSourceLocation(Spec->getPointOfInstantiation());
Richard Smithdf352052014-05-22 20:59:29 +00004727
4728 // The instantiation might have been resolved to a partial
4729 // specialization. If so, record which one.
4730 auto From = Spec->getInstantiatedFrom();
4731 if (auto PartialSpec =
4732 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
4733 Record.push_back(true);
Richard Smith69c82bf2016-04-01 22:52:03 +00004734 Record.AddDeclRef(PartialSpec);
4735 Record.AddTemplateArgumentList(
4736 &Spec->getTemplateInstantiationArgs());
Richard Smithdf352052014-05-22 20:59:29 +00004737 } else {
4738 Record.push_back(false);
4739 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00004740 }
4741 Record.push_back(RD->getTagKind());
Richard Smith69c82bf2016-04-01 22:52:03 +00004742 Record.AddSourceLocation(RD->getLocation());
4743 Record.AddSourceLocation(RD->getLocStart());
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00004744 Record.AddSourceRange(RD->getBraceRange());
Richard Smithcd45dbc2014-04-19 03:48:30 +00004745
4746 // Instantiation may change attributes; write them all out afresh.
4747 Record.push_back(D->hasAttrs());
Richard Smith69c82bf2016-04-01 22:52:03 +00004748 if (D->hasAttrs())
4749 Record.AddAttributes(D->getAttrs());
Richard Smithcd45dbc2014-04-19 03:48:30 +00004750
4751 // FIXME: Ensure we don't get here for explicit instantiations.
4752 break;
4753 }
4754
Richard Smithf8134002015-03-10 01:41:22 +00004755 case UPD_CXX_RESOLVED_DTOR_DELETE:
Richard Smith69c82bf2016-04-01 22:52:03 +00004756 Record.AddDeclRef(Update.getDecl());
Richard Smithf8134002015-03-10 01:41:22 +00004757 break;
4758
Richard Smith564417a2014-03-20 21:47:22 +00004759 case UPD_CXX_RESOLVED_EXCEPTION_SPEC:
4760 addExceptionSpec(
Richard Smith564417a2014-03-20 21:47:22 +00004761 cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>(),
4762 Record);
4763 break;
4764
Richard Smith6ef42932014-03-20 21:02:00 +00004765 case UPD_CXX_DEDUCED_RETURN_TYPE:
4766 Record.push_back(GetOrCreateTypeID(Update.getType()));
4767 break;
4768
4769 case UPD_DECL_MARKED_USED:
4770 break;
Richard Smith5652c0f2014-03-21 01:48:23 +00004771
4772 case UPD_MANGLING_NUMBER:
4773 case UPD_STATIC_LOCAL_NUMBER:
4774 Record.push_back(Update.getNumber());
4775 break;
Richard Smith65ebb4a2015-03-26 04:09:53 +00004776
Alexey Bataev97720002014-11-11 04:05:39 +00004777 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
Richard Smith69c82bf2016-04-01 22:52:03 +00004778 Record.AddSourceRange(
4779 D->getAttr<OMPThreadPrivateDeclAttr>()->getRange());
Alexey Bataev97720002014-11-11 04:05:39 +00004780 break;
Richard Smith65ebb4a2015-03-26 04:09:53 +00004781
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00004782 case UPD_DECL_MARKED_OPENMP_DECLARETARGET:
4783 Record.AddSourceRange(
4784 D->getAttr<OMPDeclareTargetDeclAttr>()->getRange());
4785 break;
4786
Richard Smith65ebb4a2015-03-26 04:09:53 +00004787 case UPD_DECL_EXPORTED:
Richard Smith4caa4492015-05-15 02:34:32 +00004788 Record.push_back(getSubmoduleID(Update.getModule()));
Richard Smith65ebb4a2015-03-26 04:09:53 +00004789 break;
Alex Denisovfde64952015-06-26 05:28:36 +00004790
4791 case UPD_ADDED_ATTR_TO_RECORD:
Richard Smith69c82bf2016-04-01 22:52:03 +00004792 Record.AddAttributes(llvm::makeArrayRef(Update.getAttr()));
Alex Denisovfde64952015-06-26 05:28:36 +00004793 break;
Richard Smith6ef42932014-03-20 21:02:00 +00004794 }
4795 }
4796
Richard Smithd28ac5b2014-03-22 23:33:22 +00004797 if (HasUpdatedBody) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004798 const auto *Def = cast<FunctionDecl>(D);
Richard Smith4d235792014-08-07 18:53:08 +00004799 Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
Richard Smithd28ac5b2014-03-22 23:33:22 +00004800 Record.push_back(Def->isInlined());
Richard Smith69c82bf2016-04-01 22:52:03 +00004801 Record.AddSourceLocation(Def->getInnerLocStart());
Richard Smith290d8012016-04-06 17:06:00 +00004802 Record.AddFunctionDefinition(Def);
Richard Smithd28ac5b2014-03-22 23:33:22 +00004803 }
4804
Richard Smithcd45dbc2014-04-19 03:48:30 +00004805 OffsetsRecord.push_back(GetDeclRef(D));
Richard Smith69c82bf2016-04-01 22:52:03 +00004806 OffsetsRecord.push_back(Record.Emit(DECL_UPDATES));
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00004807 }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00004808}
4809
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004810void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
Richard Smithb22a1d12016-03-27 20:13:24 +00004811 uint32_t Raw = Loc.getRawEncoding();
4812 Record.push_back((Raw << 1) | (Raw >> 31));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004813}
4814
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004815void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
Chris Lattnerca025db2010-05-07 21:43:38 +00004816 AddSourceLocation(Range.getBegin(), Record);
4817 AddSourceLocation(Range.getEnd(), Record);
4818}
4819
Richard Smithf144b542016-04-08 21:54:32 +00004820void ASTRecordWriter::AddAPInt(const llvm::APInt &Value) {
4821 Record->push_back(Value.getBitWidth());
Benjamin Kramer25f9ea62010-09-06 23:43:28 +00004822 const uint64_t *Words = Value.getRawData();
Richard Smithf144b542016-04-08 21:54:32 +00004823 Record->append(Words, Words + Value.getNumWords());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004824}
4825
Richard Smithf144b542016-04-08 21:54:32 +00004826void ASTRecordWriter::AddAPSInt(const llvm::APSInt &Value) {
4827 Record->push_back(Value.isUnsigned());
4828 AddAPInt(Value);
Douglas Gregor1daeb692009-04-13 18:14:40 +00004829}
4830
Richard Smithf144b542016-04-08 21:54:32 +00004831void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) {
4832 AddAPInt(Value.bitcastToAPInt());
Douglas Gregore0a3a512009-04-14 21:55:33 +00004833}
4834
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004835void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
Douglas Gregor4621c6a2009-04-22 18:49:13 +00004836 Record.push_back(getIdentifierRef(II));
4837}
4838
Sebastian Redl539c5062010-08-18 23:57:32 +00004839IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
Craig Toppera13603a2014-05-22 05:54:18 +00004840 if (!II)
Douglas Gregor4621c6a2009-04-22 18:49:13 +00004841 return 0;
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00004842
Sebastian Redl539c5062010-08-18 23:57:32 +00004843 IdentID &ID = IdentifierIDs[II];
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00004844 if (ID == 0)
Sebastian Redlff4a2952010-07-23 23:49:55 +00004845 ID = NextIdentID++;
Douglas Gregor4621c6a2009-04-22 18:49:13 +00004846 return ID;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004847}
4848
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004849MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004850 // Don't emit builtin macros like __LINE__ to the AST file unless they
4851 // have been redefined by the header (in which case they are not
4852 // isBuiltinMacro).
Craig Toppera13603a2014-05-22 05:54:18 +00004853 if (!MI || MI->isBuiltinMacro())
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004854 return 0;
4855
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004856 MacroID &ID = MacroIDs[MI];
4857 if (ID == 0) {
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004858 ID = NextMacroID++;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004859 MacroInfoToEmitData Info = { Name, MI, ID };
4860 MacroInfosToEmit.push_back(Info);
4861 }
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004862 return ID;
4863}
4864
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004865MacroID ASTWriter::getMacroID(MacroInfo *MI) {
Craig Toppera13603a2014-05-22 05:54:18 +00004866 if (!MI || MI->isBuiltinMacro())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004867 return 0;
4868
4869 assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
4870 return MacroIDs[MI];
4871}
4872
4873uint64_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
Richard Smithd7329392015-04-21 21:46:32 +00004874 return IdentMacroDirectivesOffsetMap.lookup(Name);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004875}
4876
Richard Smithe64e7452016-04-18 21:54:58 +00004877void ASTRecordWriter::AddSelectorRef(const Selector SelRef) {
4878 Record->push_back(Writer->getSelectorRef(SelRef));
Sebastian Redl834bb972010-08-04 17:20:04 +00004879}
4880
Sebastian Redl539c5062010-08-18 23:57:32 +00004881SelectorID ASTWriter::getSelectorRef(Selector Sel) {
Craig Toppera13603a2014-05-22 05:54:18 +00004882 if (Sel.getAsOpaquePtr() == nullptr) {
Sebastian Redl834bb972010-08-04 17:20:04 +00004883 return 0;
Steve Naroff2ddea052009-04-23 10:39:46 +00004884 }
4885
Douglas Gregor8d7edce2013-02-08 21:30:59 +00004886 SelectorID SID = SelectorIDs[Sel];
Sebastian Redld95a56e2010-08-04 18:21:41 +00004887 if (SID == 0 && Chain) {
4888 // This might trigger a ReadSelector callback, which will set the ID for
4889 // this selector.
4890 Chain->LoadSelector(Sel);
Douglas Gregor8d7edce2013-02-08 21:30:59 +00004891 SID = SelectorIDs[Sel];
Sebastian Redld95a56e2010-08-04 18:21:41 +00004892 }
Steve Naroff2ddea052009-04-23 10:39:46 +00004893 if (SID == 0) {
Sebastian Redld95a56e2010-08-04 18:21:41 +00004894 SID = NextSelectorID++;
Douglas Gregor8d7edce2013-02-08 21:30:59 +00004895 SelectorIDs[Sel] = SID;
Steve Naroff2ddea052009-04-23 10:39:46 +00004896 }
Sebastian Redl834bb972010-08-04 17:20:04 +00004897 return SID;
Steve Naroff2ddea052009-04-23 10:39:46 +00004898}
4899
Richard Smithe64e7452016-04-18 21:54:58 +00004900void ASTRecordWriter::AddCXXTemporary(const CXXTemporary *Temp) {
4901 AddDeclRef(Temp->getDestructor());
Chris Lattnercba86142010-05-10 00:25:06 +00004902}
4903
Richard Smith290d8012016-04-06 17:06:00 +00004904void ASTRecordWriter::AddTemplateArgumentLocInfo(
4905 TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg) {
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004906 switch (Kind) {
John McCall0ad16662009-10-29 08:12:44 +00004907 case TemplateArgument::Expression:
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004908 AddStmt(Arg.getAsExpr());
John McCall0ad16662009-10-29 08:12:44 +00004909 break;
4910 case TemplateArgument::Type:
Richard Smith290d8012016-04-06 17:06:00 +00004911 AddTypeSourceInfo(Arg.getAsTypeSourceInfo());
John McCall0ad16662009-10-29 08:12:44 +00004912 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004913 case TemplateArgument::Template:
Richard Smith290d8012016-04-06 17:06:00 +00004914 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
4915 AddSourceLocation(Arg.getTemplateNameLoc());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004916 break;
4917 case TemplateArgument::TemplateExpansion:
Richard Smith290d8012016-04-06 17:06:00 +00004918 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
4919 AddSourceLocation(Arg.getTemplateNameLoc());
4920 AddSourceLocation(Arg.getTemplateEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004921 break;
John McCall0ad16662009-10-29 08:12:44 +00004922 case TemplateArgument::Null:
4923 case TemplateArgument::Integral:
4924 case TemplateArgument::Declaration:
Eli Friedmanb826a002012-09-26 02:36:12 +00004925 case TemplateArgument::NullPtr:
John McCall0ad16662009-10-29 08:12:44 +00004926 case TemplateArgument::Pack:
Eli Friedmanb826a002012-09-26 02:36:12 +00004927 // FIXME: Is this right?
John McCall0ad16662009-10-29 08:12:44 +00004928 break;
4929 }
4930}
4931
Richard Smith290d8012016-04-06 17:06:00 +00004932void ASTRecordWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg) {
4933 AddTemplateArgument(Arg.getArgument());
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00004934
4935 if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
4936 bool InfoHasSameExpr
4937 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
Richard Smith290d8012016-04-06 17:06:00 +00004938 Record->push_back(InfoHasSameExpr);
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00004939 if (InfoHasSameExpr)
4940 return; // Avoid storing the same expr twice.
4941 }
Richard Smith290d8012016-04-06 17:06:00 +00004942 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo());
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004943}
4944
Richard Smith290d8012016-04-06 17:06:00 +00004945void ASTRecordWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo) {
Craig Toppera13603a2014-05-22 05:54:18 +00004946 if (!TInfo) {
Richard Smith290d8012016-04-06 17:06:00 +00004947 AddTypeRef(QualType());
John McCall8f115c62009-10-16 21:56:05 +00004948 return;
4949 }
4950
Richard Smith290d8012016-04-06 17:06:00 +00004951 AddTypeLoc(TInfo->getTypeLoc());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004952}
4953
Richard Smith290d8012016-04-06 17:06:00 +00004954void ASTRecordWriter::AddTypeLoc(TypeLoc TL) {
4955 AddTypeRef(TL.getType());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004956
Richard Smith290d8012016-04-06 17:06:00 +00004957 TypeLocWriter TLW(*this);
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004958 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00004959 TLW.Visit(TL);
John McCall8f115c62009-10-16 21:56:05 +00004960}
4961
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004962void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
Argyrios Kyrtzidis9ab44ea2010-08-20 16:04:14 +00004963 Record.push_back(GetOrCreateTypeID(T));
4964}
4965
Richard Smith2095ffe2015-03-16 20:11:03 +00004966TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
Richard Smith1fa5d642013-05-11 05:45:24 +00004967 assert(Context);
Richard Smith2095ffe2015-03-16 20:11:03 +00004968 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
4969 if (T.isNull())
4970 return TypeIdx();
4971 assert(!T.getLocalFastQualifiers());
4972
4973 TypeIdx &Idx = TypeIdxs[T];
4974 if (Idx.getIndex() == 0) {
4975 if (DoneWritingDeclsAndTypes) {
4976 assert(0 && "New type seen after serializing all the types to emit!");
4977 return TypeIdx();
4978 }
4979
4980 // We haven't seen this type before. Assign it a new ID and put it
4981 // into the queue of types to emit.
4982 Idx = TypeIdx(NextTypeID++);
4983 DeclTypesToEmit.push(T);
4984 }
4985 return Idx;
4986 });
Argyrios Kyrtzidis082e4612010-08-20 16:04:20 +00004987}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004988
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00004989TypeID ASTWriter::getTypeID(QualType T) const {
Richard Smith1fa5d642013-05-11 05:45:24 +00004990 assert(Context);
Richard Smith2095ffe2015-03-16 20:11:03 +00004991 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
4992 if (T.isNull())
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004993 return TypeIdx();
Richard Smith2095ffe2015-03-16 20:11:03 +00004994 assert(!T.getLocalFastQualifiers());
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004995
Richard Smith2095ffe2015-03-16 20:11:03 +00004996 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
4997 assert(I != TypeIdxs.end() && "Type not emitted!");
4998 return I->second;
4999 });
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005000}
5001
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005002void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005003 Record.push_back(GetDeclRef(D));
5004}
5005
Sebastian Redl539c5062010-08-18 23:57:32 +00005006DeclID ASTWriter::GetDeclRef(const Decl *D) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005007 assert(WritingAST && "Cannot request a declaration ID before AST writing");
Craig Toppera13603a2014-05-22 05:54:18 +00005008
5009 if (!D) {
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005010 return 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005011 }
Douglas Gregorb3163e52012-01-05 22:33:30 +00005012
5013 // If D comes from an AST file, its declaration ID is already known and
5014 // fixed.
5015 if (D->isFromASTFile())
5016 return D->getGlobalID();
5017
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005018 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
Sebastian Redl539c5062010-08-18 23:57:32 +00005019 DeclID &ID = DeclIDs[D];
Mike Stump11289f42009-09-09 15:08:12 +00005020 if (ID == 0) {
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005021 if (DoneWritingDeclsAndTypes) {
5022 assert(0 && "New decl seen after serializing all the decls to emit!");
5023 return 0;
5024 }
5025
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005026 // We haven't seen this declaration before. Give it a new ID and
5027 // enqueue it in the list of declarations to emit.
Sebastian Redlff4a2952010-07-23 23:49:55 +00005028 ID = NextDeclID++;
Douglas Gregor12bfa382009-10-17 00:13:19 +00005029 DeclTypesToEmit.push(const_cast<Decl *>(D));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005030 }
5031
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005032 return ID;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005033}
5034
Sebastian Redl539c5062010-08-18 23:57:32 +00005035DeclID ASTWriter::getDeclID(const Decl *D) {
Craig Toppera13603a2014-05-22 05:54:18 +00005036 if (!D)
Douglas Gregore84a9da2009-04-20 20:36:09 +00005037 return 0;
5038
Douglas Gregorb3163e52012-01-05 22:33:30 +00005039 // If D comes from an AST file, its declaration ID is already known and
5040 // fixed.
5041 if (D->isFromASTFile())
5042 return D->getGlobalID();
5043
Douglas Gregore84a9da2009-04-20 20:36:09 +00005044 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
5045 return DeclIDs[D];
5046}
5047
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005048void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005049 assert(ID);
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005050 assert(D);
5051
5052 SourceLocation Loc = D->getLocation();
5053 if (Loc.isInvalid())
5054 return;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005055
5056 // We only keep track of the file-level declarations of each file.
5057 if (!D->getLexicalDeclContext()->isFileContext())
5058 return;
Argyrios Kyrtzidise1bc99e2012-02-24 19:45:46 +00005059 // FIXME: ParmVarDecls that are part of a function type of a parameter of
5060 // a function/objc method, should not have TU as lexical context.
Argyrios Kyrtzidisffe055a82012-02-24 01:12:38 +00005061 if (isa<ParmVarDecl>(D))
5062 return;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005063
5064 SourceManager &SM = Context->getSourceManager();
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005065 SourceLocation FileLoc = SM.getFileLoc(Loc);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005066 assert(SM.isLocalSourceLocation(FileLoc));
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005067 FileID FID;
5068 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00005069 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005070 if (FID.isInvalid())
5071 return;
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00005072 assert(SM.getSLocEntry(FID).isFile());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005073
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00005074 DeclIDInFileInfo *&Info = FileDeclIDs[FID];
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005075 if (!Info)
5076 Info = new DeclIDInFileInfo();
5077
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005078 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005079 LocDeclIDsTy &Decls = Info->DeclIDs;
5080
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005081 if (Decls.empty() || Decls.back().first <= Offset) {
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005082 Decls.push_back(LocDecl);
5083 return;
5084 }
5085
Benjamin Kramer45025c02013-08-24 13:22:59 +00005086 LocDeclIDsTy::iterator I =
5087 std::upper_bound(Decls.begin(), Decls.end(), LocDecl, llvm::less_first());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005088
5089 Decls.insert(I, LocDecl);
5090}
5091
Richard Smithe64e7452016-04-18 21:54:58 +00005092void ASTRecordWriter::AddDeclarationName(DeclarationName Name) {
Chris Lattner258172e2009-04-27 07:35:58 +00005093 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Richard Smithe64e7452016-04-18 21:54:58 +00005094 Record->push_back(Name.getNameKind());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005095 switch (Name.getNameKind()) {
5096 case DeclarationName::Identifier:
Richard Smithe64e7452016-04-18 21:54:58 +00005097 AddIdentifierRef(Name.getAsIdentifierInfo());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005098 break;
5099
5100 case DeclarationName::ObjCZeroArgSelector:
5101 case DeclarationName::ObjCOneArgSelector:
5102 case DeclarationName::ObjCMultiArgSelector:
Richard Smithe64e7452016-04-18 21:54:58 +00005103 AddSelectorRef(Name.getObjCSelector());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005104 break;
5105
5106 case DeclarationName::CXXConstructorName:
5107 case DeclarationName::CXXDestructorName:
5108 case DeclarationName::CXXConversionFunctionName:
Richard Smithe64e7452016-04-18 21:54:58 +00005109 AddTypeRef(Name.getCXXNameType());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005110 break;
5111
5112 case DeclarationName::CXXOperatorName:
Richard Smithe64e7452016-04-18 21:54:58 +00005113 Record->push_back(Name.getCXXOverloadedOperator());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005114 break;
5115
Alexis Hunt3d221f22009-11-29 07:34:05 +00005116 case DeclarationName::CXXLiteralOperatorName:
Richard Smithe64e7452016-04-18 21:54:58 +00005117 AddIdentifierRef(Name.getCXXLiteralIdentifier());
Alexis Hunt3d221f22009-11-29 07:34:05 +00005118 break;
5119
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005120 case DeclarationName::CXXUsingDirective:
5121 // No extra data to emit
5122 break;
5123 }
5124}
Chris Lattnerca025db2010-05-07 21:43:38 +00005125
Richard Smithd08aeb62014-08-28 01:33:39 +00005126unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
5127 assert(needsAnonymousDeclarationNumber(D) &&
5128 "expected an anonymous declaration");
5129
5130 // Number the anonymous declarations within this context, if we've not
5131 // already done so.
5132 auto It = AnonymousDeclarationNumbers.find(D);
5133 if (It == AnonymousDeclarationNumbers.end()) {
Richard Smith2b560572015-02-07 03:11:11 +00005134 auto *DC = D->getLexicalDeclContext();
5135 numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
5136 AnonymousDeclarationNumbers[ND] = Number;
5137 });
Richard Smithd08aeb62014-08-28 01:33:39 +00005138
5139 It = AnonymousDeclarationNumbers.find(D);
5140 assert(It != AnonymousDeclarationNumbers.end() &&
5141 "declaration not found within its lexical context");
5142 }
5143
5144 return It->second;
5145}
5146
Richard Smith290d8012016-04-06 17:06:00 +00005147void ASTRecordWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
5148 DeclarationName Name) {
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005149 switch (Name.getNameKind()) {
5150 case DeclarationName::CXXConstructorName:
5151 case DeclarationName::CXXDestructorName:
5152 case DeclarationName::CXXConversionFunctionName:
Richard Smith290d8012016-04-06 17:06:00 +00005153 AddTypeSourceInfo(DNLoc.NamedType.TInfo);
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005154 break;
5155
5156 case DeclarationName::CXXOperatorName:
Richard Smith290d8012016-04-06 17:06:00 +00005157 AddSourceLocation(SourceLocation::getFromRawEncoding(
5158 DNLoc.CXXOperatorName.BeginOpNameLoc));
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005159 AddSourceLocation(
Richard Smith290d8012016-04-06 17:06:00 +00005160 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc));
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005161 break;
5162
5163 case DeclarationName::CXXLiteralOperatorName:
Richard Smith290d8012016-04-06 17:06:00 +00005164 AddSourceLocation(SourceLocation::getFromRawEncoding(
5165 DNLoc.CXXLiteralOperatorName.OpNameLoc));
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005166 break;
5167
5168 case DeclarationName::Identifier:
5169 case DeclarationName::ObjCZeroArgSelector:
5170 case DeclarationName::ObjCOneArgSelector:
5171 case DeclarationName::ObjCMultiArgSelector:
5172 case DeclarationName::CXXUsingDirective:
5173 break;
5174 }
5175}
5176
Richard Smith290d8012016-04-06 17:06:00 +00005177void ASTRecordWriter::AddDeclarationNameInfo(
5178 const DeclarationNameInfo &NameInfo) {
5179 AddDeclarationName(NameInfo.getName());
5180 AddSourceLocation(NameInfo.getLoc());
5181 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName());
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005182}
5183
Richard Smith290d8012016-04-06 17:06:00 +00005184void ASTRecordWriter::AddQualifierInfo(const QualifierInfo &Info) {
5185 AddNestedNameSpecifierLoc(Info.QualifierLoc);
5186 Record->push_back(Info.NumTemplParamLists);
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005187 for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i)
Richard Smith290d8012016-04-06 17:06:00 +00005188 AddTemplateParameterList(Info.TemplParamLists[i]);
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005189}
5190
Richard Smithe64e7452016-04-18 21:54:58 +00005191void ASTRecordWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS) {
Chris Lattnerca025db2010-05-07 21:43:38 +00005192 // Nested name specifiers usually aren't too long. I think that 8 would
Chris Lattner57540c52011-04-15 05:22:18 +00005193 // typically accommodate the vast majority.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005194 SmallVector<NestedNameSpecifier *, 8> NestedNames;
Chris Lattnerca025db2010-05-07 21:43:38 +00005195
5196 // Push each of the NNS's onto a stack for serialization in reverse order.
5197 while (NNS) {
5198 NestedNames.push_back(NNS);
5199 NNS = NNS->getPrefix();
5200 }
5201
Richard Smithe64e7452016-04-18 21:54:58 +00005202 Record->push_back(NestedNames.size());
Chris Lattnerca025db2010-05-07 21:43:38 +00005203 while(!NestedNames.empty()) {
5204 NNS = NestedNames.pop_back_val();
5205 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
Richard Smithe64e7452016-04-18 21:54:58 +00005206 Record->push_back(Kind);
Chris Lattnerca025db2010-05-07 21:43:38 +00005207 switch (Kind) {
5208 case NestedNameSpecifier::Identifier:
Richard Smithe64e7452016-04-18 21:54:58 +00005209 AddIdentifierRef(NNS->getAsIdentifier());
Chris Lattnerca025db2010-05-07 21:43:38 +00005210 break;
5211
5212 case NestedNameSpecifier::Namespace:
Richard Smithe64e7452016-04-18 21:54:58 +00005213 AddDeclRef(NNS->getAsNamespace());
Chris Lattnerca025db2010-05-07 21:43:38 +00005214 break;
5215
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005216 case NestedNameSpecifier::NamespaceAlias:
Richard Smithe64e7452016-04-18 21:54:58 +00005217 AddDeclRef(NNS->getAsNamespaceAlias());
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005218 break;
5219
Chris Lattnerca025db2010-05-07 21:43:38 +00005220 case NestedNameSpecifier::TypeSpec:
5221 case NestedNameSpecifier::TypeSpecWithTemplate:
Richard Smithe64e7452016-04-18 21:54:58 +00005222 AddTypeRef(QualType(NNS->getAsType(), 0));
5223 Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
Chris Lattnerca025db2010-05-07 21:43:38 +00005224 break;
5225
5226 case NestedNameSpecifier::Global:
5227 // Don't need to write an associated value.
5228 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00005229
5230 case NestedNameSpecifier::Super:
Richard Smithe64e7452016-04-18 21:54:58 +00005231 AddDeclRef(NNS->getAsRecordDecl());
Nikola Smiljanic67860242014-09-26 00:28:20 +00005232 break;
Chris Lattnerca025db2010-05-07 21:43:38 +00005233 }
5234 }
5235}
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005236
Richard Smith290d8012016-04-06 17:06:00 +00005237void ASTRecordWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005238 // Nested name specifiers usually aren't too long. I think that 8 would
Chris Lattner57540c52011-04-15 05:22:18 +00005239 // typically accommodate the vast majority.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005240 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005241
5242 // Push each of the nested-name-specifiers's onto a stack for
5243 // serialization in reverse order.
5244 while (NNS) {
5245 NestedNames.push_back(NNS);
5246 NNS = NNS.getPrefix();
5247 }
5248
Richard Smith290d8012016-04-06 17:06:00 +00005249 Record->push_back(NestedNames.size());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005250 while(!NestedNames.empty()) {
5251 NNS = NestedNames.pop_back_val();
5252 NestedNameSpecifier::SpecifierKind Kind
5253 = NNS.getNestedNameSpecifier()->getKind();
Richard Smith290d8012016-04-06 17:06:00 +00005254 Record->push_back(Kind);
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005255 switch (Kind) {
5256 case NestedNameSpecifier::Identifier:
Richard Smith290d8012016-04-06 17:06:00 +00005257 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier());
5258 AddSourceRange(NNS.getLocalSourceRange());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005259 break;
5260
5261 case NestedNameSpecifier::Namespace:
Richard Smith290d8012016-04-06 17:06:00 +00005262 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace());
5263 AddSourceRange(NNS.getLocalSourceRange());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005264 break;
5265
5266 case NestedNameSpecifier::NamespaceAlias:
Richard Smith290d8012016-04-06 17:06:00 +00005267 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias());
5268 AddSourceRange(NNS.getLocalSourceRange());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005269 break;
5270
5271 case NestedNameSpecifier::TypeSpec:
5272 case NestedNameSpecifier::TypeSpecWithTemplate:
Richard Smith290d8012016-04-06 17:06:00 +00005273 Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5274 AddTypeLoc(NNS.getTypeLoc());
5275 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005276 break;
5277
5278 case NestedNameSpecifier::Global:
Richard Smith290d8012016-04-06 17:06:00 +00005279 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005280 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00005281
5282 case NestedNameSpecifier::Super:
Richard Smith290d8012016-04-06 17:06:00 +00005283 AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl());
5284 AddSourceRange(NNS.getLocalSourceRange());
Nikola Smiljanic67860242014-09-26 00:28:20 +00005285 break;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005286 }
5287 }
5288}
5289
Richard Smith290d8012016-04-06 17:06:00 +00005290void ASTRecordWriter::AddTemplateName(TemplateName Name) {
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005291 TemplateName::NameKind Kind = Name.getKind();
Richard Smith290d8012016-04-06 17:06:00 +00005292 Record->push_back(Kind);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005293 switch (Kind) {
5294 case TemplateName::Template:
Richard Smith290d8012016-04-06 17:06:00 +00005295 AddDeclRef(Name.getAsTemplateDecl());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005296 break;
5297
5298 case TemplateName::OverloadedTemplate: {
5299 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
Richard Smith290d8012016-04-06 17:06:00 +00005300 Record->push_back(OvT->size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005301 for (const auto &I : *OvT)
Richard Smith290d8012016-04-06 17:06:00 +00005302 AddDeclRef(I);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005303 break;
5304 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005305
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005306 case TemplateName::QualifiedTemplate: {
5307 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
Richard Smith290d8012016-04-06 17:06:00 +00005308 AddNestedNameSpecifier(QualT->getQualifier());
5309 Record->push_back(QualT->hasTemplateKeyword());
5310 AddDeclRef(QualT->getTemplateDecl());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005311 break;
5312 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005313
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005314 case TemplateName::DependentTemplate: {
5315 DependentTemplateName *DepT = Name.getAsDependentTemplateName();
Richard Smith290d8012016-04-06 17:06:00 +00005316 AddNestedNameSpecifier(DepT->getQualifier());
5317 Record->push_back(DepT->isIdentifier());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005318 if (DepT->isIdentifier())
Richard Smith290d8012016-04-06 17:06:00 +00005319 AddIdentifierRef(DepT->getIdentifier());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005320 else
Richard Smith290d8012016-04-06 17:06:00 +00005321 Record->push_back(DepT->getOperator());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005322 break;
5323 }
John McCalld9dfe3a2011-06-30 08:33:18 +00005324
5325 case TemplateName::SubstTemplateTemplateParm: {
5326 SubstTemplateTemplateParmStorage *subst
5327 = Name.getAsSubstTemplateTemplateParm();
Richard Smith290d8012016-04-06 17:06:00 +00005328 AddDeclRef(subst->getParameter());
5329 AddTemplateName(subst->getReplacement());
John McCalld9dfe3a2011-06-30 08:33:18 +00005330 break;
5331 }
Douglas Gregor5590be02011-01-15 06:45:20 +00005332
5333 case TemplateName::SubstTemplateTemplateParmPack: {
5334 SubstTemplateTemplateParmPackStorage *SubstPack
5335 = Name.getAsSubstTemplateTemplateParmPack();
Richard Smith290d8012016-04-06 17:06:00 +00005336 AddDeclRef(SubstPack->getParameterPack());
5337 AddTemplateArgument(SubstPack->getArgumentPack());
Douglas Gregor5590be02011-01-15 06:45:20 +00005338 break;
5339 }
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005340 }
5341}
5342
Richard Smith290d8012016-04-06 17:06:00 +00005343void ASTRecordWriter::AddTemplateArgument(const TemplateArgument &Arg) {
5344 Record->push_back(Arg.getKind());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005345 switch (Arg.getKind()) {
5346 case TemplateArgument::Null:
5347 break;
5348 case TemplateArgument::Type:
Richard Smith290d8012016-04-06 17:06:00 +00005349 AddTypeRef(Arg.getAsType());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005350 break;
5351 case TemplateArgument::Declaration:
Richard Smith290d8012016-04-06 17:06:00 +00005352 AddDeclRef(Arg.getAsDecl());
5353 AddTypeRef(Arg.getParamTypeForDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00005354 break;
5355 case TemplateArgument::NullPtr:
Richard Smith290d8012016-04-06 17:06:00 +00005356 AddTypeRef(Arg.getNullPtrType());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005357 break;
5358 case TemplateArgument::Integral:
Richard Smith290d8012016-04-06 17:06:00 +00005359 AddAPSInt(Arg.getAsIntegral());
5360 AddTypeRef(Arg.getIntegralType());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005361 break;
5362 case TemplateArgument::Template:
Richard Smith290d8012016-04-06 17:06:00 +00005363 AddTemplateName(Arg.getAsTemplateOrTemplatePattern());
Douglas Gregore1d60df2011-01-14 23:41:42 +00005364 break;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005365 case TemplateArgument::TemplateExpansion:
Richard Smith290d8012016-04-06 17:06:00 +00005366 AddTemplateName(Arg.getAsTemplateOrTemplatePattern());
David Blaikie05785d12013-02-20 22:23:23 +00005367 if (Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
Richard Smith290d8012016-04-06 17:06:00 +00005368 Record->push_back(*NumExpansions + 1);
Douglas Gregore1d60df2011-01-14 23:41:42 +00005369 else
Richard Smith290d8012016-04-06 17:06:00 +00005370 Record->push_back(0);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005371 break;
5372 case TemplateArgument::Expression:
5373 AddStmt(Arg.getAsExpr());
5374 break;
5375 case TemplateArgument::Pack:
Richard Smith290d8012016-04-06 17:06:00 +00005376 Record->push_back(Arg.pack_size());
Aaron Ballman2a89e852014-07-15 21:32:31 +00005377 for (const auto &P : Arg.pack_elements())
Richard Smith290d8012016-04-06 17:06:00 +00005378 AddTemplateArgument(P);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005379 break;
5380 }
5381}
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005382
Richard Smithe64e7452016-04-18 21:54:58 +00005383void ASTRecordWriter::AddTemplateParameterList(
5384 const TemplateParameterList *TemplateParams) {
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005385 assert(TemplateParams && "No TemplateParams!");
Richard Smithe64e7452016-04-18 21:54:58 +00005386 AddSourceLocation(TemplateParams->getTemplateLoc());
5387 AddSourceLocation(TemplateParams->getLAngleLoc());
5388 AddSourceLocation(TemplateParams->getRAngleLoc());
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00005389 // TODO: Concepts
Richard Smithe64e7452016-04-18 21:54:58 +00005390 Record->push_back(TemplateParams->size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005391 for (const auto &P : *TemplateParams)
Richard Smithe64e7452016-04-18 21:54:58 +00005392 AddDeclRef(P);
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005393}
5394
5395/// \brief Emit a template argument list.
Richard Smith290d8012016-04-06 17:06:00 +00005396void ASTRecordWriter::AddTemplateArgumentList(
5397 const TemplateArgumentList *TemplateArgs) {
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005398 assert(TemplateArgs && "No TemplateArgs!");
Richard Smith290d8012016-04-06 17:06:00 +00005399 Record->push_back(TemplateArgs->size());
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005400 for (int i=0, e = TemplateArgs->size(); i != e; ++i)
Richard Smith290d8012016-04-06 17:06:00 +00005401 AddTemplateArgument(TemplateArgs->get(i));
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005402}
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005403
Richard Smith290d8012016-04-06 17:06:00 +00005404void ASTRecordWriter::AddASTTemplateArgumentListInfo(
5405 const ASTTemplateArgumentListInfo *ASTTemplArgList) {
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005406 assert(ASTTemplArgList && "No ASTTemplArgList!");
Richard Smith290d8012016-04-06 17:06:00 +00005407 AddSourceLocation(ASTTemplArgList->LAngleLoc);
5408 AddSourceLocation(ASTTemplArgList->RAngleLoc);
5409 Record->push_back(ASTTemplArgList->NumTemplateArgs);
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005410 const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
5411 for (int i=0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
Richard Smith290d8012016-04-06 17:06:00 +00005412 AddTemplateArgumentLoc(TemplArgs[i]);
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005413}
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005414
Richard Smithe64e7452016-04-18 21:54:58 +00005415void ASTRecordWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set) {
5416 Record->push_back(Set.size());
Argyrios Kyrtzidis0f05fb92012-11-28 03:56:16 +00005417 for (ASTUnresolvedSet::const_iterator
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005418 I = Set.begin(), E = Set.end(); I != E; ++I) {
Richard Smithe64e7452016-04-18 21:54:58 +00005419 AddDeclRef(I.getDecl());
5420 Record->push_back(I.getAccess());
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005421 }
5422}
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005423
Richard Smith290d8012016-04-06 17:06:00 +00005424// FIXME: Move this out of the main ASTRecordWriter interface.
5425void ASTRecordWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
5426 Record->push_back(Base.isVirtual());
5427 Record->push_back(Base.isBaseOfClass());
5428 Record->push_back(Base.getAccessSpecifierAsWritten());
5429 Record->push_back(Base.getInheritConstructors());
5430 AddTypeSourceInfo(Base.getTypeSourceInfo());
5431 AddSourceRange(Base.getSourceRange());
Douglas Gregor752a5952011-01-03 22:36:02 +00005432 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
Richard Smith290d8012016-04-06 17:06:00 +00005433 : SourceLocation());
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005434}
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00005435
Richard Smith645d2cf2016-04-14 00:29:55 +00005436static uint64_t EmitCXXBaseSpecifiers(ASTWriter &W,
5437 ArrayRef<CXXBaseSpecifier> Bases) {
5438 ASTWriter::RecordData Record;
5439 ASTRecordWriter Writer(W, Record);
5440 Writer.push_back(Bases.size());
Dmitry Polukhin790b5402016-04-06 10:01:46 +00005441
Richard Smith645d2cf2016-04-14 00:29:55 +00005442 for (auto &Base : Bases)
5443 Writer.AddCXXBaseSpecifier(Base);
Richard Smith290d8012016-04-06 17:06:00 +00005444
Richard Smith645d2cf2016-04-14 00:29:55 +00005445 return Writer.Emit(serialization::DECL_CXX_BASE_SPECIFIERS);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005446}
5447
Richard Smith290d8012016-04-06 17:06:00 +00005448// FIXME: Move this out of the main ASTRecordWriter interface.
Richard Smith645d2cf2016-04-14 00:29:55 +00005449void ASTRecordWriter::AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases) {
5450 AddOffset(EmitCXXBaseSpecifiers(*Writer, Bases));
5451}
5452
Richard Smithaa165cf2016-04-13 21:57:08 +00005453static uint64_t
5454EmitCXXCtorInitializers(ASTWriter &W,
5455 ArrayRef<CXXCtorInitializer *> CtorInits) {
5456 ASTWriter::RecordData Record;
5457 ASTRecordWriter Writer(W, Record);
5458 Writer.push_back(CtorInits.size());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005459
Richard Smithaa165cf2016-04-13 21:57:08 +00005460 for (auto *Init : CtorInits) {
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005461 if (Init->isBaseInitializer()) {
Richard Smithaa165cf2016-04-13 21:57:08 +00005462 Writer.push_back(CTOR_INITIALIZER_BASE);
5463 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
5464 Writer.push_back(Init->isBaseVirtual());
Alexis Hunt37a477f2011-05-04 01:19:08 +00005465 } else if (Init->isDelegatingInitializer()) {
Richard Smithaa165cf2016-04-13 21:57:08 +00005466 Writer.push_back(CTOR_INITIALIZER_DELEGATING);
5467 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
Alexis Hunt37a477f2011-05-04 01:19:08 +00005468 } else if (Init->isMemberInitializer()){
Richard Smithaa165cf2016-04-13 21:57:08 +00005469 Writer.push_back(CTOR_INITIALIZER_MEMBER);
5470 Writer.AddDeclRef(Init->getMember());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005471 } else {
Richard Smithaa165cf2016-04-13 21:57:08 +00005472 Writer.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
5473 Writer.AddDeclRef(Init->getIndirectMember());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005474 }
Francois Pichetd583da02010-12-04 09:14:42 +00005475
Richard Smithaa165cf2016-04-13 21:57:08 +00005476 Writer.AddSourceLocation(Init->getMemberLocation());
5477 Writer.AddStmt(Init->getInit());
5478 Writer.AddSourceLocation(Init->getLParenLoc());
5479 Writer.AddSourceLocation(Init->getRParenLoc());
5480 Writer.push_back(Init->isWritten());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005481 if (Init->isWritten()) {
Richard Smithaa165cf2016-04-13 21:57:08 +00005482 Writer.push_back(Init->getSourceOrder());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005483 } else {
Richard Smithaa165cf2016-04-13 21:57:08 +00005484 Writer.push_back(Init->getNumArrayIndices());
5485 for (auto *VD : Init->getArrayIndices())
5486 Writer.AddDeclRef(VD);
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005487 }
5488 }
Richard Smithaa165cf2016-04-13 21:57:08 +00005489
5490 return Writer.Emit(serialization::DECL_CXX_CTOR_INITIALIZERS);
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005491}
5492
Richard Smithaa165cf2016-04-13 21:57:08 +00005493// FIXME: Move this out of the main ASTRecordWriter interface.
5494void ASTRecordWriter::AddCXXCtorInitializers(
5495 ArrayRef<CXXCtorInitializer *> CtorInits) {
5496 AddOffset(EmitCXXCtorInitializers(*Writer, CtorInits));
Richard Smithc2bb8182015-03-24 06:36:48 +00005497}
5498
Richard Smith290d8012016-04-06 17:06:00 +00005499void ASTRecordWriter::AddCXXDefinitionData(const CXXRecordDecl *D) {
Richard Smith053f6c62014-05-16 23:01:30 +00005500 auto &Data = D->data();
Richard Smith290d8012016-04-06 17:06:00 +00005501 Record->push_back(Data.IsLambda);
5502 Record->push_back(Data.UserDeclaredConstructor);
5503 Record->push_back(Data.UserDeclaredSpecialMembers);
5504 Record->push_back(Data.Aggregate);
5505 Record->push_back(Data.PlainOldData);
5506 Record->push_back(Data.Empty);
5507 Record->push_back(Data.Polymorphic);
5508 Record->push_back(Data.Abstract);
5509 Record->push_back(Data.IsStandardLayout);
5510 Record->push_back(Data.HasNoNonEmptyBases);
5511 Record->push_back(Data.HasPrivateFields);
5512 Record->push_back(Data.HasProtectedFields);
5513 Record->push_back(Data.HasPublicFields);
5514 Record->push_back(Data.HasMutableFields);
5515 Record->push_back(Data.HasVariantMembers);
5516 Record->push_back(Data.HasOnlyCMembers);
5517 Record->push_back(Data.HasInClassInitializer);
5518 Record->push_back(Data.HasUninitializedReferenceMember);
5519 Record->push_back(Data.HasUninitializedFields);
Richard Smith12e79312016-05-13 06:47:56 +00005520 Record->push_back(Data.HasInheritedConstructor);
5521 Record->push_back(Data.HasInheritedAssignment);
Richard Smith290d8012016-04-06 17:06:00 +00005522 Record->push_back(Data.NeedOverloadResolutionForMoveConstructor);
5523 Record->push_back(Data.NeedOverloadResolutionForMoveAssignment);
5524 Record->push_back(Data.NeedOverloadResolutionForDestructor);
5525 Record->push_back(Data.DefaultedMoveConstructorIsDeleted);
5526 Record->push_back(Data.DefaultedMoveAssignmentIsDeleted);
5527 Record->push_back(Data.DefaultedDestructorIsDeleted);
5528 Record->push_back(Data.HasTrivialSpecialMembers);
5529 Record->push_back(Data.DeclaredNonTrivialSpecialMembers);
5530 Record->push_back(Data.HasIrrelevantDestructor);
5531 Record->push_back(Data.HasConstexprNonCopyMoveConstructor);
5532 Record->push_back(Data.HasDefaultedDefaultConstructor);
5533 Record->push_back(Data.DefaultedDefaultConstructorIsConstexpr);
5534 Record->push_back(Data.HasConstexprDefaultConstructor);
5535 Record->push_back(Data.HasNonLiteralTypeFieldsOrBases);
5536 Record->push_back(Data.ComputedVisibleConversions);
5537 Record->push_back(Data.UserProvidedDefaultConstructor);
5538 Record->push_back(Data.DeclaredSpecialMembers);
5539 Record->push_back(Data.ImplicitCopyConstructorHasConstParam);
5540 Record->push_back(Data.ImplicitCopyAssignmentHasConstParam);
5541 Record->push_back(Data.HasDeclaredCopyConstructorWithConstParam);
5542 Record->push_back(Data.HasDeclaredCopyAssignmentWithConstParam);
Richard Smith561fb152012-02-25 07:33:38 +00005543 // IsLambda bit is already saved.
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005544
Richard Smith290d8012016-04-06 17:06:00 +00005545 Record->push_back(Data.NumBases);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005546 if (Data.NumBases > 0)
Richard Smith645d2cf2016-04-14 00:29:55 +00005547 AddCXXBaseSpecifiers(Data.bases());
5548
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005549 // FIXME: Make VBases lazily computed when needed to avoid storing them.
Richard Smith290d8012016-04-06 17:06:00 +00005550 Record->push_back(Data.NumVBases);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005551 if (Data.NumVBases > 0)
Richard Smith645d2cf2016-04-14 00:29:55 +00005552 AddCXXBaseSpecifiers(Data.vbases());
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005553
Richard Smith290d8012016-04-06 17:06:00 +00005554 AddUnresolvedSet(Data.Conversions.get(*Writer->Context));
5555 AddUnresolvedSet(Data.VisibleConversions.get(*Writer->Context));
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005556 // Data.Definition is the owning decl, no need to write it.
Richard Smith290d8012016-04-06 17:06:00 +00005557 AddDeclRef(D->getFirstFriend());
Douglas Gregor99ae8062012-02-14 17:54:36 +00005558
5559 // Add lambda-specific data.
5560 if (Data.IsLambda) {
Richard Smith053f6c62014-05-16 23:01:30 +00005561 auto &Lambda = D->getLambdaData();
Richard Smith290d8012016-04-06 17:06:00 +00005562 Record->push_back(Lambda.Dependent);
5563 Record->push_back(Lambda.IsGenericLambda);
5564 Record->push_back(Lambda.CaptureDefault);
5565 Record->push_back(Lambda.NumCaptures);
5566 Record->push_back(Lambda.NumExplicitCaptures);
5567 Record->push_back(Lambda.ManglingNumber);
5568 AddDeclRef(Lambda.ContextDecl);
5569 AddTypeSourceInfo(Lambda.MethodTyInfo);
Douglas Gregor99ae8062012-02-14 17:54:36 +00005570 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00005571 const LambdaCapture &Capture = Lambda.Captures[I];
Richard Smith290d8012016-04-06 17:06:00 +00005572 AddSourceLocation(Capture.getLocation());
5573 Record->push_back(Capture.isImplicit());
5574 Record->push_back(Capture.getCaptureKind());
Richard Smithba71c082013-05-16 06:20:58 +00005575 switch (Capture.getCaptureKind()) {
Faisal Validc6b5962016-03-21 09:25:37 +00005576 case LCK_StarThis:
Richard Smithba71c082013-05-16 06:20:58 +00005577 case LCK_This:
Alexey Bataev39c81e22014-08-28 04:28:19 +00005578 case LCK_VLAType:
Richard Smithba71c082013-05-16 06:20:58 +00005579 break;
5580 case LCK_ByCopy:
Richard Smithbb13c9a2013-09-28 04:02:39 +00005581 case LCK_ByRef:
Richard Smithba71c082013-05-16 06:20:58 +00005582 VarDecl *Var =
Craig Toppera13603a2014-05-22 05:54:18 +00005583 Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
Richard Smith290d8012016-04-06 17:06:00 +00005584 AddDeclRef(Var);
Richard Smithba71c082013-05-16 06:20:58 +00005585 AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
Richard Smith290d8012016-04-06 17:06:00 +00005586 : SourceLocation());
Richard Smithba71c082013-05-16 06:20:58 +00005587 break;
5588 }
Douglas Gregor99ae8062012-02-14 17:54:36 +00005589 }
5590 }
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005591}
5592
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005593void ASTWriter::ReaderInitialized(ASTReader *Reader) {
Sebastian Redl07a89a82010-07-30 00:29:29 +00005594 assert(Reader && "Cannot remove chain");
Douglas Gregordf0c1512011-08-18 04:12:04 +00005595 assert((!Chain || Chain == Reader) && "Cannot replace chain");
Sebastian Redl07a89a82010-07-30 00:29:29 +00005596 assert(FirstDeclID == NextDeclID &&
5597 FirstTypeID == NextTypeID &&
5598 FirstIdentID == NextIdentID &&
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005599 FirstMacroID == NextMacroID &&
Douglas Gregor253eefe2011-12-01 00:59:36 +00005600 FirstSubmoduleID == NextSubmoduleID &&
Sebastian Redld95a56e2010-08-04 18:21:41 +00005601 FirstSelectorID == NextSelectorID &&
Sebastian Redl07a89a82010-07-30 00:29:29 +00005602 "Setting chain after writing has started.");
Douglas Gregor925296b2011-07-19 16:10:42 +00005603
Sebastian Redl07a89a82010-07-30 00:29:29 +00005604 Chain = Reader;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005605
Richard Smith7f330cd2015-03-18 01:42:29 +00005606 // Note, this will get called multiple times, once one the reader starts up
5607 // and again each time it's done reading a PCH or module.
Douglas Gregordf0c1512011-08-18 04:12:04 +00005608 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
5609 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
5610 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005611 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
Douglas Gregor253eefe2011-12-01 00:59:36 +00005612 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
Douglas Gregordf0c1512011-08-18 04:12:04 +00005613 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005614 NextDeclID = FirstDeclID;
5615 NextTypeID = FirstTypeID;
5616 NextIdentID = FirstIdentID;
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005617 NextMacroID = FirstMacroID;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005618 NextSelectorID = FirstSelectorID;
Douglas Gregor253eefe2011-12-01 00:59:36 +00005619 NextSubmoduleID = FirstSubmoduleID;
Sebastian Redl07a89a82010-07-30 00:29:29 +00005620}
5621
Sebastian Redl539c5062010-08-18 23:57:32 +00005622void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005623 // Always keep the highest ID. See \p TypeRead() for more information.
5624 IdentID &StoredID = IdentifierIDs[II];
5625 if (ID > StoredID)
5626 StoredID = ID;
Sebastian Redlff4a2952010-07-23 23:49:55 +00005627}
5628
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005629void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005630 // Always keep the highest ID. See \p TypeRead() for more information.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005631 MacroID &StoredID = MacroIDs[MI];
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005632 if (ID > StoredID)
5633 StoredID = ID;
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005634}
5635
Argyrios Kyrtzidisbb5c7eae2010-08-20 16:03:59 +00005636void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005637 // Always take the highest-numbered type index. This copes with an interesting
5638 // case for chained AST writing where we schedule writing the type and then,
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005639 // later, deserialize the type from another AST. In this case, we want to
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005640 // keep the higher-numbered entry so that we can properly write it out to
5641 // the AST file.
5642 TypeIdx &StoredIdx = TypeIdxs[T];
5643 if (Idx.getIndex() >= StoredIdx.getIndex())
5644 StoredIdx = Idx;
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00005645}
5646
Sebastian Redl539c5062010-08-18 23:57:32 +00005647void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005648 // Always keep the highest ID. See \p TypeRead() for more information.
5649 SelectorID &StoredID = SelectorIDs[S];
5650 if (ID > StoredID)
5651 StoredID = ID;
Sebastian Redl834bb972010-08-04 17:20:04 +00005652}
Douglas Gregor91096292010-10-02 19:29:26 +00005653
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00005654void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
Richard Smith66a81862015-05-04 02:25:31 +00005655 MacroDefinitionRecord *MD) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00005656 assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
Douglas Gregor91096292010-10-02 19:29:26 +00005657 MacroDefinitions[MD] = ID;
5658}
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005659
Douglas Gregore37a85a2011-12-02 17:30:13 +00005660void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
5661 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
5662 SubmoduleIDs[Mod] = ID;
5663}
5664
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005665void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005666 if (Chain && Chain->isProcessingUpdateRecords()) return;
John McCallf937c022011-10-07 06:10:15 +00005667 assert(D->isCompleteDefinition());
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005668 assert(!WritingAST && "Already writing the AST!");
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005669 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005670 // We are interested when a PCH decl is modified.
Douglas Gregorb3722e22011-09-09 23:01:35 +00005671 if (RD->isFromASTFile()) {
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005672 // A forward reference was mutated into a definition. Rewrite it.
5673 // FIXME: This happens during template instantiation, should we
5674 // have created a new definition decl instead ?
Richard Smithcd45dbc2014-04-19 03:48:30 +00005675 assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
5676 "completed a tag from another module but not by instantiation?");
5677 DeclUpdates[RD].push_back(
5678 DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION));
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005679 }
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005680 }
5681}
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005682
Richard Smithf983f7f2015-10-13 00:23:25 +00005683static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) {
5684 if (D->isFromASTFile())
5685 return true;
5686
Richard Smithf983f7f2015-10-13 00:23:25 +00005687 // The predefined __va_list_tag struct is imported if we imported any decls.
5688 // FIXME: This is a gross hack.
5689 return D == D->getASTContext().getVaListTagDecl();
5690}
5691
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005692void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005693 if (Chain && Chain->isProcessingUpdateRecords()) return;
5694 assert(DC->isLookupContext() &&
Vassil Vassilev71eafde2016-04-06 20:56:03 +00005695 "Should not add lookup results to non-lookup contexts!");
5696
Vassil Vassilev632eac32016-03-16 11:17:04 +00005697 // TU is handled elsewhere.
5698 if (isa<TranslationUnitDecl>(DC))
5699 return;
5700
5701 // Namespaces are handled elsewhere, except for template instantiations of
5702 // FunctionTemplateDecls in namespaces. We are interested in cases where the
5703 // local instantiations are added to an imported context. Only happens when
5704 // adding ADL lookup candidates, for example templated friends.
5705 if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None &&
5706 !isa<FunctionTemplateDecl>(D))
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005707 return;
5708
Richard Smithf983f7f2015-10-13 00:23:25 +00005709 // We're only interested in cases where a local declaration is added to an
5710 // imported context.
5711 if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC)))
5712 return;
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005713
Richard Smith0f4e2c42015-08-06 04:23:48 +00005714 assert(DC == DC->getPrimaryContext() && "added to non-primary context");
Douglas Gregor9f782892013-01-21 15:25:38 +00005715 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
Richard Smithe9a8bc32014-09-30 00:45:29 +00005716 assert(!WritingAST && "Already writing the AST!");
Richard Smithf983f7f2015-10-13 00:23:25 +00005717 if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) {
5718 // We're adding a visible declaration to a predefined decl context. Ensure
5719 // that we write out all of its lookup results so we don't get a nasty
5720 // surprise when we try to emit its lookup table.
5721 for (auto *Child : DC->decls())
5722 UpdatingVisibleDecls.push_back(Child);
5723 }
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005724 UpdatingVisibleDecls.push_back(D);
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005725}
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005726
5727void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005728 if (Chain && Chain->isProcessingUpdateRecords()) return;
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005729 assert(D->isImplicit());
Richard Smithf983f7f2015-10-13 00:23:25 +00005730
5731 // We're only interested in cases where a local declaration is added to an
5732 // imported context.
5733 if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD))
5734 return;
5735
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005736 if (!isa<CXXMethodDecl>(D))
Richard Smithf983f7f2015-10-13 00:23:25 +00005737 return;
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005738
5739 // A decl coming from PCH was modified.
John McCallf937c022011-10-07 06:10:15 +00005740 assert(RD->isCompleteDefinition());
Richard Smithe9a8bc32014-09-30 00:45:29 +00005741 assert(!WritingAST && "Already writing the AST!");
Aaron Ballman4f45b712014-03-21 15:22:56 +00005742 DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005743}
Argyrios Kyrtzidis402dbbb2010-10-28 07:38:42 +00005744
Richard Smith564417a2014-03-20 21:47:22 +00005745void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005746 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smith9e2341d2015-03-23 03:25:59 +00005747 assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
5748 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00005749 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005750 // If we don't already know the exception specification for this redecl
5751 // chain, add an update record for it.
5752 if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
5753 ->getType()
5754 ->castAs<FunctionProtoType>()
5755 ->getExceptionSpecType()))
5756 DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
5757 });
Richard Smith564417a2014-03-20 21:47:22 +00005758}
5759
Richard Smith1fa5d642013-05-11 05:45:24 +00005760void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005761 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smith1fa5d642013-05-11 05:45:24 +00005762 assert(!WritingAST && "Already writing the AST!");
Richard Smith9e2341d2015-03-23 03:25:59 +00005763 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00005764 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005765 DeclUpdates[D].push_back(
5766 DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
5767 });
Richard Smith1fa5d642013-05-11 05:45:24 +00005768}
5769
Richard Smithf8134002015-03-10 01:41:22 +00005770void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
5771 const FunctionDecl *Delete) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005772 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smithf8134002015-03-10 01:41:22 +00005773 assert(!WritingAST && "Already writing the AST!");
5774 assert(Delete && "Not given an operator delete");
Richard Smith9e2341d2015-03-23 03:25:59 +00005775 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00005776 Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005777 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete));
5778 });
Richard Smithf8134002015-03-10 01:41:22 +00005779}
5780
Sebastian Redlab238a72011-04-24 16:28:06 +00005781void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005782 if (Chain && Chain->isProcessingUpdateRecords()) return;
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005783 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005784 if (!D->isFromASTFile())
Sebastian Redlab238a72011-04-24 16:28:06 +00005785 return; // Declaration not imported from PCH.
5786
Richard Smith4d235792014-08-07 18:53:08 +00005787 // Implicit function decl from a PCH was defined.
5788 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
Sebastian Redlab238a72011-04-24 16:28:06 +00005789}
5790
Richard Smithd28ac5b2014-03-22 23:33:22 +00005791void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005792 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smithd28ac5b2014-03-22 23:33:22 +00005793 assert(!WritingAST && "Already writing the AST!");
5794 if (!D->isFromASTFile())
5795 return;
5796
Richard Smith9e2341d2015-03-23 03:25:59 +00005797 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
Richard Smithd28ac5b2014-03-22 23:33:22 +00005798}
5799
Sebastian Redl2ac2c722011-04-29 08:19:30 +00005800void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005801 if (Chain && Chain->isProcessingUpdateRecords()) return;
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005802 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005803 if (!D->isFromASTFile())
Sebastian Redl2ac2c722011-04-29 08:19:30 +00005804 return;
5805
5806 // Since the actual instantiation is delayed, this really means that we need
5807 // to update the instantiation location.
Richard Smith6ef42932014-03-20 21:02:00 +00005808 DeclUpdates[D].push_back(
Aaron Ballman4f45b712014-03-21 15:22:56 +00005809 DeclUpdate(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER,
5810 D->getMemberSpecializationInfo()->getPointOfInstantiation()));
Sebastian Redl2ac2c722011-04-29 08:19:30 +00005811}
5812
John McCall32791cc2016-01-06 22:34:54 +00005813void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005814 if (Chain && Chain->isProcessingUpdateRecords()) return;
John McCall32791cc2016-01-06 22:34:54 +00005815 assert(!WritingAST && "Already writing the AST!");
5816 if (!D->isFromASTFile())
5817 return;
5818
5819 DeclUpdates[D].push_back(
5820 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D));
5821}
5822
Richard Smith4b054b22016-08-24 21:25:37 +00005823void ASTWriter::DefaultMemberInitializerInstantiated(const FieldDecl *D) {
5824 assert(!WritingAST && "Already writing the AST!");
5825 if (!D->isFromASTFile())
5826 return;
5827
5828 DeclUpdates[D].push_back(
5829 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER, D));
5830}
5831
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00005832void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
5833 const ObjCInterfaceDecl *IFD) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005834 if (Chain && Chain->isProcessingUpdateRecords()) return;
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005835 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005836 if (!IFD->isFromASTFile())
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00005837 return; // Declaration not imported from PCH.
Douglas Gregor404cdde2012-01-27 01:47:08 +00005838
5839 assert(IFD->getDefinition() && "Category on a class without a definition?");
5840 ObjCClassesWithCategories.insert(
5841 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00005842}
Argyrios Kyrtzidisb97a4022011-11-12 21:07:46 +00005843
Eli Friedman276dd182013-09-05 00:02:25 +00005844void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005845 if (Chain && Chain->isProcessingUpdateRecords()) return;
Eli Friedman276dd182013-09-05 00:02:25 +00005846 assert(!WritingAST && "Already writing the AST!");
Vassil Vassilev928c8252016-04-28 14:13:28 +00005847
5848 // If there is *any* declaration of the entity that's not from an AST file,
5849 // we can skip writing the update record. We make sure that isUsed() triggers
5850 // completion of the redeclaration chain of the entity.
5851 for (auto Prev = D->getMostRecentDecl(); Prev; Prev = Prev->getPreviousDecl())
5852 if (IsLocalDecl(Prev))
5853 return;
Eli Friedman276dd182013-09-05 00:02:25 +00005854
Aaron Ballman4f45b712014-03-21 15:22:56 +00005855 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
Eli Friedman276dd182013-09-05 00:02:25 +00005856}
Alexey Bataev97720002014-11-11 04:05:39 +00005857
5858void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005859 if (Chain && Chain->isProcessingUpdateRecords()) return;
Alexey Bataev97720002014-11-11 04:05:39 +00005860 assert(!WritingAST && "Already writing the AST!");
5861 if (!D->isFromASTFile())
5862 return;
5863
5864 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE));
5865}
Richard Smith65ebb4a2015-03-26 04:09:53 +00005866
Dmitry Polukhind69b5052016-05-09 14:59:13 +00005867void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
5868 const Attr *Attr) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005869 if (Chain && Chain->isProcessingUpdateRecords()) return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00005870 assert(!WritingAST && "Already writing the AST!");
5871 if (!D->isFromASTFile())
5872 return;
5873
Dmitry Polukhind69b5052016-05-09 14:59:13 +00005874 DeclUpdates[D].push_back(
5875 DeclUpdate(UPD_DECL_MARKED_OPENMP_DECLARETARGET, Attr));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00005876}
5877
Richard Smith4caa4492015-05-15 02:34:32 +00005878void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005879 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smith65ebb4a2015-03-26 04:09:53 +00005880 assert(!WritingAST && "Already writing the AST!");
5881 assert(D->isHidden() && "expected a hidden declaration");
Richard Smith4caa4492015-05-15 02:34:32 +00005882 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M));
Richard Smith65ebb4a2015-03-26 04:09:53 +00005883}
Alex Denisovfde64952015-06-26 05:28:36 +00005884
5885void ASTWriter::AddedAttributeToRecord(const Attr *Attr,
5886 const RecordDecl *Record) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005887 if (Chain && Chain->isProcessingUpdateRecords()) return;
Alex Denisovfde64952015-06-26 05:28:36 +00005888 assert(!WritingAST && "Already writing the AST!");
5889 if (!Record->isFromASTFile())
5890 return;
5891 DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr));
5892}