blob: c644a39f426174217fa8e83d7453b462b3a2724c [file] [log] [blame]
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001//===--- ASTWriter.cpp - AST File Writer ------------------------*- C++ -*-===//
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Sebastian Redl55c0ad52010-08-18 23:56:21 +000010// This file defines the ASTWriter class, which writes AST files.
Douglas Gregoref84c4b2009-04-09 22:27:44 +000011//
12//===----------------------------------------------------------------------===//
13
Sebastian Redl1914c6f2010-08-18 23:56:37 +000014#include "clang/Serialization/ASTWriter.h"
Douglas Gregor6623e1f2015-11-03 18:33:07 +000015#include "clang/Serialization/ModuleFileExtension.h"
Argyrios Kyrtzidis4bd97102010-08-20 16:03:52 +000016#include "ASTCommon.h"
Richard Smithd88a7f12015-09-01 20:35:42 +000017#include "ASTReaderInternals.h"
18#include "MultiOnDiskHashTable.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000019#include "clang/AST/ASTContext.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/DeclContextInternals.h"
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +000022#include "clang/AST/DeclFriend.h"
Richard Smith961eae52014-03-25 01:14:22 +000023#include "clang/AST/DeclLookups.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/AST/DeclTemplate.h"
Douglas Gregorfeb84b02009-04-14 21:18:50 +000025#include "clang/AST/Expr.h"
John McCallbfd822c2010-08-24 07:32:53 +000026#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000027#include "clang/AST/Type.h"
John McCall8f115c62009-10-16 21:56:05 +000028#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000029#include "clang/Basic/DiagnosticOptions.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000030#include "clang/Basic/FileManager.h"
Chris Lattner226efd32010-11-23 19:19:34 +000031#include "clang/Basic/FileSystemStatCache.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000032#include "clang/Basic/SourceManager.h"
Douglas Gregor4c7626e2009-04-13 16:31:14 +000033#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregorbfbde532009-04-10 21:16:55 +000034#include "clang/Basic/TargetInfo.h"
Douglas Gregorcb177f12012-10-16 23:40:58 +000035#include "clang/Basic/TargetOptions.h"
Douglas Gregor7b71e632009-04-27 22:23:34 +000036#include "clang/Basic/Version.h"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000037#include "clang/Basic/VersionTuple.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "clang/Lex/HeaderSearch.h"
39#include "clang/Lex/HeaderSearchOptions.h"
40#include "clang/Lex/MacroInfo.h"
41#include "clang/Lex/PreprocessingRecord.h"
42#include "clang/Lex/Preprocessor.h"
43#include "clang/Lex/PreprocessorOptions.h"
44#include "clang/Sema/IdentifierResolver.h"
45#include "clang/Sema/Sema.h"
46#include "clang/Serialization/ASTReader.h"
Richard Smithb5aaf5a2015-09-01 02:35:58 +000047#include "clang/Serialization/SerializationDiagnostic.h"
Douglas Gregore0a3a512009-04-14 21:55:33 +000048#include "llvm/ADT/APFloat.h"
49#include "llvm/ADT/APInt.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000050#include "llvm/ADT/Hashing.h"
Daniel Dunbarf8502d52009-10-17 23:52:28 +000051#include "llvm/ADT/StringExtras.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000052#include "llvm/Bitcode/BitstreamWriter.h"
Richard Smithaada85c2016-02-06 02:06:43 +000053#include "llvm/Support/Compression.h"
Justin Bognere1c147c2014-03-28 22:03:19 +000054#include "llvm/Support/EndianStream.h"
Michael J. Spencer740857f2010-12-21 16:45:57 +000055#include "llvm/Support/FileSystem.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000056#include "llvm/Support/MemoryBuffer.h"
Justin Bognerbb094f02014-04-18 19:57:06 +000057#include "llvm/Support/OnDiskHashTable.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000058#include "llvm/Support/Path.h"
Ben Langmuir487ea142014-10-23 18:05:36 +000059#include "llvm/Support/Process.h"
Douglas Gregor925296b2011-07-19 16:10:42 +000060#include <algorithm>
Chris Lattner225dd6c2009-04-11 18:40:46 +000061#include <cstdio>
Douglas Gregor09b69892011-02-10 17:09:37 +000062#include <string.h>
Douglas Gregor925296b2011-07-19 16:10:42 +000063#include <utility>
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +000064
Douglas Gregoref84c4b2009-04-09 22:27:44 +000065using namespace clang;
Sebastian Redl539c5062010-08-18 23:57:32 +000066using namespace clang::serialization;
Douglas Gregoref84c4b2009-04-09 22:27:44 +000067
Sebastian Redl3df5a082010-07-30 17:03:48 +000068template <typename T, typename Allocator>
Reid Kleckner012665e2015-05-21 00:13:09 +000069static StringRef bytes(const std::vector<T, Allocator> &v) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000070 if (v.empty()) return StringRef();
71 return StringRef(reinterpret_cast<const char*>(&v[0]),
Benjamin Kramerd47a12a2011-04-24 17:44:50 +000072 sizeof(T) * v.size());
Sebastian Redl3df5a082010-07-30 17:03:48 +000073}
Benjamin Kramerd47a12a2011-04-24 17:44:50 +000074
75template <typename T>
Reid Kleckner012665e2015-05-21 00:13:09 +000076static StringRef bytes(const SmallVectorImpl<T> &v) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000077 return StringRef(reinterpret_cast<const char*>(v.data()),
Benjamin Kramerd47a12a2011-04-24 17:44:50 +000078 sizeof(T) * v.size());
Sebastian Redl3df5a082010-07-30 17:03:48 +000079}
80
Douglas Gregoref84c4b2009-04-09 22:27:44 +000081//===----------------------------------------------------------------------===//
82// Type serialization
83//===----------------------------------------------------------------------===//
Chris Lattner7099dbc2009-04-27 06:16:06 +000084
Richard Smith290d8012016-04-06 17:06:00 +000085namespace clang {
Sebastian Redl42a0f6a2010-08-18 23:56:27 +000086 class ASTTypeWriter {
Sebastian Redl55c0ad52010-08-18 23:56:21 +000087 ASTWriter &Writer;
Richard Smith69c82bf2016-04-01 22:52:03 +000088 ASTRecordWriter Record;
Douglas Gregoref84c4b2009-04-09 22:27:44 +000089
Douglas Gregoref84c4b2009-04-09 22:27:44 +000090 /// \brief Type code that corresponds to the record generated.
Sebastian Redl539c5062010-08-18 23:57:32 +000091 TypeCode Code;
Richard Smith01b2cb42014-07-26 06:37:51 +000092 /// \brief Abbreviation to use for the record, if any.
93 unsigned AbbrevToUse;
Douglas Gregoref84c4b2009-04-09 22:27:44 +000094
Richard Smith290d8012016-04-06 17:06:00 +000095 public:
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +000096 ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
Richard Smith290d8012016-04-06 17:06:00 +000097 : Writer(Writer), Record(Writer, Record), Code((TypeCode)0), AbbrevToUse(0) { }
98
99 uint64_t Emit() {
100 return Record.Emit(Code, AbbrevToUse);
101 }
102
103 void Visit(QualType T) {
104 if (T.hasLocalNonFastQualifiers()) {
105 Qualifiers Qs = T.getLocalQualifiers();
106 Record.AddTypeRef(T.getLocalUnqualifiedType());
107 Record.push_back(Qs.getAsOpaqueValue());
108 Code = TYPE_EXT_QUAL;
109 AbbrevToUse = Writer.TypeExtQualAbbrev;
110 } else {
111 switch (T->getTypeClass()) {
112 // For all of the concrete, non-dependent types, call the
113 // appropriate visitor function.
114#define TYPE(Class, Base) \
115 case Type::Class: Visit##Class##Type(cast<Class##Type>(T)); break;
116#define ABSTRACT_TYPE(Class, Base)
117#include "clang/AST/TypeNodes.def"
118 }
119 }
120 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000121
122 void VisitArrayType(const ArrayType *T);
123 void VisitFunctionType(const FunctionType *T);
124 void VisitTagType(const TagType *T);
125
126#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
127#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000128#include "clang/AST/TypeNodes.def"
129 };
Richard Smith290d8012016-04-06 17:06:00 +0000130} // end namespace clang
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000131
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000132void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
David Blaikie83d382b2011-09-23 05:06:16 +0000133 llvm_unreachable("Built-in types are never serialized");
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000134}
135
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000136void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000137 Record.AddTypeRef(T->getElementType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000138 Code = TYPE_COMPLEX;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000139}
140
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000141void ASTTypeWriter::VisitPointerType(const PointerType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000142 Record.AddTypeRef(T->getPointeeType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000143 Code = TYPE_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000144}
145
Reid Kleckner8a365022013-06-24 17:51:48 +0000146void ASTTypeWriter::VisitDecayedType(const DecayedType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000147 Record.AddTypeRef(T->getOriginalType());
Reid Kleckner8a365022013-06-24 17:51:48 +0000148 Code = TYPE_DECAYED;
149}
150
Reid Kleckner0503a872013-12-05 01:23:43 +0000151void ASTTypeWriter::VisitAdjustedType(const AdjustedType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000152 Record.AddTypeRef(T->getOriginalType());
153 Record.AddTypeRef(T->getAdjustedType());
Reid Kleckner0503a872013-12-05 01:23:43 +0000154 Code = TYPE_ADJUSTED;
155}
156
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000157void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000158 Record.AddTypeRef(T->getPointeeType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000159 Code = TYPE_BLOCK_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000160}
161
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000162void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000163 Record.AddTypeRef(T->getPointeeTypeAsWritten());
Richard Smith0f538462011-04-12 10:38:03 +0000164 Record.push_back(T->isSpelledAsLValue());
Sebastian Redl539c5062010-08-18 23:57:32 +0000165 Code = TYPE_LVALUE_REFERENCE;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000166}
167
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000168void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000169 Record.AddTypeRef(T->getPointeeTypeAsWritten());
Sebastian Redl539c5062010-08-18 23:57:32 +0000170 Code = TYPE_RVALUE_REFERENCE;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000171}
172
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000173void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000174 Record.AddTypeRef(T->getPointeeType());
175 Record.AddTypeRef(QualType(T->getClass(), 0));
Sebastian Redl539c5062010-08-18 23:57:32 +0000176 Code = TYPE_MEMBER_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000177}
178
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000179void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000180 Record.AddTypeRef(T->getElementType());
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000181 Record.push_back(T->getSizeModifier()); // FIXME: stable values
John McCall8ccfcb52009-09-24 19:53:00 +0000182 Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000183}
184
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000185void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000186 VisitArrayType(T);
Richard Smith69c82bf2016-04-01 22:52:03 +0000187 Record.AddAPInt(T->getSize());
Sebastian Redl539c5062010-08-18 23:57:32 +0000188 Code = TYPE_CONSTANT_ARRAY;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000189}
190
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000191void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000192 VisitArrayType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000193 Code = TYPE_INCOMPLETE_ARRAY;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000194}
195
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000196void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000197 VisitArrayType(T);
Richard Smith69c82bf2016-04-01 22:52:03 +0000198 Record.AddSourceLocation(T->getLBracketLoc());
199 Record.AddSourceLocation(T->getRBracketLoc());
Richard Smith290d8012016-04-06 17:06:00 +0000200 Record.AddStmt(T->getSizeExpr());
Sebastian Redl539c5062010-08-18 23:57:32 +0000201 Code = TYPE_VARIABLE_ARRAY;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000202}
203
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000204void ASTTypeWriter::VisitVectorType(const VectorType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000205 Record.AddTypeRef(T->getElementType());
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000206 Record.push_back(T->getNumElements());
Bob Wilsonaeb56442010-11-10 21:56:12 +0000207 Record.push_back(T->getVectorKind());
Sebastian Redl539c5062010-08-18 23:57:32 +0000208 Code = TYPE_VECTOR;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000209}
210
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000211void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000212 VisitVectorType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000213 Code = TYPE_EXT_VECTOR;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000214}
215
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000216void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000217 Record.AddTypeRef(T->getReturnType());
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000218 FunctionType::ExtInfo C = T->getExtInfo();
219 Record.push_back(C.getNoReturn());
Eli Friedmanc5b20b52011-04-09 08:18:08 +0000220 Record.push_back(C.getHasRegParm());
Rafael Espindola49b85ab2010-03-30 22:15:11 +0000221 Record.push_back(C.getRegParm());
Douglas Gregor8c940862010-01-18 17:14:39 +0000222 // FIXME: need to stabilize encoding of calling convention...
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000223 Record.push_back(C.getCC());
John McCall31168b02011-06-15 23:02:42 +0000224 Record.push_back(C.getProducesResult());
Richard Smith01b2cb42014-07-26 06:37:51 +0000225
226 if (C.getHasRegParm() || C.getRegParm() || C.getProducesResult())
227 AbbrevToUse = 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000228}
229
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000230void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000231 VisitFunctionType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000232 Code = TYPE_FUNCTION_NO_PROTO;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000233}
234
Richard Smith290d8012016-04-06 17:06:00 +0000235static void addExceptionSpec(const FunctionProtoType *T,
236 ASTRecordWriter &Record) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000237 Record.push_back(T->getExceptionSpecType());
238 if (T->getExceptionSpecType() == EST_Dynamic) {
239 Record.push_back(T->getNumExceptions());
240 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
Richard Smith69c82bf2016-04-01 22:52:03 +0000241 Record.AddTypeRef(T->getExceptionType(I));
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000242 } else if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
Richard Smith290d8012016-04-06 17:06:00 +0000243 Record.AddStmt(T->getNoexceptExpr());
Richard Smith8b987a92012-04-21 17:47:47 +0000244 } else if (T->getExceptionSpecType() == EST_Uninstantiated) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000245 Record.AddDeclRef(T->getExceptionSpecDecl());
246 Record.AddDeclRef(T->getExceptionSpecTemplate());
Richard Smithd3b5c9082012-07-27 04:22:15 +0000247 } else if (T->getExceptionSpecType() == EST_Unevaluated) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000248 Record.AddDeclRef(T->getExceptionSpecDecl());
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000249 }
Richard Smith564417a2014-03-20 21:47:22 +0000250}
251
252void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
253 VisitFunctionType(T);
Richard Smith01b2cb42014-07-26 06:37:51 +0000254
Richard Smith564417a2014-03-20 21:47:22 +0000255 Record.push_back(T->isVariadic());
256 Record.push_back(T->hasTrailingReturn());
257 Record.push_back(T->getTypeQuals());
258 Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
Richard Smith290d8012016-04-06 17:06:00 +0000259 addExceptionSpec(T, Record);
Richard Smith01b2cb42014-07-26 06:37:51 +0000260
261 Record.push_back(T->getNumParams());
262 for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
Richard Smith69c82bf2016-04-01 22:52:03 +0000263 Record.AddTypeRef(T->getParamType(I));
Richard Smith01b2cb42014-07-26 06:37:51 +0000264
John McCall18afab72016-03-01 00:49:02 +0000265 if (T->hasExtParameterInfos()) {
266 for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
267 Record.push_back(T->getExtParameterInfo(I).getOpaqueValue());
268 }
269
Richard Smith01b2cb42014-07-26 06:37:51 +0000270 if (T->isVariadic() || T->hasTrailingReturn() || T->getTypeQuals() ||
John McCall18afab72016-03-01 00:49:02 +0000271 T->getRefQualifier() || T->getExceptionSpecType() != EST_None ||
272 T->hasExtParameterInfos())
Richard Smith01b2cb42014-07-26 06:37:51 +0000273 AbbrevToUse = 0;
274
Sebastian Redl539c5062010-08-18 23:57:32 +0000275 Code = TYPE_FUNCTION_PROTO;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000276}
277
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000278void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000279 Record.AddDeclRef(T->getDecl());
Sebastian Redl539c5062010-08-18 23:57:32 +0000280 Code = TYPE_UNRESOLVED_USING;
John McCallb96ec562009-12-04 22:46:56 +0000281}
John McCallb96ec562009-12-04 22:46:56 +0000282
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000283void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000284 Record.AddDeclRef(T->getDecl());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +0000285 assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
Richard Smith69c82bf2016-04-01 22:52:03 +0000286 Record.AddTypeRef(T->getCanonicalTypeInternal());
Sebastian Redl539c5062010-08-18 23:57:32 +0000287 Code = TYPE_TYPEDEF;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000288}
289
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000290void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
Richard Smith290d8012016-04-06 17:06:00 +0000291 Record.AddStmt(T->getUnderlyingExpr());
Sebastian Redl539c5062010-08-18 23:57:32 +0000292 Code = TYPE_TYPEOF_EXPR;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000293}
294
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000295void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000296 Record.AddTypeRef(T->getUnderlyingType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000297 Code = TYPE_TYPEOF;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000298}
299
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000300void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000301 Record.AddTypeRef(T->getUnderlyingType());
Richard Smith290d8012016-04-06 17:06:00 +0000302 Record.AddStmt(T->getUnderlyingExpr());
Sebastian Redl539c5062010-08-18 23:57:32 +0000303 Code = TYPE_DECLTYPE;
Anders Carlsson81df7b82009-06-24 19:06:50 +0000304}
305
Alexis Hunte852b102011-05-24 22:41:36 +0000306void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000307 Record.AddTypeRef(T->getBaseType());
308 Record.AddTypeRef(T->getUnderlyingType());
Alexis Hunte852b102011-05-24 22:41:36 +0000309 Record.push_back(T->getUTTKind());
310 Code = TYPE_UNARY_TRANSFORM;
311}
312
Richard Smith30482bc2011-02-20 03:19:35 +0000313void ASTTypeWriter::VisitAutoType(const AutoType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000314 Record.AddTypeRef(T->getDeducedType());
Richard Smithe301ba22015-11-11 02:02:15 +0000315 Record.push_back((unsigned)T->getKeyword());
Richard Smith27d807c2013-04-30 13:56:41 +0000316 if (T->getDeducedType().isNull())
317 Record.push_back(T->isDependentType());
Richard Smith30482bc2011-02-20 03:19:35 +0000318 Code = TYPE_AUTO;
319}
320
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000321void ASTTypeWriter::VisitTagType(const TagType *T) {
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +0000322 Record.push_back(T->isDependentType());
Richard Smith69c82bf2016-04-01 22:52:03 +0000323 Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +0000324 assert(!T->isBeingDefined() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000325 "Cannot serialize in the middle of a type definition");
326}
327
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000328void ASTTypeWriter::VisitRecordType(const RecordType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000329 VisitTagType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000330 Code = TYPE_RECORD;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000331}
332
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000333void ASTTypeWriter::VisitEnumType(const EnumType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000334 VisitTagType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000335 Code = TYPE_ENUM;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000336}
337
John McCall81904512011-01-06 01:58:22 +0000338void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000339 Record.AddTypeRef(T->getModifiedType());
340 Record.AddTypeRef(T->getEquivalentType());
John McCall81904512011-01-06 01:58:22 +0000341 Record.push_back(T->getAttrKind());
342 Code = TYPE_ATTRIBUTED;
343}
344
Mike Stump11289f42009-09-09 15:08:12 +0000345void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000346ASTTypeWriter::VisitSubstTemplateTypeParmType(
John McCallcebee162009-10-18 09:09:24 +0000347 const SubstTemplateTypeParmType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000348 Record.AddTypeRef(QualType(T->getReplacedParameter(), 0));
349 Record.AddTypeRef(T->getReplacementType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000350 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
John McCallcebee162009-10-18 09:09:24 +0000351}
352
353void
Douglas Gregorada4b792011-01-14 02:55:32 +0000354ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
355 const SubstTemplateTypeParmPackType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000356 Record.AddTypeRef(QualType(T->getReplacedParameter(), 0));
357 Record.AddTemplateArgument(T->getArgumentPack());
Douglas Gregorada4b792011-01-14 02:55:32 +0000358 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK;
359}
360
361void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000362ASTTypeWriter::VisitTemplateSpecializationType(
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000363 const TemplateSpecializationType *T) {
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +0000364 Record.push_back(T->isDependentType());
Richard Smith69c82bf2016-04-01 22:52:03 +0000365 Record.AddTemplateName(T->getTemplateName());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000366 Record.push_back(T->getNumArgs());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +0000367 for (const auto &ArgI : *T)
Richard Smith69c82bf2016-04-01 22:52:03 +0000368 Record.AddTemplateArgument(ArgI);
369 Record.AddTypeRef(T->isTypeAlias() ? T->getAliasedType()
370 : T->isCanonicalUnqualified()
371 ? QualType()
372 : T->getCanonicalTypeInternal());
Sebastian Redl539c5062010-08-18 23:57:32 +0000373 Code = TYPE_TEMPLATE_SPECIALIZATION;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000374}
375
376void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000377ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
Argyrios Kyrtzidis4a57bd02010-06-30 08:49:25 +0000378 VisitArrayType(T);
Richard Smith290d8012016-04-06 17:06:00 +0000379 Record.AddStmt(T->getSizeExpr());
Richard Smith69c82bf2016-04-01 22:52:03 +0000380 Record.AddSourceRange(T->getBracketsRange());
Sebastian Redl539c5062010-08-18 23:57:32 +0000381 Code = TYPE_DEPENDENT_SIZED_ARRAY;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000382}
383
384void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000385ASTTypeWriter::VisitDependentSizedExtVectorType(
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000386 const DependentSizedExtVectorType *T) {
387 // FIXME: Serialize this type (C++ only)
David Blaikie83d382b2011-09-23 05:06:16 +0000388 llvm_unreachable("Cannot serialize dependent sized extended vector types");
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000389}
390
391void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000392ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000393 Record.push_back(T->getDepth());
394 Record.push_back(T->getIndex());
395 Record.push_back(T->isParameterPack());
Richard Smith69c82bf2016-04-01 22:52:03 +0000396 Record.AddDeclRef(T->getDecl());
Sebastian Redl539c5062010-08-18 23:57:32 +0000397 Code = TYPE_TEMPLATE_TYPE_PARM;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000398}
399
400void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000401ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
Argyrios Kyrtzidisbfcacee2010-06-24 08:57:31 +0000402 Record.push_back(T->getKeyword());
Richard Smith69c82bf2016-04-01 22:52:03 +0000403 Record.AddNestedNameSpecifier(T->getQualifier());
404 Record.AddIdentifierRef(T->getIdentifier());
405 Record.AddTypeRef(
406 T->isCanonicalUnqualified() ? QualType() : T->getCanonicalTypeInternal());
Sebastian Redl539c5062010-08-18 23:57:32 +0000407 Code = TYPE_DEPENDENT_NAME;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000408}
409
410void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000411ASTTypeWriter::VisitDependentTemplateSpecializationType(
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000412 const DependentTemplateSpecializationType *T) {
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +0000413 Record.push_back(T->getKeyword());
Richard Smith69c82bf2016-04-01 22:52:03 +0000414 Record.AddNestedNameSpecifier(T->getQualifier());
415 Record.AddIdentifierRef(T->getIdentifier());
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +0000416 Record.push_back(T->getNumArgs());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +0000417 for (const auto &I : *T)
Richard Smith69c82bf2016-04-01 22:52:03 +0000418 Record.AddTemplateArgument(I);
Sebastian Redl539c5062010-08-18 23:57:32 +0000419 Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000420}
421
Douglas Gregord2fa7662010-12-20 02:24:11 +0000422void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000423 Record.AddTypeRef(T->getPattern());
David Blaikie05785d12013-02-20 22:23:23 +0000424 if (Optional<unsigned> NumExpansions = T->getNumExpansions())
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000425 Record.push_back(*NumExpansions + 1);
426 else
427 Record.push_back(0);
Douglas Gregord2fa7662010-12-20 02:24:11 +0000428 Code = TYPE_PACK_EXPANSION;
429}
430
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000431void ASTTypeWriter::VisitParenType(const ParenType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000432 Record.AddTypeRef(T->getInnerType());
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000433 Code = TYPE_PAREN;
434}
435
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000436void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000437 Record.push_back(T->getKeyword());
Richard Smith69c82bf2016-04-01 22:52:03 +0000438 Record.AddNestedNameSpecifier(T->getQualifier());
439 Record.AddTypeRef(T->getNamedType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000440 Code = TYPE_ELABORATED;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000441}
442
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000443void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000444 Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
445 Record.AddTypeRef(T->getInjectedSpecializationType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000446 Code = TYPE_INJECTED_CLASS_NAME;
John McCalle78aac42010-03-10 03:28:59 +0000447}
448
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000449void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000450 Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
Sebastian Redl539c5062010-08-18 23:57:32 +0000451 Code = TYPE_OBJC_INTERFACE;
John McCall8b07ec22010-05-15 11:32:37 +0000452}
453
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000454void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000455 Record.AddTypeRef(T->getBaseType());
Douglas Gregore83b9562015-07-07 03:57:53 +0000456 Record.push_back(T->getTypeArgsAsWritten().size());
457 for (auto TypeArg : T->getTypeArgsAsWritten())
Richard Smith69c82bf2016-04-01 22:52:03 +0000458 Record.AddTypeRef(TypeArg);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000459 Record.push_back(T->getNumProtocols());
Aaron Ballman1683f7b2014-03-17 15:55:30 +0000460 for (const auto *I : T->quals())
Richard Smith69c82bf2016-04-01 22:52:03 +0000461 Record.AddDeclRef(I);
Douglas Gregorab209d82015-07-07 03:58:42 +0000462 Record.push_back(T->isKindOfTypeAsWritten());
Sebastian Redl539c5062010-08-18 23:57:32 +0000463 Code = TYPE_OBJC_OBJECT;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000464}
465
Steve Narofffb4330f2009-06-17 22:40:22 +0000466void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000467ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000468 Record.AddTypeRef(T->getPointeeType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000469 Code = TYPE_OBJC_OBJECT_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000470}
471
Eli Friedman0dfb8892011-10-06 23:00:33 +0000472void
473ASTTypeWriter::VisitAtomicType(const AtomicType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000474 Record.AddTypeRef(T->getValueType());
Eli Friedman0dfb8892011-10-06 23:00:33 +0000475 Code = TYPE_ATOMIC;
476}
477
Xiuli Pan9c14e282016-01-09 12:53:17 +0000478void
479ASTTypeWriter::VisitPipeType(const PipeType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000480 Record.AddTypeRef(T->getElementType());
Xiuli Pan9c14e282016-01-09 12:53:17 +0000481 Code = TYPE_PIPE;
482}
483
John McCall8f115c62009-10-16 21:56:05 +0000484namespace {
485
486class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
Richard Smith290d8012016-04-06 17:06:00 +0000487 ASTRecordWriter &Record;
John McCall8f115c62009-10-16 21:56:05 +0000488
489public:
Richard Smith290d8012016-04-06 17:06:00 +0000490 TypeLocWriter(ASTRecordWriter &Record)
491 : Record(Record) { }
John McCall8f115c62009-10-16 21:56:05 +0000492
John McCall17001972009-10-18 01:05:36 +0000493#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCall8f115c62009-10-16 21:56:05 +0000494#define TYPELOC(CLASS, PARENT) \
John McCall17001972009-10-18 01:05:36 +0000495 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +0000496#include "clang/AST/TypeLocNodes.def"
497
John McCall17001972009-10-18 01:05:36 +0000498 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
499 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +0000500};
501
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +0000502} // end anonymous namespace
John McCall8f115c62009-10-16 21:56:05 +0000503
John McCall17001972009-10-18 01:05:36 +0000504void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
505 // nothing to do
John McCall8f115c62009-10-16 21:56:05 +0000506}
John McCall17001972009-10-18 01:05:36 +0000507void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000508 Record.AddSourceLocation(TL.getBuiltinLoc());
Douglas Gregorc9b7a592010-01-18 18:04:31 +0000509 if (TL.needsExtraLocalData()) {
510 Record.push_back(TL.getWrittenTypeSpec());
511 Record.push_back(TL.getWrittenSignSpec());
512 Record.push_back(TL.getWrittenWidthSpec());
513 Record.push_back(TL.hasModeAttr());
514 }
John McCall8f115c62009-10-16 21:56:05 +0000515}
John McCall17001972009-10-18 01:05:36 +0000516void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000517 Record.AddSourceLocation(TL.getNameLoc());
John McCall8f115c62009-10-16 21:56:05 +0000518}
John McCall17001972009-10-18 01:05:36 +0000519void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000520 Record.AddSourceLocation(TL.getStarLoc());
John McCall8f115c62009-10-16 21:56:05 +0000521}
Reid Kleckner8a365022013-06-24 17:51:48 +0000522void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
523 // nothing to do
524}
Reid Kleckner0503a872013-12-05 01:23:43 +0000525void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
526 // nothing to do
527}
John McCall17001972009-10-18 01:05:36 +0000528void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000529 Record.AddSourceLocation(TL.getCaretLoc());
John McCall8f115c62009-10-16 21:56:05 +0000530}
John McCall17001972009-10-18 01:05:36 +0000531void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000532 Record.AddSourceLocation(TL.getAmpLoc());
John McCall8f115c62009-10-16 21:56:05 +0000533}
John McCall17001972009-10-18 01:05:36 +0000534void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000535 Record.AddSourceLocation(TL.getAmpAmpLoc());
John McCall8f115c62009-10-16 21:56:05 +0000536}
John McCall17001972009-10-18 01:05:36 +0000537void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000538 Record.AddSourceLocation(TL.getStarLoc());
539 Record.AddTypeSourceInfo(TL.getClassTInfo());
John McCall8f115c62009-10-16 21:56:05 +0000540}
John McCall17001972009-10-18 01:05:36 +0000541void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000542 Record.AddSourceLocation(TL.getLBracketLoc());
543 Record.AddSourceLocation(TL.getRBracketLoc());
John McCall17001972009-10-18 01:05:36 +0000544 Record.push_back(TL.getSizeExpr() ? 1 : 0);
545 if (TL.getSizeExpr())
Richard Smith290d8012016-04-06 17:06:00 +0000546 Record.AddStmt(TL.getSizeExpr());
John McCall8f115c62009-10-16 21:56:05 +0000547}
John McCall17001972009-10-18 01:05:36 +0000548void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
549 VisitArrayTypeLoc(TL);
550}
551void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
552 VisitArrayTypeLoc(TL);
553}
554void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
555 VisitArrayTypeLoc(TL);
556}
557void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
558 DependentSizedArrayTypeLoc TL) {
559 VisitArrayTypeLoc(TL);
560}
561void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
562 DependentSizedExtVectorTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000563 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000564}
565void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000566 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000567}
568void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000569 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000570}
571void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000572 Record.AddSourceLocation(TL.getLocalRangeBegin());
573 Record.AddSourceLocation(TL.getLParenLoc());
574 Record.AddSourceLocation(TL.getRParenLoc());
575 Record.AddSourceLocation(TL.getLocalRangeEnd());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +0000576 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000577 Record.AddDeclRef(TL.getParam(i));
John McCall17001972009-10-18 01:05:36 +0000578}
579void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
580 VisitFunctionTypeLoc(TL);
581}
582void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
583 VisitFunctionTypeLoc(TL);
584}
John McCallb96ec562009-12-04 22:46:56 +0000585void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000586 Record.AddSourceLocation(TL.getNameLoc());
John McCallb96ec562009-12-04 22:46:56 +0000587}
John McCall17001972009-10-18 01:05:36 +0000588void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000589 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000590}
591void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000592 Record.AddSourceLocation(TL.getTypeofLoc());
593 Record.AddSourceLocation(TL.getLParenLoc());
594 Record.AddSourceLocation(TL.getRParenLoc());
John McCall17001972009-10-18 01:05:36 +0000595}
596void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000597 Record.AddSourceLocation(TL.getTypeofLoc());
598 Record.AddSourceLocation(TL.getLParenLoc());
599 Record.AddSourceLocation(TL.getRParenLoc());
600 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
John McCall17001972009-10-18 01:05:36 +0000601}
602void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000603 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000604}
Alexis Hunte852b102011-05-24 22:41:36 +0000605void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000606 Record.AddSourceLocation(TL.getKWLoc());
607 Record.AddSourceLocation(TL.getLParenLoc());
608 Record.AddSourceLocation(TL.getRParenLoc());
609 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
Alexis Hunte852b102011-05-24 22:41:36 +0000610}
Richard Smith30482bc2011-02-20 03:19:35 +0000611void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000612 Record.AddSourceLocation(TL.getNameLoc());
Richard Smith30482bc2011-02-20 03:19:35 +0000613}
John McCall17001972009-10-18 01:05:36 +0000614void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000615 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000616}
617void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000618 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000619}
John McCall81904512011-01-06 01:58:22 +0000620void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000621 Record.AddSourceLocation(TL.getAttrNameLoc());
John McCall81904512011-01-06 01:58:22 +0000622 if (TL.hasAttrOperand()) {
623 SourceRange range = TL.getAttrOperandParensRange();
Richard Smith69c82bf2016-04-01 22:52:03 +0000624 Record.AddSourceLocation(range.getBegin());
625 Record.AddSourceLocation(range.getEnd());
John McCall81904512011-01-06 01:58:22 +0000626 }
627 if (TL.hasAttrExprOperand()) {
628 Expr *operand = TL.getAttrExprOperand();
629 Record.push_back(operand ? 1 : 0);
Richard Smith290d8012016-04-06 17:06:00 +0000630 if (operand) Record.AddStmt(operand);
John McCall81904512011-01-06 01:58:22 +0000631 } else if (TL.hasAttrEnumOperand()) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000632 Record.AddSourceLocation(TL.getAttrEnumOperandLoc());
John McCall81904512011-01-06 01:58:22 +0000633 }
634}
John McCall17001972009-10-18 01:05:36 +0000635void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000636 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000637}
John McCallcebee162009-10-18 09:09:24 +0000638void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
639 SubstTemplateTypeParmTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000640 Record.AddSourceLocation(TL.getNameLoc());
John McCallcebee162009-10-18 09:09:24 +0000641}
Douglas Gregorada4b792011-01-14 02:55:32 +0000642void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
643 SubstTemplateTypeParmPackTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000644 Record.AddSourceLocation(TL.getNameLoc());
Douglas Gregorada4b792011-01-14 02:55:32 +0000645}
John McCall17001972009-10-18 01:05:36 +0000646void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
647 TemplateSpecializationTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000648 Record.AddSourceLocation(TL.getTemplateKeywordLoc());
649 Record.AddSourceLocation(TL.getTemplateNameLoc());
650 Record.AddSourceLocation(TL.getLAngleLoc());
651 Record.AddSourceLocation(TL.getRAngleLoc());
John McCall0ad16662009-10-29 08:12:44 +0000652 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000653 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
654 TL.getArgLoc(i).getLocInfo());
John McCall17001972009-10-18 01:05:36 +0000655}
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000656void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000657 Record.AddSourceLocation(TL.getLParenLoc());
658 Record.AddSourceLocation(TL.getRParenLoc());
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000659}
Abramo Bagnara6150c882010-05-11 21:36:43 +0000660void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000661 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
662 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
John McCall17001972009-10-18 01:05:36 +0000663}
John McCalle78aac42010-03-10 03:28:59 +0000664void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000665 Record.AddSourceLocation(TL.getNameLoc());
John McCalle78aac42010-03-10 03:28:59 +0000666}
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +0000667void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000668 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
669 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
670 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000671}
John McCallc392f372010-06-11 00:33:02 +0000672void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
673 DependentTemplateSpecializationTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000674 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
675 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
676 Record.AddSourceLocation(TL.getTemplateKeywordLoc());
677 Record.AddSourceLocation(TL.getTemplateNameLoc());
678 Record.AddSourceLocation(TL.getLAngleLoc());
679 Record.AddSourceLocation(TL.getRAngleLoc());
John McCallc392f372010-06-11 00:33:02 +0000680 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
Richard Smith69c82bf2016-04-01 22:52:03 +0000681 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
682 TL.getArgLoc(I).getLocInfo());
John McCallc392f372010-06-11 00:33:02 +0000683}
Douglas Gregord2fa7662010-12-20 02:24:11 +0000684void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000685 Record.AddSourceLocation(TL.getEllipsisLoc());
Douglas Gregord2fa7662010-12-20 02:24:11 +0000686}
John McCall17001972009-10-18 01:05:36 +0000687void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000688 Record.AddSourceLocation(TL.getNameLoc());
John McCall8b07ec22010-05-15 11:32:37 +0000689}
690void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
691 Record.push_back(TL.hasBaseTypeAsWritten());
Richard Smith69c82bf2016-04-01 22:52:03 +0000692 Record.AddSourceLocation(TL.getTypeArgsLAngleLoc());
693 Record.AddSourceLocation(TL.getTypeArgsRAngleLoc());
Douglas Gregore9d95f12015-07-07 03:57:35 +0000694 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000695 Record.AddTypeSourceInfo(TL.getTypeArgTInfo(i));
696 Record.AddSourceLocation(TL.getProtocolLAngleLoc());
697 Record.AddSourceLocation(TL.getProtocolRAngleLoc());
John McCall17001972009-10-18 01:05:36 +0000698 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000699 Record.AddSourceLocation(TL.getProtocolLoc(i));
John McCall8f115c62009-10-16 21:56:05 +0000700}
John McCallfc93cf92009-10-22 22:37:11 +0000701void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000702 Record.AddSourceLocation(TL.getStarLoc());
John McCallfc93cf92009-10-22 22:37:11 +0000703}
Eli Friedman0dfb8892011-10-06 23:00:33 +0000704void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000705 Record.AddSourceLocation(TL.getKWLoc());
706 Record.AddSourceLocation(TL.getLParenLoc());
707 Record.AddSourceLocation(TL.getRParenLoc());
Eli Friedman0dfb8892011-10-06 23:00:33 +0000708}
Xiuli Pan9c14e282016-01-09 12:53:17 +0000709void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000710 Record.AddSourceLocation(TL.getKWLoc());
Xiuli Pan9c14e282016-01-09 12:53:17 +0000711}
John McCall8f115c62009-10-16 21:56:05 +0000712
Richard Smith01b2cb42014-07-26 06:37:51 +0000713void ASTWriter::WriteTypeAbbrevs() {
714 using namespace llvm;
715
716 BitCodeAbbrev *Abv;
717
718 // Abbreviation for TYPE_EXT_QUAL
719 Abv = new BitCodeAbbrev();
720 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
721 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
722 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals
723 TypeExtQualAbbrev = Stream.EmitAbbrev(Abv);
724
725 // Abbreviation for TYPE_FUNCTION_PROTO
726 Abv = new BitCodeAbbrev();
727 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_FUNCTION_PROTO));
728 // FunctionType
729 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ReturnType
730 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NoReturn
731 Abv->Add(BitCodeAbbrevOp(0)); // HasRegParm
732 Abv->Add(BitCodeAbbrevOp(0)); // RegParm
733 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // CC
734 Abv->Add(BitCodeAbbrevOp(0)); // ProducesResult
735 // FunctionProtoType
736 Abv->Add(BitCodeAbbrevOp(0)); // IsVariadic
737 Abv->Add(BitCodeAbbrevOp(0)); // HasTrailingReturn
738 Abv->Add(BitCodeAbbrevOp(0)); // TypeQuals
739 Abv->Add(BitCodeAbbrevOp(0)); // RefQualifier
740 Abv->Add(BitCodeAbbrevOp(EST_None)); // ExceptionSpec
741 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // NumParams
742 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
743 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Params
744 TypeFunctionProtoAbbrev = Stream.EmitAbbrev(Abv);
745}
746
Chris Lattner19cea4e2009-04-22 05:57:30 +0000747//===----------------------------------------------------------------------===//
Sebastian Redl55c0ad52010-08-18 23:56:21 +0000748// ASTWriter Implementation
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000749//===----------------------------------------------------------------------===//
750
Chris Lattner28fa4e62009-04-26 22:26:21 +0000751static void EmitBlockID(unsigned ID, const char *Name,
752 llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000753 ASTWriter::RecordDataImpl &Record) {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000754 Record.clear();
755 Record.push_back(ID);
756 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
757
758 // Emit the block name if present.
Craig Toppera13603a2014-05-22 05:54:18 +0000759 if (!Name || Name[0] == 0)
760 return;
Chris Lattner28fa4e62009-04-26 22:26:21 +0000761 Record.clear();
762 while (*Name)
763 Record.push_back(*Name++);
764 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
765}
766
767static void EmitRecordID(unsigned ID, const char *Name,
768 llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000769 ASTWriter::RecordDataImpl &Record) {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000770 Record.clear();
771 Record.push_back(ID);
772 while (*Name)
773 Record.push_back(*Name++);
774 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000775}
776
777static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000778 ASTWriter::RecordDataImpl &Record) {
Sebastian Redl539c5062010-08-18 23:57:32 +0000779#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
Chris Lattnerccac3a62009-04-27 00:49:53 +0000780 RECORD(STMT_STOP);
781 RECORD(STMT_NULL_PTR);
Richard Smith01b2cb42014-07-26 06:37:51 +0000782 RECORD(STMT_REF_PTR);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000783 RECORD(STMT_NULL);
784 RECORD(STMT_COMPOUND);
785 RECORD(STMT_CASE);
786 RECORD(STMT_DEFAULT);
787 RECORD(STMT_LABEL);
Richard Smithc202b282012-04-14 00:33:13 +0000788 RECORD(STMT_ATTRIBUTED);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000789 RECORD(STMT_IF);
790 RECORD(STMT_SWITCH);
791 RECORD(STMT_WHILE);
792 RECORD(STMT_DO);
793 RECORD(STMT_FOR);
794 RECORD(STMT_GOTO);
795 RECORD(STMT_INDIRECT_GOTO);
796 RECORD(STMT_CONTINUE);
797 RECORD(STMT_BREAK);
798 RECORD(STMT_RETURN);
799 RECORD(STMT_DECL);
Chad Rosierde70e0e2012-08-25 00:11:56 +0000800 RECORD(STMT_GCCASM);
Chad Rosiere30d4992012-08-24 23:51:02 +0000801 RECORD(STMT_MSASM);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000802 RECORD(EXPR_PREDEFINED);
803 RECORD(EXPR_DECL_REF);
804 RECORD(EXPR_INTEGER_LITERAL);
805 RECORD(EXPR_FLOATING_LITERAL);
806 RECORD(EXPR_IMAGINARY_LITERAL);
807 RECORD(EXPR_STRING_LITERAL);
808 RECORD(EXPR_CHARACTER_LITERAL);
809 RECORD(EXPR_PAREN);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000810 RECORD(EXPR_PAREN_LIST);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000811 RECORD(EXPR_UNARY_OPERATOR);
812 RECORD(EXPR_SIZEOF_ALIGN_OF);
813 RECORD(EXPR_ARRAY_SUBSCRIPT);
814 RECORD(EXPR_CALL);
815 RECORD(EXPR_MEMBER);
816 RECORD(EXPR_BINARY_OPERATOR);
817 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
818 RECORD(EXPR_CONDITIONAL_OPERATOR);
819 RECORD(EXPR_IMPLICIT_CAST);
820 RECORD(EXPR_CSTYLE_CAST);
821 RECORD(EXPR_COMPOUND_LITERAL);
822 RECORD(EXPR_EXT_VECTOR_ELEMENT);
823 RECORD(EXPR_INIT_LIST);
824 RECORD(EXPR_DESIGNATED_INIT);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000825 RECORD(EXPR_DESIGNATED_INIT_UPDATE);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000826 RECORD(EXPR_IMPLICIT_VALUE_INIT);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000827 RECORD(EXPR_NO_INIT);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000828 RECORD(EXPR_VA_ARG);
829 RECORD(EXPR_ADDR_LABEL);
830 RECORD(EXPR_STMT);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000831 RECORD(EXPR_CHOOSE);
832 RECORD(EXPR_GNU_NULL);
833 RECORD(EXPR_SHUFFLE_VECTOR);
834 RECORD(EXPR_BLOCK);
Peter Collingbourne91147592011-04-15 00:35:48 +0000835 RECORD(EXPR_GENERIC_SELECTION);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000836 RECORD(EXPR_OBJC_STRING_LITERAL);
Patrick Beard0caa3942012-04-19 00:25:12 +0000837 RECORD(EXPR_OBJC_BOXED_EXPRESSION);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000838 RECORD(EXPR_OBJC_ARRAY_LITERAL);
839 RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000840 RECORD(EXPR_OBJC_ENCODE);
841 RECORD(EXPR_OBJC_SELECTOR_EXPR);
842 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
843 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
844 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
845 RECORD(EXPR_OBJC_KVC_REF_EXPR);
846 RECORD(EXPR_OBJC_MESSAGE_EXPR);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000847 RECORD(STMT_OBJC_FOR_COLLECTION);
848 RECORD(STMT_OBJC_CATCH);
849 RECORD(STMT_OBJC_FINALLY);
850 RECORD(STMT_OBJC_AT_TRY);
851 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
852 RECORD(STMT_OBJC_AT_THROW);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000853 RECORD(EXPR_OBJC_BOOL_LITERAL);
Richard Smith01b2cb42014-07-26 06:37:51 +0000854 RECORD(STMT_CXX_CATCH);
855 RECORD(STMT_CXX_TRY);
856 RECORD(STMT_CXX_FOR_RANGE);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000857 RECORD(EXPR_CXX_OPERATOR_CALL);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000858 RECORD(EXPR_CXX_MEMBER_CALL);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000859 RECORD(EXPR_CXX_CONSTRUCT);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000860 RECORD(EXPR_CXX_TEMPORARY_OBJECT);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000861 RECORD(EXPR_CXX_STATIC_CAST);
862 RECORD(EXPR_CXX_DYNAMIC_CAST);
863 RECORD(EXPR_CXX_REINTERPRET_CAST);
864 RECORD(EXPR_CXX_CONST_CAST);
865 RECORD(EXPR_CXX_FUNCTIONAL_CAST);
Richard Smithc67fdd42012-03-07 08:35:16 +0000866 RECORD(EXPR_USER_DEFINED_LITERAL);
Richard Smithcc1b96d2013-06-12 22:31:48 +0000867 RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000868 RECORD(EXPR_CXX_BOOL_LITERAL);
869 RECORD(EXPR_CXX_NULL_PTR_LITERAL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000870 RECORD(EXPR_CXX_TYPEID_EXPR);
871 RECORD(EXPR_CXX_TYPEID_TYPE);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000872 RECORD(EXPR_CXX_THIS);
873 RECORD(EXPR_CXX_THROW);
874 RECORD(EXPR_CXX_DEFAULT_ARG);
Richard Smith01b2cb42014-07-26 06:37:51 +0000875 RECORD(EXPR_CXX_DEFAULT_INIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000876 RECORD(EXPR_CXX_BIND_TEMPORARY);
877 RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
878 RECORD(EXPR_CXX_NEW);
879 RECORD(EXPR_CXX_DELETE);
880 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
881 RECORD(EXPR_EXPR_WITH_CLEANUPS);
882 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
883 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
884 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
885 RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
886 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
Richard Smith01b2cb42014-07-26 06:37:51 +0000887 RECORD(EXPR_CXX_EXPRESSION_TRAIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000888 RECORD(EXPR_CXX_NOEXCEPT);
889 RECORD(EXPR_OPAQUE_VALUE);
Richard Smith01b2cb42014-07-26 06:37:51 +0000890 RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR);
891 RECORD(EXPR_TYPE_TRAIT);
892 RECORD(EXPR_ARRAY_TYPE_TRAIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000893 RECORD(EXPR_PACK_EXPANSION);
894 RECORD(EXPR_SIZEOF_PACK);
Richard Smith01b2cb42014-07-26 06:37:51 +0000895 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000896 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
Richard Smith01b2cb42014-07-26 06:37:51 +0000897 RECORD(EXPR_FUNCTION_PARM_PACK);
898 RECORD(EXPR_MATERIALIZE_TEMPORARY);
Peter Collingbourne41f85462011-02-09 21:07:24 +0000899 RECORD(EXPR_CUDA_KERNEL_CALL);
Richard Smith01b2cb42014-07-26 06:37:51 +0000900 RECORD(EXPR_CXX_UUIDOF_EXPR);
901 RECORD(EXPR_CXX_UUIDOF_TYPE);
902 RECORD(EXPR_LAMBDA);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000903#undef RECORD
Chris Lattner28fa4e62009-04-26 22:26:21 +0000904}
Mike Stump11289f42009-09-09 15:08:12 +0000905
Sebastian Redl55c0ad52010-08-18 23:56:21 +0000906void ASTWriter::WriteBlockInfoBlock() {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000907 RecordData Record;
908 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
Mike Stump11289f42009-09-09 15:08:12 +0000909
Sebastian Redl539c5062010-08-18 23:57:32 +0000910#define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
911#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
Mike Stump11289f42009-09-09 15:08:12 +0000912
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000913 // Control Block.
914 BLOCK(CONTROL_BLOCK);
915 RECORD(METADATA);
Ben Langmuir487ea142014-10-23 18:05:36 +0000916 RECORD(SIGNATURE);
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000917 RECORD(MODULE_NAME);
Richard Smithfa715652015-08-31 22:43:10 +0000918 RECORD(MODULE_DIRECTORY);
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000919 RECORD(MODULE_MAP_FILE);
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000920 RECORD(IMPORTS);
Douglas Gregorfad10d82012-10-18 18:36:53 +0000921 RECORD(ORIGINAL_FILE);
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000922 RECORD(ORIGINAL_PCH_DIR);
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +0000923 RECORD(ORIGINAL_FILE_ID);
Douglas Gregor3120d2c2012-10-22 18:42:04 +0000924 RECORD(INPUT_FILE_OFFSETS);
Richard Smith0516b182015-09-08 19:40:14 +0000925
926 BLOCK(OPTIONS_BLOCK);
927 RECORD(LANGUAGE_OPTIONS);
928 RECORD(TARGET_OPTIONS);
Douglas Gregor8263ffb2012-10-24 15:17:15 +0000929 RECORD(DIAGNOSTIC_OPTIONS);
Douglas Gregorc6317db2012-10-24 15:49:58 +0000930 RECORD(FILE_SYSTEM_OPTIONS);
Douglas Gregor2d302362012-10-24 16:50:34 +0000931 RECORD(HEADER_SEARCH_OPTIONS);
Douglas Gregorb6af6c22012-10-24 20:05:57 +0000932 RECORD(PREPROCESSOR_OPTIONS);
933
Douglas Gregor108cb222012-10-19 00:45:00 +0000934 BLOCK(INPUT_FILES_BLOCK);
935 RECORD(INPUT_FILE);
936
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000937 // AST Top-Level Block.
938 BLOCK(AST_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000939 RECORD(TYPE_OFFSET);
940 RECORD(DECL_OFFSET);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000941 RECORD(IDENTIFIER_OFFSET);
942 RECORD(IDENTIFIER_TABLE);
Ben Langmuir332aafe2014-01-31 01:06:56 +0000943 RECORD(EAGERLY_DESERIALIZED_DECLS);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000944 RECORD(SPECIAL_TYPES);
945 RECORD(STATISTICS);
946 RECORD(TENTATIVE_DEFINITIONS);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000947 RECORD(SELECTOR_OFFSETS);
948 RECORD(METHOD_POOL);
949 RECORD(PP_COUNTER_VALUE);
Douglas Gregor258ae542009-04-27 06:38:32 +0000950 RECORD(SOURCE_LOCATION_OFFSETS);
951 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor61cac2b2009-04-27 20:06:05 +0000952 RECORD(EXT_VECTOR_DECLS);
Richard Smithfa715652015-08-31 22:43:10 +0000953 RECORD(UNUSED_FILESCOPED_DECLS);
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +0000954 RECORD(PPD_ENTITIES_OFFSETS);
Richard Smithfa715652015-08-31 22:43:10 +0000955 RECORD(VTABLE_USES);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +0000956 RECORD(REFERENCED_SELECTOR_POOL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000957 RECORD(TU_UPDATE_LEXICAL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000958 RECORD(SEMA_DECL_REFS);
959 RECORD(WEAK_UNDECLARED_IDENTIFIERS);
960 RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000961 RECORD(UPDATE_VISIBLE);
962 RECORD(DECL_UPDATE_OFFSETS);
963 RECORD(DECL_UPDATES);
964 RECORD(CXX_BASE_SPECIFIER_OFFSETS);
965 RECORD(DIAG_PRAGMA_MAPPINGS);
Peter Collingbourne5df20e02011-02-15 19:46:30 +0000966 RECORD(CUDA_SPECIAL_DECL_REFS);
Douglas Gregor09b69892011-02-10 17:09:37 +0000967 RECORD(HEADER_SEARCH_TABLE);
Peter Collingbourne5df20e02011-02-15 19:46:30 +0000968 RECORD(FP_PRAGMA_OPTIONS);
969 RECORD(OPENCL_EXTENSIONS);
Alexis Hunt27a761d2011-05-04 23:29:54 +0000970 RECORD(DELEGATING_CTORS);
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000971 RECORD(KNOWN_NAMESPACES);
Douglas Gregor78d0b572011-08-04 16:39:39 +0000972 RECORD(MODULE_OFFSET_MAP);
973 RECORD(SOURCE_MANAGER_LINE_TABLE);
Douglas Gregor404cdde2012-01-27 01:47:08 +0000974 RECORD(OBJC_CATEGORIES_MAP);
Douglas Gregor66e4add2011-12-19 21:09:25 +0000975 RECORD(FILE_SORTED_DECLS);
976 RECORD(IMPORTED_MODULES);
Douglas Gregor404cdde2012-01-27 01:47:08 +0000977 RECORD(OBJC_CATEGORIES);
Douglas Gregorcb28f9d2012-10-09 23:05:51 +0000978 RECORD(MACRO_OFFSET);
Richard Smithfa715652015-08-31 22:43:10 +0000979 RECORD(INTERESTING_IDENTIFIERS);
980 RECORD(UNDEFINED_BUT_USED);
Richard Smithe40f2ba2013-08-07 21:41:30 +0000981 RECORD(LATE_PARSED_TEMPLATE);
Dario Domizioli13a0a382014-05-23 12:13:25 +0000982 RECORD(OPTIMIZE_PRAGMA_OPTIONS);
Nico Weber779355f2016-03-02 23:22:00 +0000983 RECORD(MSSTRUCT_PRAGMA_OPTIONS);
Nico Weber42932312016-03-03 00:17:35 +0000984 RECORD(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS);
Richard Smithfa715652015-08-31 22:43:10 +0000985 RECORD(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES);
986 RECORD(CXX_CTOR_INITIALIZERS_OFFSETS);
987 RECORD(DELETE_EXPRS_TO_ANALYZE);
Douglas Gregor358cd442012-01-15 16:58:34 +0000988
Chris Lattner28fa4e62009-04-26 22:26:21 +0000989 // SourceManager Block.
Chris Lattner64031982009-04-27 00:40:25 +0000990 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000991 RECORD(SM_SLOC_FILE_ENTRY);
992 RECORD(SM_SLOC_BUFFER_ENTRY);
993 RECORD(SM_SLOC_BUFFER_BLOB);
Richard Smithaada85c2016-02-06 02:06:43 +0000994 RECORD(SM_SLOC_BUFFER_BLOB_COMPRESSED);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +0000995 RECORD(SM_SLOC_EXPANSION_ENTRY);
Mike Stump11289f42009-09-09 15:08:12 +0000996
Chris Lattner28fa4e62009-04-26 22:26:21 +0000997 // Preprocessor Block.
Chris Lattner64031982009-04-27 00:40:25 +0000998 BLOCK(PREPROCESSOR_BLOCK);
Richard Smithec216502015-02-13 19:48:37 +0000999 RECORD(PP_MACRO_DIRECTIVE_HISTORY);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001000 RECORD(PP_MACRO_FUNCTION_LIKE);
Richard Smithd7329392015-04-21 21:46:32 +00001001 RECORD(PP_MACRO_OBJECT_LIKE);
1002 RECORD(PP_MODULE_MACRO);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001003 RECORD(PP_TOKEN);
Richard Smithec216502015-02-13 19:48:37 +00001004
Richard Smithfa715652015-08-31 22:43:10 +00001005 // Submodule Block.
1006 BLOCK(SUBMODULE_BLOCK);
1007 RECORD(SUBMODULE_METADATA);
1008 RECORD(SUBMODULE_DEFINITION);
1009 RECORD(SUBMODULE_UMBRELLA_HEADER);
1010 RECORD(SUBMODULE_HEADER);
1011 RECORD(SUBMODULE_TOPHEADER);
1012 RECORD(SUBMODULE_UMBRELLA_DIR);
1013 RECORD(SUBMODULE_IMPORTS);
1014 RECORD(SUBMODULE_EXPORTS);
1015 RECORD(SUBMODULE_REQUIRES);
1016 RECORD(SUBMODULE_EXCLUDED_HEADER);
1017 RECORD(SUBMODULE_LINK_LIBRARY);
1018 RECORD(SUBMODULE_CONFIG_MACRO);
1019 RECORD(SUBMODULE_CONFLICT);
1020 RECORD(SUBMODULE_PRIVATE_HEADER);
1021 RECORD(SUBMODULE_TEXTUAL_HEADER);
1022 RECORD(SUBMODULE_PRIVATE_TEXTUAL_HEADER);
1023
1024 // Comments Block.
1025 BLOCK(COMMENTS_BLOCK);
1026 RECORD(COMMENTS_RAW_COMMENT);
1027
Douglas Gregor12bfa382009-10-17 00:13:19 +00001028 // Decls and Types block.
1029 BLOCK(DECLTYPES_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001030 RECORD(TYPE_EXT_QUAL);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001031 RECORD(TYPE_COMPLEX);
1032 RECORD(TYPE_POINTER);
1033 RECORD(TYPE_BLOCK_POINTER);
1034 RECORD(TYPE_LVALUE_REFERENCE);
1035 RECORD(TYPE_RVALUE_REFERENCE);
1036 RECORD(TYPE_MEMBER_POINTER);
1037 RECORD(TYPE_CONSTANT_ARRAY);
1038 RECORD(TYPE_INCOMPLETE_ARRAY);
1039 RECORD(TYPE_VARIABLE_ARRAY);
1040 RECORD(TYPE_VECTOR);
1041 RECORD(TYPE_EXT_VECTOR);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001042 RECORD(TYPE_FUNCTION_NO_PROTO);
Richard Smithf1b4b8b2014-07-27 04:29:04 +00001043 RECORD(TYPE_FUNCTION_PROTO);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001044 RECORD(TYPE_TYPEDEF);
1045 RECORD(TYPE_TYPEOF_EXPR);
1046 RECORD(TYPE_TYPEOF);
1047 RECORD(TYPE_RECORD);
1048 RECORD(TYPE_ENUM);
1049 RECORD(TYPE_OBJC_INTERFACE);
Steve Narofffb4330f2009-06-17 22:40:22 +00001050 RECORD(TYPE_OBJC_OBJECT_POINTER);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001051 RECORD(TYPE_DECLTYPE);
1052 RECORD(TYPE_ELABORATED);
1053 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
1054 RECORD(TYPE_UNRESOLVED_USING);
1055 RECORD(TYPE_INJECTED_CLASS_NAME);
1056 RECORD(TYPE_OBJC_OBJECT);
1057 RECORD(TYPE_TEMPLATE_TYPE_PARM);
1058 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
1059 RECORD(TYPE_DEPENDENT_NAME);
1060 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
1061 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
1062 RECORD(TYPE_PAREN);
1063 RECORD(TYPE_PACK_EXPANSION);
1064 RECORD(TYPE_ATTRIBUTED);
1065 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
Richard Smithf1b4b8b2014-07-27 04:29:04 +00001066 RECORD(TYPE_AUTO);
1067 RECORD(TYPE_UNARY_TRANSFORM);
Eli Friedman0dfb8892011-10-06 23:00:33 +00001068 RECORD(TYPE_ATOMIC);
Richard Smithf1b4b8b2014-07-27 04:29:04 +00001069 RECORD(TYPE_DECAYED);
1070 RECORD(TYPE_ADJUSTED);
Richard Smithd61d4ac2015-08-22 20:13:39 +00001071 RECORD(LOCAL_REDECLARATIONS);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001072 RECORD(DECL_TYPEDEF);
Richard Smith01b2cb42014-07-26 06:37:51 +00001073 RECORD(DECL_TYPEALIAS);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001074 RECORD(DECL_ENUM);
1075 RECORD(DECL_RECORD);
1076 RECORD(DECL_ENUM_CONSTANT);
1077 RECORD(DECL_FUNCTION);
1078 RECORD(DECL_OBJC_METHOD);
1079 RECORD(DECL_OBJC_INTERFACE);
1080 RECORD(DECL_OBJC_PROTOCOL);
1081 RECORD(DECL_OBJC_IVAR);
1082 RECORD(DECL_OBJC_AT_DEFS_FIELD);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001083 RECORD(DECL_OBJC_CATEGORY);
1084 RECORD(DECL_OBJC_CATEGORY_IMPL);
1085 RECORD(DECL_OBJC_IMPLEMENTATION);
1086 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
1087 RECORD(DECL_OBJC_PROPERTY);
1088 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001089 RECORD(DECL_FIELD);
John McCall5e77d762013-04-16 07:28:30 +00001090 RECORD(DECL_MS_PROPERTY);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001091 RECORD(DECL_VAR);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001092 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001093 RECORD(DECL_PARM_VAR);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001094 RECORD(DECL_FILE_SCOPE_ASM);
1095 RECORD(DECL_BLOCK);
1096 RECORD(DECL_CONTEXT_LEXICAL);
1097 RECORD(DECL_CONTEXT_VISIBLE);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001098 RECORD(DECL_NAMESPACE);
1099 RECORD(DECL_NAMESPACE_ALIAS);
1100 RECORD(DECL_USING);
1101 RECORD(DECL_USING_SHADOW);
1102 RECORD(DECL_USING_DIRECTIVE);
1103 RECORD(DECL_UNRESOLVED_USING_VALUE);
1104 RECORD(DECL_UNRESOLVED_USING_TYPENAME);
1105 RECORD(DECL_LINKAGE_SPEC);
1106 RECORD(DECL_CXX_RECORD);
1107 RECORD(DECL_CXX_METHOD);
1108 RECORD(DECL_CXX_CONSTRUCTOR);
1109 RECORD(DECL_CXX_DESTRUCTOR);
1110 RECORD(DECL_CXX_CONVERSION);
1111 RECORD(DECL_ACCESS_SPEC);
1112 RECORD(DECL_FRIEND);
1113 RECORD(DECL_FRIEND_TEMPLATE);
1114 RECORD(DECL_CLASS_TEMPLATE);
1115 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
1116 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001117 RECORD(DECL_VAR_TEMPLATE);
1118 RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
1119 RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001120 RECORD(DECL_FUNCTION_TEMPLATE);
1121 RECORD(DECL_TEMPLATE_TYPE_PARM);
1122 RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
1123 RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
Richard Smithefc884a2016-04-13 07:41:35 +00001124 RECORD(DECL_TYPE_ALIAS_TEMPLATE);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001125 RECORD(DECL_STATIC_ASSERT);
1126 RECORD(DECL_CXX_BASE_SPECIFIERS);
Richard Smithefc884a2016-04-13 07:41:35 +00001127 RECORD(DECL_CXX_CTOR_INITIALIZERS);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001128 RECORD(DECL_INDIRECTFIELD);
1129 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
Richard Smithefc884a2016-04-13 07:41:35 +00001130 RECORD(DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK);
1131 RECORD(DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION);
1132 RECORD(DECL_IMPORT);
1133 RECORD(DECL_OMP_THREADPRIVATE);
1134 RECORD(DECL_EMPTY);
1135 RECORD(DECL_OBJC_TYPE_PARAM);
1136 RECORD(DECL_OMP_CAPTUREDEXPR);
1137 RECORD(DECL_PRAGMA_COMMENT);
1138 RECORD(DECL_PRAGMA_DETECT_MISMATCH);
1139 RECORD(DECL_OMP_DECLARE_REDUCTION);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001140
Douglas Gregor03412ba2011-06-03 02:27:19 +00001141 // Statements and Exprs can occur in the Decls and Types block.
1142 AddStmtsExprs(Stream, Record);
1143
Douglas Gregor92a96f52011-02-08 21:58:10 +00001144 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001145 RECORD(PPD_MACRO_EXPANSION);
Douglas Gregor92a96f52011-02-08 21:58:10 +00001146 RECORD(PPD_MACRO_DEFINITION);
1147 RECORD(PPD_INCLUSION_DIRECTIVE);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00001148
1149 // Decls and Types block.
1150 BLOCK(EXTENSION_BLOCK);
1151 RECORD(EXTENSION_METADATA);
1152
Chris Lattner28fa4e62009-04-26 22:26:21 +00001153#undef RECORD
1154#undef BLOCK
1155 Stream.ExitBlock();
1156}
1157
Richard Smith54cc3c22014-12-11 20:50:24 +00001158/// \brief Prepares a path for being written to an AST file by converting it
1159/// to an absolute path and removing nested './'s.
1160///
1161/// \return \c true if the path was changed.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001162static bool cleanPathForOutput(FileManager &FileMgr,
1163 SmallVectorImpl<char> &Path) {
Argyrios Kyrtzidis403cbcb2015-07-31 01:39:23 +00001164 bool Changed = FileMgr.makeAbsolutePath(Path);
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +00001165 return Changed | llvm::sys::path::remove_dots(Path);
Richard Smith54cc3c22014-12-11 20:50:24 +00001166}
1167
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001168/// \brief Adjusts the given filename to only write out the portion of the
1169/// filename that is not part of the system root directory.
Mike Stump11289f42009-09-09 15:08:12 +00001170///
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001171/// \param Filename the file name to adjust.
1172///
Richard Smith7ed1bc92014-12-05 22:42:13 +00001173/// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
1174/// the returned filename will be adjusted by this root directory.
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001175///
1176/// \returns either the original filename (if it needs no adjustment) or the
1177/// adjusted filename (which points into the @p Filename parameter).
Mike Stump11289f42009-09-09 15:08:12 +00001178static const char *
Richard Smith7ed1bc92014-12-05 22:42:13 +00001179adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001180 assert(Filename && "No file name to adjust?");
Mike Stump11289f42009-09-09 15:08:12 +00001181
Richard Smith7ed1bc92014-12-05 22:42:13 +00001182 if (BaseDir.empty())
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001183 return Filename;
Mike Stump11289f42009-09-09 15:08:12 +00001184
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001185 // Verify that the filename and the system root have the same prefix.
1186 unsigned Pos = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001187 for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
1188 if (Filename[Pos] != BaseDir[Pos])
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001189 return Filename; // Prefixes don't match.
Mike Stump11289f42009-09-09 15:08:12 +00001190
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001191 // We hit the end of the filename before we hit the end of the system root.
1192 if (!Filename[Pos])
1193 return Filename;
Mike Stump11289f42009-09-09 15:08:12 +00001194
Richard Smith7ed1bc92014-12-05 22:42:13 +00001195 // If there's not a path separator at the end of the base directory nor
1196 // immediately after it, then this isn't within the base directory.
1197 if (!llvm::sys::path::is_separator(Filename[Pos])) {
1198 if (!llvm::sys::path::is_separator(BaseDir.back()))
1199 return Filename;
1200 } else {
1201 // If the file name has a '/' at the current position, skip over the '/'.
1202 // We distinguish relative paths from absolute paths by the
1203 // absence of '/' at the beginning of relative paths.
1204 //
1205 // FIXME: This is wrong. We distinguish them by asking if the path is
1206 // absolute, which isn't the same thing. And there might be multiple '/'s
1207 // in a row. Use a better mechanism to indicate whether we have emitted an
1208 // absolute or relative path.
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001209 ++Pos;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001210 }
Mike Stump11289f42009-09-09 15:08:12 +00001211
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001212 return Filename + Pos;
1213}
Chris Lattner28fa4e62009-04-26 22:26:21 +00001214
Ben Langmuir487ea142014-10-23 18:05:36 +00001215static ASTFileSignature getSignature() {
1216 while (1) {
1217 if (ASTFileSignature S = llvm::sys::Process::GetRandomNumber())
1218 return S;
1219 // Rely on GetRandomNumber to eventually return non-zero...
1220 }
1221}
1222
Douglas Gregor112b9072012-10-18 05:31:06 +00001223/// \brief Write the control block.
Adrian Prantladbd2b12015-09-22 23:26:31 +00001224uint64_t ASTWriter::WriteControlBlock(Preprocessor &PP,
1225 ASTContext &Context,
1226 StringRef isysroot,
1227 const std::string &OutputFile) {
1228 ASTFileSignature Signature = 0;
1229
Douglas Gregorbfbde532009-04-10 21:16:55 +00001230 using namespace llvm;
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001231 Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001232 RecordData Record;
1233
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001234 // Metadata
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001235 auto *MetadataAbbrev = new BitCodeAbbrev();
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001236 MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1237 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1238 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1239 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1240 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1241 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
Richard Smithe75ee0f2015-08-17 07:13:32 +00001242 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001243 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1244 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1245 unsigned MetadataAbbrevCode = Stream.EmitAbbrev(MetadataAbbrev);
Richard Smith7ed1bc92014-12-05 22:42:13 +00001246 assert((!WritingModule || isysroot.empty()) &&
1247 "writing module as a relocatable PCH?");
Mehdi Amini57a41912015-09-10 01:46:39 +00001248 {
1249 RecordData::value_type Record[] = {METADATA, VERSION_MAJOR, VERSION_MINOR,
1250 CLANG_VERSION_MAJOR, CLANG_VERSION_MINOR,
1251 !isysroot.empty(), IncludeTimestamps,
1252 ASTHasCompilerErrors};
1253 Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1254 getClangFullRepositoryVersion());
1255 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001256 if (WritingModule) {
Chandler Carruth885e78c2015-03-24 21:18:10 +00001257 // For implicit modules we output a signature that we can use to ensure
1258 // duplicate module builds don't collide in the cache as their output order
1259 // is non-deterministic.
1260 // FIXME: Remove this when output is deterministic.
1261 if (Context.getLangOpts().ImplicitModules) {
Adrian Prantladbd2b12015-09-22 23:26:31 +00001262 Signature = getSignature();
1263 RecordData::value_type Record[] = {Signature};
Chandler Carruth885e78c2015-03-24 21:18:10 +00001264 Stream.EmitRecord(SIGNATURE, Record);
1265 }
1266
Richard Smith7ed1bc92014-12-05 22:42:13 +00001267 // Module name
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001268 auto *Abbrev = new BitCodeAbbrev();
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001269 Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1270 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1271 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00001272 RecordData::value_type Record[] = {MODULE_NAME};
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001273 Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1274 }
1275
Richard Smith7ed1bc92014-12-05 22:42:13 +00001276 if (WritingModule && WritingModule->Directory) {
Richard Smith7ed1bc92014-12-05 22:42:13 +00001277 SmallString<128> BaseDir(WritingModule->Directory->getName());
Richard Smith54cc3c22014-12-11 20:50:24 +00001278 cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
Richard Smithf7b41372015-08-13 23:47:44 +00001279
1280 // If the home of the module is the current working directory, then we
1281 // want to pick up the cwd of the build process loading the module, not
1282 // our cwd, when we load this module.
1283 if (!PP.getHeaderSearchInfo()
1284 .getHeaderSearchOpts()
1285 .ModuleMapFileHomeIsCwd ||
1286 WritingModule->Directory->getName() != StringRef(".")) {
1287 // Module directory.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001288 auto *Abbrev = new BitCodeAbbrev();
Richard Smithf7b41372015-08-13 23:47:44 +00001289 Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1290 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
1291 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1292
Mehdi Amini57a41912015-09-10 01:46:39 +00001293 RecordData::value_type Record[] = {MODULE_DIRECTORY};
Richard Smithf7b41372015-08-13 23:47:44 +00001294 Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
1295 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001296
1297 // Write out all other paths relative to the base directory if possible.
1298 BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1299 } else if (!isysroot.empty()) {
1300 // Write out paths relative to the sysroot if possible.
1301 BaseDirectory = isysroot;
1302 }
1303
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001304 // Module map file
1305 if (WritingModule) {
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001306 Record.clear();
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001307
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001308 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
1309
1310 // Primary module map file.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001311 AddPath(Map.getModuleMapFileForUniquing(WritingModule)->getName(), Record);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001312
1313 // Additional module map files.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001314 if (auto *AdditionalModMaps =
1315 Map.getAdditionalModuleMapFiles(WritingModule)) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001316 Record.push_back(AdditionalModMaps->size());
1317 for (const FileEntry *F : *AdditionalModMaps)
Richard Smith7ed1bc92014-12-05 22:42:13 +00001318 AddPath(F->getName(), Record);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001319 } else {
1320 Record.push_back(0);
1321 }
1322
1323 Stream.EmitRecord(MODULE_MAP_FILE, Record);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001324 }
1325
Douglas Gregor112b9072012-10-18 05:31:06 +00001326 // Imports
Douglas Gregor29cc6422011-08-17 21:07:30 +00001327 if (Chain) {
Douglas Gregor29cc6422011-08-17 21:07:30 +00001328 serialization::ModuleManager &Mgr = Chain->getModuleManager();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001329 Record.clear();
Douglas Gregordf0c1512011-08-18 04:12:04 +00001330
Richard Smith7f330cd2015-03-18 01:42:29 +00001331 for (auto *M : Mgr) {
Douglas Gregordf0c1512011-08-18 04:12:04 +00001332 // Skip modules that weren't directly imported.
Richard Smith7f330cd2015-03-18 01:42:29 +00001333 if (!M->isDirectlyImported())
Douglas Gregordf0c1512011-08-18 04:12:04 +00001334 continue;
1335
Richard Smith7f330cd2015-03-18 01:42:29 +00001336 Record.push_back((unsigned)M->Kind); // FIXME: Stable encoding
1337 AddSourceLocation(M->ImportLoc, Record);
1338 Record.push_back(M->File->getSize());
Richard Smithe75ee0f2015-08-17 07:13:32 +00001339 Record.push_back(getTimestampForOutput(M->File));
Richard Smith7f330cd2015-03-18 01:42:29 +00001340 Record.push_back(M->Signature);
1341 AddPath(M->FileName, Record);
Douglas Gregordf0c1512011-08-18 04:12:04 +00001342 }
Douglas Gregor29cc6422011-08-17 21:07:30 +00001343 Stream.EmitRecord(IMPORTS, Record);
1344 }
Mike Stump11289f42009-09-09 15:08:12 +00001345
Richard Smith0516b182015-09-08 19:40:14 +00001346 // Write the options block.
1347 Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
1348
Douglas Gregor112b9072012-10-18 05:31:06 +00001349 // Language options.
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001350 Record.clear();
Douglas Gregor112b9072012-10-18 05:31:06 +00001351 const LangOptions &LangOpts = Context.getLangOpts();
1352#define LANGOPT(Name, Bits, Default, Description) \
1353 Record.push_back(LangOpts.Name);
1354#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1355 Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001356#include "clang/Basic/LangOptions.def"
1357#define SANITIZER(NAME, ID) \
1358 Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
Will Dietzf54319c2013-01-18 11:30:38 +00001359#include "clang/Basic/Sanitizers.def"
Douglas Gregor112b9072012-10-18 05:31:06 +00001360
Ben Langmuircd98cb72015-06-23 18:20:18 +00001361 Record.push_back(LangOpts.ModuleFeatures.size());
1362 for (StringRef Feature : LangOpts.ModuleFeatures)
1363 AddString(Feature, Record);
1364
Douglas Gregor112b9072012-10-18 05:31:06 +00001365 Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1366 AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
Ben Langmuird4a667a2015-06-23 18:20:23 +00001367
1368 AddString(LangOpts.CurrentModule, Record);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001369
1370 // Comment options.
1371 Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001372 for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1373 AddString(I, Record);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001374 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00001375 Record.push_back(LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001376
Samuel Antaoee8fb302016-01-06 13:42:12 +00001377 // OpenMP offloading options.
1378 Record.push_back(LangOpts.OMPTargetTriples.size());
1379 for (auto &T : LangOpts.OMPTargetTriples)
1380 AddString(T.getTriple(), Record);
1381
1382 AddString(LangOpts.OMPHostIRFile, Record);
1383
Douglas Gregor112b9072012-10-18 05:31:06 +00001384 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1385
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001386 // Target options.
1387 Record.clear();
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001388 const TargetInfo &Target = Context.getTargetInfo();
1389 const TargetOptions &TargetOpts = Target.getTargetOpts();
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001390 AddString(TargetOpts.Triple, Record);
1391 AddString(TargetOpts.CPU, Record);
1392 AddString(TargetOpts.ABI, Record);
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001393 Record.push_back(TargetOpts.FeaturesAsWritten.size());
1394 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1395 AddString(TargetOpts.FeaturesAsWritten[I], Record);
1396 }
1397 Record.push_back(TargetOpts.Features.size());
1398 for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1399 AddString(TargetOpts.Features[I], Record);
1400 }
1401 Stream.EmitRecord(TARGET_OPTIONS, Record);
1402
Douglas Gregor8263ffb2012-10-24 15:17:15 +00001403 // Diagnostic options.
1404 Record.clear();
1405 const DiagnosticOptions &DiagOpts
1406 = Context.getDiagnostics().getDiagnosticOptions();
1407#define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1408#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1409 Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1410#include "clang/Basic/DiagnosticOptions.def"
1411 Record.push_back(DiagOpts.Warnings.size());
1412 for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1413 AddString(DiagOpts.Warnings[I], Record);
Richard Smith3be1cb22014-08-07 00:24:21 +00001414 Record.push_back(DiagOpts.Remarks.size());
1415 for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1416 AddString(DiagOpts.Remarks[I], Record);
Douglas Gregor8263ffb2012-10-24 15:17:15 +00001417 // Note: we don't serialize the log or serialization file names, because they
1418 // are generally transient files and will almost always be overridden.
1419 Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1420
Douglas Gregorc6317db2012-10-24 15:49:58 +00001421 // File system options.
1422 Record.clear();
Yaron Keren8dec46c2015-08-26 08:10:22 +00001423 const FileSystemOptions &FSOpts =
1424 Context.getSourceManager().getFileManager().getFileSystemOpts();
Douglas Gregorc6317db2012-10-24 15:49:58 +00001425 AddString(FSOpts.WorkingDir, Record);
1426 Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1427
Douglas Gregor2d302362012-10-24 16:50:34 +00001428 // Header search options.
1429 Record.clear();
1430 const HeaderSearchOptions &HSOpts
1431 = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1432 AddString(HSOpts.Sysroot, Record);
1433
1434 // Include entries.
1435 Record.push_back(HSOpts.UserEntries.size());
1436 for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1437 const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1438 AddString(Entry.Path, Record);
1439 Record.push_back(static_cast<unsigned>(Entry.Group));
Douglas Gregor2d302362012-10-24 16:50:34 +00001440 Record.push_back(Entry.IsFramework);
1441 Record.push_back(Entry.IgnoreSysRoot);
Douglas Gregor2d302362012-10-24 16:50:34 +00001442 }
1443
1444 // System header prefixes.
1445 Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1446 for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1447 AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1448 Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1449 }
1450
1451 AddString(HSOpts.ResourceDir, Record);
1452 AddString(HSOpts.ModuleCachePath, Record);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00001453 AddString(HSOpts.ModuleUserBuildPath, Record);
Douglas Gregor2d302362012-10-24 16:50:34 +00001454 Record.push_back(HSOpts.DisableModuleHash);
1455 Record.push_back(HSOpts.UseBuiltinIncludes);
1456 Record.push_back(HSOpts.UseStandardSystemIncludes);
1457 Record.push_back(HSOpts.UseStandardCXXIncludes);
1458 Record.push_back(HSOpts.UseLibcxx);
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00001459 // Write out the specific module cache path that contains the module files.
1460 AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
Douglas Gregor2d302362012-10-24 16:50:34 +00001461 Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1462
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001463 // Preprocessor options.
1464 Record.clear();
1465 const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1466
1467 // Macro definitions.
1468 Record.push_back(PPOpts.Macros.size());
1469 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1470 AddString(PPOpts.Macros[I].first, Record);
1471 Record.push_back(PPOpts.Macros[I].second);
1472 }
1473
1474 // Includes
1475 Record.push_back(PPOpts.Includes.size());
1476 for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1477 AddString(PPOpts.Includes[I], Record);
1478
1479 // Macro includes
1480 Record.push_back(PPOpts.MacroIncludes.size());
1481 for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1482 AddString(PPOpts.MacroIncludes[I], Record);
1483
Douglas Gregorb6368752012-10-24 23:41:50 +00001484 Record.push_back(PPOpts.UsePredefines);
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00001485 // Detailed record is important since it is used for the module cache hash.
1486 Record.push_back(PPOpts.DetailedRecord);
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001487 AddString(PPOpts.ImplicitPCHInclude, Record);
1488 AddString(PPOpts.ImplicitPTHInclude, Record);
1489 Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1490 Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1491
Richard Smith0516b182015-09-08 19:40:14 +00001492 // Leave the options block.
1493 Stream.ExitBlock();
1494
Douglas Gregora3b20262011-05-06 21:43:30 +00001495 // Original file name and file ID
Douglas Gregor45fe0362009-05-12 01:31:05 +00001496 SourceManager &SM = Context.getSourceManager();
1497 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001498 auto *FileAbbrev = new BitCodeAbbrev();
Douglas Gregorfad10d82012-10-18 18:36:53 +00001499 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1500 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
Douglas Gregor45fe0362009-05-12 01:31:05 +00001501 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1502 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
1503
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001504 Record.clear();
Douglas Gregorfad10d82012-10-18 18:36:53 +00001505 Record.push_back(ORIGINAL_FILE);
Douglas Gregora3b20262011-05-06 21:43:30 +00001506 Record.push_back(SM.getMainFileID().getOpaqueValue());
Richard Smith7ed1bc92014-12-05 22:42:13 +00001507 EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
Douglas Gregor45fe0362009-05-12 01:31:05 +00001508 }
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00001509
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +00001510 Record.clear();
1511 Record.push_back(SM.getMainFileID().getOpaqueValue());
1512 Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1513
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001514 // Original PCH directory
1515 if (!OutputFile.empty() && OutputFile != "-") {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001516 auto *Abbrev = new BitCodeAbbrev();
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001517 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1518 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1519 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1520
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001521 SmallString<128> OutputPath(OutputFile);
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001522
Argyrios Kyrtzidisc56419e2015-07-31 00:58:32 +00001523 SM.getFileManager().makeAbsolutePath(OutputPath);
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001524 StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1525
Mehdi Amini57a41912015-09-10 01:46:39 +00001526 RecordData::value_type Record[] = {ORIGINAL_PCH_DIR};
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001527 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1528 }
1529
Douglas Gregor49491f72013-03-15 22:15:07 +00001530 WriteInputFiles(Context.SourceMgr,
1531 PP.getHeaderSearchInfo().getHeaderSearchOpts(),
Douglas Gregora3dd9002013-07-22 20:48:33 +00001532 PP.getLangOpts().Modules);
Douglas Gregor72be3902012-10-19 00:38:02 +00001533 Stream.ExitBlock();
Adrian Prantladbd2b12015-09-22 23:26:31 +00001534 return Signature;
Douglas Gregor72be3902012-10-19 00:38:02 +00001535}
1536
Douglas Gregor49491f72013-03-15 22:15:07 +00001537namespace {
1538 /// \brief An input file.
1539 struct InputFileEntry {
1540 const FileEntry *File;
1541 bool IsSystemFile;
Richard Smitha8cfffa2015-11-26 02:04:16 +00001542 bool IsTransient;
Douglas Gregor49491f72013-03-15 22:15:07 +00001543 bool BufferOverridden;
1544 };
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001545} // end anonymous namespace
Douglas Gregor49491f72013-03-15 22:15:07 +00001546
1547void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1548 HeaderSearchOptions &HSOpts,
Douglas Gregora3dd9002013-07-22 20:48:33 +00001549 bool Modules) {
Douglas Gregor72be3902012-10-19 00:38:02 +00001550 using namespace llvm;
1551 Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
Mehdi Amini57a41912015-09-10 01:46:39 +00001552
Douglas Gregor72be3902012-10-19 00:38:02 +00001553 // Create input-file abbreviation.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001554 auto *IFAbbrev = new BitCodeAbbrev();
Douglas Gregor72be3902012-10-19 00:38:02 +00001555 IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001556 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
Douglas Gregor72be3902012-10-19 00:38:02 +00001557 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1558 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001559 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
Richard Smitha8cfffa2015-11-26 02:04:16 +00001560 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
Douglas Gregor72be3902012-10-19 00:38:02 +00001561 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1562 unsigned IFAbbrevCode = Stream.EmitAbbrev(IFAbbrev);
1563
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001564 // Get all ContentCache objects for files, sorted by whether the file is a
1565 // system one or not. System files go at the back, users files at the front.
Douglas Gregor49491f72013-03-15 22:15:07 +00001566 std::deque<InputFileEntry> SortedFiles;
Douglas Gregor72be3902012-10-19 00:38:02 +00001567 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1568 // Get this source location entry.
1569 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
NAKAMURA Takumideca50f2012-10-19 01:53:57 +00001570 assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
Douglas Gregor72be3902012-10-19 00:38:02 +00001571
1572 // We only care about file entries that were not overridden.
1573 if (!SLoc->isFile())
1574 continue;
1575 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001576 if (!Cache->OrigEntry)
Douglas Gregor72be3902012-10-19 00:38:02 +00001577 continue;
1578
Douglas Gregor49491f72013-03-15 22:15:07 +00001579 InputFileEntry Entry;
1580 Entry.File = Cache->OrigEntry;
1581 Entry.IsSystemFile = Cache->IsSystemFile;
Richard Smitha8cfffa2015-11-26 02:04:16 +00001582 Entry.IsTransient = Cache->IsTransient;
Douglas Gregor49491f72013-03-15 22:15:07 +00001583 Entry.BufferOverridden = Cache->BufferOverridden;
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001584 if (Cache->IsSystemFile)
Douglas Gregor49491f72013-03-15 22:15:07 +00001585 SortedFiles.push_back(Entry);
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001586 else
Douglas Gregor49491f72013-03-15 22:15:07 +00001587 SortedFiles.push_front(Entry);
1588 }
1589
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001590 unsigned UserFilesNum = 0;
1591 // Write out all of the input files.
Richard Smithec216502015-02-13 19:48:37 +00001592 std::vector<uint64_t> InputFileOffsets;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001593 for (const auto &Entry : SortedFiles) {
Douglas Gregor49491f72013-03-15 22:15:07 +00001594 uint32_t &InputFileID = InputFileIDs[Entry.File];
Argyrios Kyrtzidise65856f2012-12-11 07:48:08 +00001595 if (InputFileID != 0)
1596 continue; // already recorded this file.
1597
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001598 // Record this entry's offset.
1599 InputFileOffsets.push_back(Stream.GetCurrentBitNo());
Argyrios Kyrtzidise65856f2012-12-11 07:48:08 +00001600
1601 InputFileID = InputFileOffsets.size();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001602
Douglas Gregor49491f72013-03-15 22:15:07 +00001603 if (!Entry.IsSystemFile)
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001604 ++UserFilesNum;
1605
Douglas Gregor72be3902012-10-19 00:38:02 +00001606 // Emit size/modification time for this file.
Mehdi Amini57a41912015-09-10 01:46:39 +00001607 // And whether this file was overridden.
1608 RecordData::value_type Record[] = {
Richard Smitha8cfffa2015-11-26 02:04:16 +00001609 INPUT_FILE,
1610 InputFileOffsets.size(),
1611 (uint64_t)Entry.File->getSize(),
1612 (uint64_t)getTimestampForOutput(Entry.File),
1613 Entry.BufferOverridden,
1614 Entry.IsTransient};
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001615
Richard Smith7ed1bc92014-12-05 22:42:13 +00001616 EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
1617 }
Douglas Gregor49491f72013-03-15 22:15:07 +00001618
Douglas Gregor112b9072012-10-18 05:31:06 +00001619 Stream.ExitBlock();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001620
1621 // Create input file offsets abbreviation.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001622 auto *OffsetsAbbrev = new BitCodeAbbrev();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001623 OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1624 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001625 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1626 // input files
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001627 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
1628 unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(OffsetsAbbrev);
1629
1630 // Write input file offsets.
Mehdi Amini57a41912015-09-10 01:46:39 +00001631 RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
1632 InputFileOffsets.size(), UserFilesNum};
Reid Kleckner012665e2015-05-21 00:13:09 +00001633 Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
Douglas Gregor55abb232009-04-10 20:39:37 +00001634}
1635
Douglas Gregora7f71a92009-04-10 03:52:48 +00001636//===----------------------------------------------------------------------===//
1637// Source Manager Serialization
1638//===----------------------------------------------------------------------===//
1639
1640/// \brief Create an abbreviation for the SLocEntry that refers to a
1641/// file.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001642static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001643 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001644
1645 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00001646 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001647 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1648 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1649 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1650 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregorb41ca8f2010-03-21 22:49:54 +00001651 // FileEntry fields.
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001652 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001653 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00001654 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1655 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
Douglas Gregor8f45df52009-04-16 22:23:12 +00001656 return Stream.EmitAbbrev(Abbrev);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001657}
1658
1659/// \brief Create an abbreviation for the SLocEntry that refers to a
1660/// buffer.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001661static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001662 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001663
1664 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00001665 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001666 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1667 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1668 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1669 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1670 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregor8f45df52009-04-16 22:23:12 +00001671 return Stream.EmitAbbrev(Abbrev);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001672}
1673
1674/// \brief Create an abbreviation for the SLocEntry that refers to a
1675/// buffer's blob.
Richard Smithaada85c2016-02-06 02:06:43 +00001676static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
1677 bool Compressed) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001678 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001679
1680 auto *Abbrev = new BitCodeAbbrev();
Richard Smithaada85c2016-02-06 02:06:43 +00001681 Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED
1682 : SM_SLOC_BUFFER_BLOB));
1683 if (Compressed)
1684 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
Douglas Gregora7f71a92009-04-10 03:52:48 +00001685 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregor8f45df52009-04-16 22:23:12 +00001686 return Stream.EmitAbbrev(Abbrev);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001687}
1688
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001689/// \brief Create an abbreviation for the SLocEntry that refers to a macro
1690/// expansion.
1691static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001692 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001693
1694 auto *Abbrev = new BitCodeAbbrev();
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001695 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001696 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1697 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1698 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1699 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregor83243272009-04-15 18:05:10 +00001700 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregor8f45df52009-04-16 22:23:12 +00001701 return Stream.EmitAbbrev(Abbrev);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001702}
1703
Douglas Gregor09b69892011-02-10 17:09:37 +00001704namespace {
1705 // Trait used for the on-disk hash table of header search information.
1706 class HeaderFileInfoTrait {
1707 ASTWriter &Writer;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001708 const HeaderSearch &HS;
Douglas Gregor09b69892011-02-10 17:09:37 +00001709
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001710 // Keep track of the framework names we've used during serialization.
1711 SmallVector<char, 128> FrameworkStringData;
1712 llvm::StringMap<unsigned> FrameworkNameOffset;
1713
Douglas Gregor09b69892011-02-10 17:09:37 +00001714 public:
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001715 HeaderFileInfoTrait(ASTWriter &Writer, const HeaderSearch &HS)
1716 : Writer(Writer), HS(HS) { }
Douglas Gregor09b69892011-02-10 17:09:37 +00001717
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001718 struct key_type {
1719 const FileEntry *FE;
1720 const char *Filename;
1721 };
1722 typedef const key_type &key_type_ref;
Douglas Gregor09b69892011-02-10 17:09:37 +00001723
1724 typedef HeaderFileInfo data_type;
1725 typedef const data_type &data_type_ref;
Justin Bogner25463f12014-04-18 20:27:24 +00001726 typedef unsigned hash_value_type;
1727 typedef unsigned offset_type;
Douglas Gregor09b69892011-02-10 17:09:37 +00001728
Richard Smithe75ee0f2015-08-17 07:13:32 +00001729 hash_value_type ComputeHash(key_type_ref key) {
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001730 // The hash is based only on size/time of the file, so that the reader can
1731 // match even when symlinking or excess path elements ("foo/../", "../")
1732 // change the form of the name. However, complete path is still the key.
1733 return llvm::hash_combine(key.FE->getSize(),
Richard Smithe75ee0f2015-08-17 07:13:32 +00001734 Writer.getTimestampForOutput(key.FE));
Douglas Gregor09b69892011-02-10 17:09:37 +00001735 }
1736
1737 std::pair<unsigned,unsigned>
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001738 EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001739 using namespace llvm::support;
Richard Smith386bb072015-08-18 23:42:23 +00001740 endian::Writer<little> LE(Out);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001741 unsigned KeyLen = strlen(key.Filename) + 1 + 8 + 8;
Richard Smith386bb072015-08-18 23:42:23 +00001742 LE.write<uint16_t>(KeyLen);
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001743 unsigned DataLen = 1 + 2 + 4 + 4;
Richard Smith386bb072015-08-18 23:42:23 +00001744 for (auto ModInfo : HS.getModuleMap().findAllModulesForHeader(key.FE))
1745 if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
1746 DataLen += 4;
1747 LE.write<uint8_t>(DataLen);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001748 return std::make_pair(KeyLen, DataLen);
Douglas Gregor09b69892011-02-10 17:09:37 +00001749 }
1750
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001751 void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001752 using namespace llvm::support;
1753 endian::Writer<little> LE(Out);
1754 LE.write<uint64_t>(key.FE->getSize());
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001755 KeyLen -= 8;
Richard Smithe75ee0f2015-08-17 07:13:32 +00001756 LE.write<uint64_t>(Writer.getTimestampForOutput(key.FE));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001757 KeyLen -= 8;
1758 Out.write(key.Filename, KeyLen);
Douglas Gregor09b69892011-02-10 17:09:37 +00001759 }
1760
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001761 void EmitData(raw_ostream &Out, key_type_ref key,
Douglas Gregor09b69892011-02-10 17:09:37 +00001762 data_type_ref Data, unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001763 using namespace llvm::support;
1764 endian::Writer<little> LE(Out);
Douglas Gregor09b69892011-02-10 17:09:37 +00001765 uint64_t Start = Out.tell(); (void)Start;
1766
Richard Smith386bb072015-08-18 23:42:23 +00001767 unsigned char Flags = (Data.isImport << 4)
1768 | (Data.isPragmaOnce << 3)
1769 | (Data.DirInfo << 1)
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001770 | Data.IndexHeaderMapHeader;
Justin Bognere1c147c2014-03-28 22:03:19 +00001771 LE.write<uint8_t>(Flags);
1772 LE.write<uint16_t>(Data.NumIncludes);
Douglas Gregor09b69892011-02-10 17:09:37 +00001773
1774 if (!Data.ControllingMacro)
Justin Bognere1c147c2014-03-28 22:03:19 +00001775 LE.write<uint32_t>(Data.ControllingMacroID);
Douglas Gregor09b69892011-02-10 17:09:37 +00001776 else
Justin Bognere1c147c2014-03-28 22:03:19 +00001777 LE.write<uint32_t>(Writer.getIdentifierRef(Data.ControllingMacro));
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001778
1779 unsigned Offset = 0;
1780 if (!Data.Framework.empty()) {
1781 // If this header refers into a framework, save the framework name.
1782 llvm::StringMap<unsigned>::iterator Pos
1783 = FrameworkNameOffset.find(Data.Framework);
1784 if (Pos == FrameworkNameOffset.end()) {
1785 Offset = FrameworkStringData.size() + 1;
1786 FrameworkStringData.append(Data.Framework.begin(),
1787 Data.Framework.end());
1788 FrameworkStringData.push_back(0);
1789
1790 FrameworkNameOffset[Data.Framework] = Offset;
1791 } else
1792 Offset = Pos->second;
1793 }
Justin Bognere1c147c2014-03-28 22:03:19 +00001794 LE.write<uint32_t>(Offset);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001795
Richard Smith386bb072015-08-18 23:42:23 +00001796 // FIXME: If the header is excluded, we should write out some
1797 // record of that fact.
1798 for (auto ModInfo : HS.getModuleMap().findAllModulesForHeader(key.FE)) {
1799 if (uint32_t ModID =
1800 Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule())) {
1801 uint32_t Value = (ModID << 2) | (unsigned)ModInfo.getRole();
1802 assert((Value >> 2) == ModID && "overflow in header module info");
1803 LE.write<uint32_t>(Value);
1804 }
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001805 }
1806
Douglas Gregor09b69892011-02-10 17:09:37 +00001807 assert(Out.tell() - Start == DataLen && "Wrong data length");
1808 }
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001809
1810 const char *strings_begin() const { return FrameworkStringData.begin(); }
1811 const char *strings_end() const { return FrameworkStringData.end(); }
Douglas Gregor09b69892011-02-10 17:09:37 +00001812 };
1813} // end anonymous namespace
1814
1815/// \brief Write the header search block for the list of files that
1816///
1817/// \param HS The header search structure to save.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001818void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001819 SmallVector<const FileEntry *, 16> FilesByUID;
Douglas Gregor09b69892011-02-10 17:09:37 +00001820 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
1821
1822 if (FilesByUID.size() > HS.header_file_size())
1823 FilesByUID.resize(HS.header_file_size());
1824
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001825 HeaderFileInfoTrait GeneratorTrait(*this, HS);
Justin Bognerbb094f02014-04-18 19:57:06 +00001826 llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001827 SmallVector<const char *, 4> SavedStrings;
Douglas Gregor09b69892011-02-10 17:09:37 +00001828 unsigned NumHeaderSearchEntries = 0;
1829 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1830 const FileEntry *File = FilesByUID[UID];
1831 if (!File)
1832 continue;
1833
Richard Smith386bb072015-08-18 23:42:23 +00001834 // Get the file info. This will load info from the external source if
1835 // necessary. Skip emitting this file if we have no information on it
1836 // as a header file (in which case HFI will be null) or if it hasn't
1837 // changed since it was loaded. Also skip it if it's for a modular header
1838 // from a different module; in that case, we rely on the module(s)
1839 // containing the header to provide this information.
Richard Smithd8879c82015-08-24 21:59:32 +00001840 const HeaderFileInfo *HFI =
1841 HS.getExistingFileInfo(File, /*WantExternal*/!Chain);
1842 if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001843 continue;
Douglas Gregor09b69892011-02-10 17:09:37 +00001844
Richard Smith7ed1bc92014-12-05 22:42:13 +00001845 // Massage the file path into an appropriate form.
Douglas Gregor09b69892011-02-10 17:09:37 +00001846 const char *Filename = File->getName();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001847 SmallString<128> FilenameTmp(Filename);
1848 if (PreparePathForOutput(FilenameTmp)) {
1849 // If we performed any translation on the file name at all, we need to
1850 // save this string, since the generator will refer to it later.
1851 Filename = strdup(FilenameTmp.c_str());
Douglas Gregor09b69892011-02-10 17:09:37 +00001852 SavedStrings.push_back(Filename);
1853 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001854
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001855 HeaderFileInfoTrait::key_type key = { File, Filename };
Richard Smith386bb072015-08-18 23:42:23 +00001856 Generator.insert(key, *HFI, GeneratorTrait);
Douglas Gregor09b69892011-02-10 17:09:37 +00001857 ++NumHeaderSearchEntries;
1858 }
1859
1860 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001861 SmallString<4096> TableData;
Douglas Gregor09b69892011-02-10 17:09:37 +00001862 uint32_t BucketOffset;
1863 {
Justin Bognere1c147c2014-03-28 22:03:19 +00001864 using namespace llvm::support;
Douglas Gregor09b69892011-02-10 17:09:37 +00001865 llvm::raw_svector_ostream Out(TableData);
1866 // Make sure that no bucket is at offset 0
Justin Bognere1c147c2014-03-28 22:03:19 +00001867 endian::Writer<little>(Out).write<uint32_t>(0);
Douglas Gregor09b69892011-02-10 17:09:37 +00001868 BucketOffset = Generator.Emit(Out, GeneratorTrait);
1869 }
1870
1871 // Create a blob abbreviation
1872 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001873
1874 auto *Abbrev = new BitCodeAbbrev();
Douglas Gregor09b69892011-02-10 17:09:37 +00001875 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1876 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1877 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001878 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor09b69892011-02-10 17:09:37 +00001879 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1880 unsigned TableAbbrev = Stream.EmitAbbrev(Abbrev);
1881
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001882 // Write the header search table
Mehdi Amini57a41912015-09-10 01:46:39 +00001883 RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
1884 NumHeaderSearchEntries, TableData.size()};
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001885 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
Yaron Keren92e1b622015-03-18 10:17:07 +00001886 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
Douglas Gregor09b69892011-02-10 17:09:37 +00001887
1888 // Free all of the strings we had to duplicate.
1889 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
David Greenebae0e352013-01-15 22:09:43 +00001890 free(const_cast<char *>(SavedStrings[I]));
Douglas Gregor09b69892011-02-10 17:09:37 +00001891}
1892
Douglas Gregora7f71a92009-04-10 03:52:48 +00001893/// \brief Writes the block containing the serialized form of the
1894/// source manager.
1895///
1896/// TODO: We should probably use an on-disk hash table (stored in a
1897/// blob), indexed based on the file name, so that we only create
1898/// entries for files that we actually need. In the common case (no
1899/// errors), we probably won't have to create file entries for any of
1900/// the files in the AST.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00001901void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001902 const Preprocessor &PP) {
Douglas Gregor258ae542009-04-27 06:38:32 +00001903 RecordData Record;
1904
Chris Lattner0910e3b2009-04-10 17:16:57 +00001905 // Enter the source manager block.
Richard Smithaada85c2016-02-06 02:06:43 +00001906 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001907
1908 // Abbreviations for the various kinds of source-location entries.
Chris Lattnerc4976c732009-04-27 19:03:22 +00001909 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
1910 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
Richard Smithaada85c2016-02-06 02:06:43 +00001911 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
1912 unsigned SLocBufferBlobCompressedAbbrv =
1913 CreateSLocBufferBlobAbbrev(Stream, true);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001914 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001915
Douglas Gregor258ae542009-04-27 06:38:32 +00001916 // Write out the source location entry table. We skip the first
1917 // entry, which is always the same dummy entry.
Chris Lattner12d61d32009-04-27 19:01:47 +00001918 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor258ae542009-04-27 06:38:32 +00001919 RecordData PreloadSLocs;
Douglas Gregor925296b2011-07-19 16:10:42 +00001920 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
1921 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
Sebastian Redl5c415f32010-07-22 17:01:13 +00001922 I != N; ++I) {
Douglas Gregor8655e882009-10-16 22:46:09 +00001923 // Get this source location entry.
Douglas Gregor925296b2011-07-19 16:10:42 +00001924 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00001925 FileID FID = FileID::get(I);
1926 assert(&SourceMgr.getSLocEntry(FID) == SLoc);
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00001927
Douglas Gregor258ae542009-04-27 06:38:32 +00001928 // Record the offset of this source-location entry.
1929 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
1930
1931 // Figure out which record code to use.
1932 unsigned Code;
1933 if (SLoc->isFile()) {
Douglas Gregor9dc32122011-11-16 20:05:18 +00001934 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1935 if (Cache->OrigEntry) {
Sebastian Redl539c5062010-08-18 23:57:32 +00001936 Code = SM_SLOC_FILE_ENTRY;
Argyrios Kyrtzidis92dd4662011-06-02 20:01:46 +00001937 } else
Sebastian Redl539c5062010-08-18 23:57:32 +00001938 Code = SM_SLOC_BUFFER_ENTRY;
Douglas Gregor258ae542009-04-27 06:38:32 +00001939 } else
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001940 Code = SM_SLOC_EXPANSION_ENTRY;
Douglas Gregor258ae542009-04-27 06:38:32 +00001941 Record.clear();
1942 Record.push_back(Code);
1943
Douglas Gregor925296b2011-07-19 16:10:42 +00001944 // Starting offset of this entry within this module, so skip the dummy.
1945 Record.push_back(SLoc->getOffset() - 2);
Douglas Gregor258ae542009-04-27 06:38:32 +00001946 if (SLoc->isFile()) {
1947 const SrcMgr::FileInfo &File = SLoc->getFile();
Richard Smithb22a1d12016-03-27 20:13:24 +00001948 AddSourceLocation(File.getIncludeLoc(), Record);
Douglas Gregor258ae542009-04-27 06:38:32 +00001949 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
1950 Record.push_back(File.hasLineDirectives());
1951
1952 const SrcMgr::ContentCache *Content = File.getContentCache();
Richard Smithaada85c2016-02-06 02:06:43 +00001953 bool EmitBlob = false;
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001954 if (Content->OrigEntry) {
1955 assert(Content->OrigEntry == Content->ContentsEntry &&
Douglas Gregor9dc32122011-11-16 20:05:18 +00001956 "Writing to AST an overridden file is not supported");
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001957
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001958 // The source location entry is a file. Emit input file ID.
1959 assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
1960 Record.push_back(InputFileIDs[Content->OrigEntry]);
Mike Stump11289f42009-09-09 15:08:12 +00001961
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001962 Record.push_back(File.NumCreatedFIDs);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00001963
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00001964 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00001965 if (FDI != FileDeclIDs.end()) {
1966 Record.push_back(FDI->second->FirstDeclIndex);
1967 Record.push_back(FDI->second->DeclIDs.size());
1968 } else {
1969 Record.push_back(0);
1970 Record.push_back(0);
1971 }
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001972
1973 Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
1974
Richard Smithaada85c2016-02-06 02:06:43 +00001975 if (Content->BufferOverridden || Content->IsTransient)
1976 EmitBlob = true;
Douglas Gregor258ae542009-04-27 06:38:32 +00001977 } else {
1978 // The source location entry is a buffer. The blob associated
1979 // with this entry contains the contents of the buffer.
1980
1981 // We add one to the size so that we capture the trailing NULL
1982 // that is required by llvm::MemoryBuffer::getMemBuffer (on
1983 // the reader side).
Douglas Gregor874cc622010-03-16 00:35:39 +00001984 const llvm::MemoryBuffer *Buffer
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001985 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
Douglas Gregor258ae542009-04-27 06:38:32 +00001986 const char *Name = Buffer->getBufferIdentifier();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001987 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001988 StringRef(Name, strlen(Name) + 1));
Richard Smithaada85c2016-02-06 02:06:43 +00001989 EmitBlob = true;
Douglas Gregor258ae542009-04-27 06:38:32 +00001990
Douglas Gregor925296b2011-07-19 16:10:42 +00001991 if (strcmp(Name, "<built-in>") == 0) {
1992 PreloadSLocs.push_back(SLocEntryOffsets.size());
1993 }
Douglas Gregor258ae542009-04-27 06:38:32 +00001994 }
Richard Smithaada85c2016-02-06 02:06:43 +00001995
1996 if (EmitBlob) {
1997 // Include the implicit terminating null character in the on-disk buffer
1998 // if we're writing it uncompressed.
1999 const llvm::MemoryBuffer *Buffer =
2000 Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
2001 StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
2002
2003 // Compress the buffer if possible. We expect that almost all PCM
2004 // consumers will not want its contents.
2005 SmallString<0> CompressedBuffer;
2006 if (llvm::zlib::compress(Blob.drop_back(1), CompressedBuffer) ==
2007 llvm::zlib::StatusOK) {
2008 RecordData::value_type Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED,
2009 Blob.size() - 1};
2010 Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
2011 CompressedBuffer);
2012 } else {
2013 RecordData::value_type Record[] = {SM_SLOC_BUFFER_BLOB};
2014 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob);
2015 }
2016 }
Douglas Gregor258ae542009-04-27 06:38:32 +00002017 } else {
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00002018 // The source location entry is a macro expansion.
Chandler Carruthee4c1d12011-07-26 04:56:51 +00002019 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
Richard Smithb22a1d12016-03-27 20:13:24 +00002020 AddSourceLocation(Expansion.getSpellingLoc(), Record);
2021 AddSourceLocation(Expansion.getExpansionLocStart(), Record);
2022 AddSourceLocation(Expansion.isMacroArgExpansion()
2023 ? SourceLocation()
2024 : Expansion.getExpansionLocEnd(),
2025 Record);
Douglas Gregor258ae542009-04-27 06:38:32 +00002026
2027 // Compute the token length for this macro expansion.
Douglas Gregor925296b2011-07-19 16:10:42 +00002028 unsigned NextOffset = SourceMgr.getNextLocalOffset();
Douglas Gregor8655e882009-10-16 22:46:09 +00002029 if (I + 1 != N)
Douglas Gregor925296b2011-07-19 16:10:42 +00002030 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
Douglas Gregor258ae542009-04-27 06:38:32 +00002031 Record.push_back(NextOffset - SLoc->getOffset() - 1);
Mehdi Amini5ae4a852015-09-09 20:35:37 +00002032 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
Douglas Gregor258ae542009-04-27 06:38:32 +00002033 }
2034 }
2035
Douglas Gregor8f45df52009-04-16 22:23:12 +00002036 Stream.ExitBlock();
Douglas Gregor258ae542009-04-27 06:38:32 +00002037
2038 if (SLocEntryOffsets.empty())
2039 return;
2040
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002041 // Write the source-location offsets table into the AST block. This
Douglas Gregor258ae542009-04-27 06:38:32 +00002042 // table is used for lazily loading source-location information.
2043 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002044
2045 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00002046 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
Douglas Gregor258ae542009-04-27 06:38:32 +00002047 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
Douglas Gregor925296b2011-07-19 16:10:42 +00002048 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
Douglas Gregor258ae542009-04-27 06:38:32 +00002049 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
2050 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00002051 {
2052 RecordData::value_type Record[] = {
2053 SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
2054 SourceMgr.getNextLocalOffset() - 1 /* skip dummy */};
2055 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
2056 bytes(SLocEntryOffsets));
2057 }
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002058 // Write the source location entry preloads array, telling the AST
Douglas Gregor258ae542009-04-27 06:38:32 +00002059 // reader which source locations entries it should load eagerly.
Sebastian Redl539c5062010-08-18 23:57:32 +00002060 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregor925296b2011-07-19 16:10:42 +00002061
2062 // Write the line table. It depends on remapping working, so it must come
2063 // after the source location offsets.
2064 if (SourceMgr.hasLineTable()) {
2065 LineTableInfo &LineTable = SourceMgr.getLineTable();
2066
2067 Record.clear();
Richard Smith63078492015-09-01 07:41:55 +00002068
2069 // Emit the needed file names.
2070 llvm::DenseMap<int, int> FilenameMap;
2071 for (const auto &L : LineTable) {
2072 if (L.first.ID < 0)
2073 continue;
2074 for (auto &LE : L.second) {
2075 if (FilenameMap.insert(std::make_pair(LE.FilenameID,
2076 FilenameMap.size())).second)
2077 AddPath(LineTable.getFilename(LE.FilenameID), Record);
2078 }
2079 }
2080 Record.push_back(0);
Douglas Gregor925296b2011-07-19 16:10:42 +00002081
2082 // Emit the line entries
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002083 for (const auto &L : LineTable) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002084 // Only emit entries for local files.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002085 if (L.first.ID < 0)
Douglas Gregor925296b2011-07-19 16:10:42 +00002086 continue;
2087
2088 // Emit the file ID
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002089 Record.push_back(L.first.ID);
Douglas Gregor925296b2011-07-19 16:10:42 +00002090
2091 // Emit the line entries
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002092 Record.push_back(L.second.size());
2093 for (const auto &LE : L.second) {
2094 Record.push_back(LE.FileOffset);
2095 Record.push_back(LE.LineNo);
2096 Record.push_back(FilenameMap[LE.FilenameID]);
2097 Record.push_back((unsigned)LE.FileKind);
2098 Record.push_back(LE.IncludeOffset);
Douglas Gregor925296b2011-07-19 16:10:42 +00002099 }
2100 }
Richard Smith63078492015-09-01 07:41:55 +00002101
Douglas Gregor925296b2011-07-19 16:10:42 +00002102 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
2103 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00002104}
2105
Douglas Gregorc5046832009-04-27 18:38:38 +00002106//===----------------------------------------------------------------------===//
2107// Preprocessor Serialization
2108//===----------------------------------------------------------------------===//
2109
Argyrios Kyrtzidis0aef0f02013-03-15 22:43:10 +00002110static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
2111 const Preprocessor &PP) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002112 if (MacroInfo *MI = MD->getMacroInfo())
2113 if (MI->isBuiltinMacro())
2114 return true;
Argyrios Kyrtzidis0aef0f02013-03-15 22:43:10 +00002115
2116 if (IsModule) {
2117 SourceLocation Loc = MD->getLocation();
2118 if (Loc.isInvalid())
2119 return true;
2120 if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
2121 return true;
2122 }
2123
2124 return false;
2125}
2126
Chris Lattnereeffaef2009-04-10 17:15:23 +00002127/// \brief Writes the block containing the serialized form of the
2128/// preprocessor.
2129///
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00002130void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002131 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
2132 if (PPRec)
2133 WritePreprocessorDetail(*PPRec);
2134
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002135 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00002136 RecordData ModuleMacroRecord;
Chris Lattner0910e3b2009-04-10 17:16:57 +00002137
Chris Lattner0af3ba12009-04-13 01:29:17 +00002138 // If the preprocessor __COUNTER__ value has been bumped, remember it.
2139 if (PP.getCounterValue() != 0) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002140 RecordData::value_type Record[] = {PP.getCounterValue()};
Sebastian Redl539c5062010-08-18 23:57:32 +00002141 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
Douglas Gregoreda6a892009-04-26 00:07:37 +00002142 }
2143
2144 // Enter the preprocessor block.
Douglas Gregor796d76a2010-10-20 22:00:55 +00002145 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
Mike Stump11289f42009-09-09 15:08:12 +00002146
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002147 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
Richard Smithb5aaf5a2015-09-01 02:35:58 +00002148 // FIXME: Include a location for the use, and say which one was used.
Douglas Gregoreda6a892009-04-26 00:07:37 +00002149 if (PP.SawDateOrTime())
Richard Smithb5aaf5a2015-09-01 02:35:58 +00002150 PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
Douglas Gregor796d76a2010-10-20 22:00:55 +00002151
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002152 // Loop over all the macro directives that are live at the end of the file,
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002153 // emitting each to the PP section.
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002154
Richard Smithee977932015-05-01 21:22:17 +00002155 // Construct the list of identifiers with macro directives that need to be
2156 // serialized.
2157 SmallVector<const IdentifierInfo *, 128> MacroIdentifiers;
2158 for (auto &Id : PP.getIdentifierTable())
2159 if (Id.second->hadMacroDefinition() &&
2160 (!Id.second->isFromAST() ||
2161 Id.second->hasChangedSinceDeserialization()))
2162 MacroIdentifiers.push_back(Id.second);
Douglas Gregor2e5571d2011-02-10 18:20:09 +00002163 // Sort the set of macro definitions that need to be serialized by the
2164 // name of the macro, to provide a stable ordering.
Richard Smithee977932015-05-01 21:22:17 +00002165 std::sort(MacroIdentifiers.begin(), MacroIdentifiers.end(),
2166 llvm::less_ptr<IdentifierInfo>());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002167
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002168 // Emit the macro directives as a list and associate the offset with the
2169 // identifier they belong to.
Richard Smithee977932015-05-01 21:22:17 +00002170 for (const IdentifierInfo *Name : MacroIdentifiers) {
2171 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name);
Richard Smithd7329392015-04-21 21:46:32 +00002172 auto StartOffset = Stream.GetCurrentBitNo();
2173
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002174 // Emit the macro directives in reverse source order.
2175 for (; MD; MD = MD->getPrevious()) {
Richard Smithd7329392015-04-21 21:46:32 +00002176 // Once we hit an ignored macro, we're done: the rest of the chain
2177 // will all be ignored macros.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002178 if (shouldIgnoreMacro(MD, IsModule, PP))
Richard Smithd7329392015-04-21 21:46:32 +00002179 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002180
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002181 AddSourceLocation(MD->getLocation(), Record);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002182 Record.push_back(MD->getKind());
Richard Smithdaa69e02014-07-25 04:40:03 +00002183 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
Richard Smith3981b172015-04-30 02:16:23 +00002184 Record.push_back(getMacroRef(DefMD->getInfo(), Name));
Richard Smith713369b2015-04-23 20:40:50 +00002185 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002186 Record.push_back(VisMD->isPublic());
2187 }
Richard Smithb8b2ed62015-04-23 18:18:26 +00002188 }
Richard Smithd7329392015-04-21 21:46:32 +00002189
Richard Smithb8b2ed62015-04-23 18:18:26 +00002190 // Write out any exported module macros.
Richard Smithee977932015-05-01 21:22:17 +00002191 bool EmittedModuleMacros = false;
Richard Smithb8b2ed62015-04-23 18:18:26 +00002192 if (IsModule) {
2193 auto Leafs = PP.getLeafModuleMacros(Name);
2194 SmallVector<ModuleMacro*, 8> Worklist(Leafs.begin(), Leafs.end());
2195 llvm::DenseMap<ModuleMacro*, unsigned> Visits;
2196 while (!Worklist.empty()) {
2197 auto *Macro = Worklist.pop_back_val();
Richard Smithd7329392015-04-21 21:46:32 +00002198
Richard Smithb8b2ed62015-04-23 18:18:26 +00002199 // Emit a record indicating this submodule exports this macro.
2200 ModuleMacroRecord.push_back(
2201 getSubmoduleID(Macro->getOwningModule()));
Richard Smithee977932015-05-01 21:22:17 +00002202 ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
Richard Smithb8b2ed62015-04-23 18:18:26 +00002203 for (auto *M : Macro->overrides())
2204 ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
Richard Smithd7329392015-04-21 21:46:32 +00002205
Richard Smithb8b2ed62015-04-23 18:18:26 +00002206 Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2207 ModuleMacroRecord.clear();
Richard Smithd7329392015-04-21 21:46:32 +00002208
Richard Smithb8b2ed62015-04-23 18:18:26 +00002209 // Enqueue overridden macros once we've visited all their ancestors.
2210 for (auto *M : Macro->overrides())
2211 if (++Visits[M] == M->getNumOverridingMacros())
2212 Worklist.push_back(M);
Richard Smithee977932015-05-01 21:22:17 +00002213
2214 EmittedModuleMacros = true;
Richard Smithd7329392015-04-21 21:46:32 +00002215 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002216 }
Richard Smithd7329392015-04-21 21:46:32 +00002217
Richard Smithee977932015-05-01 21:22:17 +00002218 if (Record.empty() && !EmittedModuleMacros)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002219 continue;
2220
Richard Smithd7329392015-04-21 21:46:32 +00002221 IdentMacroDirectivesOffsetMap[Name] = StartOffset;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002222 Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2223 Record.clear();
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002224 }
Alexander Kornienko1d26c022012-09-25 17:18:14 +00002225
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002226 /// \brief Offsets of each of the macros into the bitstream, indexed by
2227 /// the local macro ID
2228 ///
2229 /// For each identifier that is associated with a macro, this map
2230 /// provides the offset into the bitstream where that macro is
2231 /// defined.
2232 std::vector<uint32_t> MacroOffsets;
2233
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002234 for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2235 const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2236 MacroInfo *MI = MacroInfosToEmit[I].MI;
2237 MacroID ID = MacroInfosToEmit[I].ID;
Douglas Gregoreb114da2010-10-01 01:03:07 +00002238
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002239 if (ID < FirstMacroID) {
2240 assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2241 continue;
Chris Lattner2199f5b2009-04-10 18:08:30 +00002242 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002243
2244 // Record the local offset of this macro.
2245 unsigned Index = ID - FirstMacroID;
2246 if (Index == MacroOffsets.size())
2247 MacroOffsets.push_back(Stream.GetCurrentBitNo());
2248 else {
2249 if (Index > MacroOffsets.size())
2250 MacroOffsets.resize(Index + 1);
2251
2252 MacroOffsets[Index] = Stream.GetCurrentBitNo();
2253 }
2254
2255 AddIdentifierRef(Name, Record);
2256 Record.push_back(inferSubmoduleIDFromLocation(MI->getDefinitionLoc()));
2257 AddSourceLocation(MI->getDefinitionLoc(), Record);
2258 AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2259 Record.push_back(MI->isUsed());
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00002260 Record.push_back(MI->isUsedForHeaderGuard());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002261 unsigned Code;
2262 if (MI->isObjectLike()) {
2263 Code = PP_MACRO_OBJECT_LIKE;
2264 } else {
2265 Code = PP_MACRO_FUNCTION_LIKE;
2266
2267 Record.push_back(MI->isC99Varargs());
2268 Record.push_back(MI->isGNUVarargs());
2269 Record.push_back(MI->hasCommaPasting());
2270 Record.push_back(MI->getNumArgs());
Daniel Marjamakie4770da2015-05-29 09:15:24 +00002271 for (const IdentifierInfo *Arg : MI->args())
2272 AddIdentifierRef(Arg, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002273 }
2274
2275 // If we have a detailed preprocessing record, record the macro definition
2276 // ID that corresponds to this macro.
2277 if (PPRec)
2278 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2279
2280 Stream.EmitRecord(Code, Record);
2281 Record.clear();
2282
2283 // Emit the tokens array.
2284 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2285 // Note that we know that the preprocessor does not have any annotation
2286 // tokens in it because they are created by the parser, and thus can't
2287 // be in a macro definition.
2288 const Token &Tok = MI->getReplacementToken(TokNo);
John McCallf413f5e2013-05-03 00:10:13 +00002289 AddToken(Tok, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002290 Stream.EmitRecord(PP_TOKEN, Record);
2291 Record.clear();
2292 }
2293 ++NumMacros;
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002294 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002295
Douglas Gregor92a96f52011-02-08 21:58:10 +00002296 Stream.ExitBlock();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002297
2298 // Write the offsets table for macro IDs.
2299 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002300
Richard Smith13090a22015-04-10 02:02:24 +00002301 auto *Abbrev = new BitCodeAbbrev();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002302 Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2303 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2304 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2305 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2306
2307 unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00002308 {
2309 RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
2310 FirstMacroID - NUM_PREDEF_MACRO_IDS};
2311 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
2312 }
Douglas Gregor92a96f52011-02-08 21:58:10 +00002313}
2314
2315void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
Argyrios Kyrtzidis7f448362011-09-19 20:40:42 +00002316 if (PPRec.local_begin() == PPRec.local_end())
Douglas Gregor92a96f52011-02-08 21:58:10 +00002317 return;
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002318
Argyrios Kyrtzidis64f63812011-09-19 20:40:25 +00002319 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002320
Douglas Gregor92a96f52011-02-08 21:58:10 +00002321 // Enter the preprocessor block.
2322 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002323
Douglas Gregoraae92242010-03-19 21:51:54 +00002324 // If the preprocessor has a preprocessing record, emit it.
2325 unsigned NumPreprocessingRecords = 0;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002326 using namespace llvm;
2327
2328 // Set up the abbreviation for
2329 unsigned InclusionAbbrev = 0;
2330 {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002331 auto *Abbrev = new BitCodeAbbrev();
Douglas Gregor92a96f52011-02-08 21:58:10 +00002332 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
Douglas Gregor92a96f52011-02-08 21:58:10 +00002333 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2334 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2335 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
Argyrios Kyrtzidisf590e092012-10-02 16:10:46 +00002336 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
Douglas Gregor92a96f52011-02-08 21:58:10 +00002337 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2338 InclusionAbbrev = Stream.EmitAbbrev(Abbrev);
2339 }
2340
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002341 unsigned FirstPreprocessorEntityID
2342 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
2343 + NUM_PREDEF_PP_ENTITY_IDS;
2344 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002345 RecordData Record;
Argyrios Kyrtzidis7f448362011-09-19 20:40:42 +00002346 for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2347 EEnd = PPRec.local_end();
Douglas Gregor0d4b4312011-08-04 17:06:18 +00002348 E != EEnd;
2349 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
Douglas Gregor92a96f52011-02-08 21:58:10 +00002350 Record.clear();
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002351
Richard Smith66a81862015-05-04 02:25:31 +00002352 PreprocessedEntityOffsets.push_back(
2353 PPEntityOffset((*E)->getSourceRange(), Stream.GetCurrentBitNo()));
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002354
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002355 if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002356 // Record this macro definition's ID.
2357 MacroDefinitions[MD] = NextPreprocessorEntityID;
Richard Smith66a81862015-05-04 02:25:31 +00002358
Douglas Gregor92a96f52011-02-08 21:58:10 +00002359 AddIdentifierRef(MD->getName(), Record);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002360 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2361 continue;
Douglas Gregoraae92242010-03-19 21:51:54 +00002362 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002363
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002364 if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
Argyrios Kyrtzidis80f78b92011-09-08 17:18:41 +00002365 Record.push_back(ME->isBuiltinMacro());
2366 if (ME->isBuiltinMacro())
2367 AddIdentifierRef(ME->getName(), Record);
2368 else
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002369 Record.push_back(MacroDefinitions[ME->getDefinition()]);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00002370 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002371 continue;
2372 }
2373
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002374 if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
Douglas Gregor92a96f52011-02-08 21:58:10 +00002375 Record.push_back(PPD_INCLUSION_DIRECTIVE);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002376 Record.push_back(ID->getFileName().size());
2377 Record.push_back(ID->wasInQuotes());
2378 Record.push_back(static_cast<unsigned>(ID->getKind()));
Argyrios Kyrtzidisf590e092012-10-02 16:10:46 +00002379 Record.push_back(ID->importedModule());
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002380 SmallString<64> Buffer;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002381 Buffer += ID->getFileName();
Argyrios Kyrtzidis8dbcfc32012-03-08 01:08:28 +00002382 // Check that the FileEntry is not null because it was not resolved and
2383 // we create a PCH even with compiler errors.
2384 if (ID->getFile())
2385 Buffer += ID->getFile()->getName();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00002386 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002387 continue;
2388 }
2389
2390 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2391 }
Douglas Gregor8f45df52009-04-16 22:23:12 +00002392 Stream.ExitBlock();
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002393
Douglas Gregoraae92242010-03-19 21:51:54 +00002394 // Write the offsets table for the preprocessing record.
2395 if (NumPreprocessingRecords > 0) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002396 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2397
Douglas Gregoraae92242010-03-19 21:51:54 +00002398 // Write the offsets table for identifier IDs.
2399 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002400
2401 auto *Abbrev = new BitCodeAbbrev();
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002402 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002403 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
Douglas Gregoraae92242010-03-19 21:51:54 +00002404 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002405 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002406
Mehdi Amini57a41912015-09-10 01:46:39 +00002407 RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
2408 FirstPreprocessorEntityID -
2409 NUM_PREDEF_PP_ENTITY_IDS};
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002410 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00002411 bytes(PreprocessedEntityOffsets));
Douglas Gregoraae92242010-03-19 21:51:54 +00002412 }
Chris Lattnereeffaef2009-04-10 17:15:23 +00002413}
2414
Richard Smith386bb072015-08-18 23:42:23 +00002415unsigned ASTWriter::getLocalOrImportedSubmoduleID(Module *Mod) {
Richard Smith080056b2015-08-18 21:53:42 +00002416 if (!Mod)
2417 return 0;
2418
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002419 llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
2420 if (Known != SubmoduleIDs.end())
2421 return Known->second;
Richard Smith386bb072015-08-18 23:42:23 +00002422
2423 if (Mod->getTopLevelModule() != WritingModule)
2424 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
Douglas Gregor69021972011-11-30 17:33:56 +00002655 // Queue up the submodules of this module.
Richard Smith080056b2015-08-18 21:53:42 +00002656 for (auto *M : Mod->submodules())
2657 Q.push(M);
Douglas Gregor69021972011-11-30 17:33:56 +00002658 }
2659
2660 Stream.ExitBlock();
Richard Smith23d8d032015-05-14 00:45:20 +00002661
Richard Smith23d8d032015-05-14 00:45:20 +00002662 assert((NextSubmoduleID - FirstSubmoduleID ==
2663 getNumberOfModules(WritingModule)) &&
2664 "Wrong # of submodules; found a reference to a non-local, "
2665 "non-imported submodule?");
Douglas Gregor69021972011-11-30 17:33:56 +00002666}
2667
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002668serialization::SubmoduleID
2669ASTWriter::inferSubmoduleIDFromLocation(SourceLocation Loc) {
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002670 if (Loc.isInvalid() || !WritingModule)
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002671 return 0; // No submodule
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002672
2673 // Find the module that owns this location.
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002674 ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002675 Module *OwningMod
2676 = ModMap.inferModuleFromLocation(FullSourceLoc(Loc,PP->getSourceManager()));
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002677 if (!OwningMod)
2678 return 0;
2679
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002680 // Check whether this submodule is part of our own module.
2681 if (WritingModule != OwningMod && !OwningMod->isSubModuleOf(WritingModule))
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002682 return 0;
2683
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002684 return getSubmoduleID(OwningMod);
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002685}
2686
Argyrios Kyrtzidis0f06b982013-03-27 17:17:23 +00002687void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
2688 bool isModule) {
2689 // Make sure set diagnostic pragmas don't affect the translation unit that
2690 // imports the module.
2691 // FIXME: Make diagnostic pragma sections work properly with modules.
2692 if (isModule)
2693 return;
2694
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002695 llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
2696 DiagStateIDMap;
2697 unsigned CurrID = 0;
2698 DiagStateIDMap[&Diag.DiagStates.front()] = ++CurrID; // the command-line one.
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002699 RecordData Record;
David Blaikie9c902b52011-09-25 23:23:43 +00002700 for (DiagnosticsEngine::DiagStatePointsTy::const_iterator
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002701 I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end();
2702 I != E; ++I) {
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002703 const DiagnosticsEngine::DiagStatePoint &point = *I;
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002704 if (point.Loc.isInvalid())
2705 continue;
2706
Richard Smithb22a1d12016-03-27 20:13:24 +00002707 AddSourceLocation(point.Loc, Record);
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002708 unsigned &DiagStateID = DiagStateIDMap[point.State];
2709 Record.push_back(DiagStateID);
2710
2711 if (DiagStateID == 0) {
2712 DiagStateID = ++CurrID;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002713 for (const auto &I : *(point.State)) {
2714 if (I.second.isPragma()) {
2715 Record.push_back(I.first);
2716 Record.push_back((unsigned)I.second.getSeverity());
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002717 }
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002718 }
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002719 Record.push_back(-1); // mark the end of the diag/map pairs for this
2720 // location.
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002721 }
2722 }
2723
Argyrios Kyrtzidisb0ca9eb2010-11-05 22:20:49 +00002724 if (!Record.empty())
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002725 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002726}
2727
Richard Smithc2bb8182015-03-24 06:36:48 +00002728void ASTWriter::WriteCXXCtorInitializersOffsets() {
2729 if (CXXCtorInitializersOffsets.empty())
2730 return;
2731
Richard Smithc2bb8182015-03-24 06:36:48 +00002732 // Create a blob abbreviation for the C++ ctor initializer offsets.
2733 using namespace llvm;
2734
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002735 auto *Abbrev = new BitCodeAbbrev();
Richard Smithc2bb8182015-03-24 06:36:48 +00002736 Abbrev->Add(BitCodeAbbrevOp(CXX_CTOR_INITIALIZERS_OFFSETS));
2737 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2738 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2739 unsigned CtorInitializersOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2740
2741 // Write the base specifier offsets table.
Mehdi Amini57a41912015-09-10 01:46:39 +00002742 RecordData::value_type Record[] = {CXX_CTOR_INITIALIZERS_OFFSETS,
2743 CXXCtorInitializersOffsets.size()};
Richard Smithc2bb8182015-03-24 06:36:48 +00002744 Stream.EmitRecordWithBlob(CtorInitializersOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00002745 bytes(CXXCtorInitializersOffsets));
Richard Smithc2bb8182015-03-24 06:36:48 +00002746}
2747
Anders Carlsson9bb83e82011-03-06 18:41:18 +00002748void ASTWriter::WriteCXXBaseSpecifiersOffsets() {
2749 if (CXXBaseSpecifiersOffsets.empty())
2750 return;
2751
Anders Carlsson9bb83e82011-03-06 18:41:18 +00002752 // Create a blob abbreviation for the C++ base specifiers offsets.
2753 using namespace llvm;
2754
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002755 auto *Abbrev = new BitCodeAbbrev();
Anders Carlsson9bb83e82011-03-06 18:41:18 +00002756 Abbrev->Add(BitCodeAbbrevOp(CXX_BASE_SPECIFIER_OFFSETS));
2757 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2758 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2759 unsigned BaseSpecifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2760
Douglas Gregorc27b2872011-08-04 00:01:48 +00002761 // Write the base specifier offsets table.
Mehdi Amini57a41912015-09-10 01:46:39 +00002762 RecordData::value_type Record[] = {CXX_BASE_SPECIFIER_OFFSETS,
2763 CXXBaseSpecifiersOffsets.size()};
Anders Carlsson9bb83e82011-03-06 18:41:18 +00002764 Stream.EmitRecordWithBlob(BaseSpecifierOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00002765 bytes(CXXBaseSpecifiersOffsets));
Anders Carlsson9bb83e82011-03-06 18:41:18 +00002766}
2767
Douglas Gregorc5046832009-04-27 18:38:38 +00002768//===----------------------------------------------------------------------===//
2769// Type Serialization
2770//===----------------------------------------------------------------------===//
Chris Lattnereeffaef2009-04-10 17:15:23 +00002771
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002772/// \brief Write the representation of a type to the AST stream.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002773void ASTWriter::WriteType(QualType T) {
Richard Smith290d8012016-04-06 17:06:00 +00002774 TypeIdx &IdxRef = TypeIdxs[T];
2775 if (IdxRef.getIndex() == 0) // we haven't seen this type before.
2776 IdxRef = TypeIdx(NextTypeID++);
2777 TypeIdx Idx = IdxRef;
Mike Stump11289f42009-09-09 15:08:12 +00002778
Douglas Gregor9b3932c2010-10-05 18:37:06 +00002779 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
Douglas Gregordc72caa2010-10-04 18:21:45 +00002780
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002781 RecordData Record;
Mike Stump11289f42009-09-09 15:08:12 +00002782
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002783 // Emit the type's representation.
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002784 ASTTypeWriter W(*this, Record);
Richard Smith290d8012016-04-06 17:06:00 +00002785 W.Visit(T);
2786 uint64_t Offset = W.Emit();
John McCall8ccfcb52009-09-24 19:53:00 +00002787
Richard Smith290d8012016-04-06 17:06:00 +00002788 // Record the offset for this type.
2789 unsigned Index = Idx.getIndex() - FirstTypeID;
2790 if (TypeOffsets.size() == Index)
2791 TypeOffsets.push_back(Offset);
2792 else if (TypeOffsets.size() < Index) {
2793 TypeOffsets.resize(Index + 1);
2794 TypeOffsets[Index] = Offset;
John McCall8ccfcb52009-09-24 19:53:00 +00002795 } else {
Richard Smith290d8012016-04-06 17:06:00 +00002796 llvm_unreachable("Types emitted in wrong order");
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002797 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002798}
2799
Douglas Gregorc5046832009-04-27 18:38:38 +00002800//===----------------------------------------------------------------------===//
2801// Declaration Serialization
2802//===----------------------------------------------------------------------===//
2803
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002804/// \brief Write the block containing all of the declaration IDs
2805/// lexically declared within the given DeclContext.
2806///
2807/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
2808/// bistream, or 0 if no block was written.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002809uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002810 DeclContext *DC) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002811 if (DC->decls_empty())
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002812 return 0;
2813
Douglas Gregor8f45df52009-04-16 22:23:12 +00002814 uint64_t Offset = Stream.GetCurrentBitNo();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002815 SmallVector<uint32_t, 128> KindDeclPairs;
2816 for (const auto *D : DC->decls()) {
2817 KindDeclPairs.push_back(D->getKind());
2818 KindDeclPairs.push_back(GetDeclRef(D));
2819 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002820
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002821 ++NumLexicalDeclContexts;
Mehdi Amini57a41912015-09-10 01:46:39 +00002822 RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
Richard Smith82f8fcd2015-08-06 22:07:25 +00002823 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
2824 bytes(KindDeclPairs));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002825 return Offset;
2826}
2827
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002828void ASTWriter::WriteTypeDeclOffsets() {
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002829 using namespace llvm;
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002830
2831 // Write the type offsets array
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002832 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00002833 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002834 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
Douglas Gregor5204bde2011-08-02 16:26:37 +00002835 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002836 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
2837 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00002838 {
2839 RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(),
2840 FirstTypeID - NUM_PREDEF_TYPE_IDS};
2841 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
2842 }
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002843
2844 // Write the declaration offsets array
2845 Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00002846 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002847 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
Douglas Gregorf7180622011-08-03 15:48:04 +00002848 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002849 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
2850 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00002851 {
2852 RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(),
2853 FirstDeclID - NUM_PREDEF_DECL_IDS};
2854 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
2855 }
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002856}
2857
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002858void ASTWriter::WriteFileDeclIDsMap() {
2859 using namespace llvm;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002860
Chandler Carruthb306d732015-03-27 00:31:20 +00002861 SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs(
2862 FileDeclIDs.begin(), FileDeclIDs.end());
2863 std::sort(SortedFileDeclIDs.begin(), SortedFileDeclIDs.end(),
2864 llvm::less_first());
2865
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002866 // Join the vectors of DeclIDs from all files.
Chandler Carruthb306d732015-03-27 00:31:20 +00002867 SmallVector<DeclID, 256> FileGroupedDeclIDs;
2868 for (auto &FileDeclEntry : SortedFileDeclIDs) {
2869 DeclIDInFileInfo &Info = *FileDeclEntry.second;
2870 Info.FirstDeclIndex = FileGroupedDeclIDs.size();
2871 for (auto &LocDeclEntry : Info.DeclIDs)
2872 FileGroupedDeclIDs.push_back(LocDeclEntry.second);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002873 }
2874
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002875 auto *Abbrev = new BitCodeAbbrev();
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002876 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002877 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002878 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2879 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00002880 RecordData::value_type Record[] = {FILE_SORTED_DECLS,
2881 FileGroupedDeclIDs.size()};
Reid Kleckner012665e2015-05-21 00:13:09 +00002882 Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002883}
2884
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002885void ASTWriter::WriteComments() {
2886 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +00002887 ArrayRef<RawComment *> RawComments = Context->Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002888 RecordData Record;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002889 for (const auto *I : RawComments) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002890 Record.clear();
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002891 AddSourceRange(I->getSourceRange(), Record);
2892 Record.push_back(I->getKind());
2893 Record.push_back(I->isTrailingComment());
2894 Record.push_back(I->isAlmostTrailingComment());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002895 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
2896 }
2897 Stream.ExitBlock();
2898}
2899
Douglas Gregorc5046832009-04-27 18:38:38 +00002900//===----------------------------------------------------------------------===//
2901// Global Method Pool and Selector Serialization
2902//===----------------------------------------------------------------------===//
2903
Douglas Gregore84a9da2009-04-20 20:36:09 +00002904namespace {
Douglas Gregorc78d3462009-04-24 21:10:55 +00002905// Trait used for the on-disk hash table used in the method pool.
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002906class ASTMethodPoolTrait {
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002907 ASTWriter &Writer;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002908
2909public:
2910 typedef Selector key_type;
2911 typedef key_type key_type_ref;
Mike Stump11289f42009-09-09 15:08:12 +00002912
Sebastian Redl834bb972010-08-04 17:20:04 +00002913 struct data_type {
Sebastian Redl539c5062010-08-18 23:57:32 +00002914 SelectorID ID;
Sebastian Redl834bb972010-08-04 17:20:04 +00002915 ObjCMethodList Instance, Factory;
2916 };
Douglas Gregorc78d3462009-04-24 21:10:55 +00002917 typedef const data_type& data_type_ref;
2918
Justin Bogner25463f12014-04-18 20:27:24 +00002919 typedef unsigned hash_value_type;
2920 typedef unsigned offset_type;
2921
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002922 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { }
Mike Stump11289f42009-09-09 15:08:12 +00002923
Justin Bogner25463f12014-04-18 20:27:24 +00002924 static hash_value_type ComputeHash(Selector Sel) {
Argyrios Kyrtzidis4bd97102010-08-20 16:03:52 +00002925 return serialization::ComputeHash(Sel);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002926 }
Mike Stump11289f42009-09-09 15:08:12 +00002927
2928 std::pair<unsigned,unsigned>
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002929 EmitKeyDataLength(raw_ostream& Out, Selector Sel,
Douglas Gregorc78d3462009-04-24 21:10:55 +00002930 data_type_ref Methods) {
Justin Bognere1c147c2014-03-28 22:03:19 +00002931 using namespace llvm::support;
2932 endian::Writer<little> LE(Out);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002933 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
Justin Bognere1c147c2014-03-28 22:03:19 +00002934 LE.write<uint16_t>(KeyLen);
Sebastian Redl834bb972010-08-04 17:20:04 +00002935 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
2936 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002937 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002938 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002939 DataLen += 4;
Sebastian Redl834bb972010-08-04 17:20:04 +00002940 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002941 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002942 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002943 DataLen += 4;
Justin Bognere1c147c2014-03-28 22:03:19 +00002944 LE.write<uint16_t>(DataLen);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002945 return std::make_pair(KeyLen, DataLen);
2946 }
Mike Stump11289f42009-09-09 15:08:12 +00002947
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002948 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00002949 using namespace llvm::support;
2950 endian::Writer<little> LE(Out);
Mike Stump11289f42009-09-09 15:08:12 +00002951 uint64_t Start = Out.tell();
Douglas Gregor95c13f52009-04-25 17:48:32 +00002952 assert((Start >> 32) == 0 && "Selector key offset too large");
2953 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002954 unsigned N = Sel.getNumArgs();
Justin Bognere1c147c2014-03-28 22:03:19 +00002955 LE.write<uint16_t>(N);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002956 if (N == 0)
2957 N = 1;
2958 for (unsigned I = 0; I != N; ++I)
Justin Bognere1c147c2014-03-28 22:03:19 +00002959 LE.write<uint32_t>(
2960 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
Douglas Gregorc78d3462009-04-24 21:10:55 +00002961 }
Mike Stump11289f42009-09-09 15:08:12 +00002962
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002963 void EmitData(raw_ostream& Out, key_type_ref,
Douglas Gregor4647cfa2009-04-24 21:49:02 +00002964 data_type_ref Methods, unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00002965 using namespace llvm::support;
2966 endian::Writer<little> LE(Out);
Douglas Gregor4647cfa2009-04-24 21:49:02 +00002967 uint64_t Start = Out.tell(); (void)Start;
Justin Bognere1c147c2014-03-28 22:03:19 +00002968 LE.write<uint32_t>(Methods.ID);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002969 unsigned NumInstanceMethods = 0;
Sebastian Redl834bb972010-08-04 17:20:04 +00002970 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002971 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002972 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002973 ++NumInstanceMethods;
2974
2975 unsigned NumFactoryMethods = 0;
Sebastian Redl834bb972010-08-04 17:20:04 +00002976 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002977 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002978 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002979 ++NumFactoryMethods;
2980
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002981 unsigned InstanceBits = Methods.Instance.getBits();
2982 assert(InstanceBits < 4);
Nico Weberff4b35e2014-12-27 22:14:15 +00002983 unsigned InstanceHasMoreThanOneDeclBit =
2984 Methods.Instance.hasMoreThanOneDecl();
2985 unsigned FullInstanceBits = (NumInstanceMethods << 3) |
2986 (InstanceHasMoreThanOneDeclBit << 2) |
2987 InstanceBits;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002988 unsigned FactoryBits = Methods.Factory.getBits();
2989 assert(FactoryBits < 4);
Nico Weberff4b35e2014-12-27 22:14:15 +00002990 unsigned FactoryHasMoreThanOneDeclBit =
2991 Methods.Factory.hasMoreThanOneDecl();
2992 unsigned FullFactoryBits = (NumFactoryMethods << 3) |
2993 (FactoryHasMoreThanOneDeclBit << 2) |
2994 FactoryBits;
2995 LE.write<uint16_t>(FullInstanceBits);
2996 LE.write<uint16_t>(FullFactoryBits);
Sebastian Redl834bb972010-08-04 17:20:04 +00002997 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002998 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002999 if (Method->getMethod())
3000 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
Sebastian Redl834bb972010-08-04 17:20:04 +00003001 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003002 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003003 if (Method->getMethod())
3004 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
Douglas Gregor4647cfa2009-04-24 21:49:02 +00003005
3006 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorc78d3462009-04-24 21:10:55 +00003007 }
3008};
3009} // end anonymous namespace
3010
Sebastian Redla19a67f2010-08-03 21:58:15 +00003011/// \brief Write ObjC data: selectors and the method pool.
Douglas Gregorc78d3462009-04-24 21:10:55 +00003012///
3013/// The method pool contains both instance and factory methods, stored
Sebastian Redla19a67f2010-08-03 21:58:15 +00003014/// in an on-disk hash table indexed by the selector. The hash table also
3015/// contains an empty entry for every other selector known to Sema.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003016void ASTWriter::WriteSelectors(Sema &SemaRef) {
Douglas Gregorc78d3462009-04-24 21:10:55 +00003017 using namespace llvm;
3018
Sebastian Redla19a67f2010-08-03 21:58:15 +00003019 // Do we have to do anything at all?
Sebastian Redl834bb972010-08-04 17:20:04 +00003020 if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
Sebastian Redla19a67f2010-08-03 21:58:15 +00003021 return;
Sebastian Redld95a56e2010-08-04 18:21:41 +00003022 unsigned NumTableEntries = 0;
Sebastian Redla19a67f2010-08-03 21:58:15 +00003023 // Create and write out the blob that contains selectors and the method pool.
Douglas Gregorc78d3462009-04-24 21:10:55 +00003024 {
Justin Bognerbb094f02014-04-18 19:57:06 +00003025 llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003026 ASTMethodPoolTrait Trait(*this);
Mike Stump11289f42009-09-09 15:08:12 +00003027
Sebastian Redla19a67f2010-08-03 21:58:15 +00003028 // Create the on-disk hash table representation. We walk through every
3029 // selector we've seen and look it up in the method pool.
Sebastian Redld95a56e2010-08-04 18:21:41 +00003030 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003031 for (auto &SelectorAndID : SelectorIDs) {
3032 Selector S = SelectorAndID.first;
3033 SelectorID ID = SelectorAndID.second;
Sebastian Redla19a67f2010-08-03 21:58:15 +00003034 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003035 ASTMethodPoolTrait::data_type Data = {
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003036 ID,
Sebastian Redl834bb972010-08-04 17:20:04 +00003037 ObjCMethodList(),
3038 ObjCMethodList()
3039 };
3040 if (F != SemaRef.MethodPool.end()) {
3041 Data.Instance = F->second.first;
3042 Data.Factory = F->second.second;
3043 }
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003044 // Only write this selector if it's not in an existing AST or something
Sebastian Redld95a56e2010-08-04 18:21:41 +00003045 // changed.
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003046 if (Chain && ID < FirstSelectorID) {
Sebastian Redld95a56e2010-08-04 18:21:41 +00003047 // Selector already exists. Did it change?
3048 bool changed = false;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003049 for (ObjCMethodList *M = &Data.Instance;
3050 !changed && M && M->getMethod(); M = M->getNext()) {
3051 if (!M->getMethod()->isFromASTFile())
Sebastian Redld95a56e2010-08-04 18:21:41 +00003052 changed = true;
3053 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003054 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003055 M = M->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003056 if (!M->getMethod()->isFromASTFile())
Sebastian Redld95a56e2010-08-04 18:21:41 +00003057 changed = true;
3058 }
3059 if (!changed)
3060 continue;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003061 } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
Sebastian Redl6e1a2a02010-08-04 21:22:45 +00003062 // A new method pool entry.
3063 ++NumTableEntries;
Sebastian Redld95a56e2010-08-04 18:21:41 +00003064 }
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003065 Generator.insert(S, Data, Trait);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003066 }
3067
Douglas Gregorc78d3462009-04-24 21:10:55 +00003068 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003069 SmallString<4096> MethodPool;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003070 uint32_t BucketOffset;
3071 {
Justin Bognere1c147c2014-03-28 22:03:19 +00003072 using namespace llvm::support;
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003073 ASTMethodPoolTrait Trait(*this);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003074 llvm::raw_svector_ostream Out(MethodPool);
3075 // Make sure that no bucket is at offset 0
Justin Bognere1c147c2014-03-28 22:03:19 +00003076 endian::Writer<little>(Out).write<uint32_t>(0);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003077 BucketOffset = Generator.Emit(Out, Trait);
3078 }
3079
3080 // Create a blob abbreviation
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003081 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00003082 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003083 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor95c13f52009-04-25 17:48:32 +00003084 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003085 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3086 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
3087
Douglas Gregor95c13f52009-04-25 17:48:32 +00003088 // Write the method pool
Mehdi Amini57a41912015-09-10 01:46:39 +00003089 {
3090 RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3091 NumTableEntries};
3092 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3093 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00003094
3095 // Create a blob abbreviation for the selector table offsets.
3096 Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00003097 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
Douglas Gregord4c5ed02010-10-29 22:39:52 +00003098 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
Douglas Gregor8f364fb2011-08-03 23:28:44 +00003099 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
Douglas Gregor95c13f52009-04-25 17:48:32 +00003100 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3101 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
3102
3103 // Write the selector offsets table.
Mehdi Amini57a41912015-09-10 01:46:39 +00003104 {
3105 RecordData::value_type Record[] = {
3106 SELECTOR_OFFSETS, SelectorOffsets.size(),
3107 FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3108 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3109 bytes(SelectorOffsets));
3110 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00003111 }
3112}
3113
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003114/// \brief Write the selectors referenced in @selector expression into AST file.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003115void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003116 using namespace llvm;
3117 if (SemaRef.ReferencedSelectors.empty())
3118 return;
Sebastian Redlada023c2010-08-04 20:40:17 +00003119
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003120 RecordData Record;
Sebastian Redlada023c2010-08-04 20:40:17 +00003121
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003122 // Note: this writes out all references even for a dependent AST. But it is
Sebastian Redl51c79d82010-08-04 22:21:29 +00003123 // very tricky to fix, and given that @selector shouldn't really appear in
3124 // headers, probably not worth it. It's not a correctness issue.
Chandler Carruth12c8f652015-03-27 00:55:05 +00003125 for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
3126 Selector Sel = SelectorAndLocation.first;
3127 SourceLocation Loc = SelectorAndLocation.second;
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003128 AddSelectorRef(Sel, Record);
3129 AddSourceLocation(Loc, Record);
3130 }
Sebastian Redl539c5062010-08-18 23:57:32 +00003131 Stream.EmitRecord(REFERENCED_SELECTOR_POOL, Record);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003132}
3133
Douglas Gregorc5046832009-04-27 18:38:38 +00003134//===----------------------------------------------------------------------===//
3135// Identifier Table Serialization
3136//===----------------------------------------------------------------------===//
3137
Richard Smithb3761912015-02-05 23:08:52 +00003138/// Determine the declaration that should be put into the name lookup table to
3139/// represent the given declaration in this module. This is usually D itself,
3140/// but if D was imported and merged into a local declaration, we want the most
3141/// recent local declaration instead. The chosen declaration will be the most
3142/// recent declaration in any module that imports this one.
3143static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
3144 NamedDecl *D) {
3145 if (!LangOpts.Modules || !D->isFromASTFile())
3146 return D;
3147
3148 if (Decl *Redecl = D->getPreviousDecl()) {
3149 // For Redeclarable decls, a prior declaration might be local.
3150 for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
3151 if (!Redecl->isFromASTFile())
3152 return cast<NamedDecl>(Redecl);
Richard Smithfe620d22015-03-05 23:24:12 +00003153 // If we find a decl from a (chained-)PCH stop since we won't find a
Richard Smithb3761912015-02-05 23:08:52 +00003154 // local one.
3155 if (D->getOwningModuleID() == 0)
3156 break;
3157 }
3158 } else if (Decl *First = D->getCanonicalDecl()) {
3159 // For Mergeable decls, the first decl might be local.
3160 if (!First->isFromASTFile())
3161 return cast<NamedDecl>(First);
3162 }
3163
3164 // All declarations are imported. Our most recent declaration will also be
3165 // the most recent one in anyone who imports us.
3166 return D;
3167}
3168
Douglas Gregorc78d3462009-04-24 21:10:55 +00003169namespace {
Richard Smithcf97cf62015-04-19 01:34:23 +00003170class ASTIdentifierTableTrait {
3171 ASTWriter &Writer;
3172 Preprocessor &PP;
3173 IdentifierResolver &IdResolver;
Richard Smith9c254182015-07-19 21:41:12 +00003174 bool IsModule;
Richard Smitha534a312015-07-21 23:54:07 +00003175 bool NeedDecls;
Richard Smith33e0f7e2015-07-22 02:08:40 +00003176 ASTWriter::RecordData *InterestingIdentifierOffsets;
Richard Smithcf97cf62015-04-19 01:34:23 +00003177
3178 /// \brief Determines whether this is an "interesting" identifier that needs a
3179 /// full IdentifierInfo structure written into the hash table. Notably, this
3180 /// doesn't check whether the name has macros defined; use PublicMacroIterator
3181 /// to check that.
Richard Smith9c254182015-07-19 21:41:12 +00003182 bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
Richard Smithd7329392015-04-21 21:46:32 +00003183 if (MacroOffset ||
3184 II->isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +00003185 (IsModule ? II->hasRevertedBuiltin() : II->getObjCOrBuiltinID()) ||
Richard Smithcf97cf62015-04-19 01:34:23 +00003186 II->hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +00003187 (NeedDecls && II->getFETokenInfo<void>()))
Richard Smithcf97cf62015-04-19 01:34:23 +00003188 return true;
3189
3190 return false;
3191 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003192
Douglas Gregore84a9da2009-04-20 20:36:09 +00003193public:
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00003194 typedef IdentifierInfo* key_type;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003195 typedef key_type key_type_ref;
Mike Stump11289f42009-09-09 15:08:12 +00003196
Sebastian Redl539c5062010-08-18 23:57:32 +00003197 typedef IdentID data_type;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003198 typedef data_type data_type_ref;
Mike Stump11289f42009-09-09 15:08:12 +00003199
Justin Bogner25463f12014-04-18 20:27:24 +00003200 typedef unsigned hash_value_type;
3201 typedef unsigned offset_type;
3202
Richard Smithd7329392015-04-21 21:46:32 +00003203 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
Richard Smith33e0f7e2015-07-22 02:08:40 +00003204 IdentifierResolver &IdResolver, bool IsModule,
3205 ASTWriter::RecordData *InterestingIdentifierOffsets)
Richard Smitha534a312015-07-21 23:54:07 +00003206 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
Richard Smith33e0f7e2015-07-22 02:08:40 +00003207 NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3208 InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
Douglas Gregore84a9da2009-04-20 20:36:09 +00003209
Richard Smithd79514e2016-02-05 19:03:40 +00003210 bool needDecls() const { return NeedDecls; }
3211
Justin Bogner25463f12014-04-18 20:27:24 +00003212 static hash_value_type ComputeHash(const IdentifierInfo* II) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +00003213 return llvm::HashString(II->getName());
Douglas Gregore84a9da2009-04-20 20:36:09 +00003214 }
Mike Stump11289f42009-09-09 15:08:12 +00003215
Richard Smith33e0f7e2015-07-22 02:08:40 +00003216 bool isInterestingIdentifier(const IdentifierInfo *II) {
3217 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3218 return isInterestingIdentifier(II, MacroOffset);
3219 }
Richard Smith9c254182015-07-19 21:41:12 +00003220 bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) {
3221 return isInterestingIdentifier(II, 0);
3222 }
3223
Mike Stump11289f42009-09-09 15:08:12 +00003224 std::pair<unsigned,unsigned>
Douglas Gregor935bc7a22011-10-27 09:33:13 +00003225 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003226 unsigned KeyLen = II->getLength() + 1;
Douglas Gregor1d583f22009-04-28 21:18:29 +00003227 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
Richard Smithd7329392015-04-21 21:46:32 +00003228 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3229 if (isInterestingIdentifier(II, MacroOffset)) {
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003230 DataLen += 2; // 2 bytes for builtin ID
3231 DataLen += 2; // 2 bytes for flags
Richard Smithd7329392015-04-21 21:46:32 +00003232 if (MacroOffset)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003233 DataLen += 4; // MacroDirectives offset.
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003234
Richard Smitha534a312015-07-21 23:54:07 +00003235 if (NeedDecls) {
3236 for (IdentifierResolver::iterator D = IdResolver.begin(II),
3237 DEnd = IdResolver.end();
3238 D != DEnd; ++D)
3239 DataLen += 4;
3240 }
Douglas Gregor1d583f22009-04-28 21:18:29 +00003241 }
Justin Bognere1c147c2014-03-28 22:03:19 +00003242 using namespace llvm::support;
3243 endian::Writer<little> LE(Out);
3244
Richard Smithdf8a8312015-03-13 04:05:01 +00003245 assert((uint16_t)DataLen == DataLen && (uint16_t)KeyLen == KeyLen);
Justin Bognere1c147c2014-03-28 22:03:19 +00003246 LE.write<uint16_t>(DataLen);
Douglas Gregorab4df582009-04-28 20:01:51 +00003247 // We emit the key length after the data length so that every
3248 // string is preceded by a 16-bit length. This matches the PTH
3249 // format for storing identifiers.
Justin Bognere1c147c2014-03-28 22:03:19 +00003250 LE.write<uint16_t>(KeyLen);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003251 return std::make_pair(KeyLen, DataLen);
3252 }
Mike Stump11289f42009-09-09 15:08:12 +00003253
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003254 void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
Douglas Gregore84a9da2009-04-20 20:36:09 +00003255 unsigned KeyLen) {
3256 // Record the location of the key data. This is used when generating
3257 // the mapping from persistent IDs to strings.
3258 Writer.SetIdentifierOffset(II, Out.tell());
Richard Smith33e0f7e2015-07-22 02:08:40 +00003259
3260 // Emit the offset of the key/data length information to the interesting
3261 // identifiers table if necessary.
3262 if (InterestingIdentifierOffsets && isInterestingIdentifier(II))
3263 InterestingIdentifierOffsets->push_back(Out.tell() - 4);
3264
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003265 Out.write(II->getNameStart(), KeyLen);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003266 }
Mike Stump11289f42009-09-09 15:08:12 +00003267
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00003268 void EmitData(raw_ostream& Out, IdentifierInfo* II,
Sebastian Redl539c5062010-08-18 23:57:32 +00003269 IdentID ID, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003270 using namespace llvm::support;
3271 endian::Writer<little> LE(Out);
Richard Smithcf97cf62015-04-19 01:34:23 +00003272
Richard Smithd7329392015-04-21 21:46:32 +00003273 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3274 if (!isInterestingIdentifier(II, MacroOffset)) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003275 LE.write<uint32_t>(ID << 1);
Douglas Gregor1d583f22009-04-28 21:18:29 +00003276 return;
3277 }
Douglas Gregorb9256522009-04-28 21:32:13 +00003278
Justin Bognere1c147c2014-03-28 22:03:19 +00003279 LE.write<uint32_t>((ID << 1) | 0x01);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003280 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3281 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
Justin Bognere1c147c2014-03-28 22:03:19 +00003282 LE.write<uint16_t>(Bits);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003283 Bits = 0;
Richard Smithd7329392015-04-21 21:46:32 +00003284 bool HadMacroDefinition = MacroOffset != 0;
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003285 Bits = (Bits << 1) | unsigned(HadMacroDefinition);
Daniel Dunbar91b640a2009-12-18 20:58:47 +00003286 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3287 Bits = (Bits << 1) | unsigned(II->isPoisoned());
Richard Smith9c254182015-07-19 21:41:12 +00003288 Bits = (Bits << 1) | unsigned(II->hasRevertedBuiltin());
Argyrios Kyrtzidis3084a612010-08-11 22:55:12 +00003289 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
Daniel Dunbar91b640a2009-12-18 20:58:47 +00003290 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
Justin Bognere1c147c2014-03-28 22:03:19 +00003291 LE.write<uint16_t>(Bits);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003292
Richard Smithd7329392015-04-21 21:46:32 +00003293 if (HadMacroDefinition)
3294 LE.write<uint32_t>(MacroOffset);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003295
Richard Smitha534a312015-07-21 23:54:07 +00003296 if (NeedDecls) {
3297 // Emit the declaration IDs in reverse order, because the
3298 // IdentifierResolver provides the declarations as they would be
3299 // visible (e.g., the function "stat" would come before the struct
3300 // "stat"), but the ASTReader adds declarations to the end of the list
3301 // (so we need to see the struct "stat" before the function "stat").
3302 // Only emit declarations that aren't from a chained PCH, though.
3303 SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II),
3304 IdResolver.end());
3305 for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(),
3306 DEnd = Decls.rend();
3307 D != DEnd; ++D)
3308 LE.write<uint32_t>(
3309 Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D)));
3310 }
Douglas Gregore84a9da2009-04-20 20:36:09 +00003311 }
3312};
3313} // end anonymous namespace
3314
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003315/// \brief Write the identifier table into the AST file.
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003316///
3317/// The identifier table consists of a blob containing string data
3318/// (the actual identifiers themselves) and a separate "offsets" index
3319/// that maps identifier IDs to locations within the blob.
Douglas Gregor935bc7a22011-10-27 09:33:13 +00003320void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3321 IdentifierResolver &IdResolver,
3322 bool IsModule) {
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003323 using namespace llvm;
3324
Richard Smith33e0f7e2015-07-22 02:08:40 +00003325 RecordData InterestingIdents;
3326
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003327 // Create and write out the blob that contains the identifier
3328 // strings.
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003329 {
Justin Bognerbb094f02014-04-18 19:57:06 +00003330 llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
Richard Smith33e0f7e2015-07-22 02:08:40 +00003331 ASTIdentifierTableTrait Trait(
3332 *this, PP, IdResolver, IsModule,
3333 (getLangOpts().CPlusPlus && IsModule) ? &InterestingIdents : nullptr);
Mike Stump11289f42009-09-09 15:08:12 +00003334
Douglas Gregore6648fb2009-04-28 20:33:11 +00003335 // Look for any identifiers that were named while processing the
3336 // headers, but are otherwise not needed. We add these to the hash
3337 // table to enable checking of the predefines buffer in the case
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003338 // where the user adds new macro definitions when building the AST
Douglas Gregore6648fb2009-04-28 20:33:11 +00003339 // file.
Chandler Carruth8440c982015-03-26 23:54:15 +00003340 SmallVector<const IdentifierInfo *, 128> IIs;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003341 for (const auto &ID : PP.getIdentifierTable())
3342 IIs.push_back(ID.second);
Chandler Carruth8440c982015-03-26 23:54:15 +00003343 // Sort the identifiers lexicographically before getting them references so
3344 // that their order is stable.
3345 std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
3346 for (const IdentifierInfo *II : IIs)
Richard Smith9c254182015-07-19 21:41:12 +00003347 if (Trait.isInterestingNonMacroIdentifier(II))
3348 getIdentifierRef(II);
Douglas Gregore6648fb2009-04-28 20:33:11 +00003349
Sebastian Redlff4a2952010-07-23 23:49:55 +00003350 // Create the on-disk hash table representation. We only store offsets
3351 // for identifiers that appear here for the first time.
3352 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
Chandler Carruth885e78c2015-03-24 21:18:10 +00003353 for (auto IdentIDPair : IdentifierIDs) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003354 auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
Chandler Carruth885e78c2015-03-24 21:18:10 +00003355 IdentID ID = IdentIDPair.second;
3356 assert(II && "NULL identifier in identifier table");
Vassil Vassilev262f41e2016-03-30 20:16:03 +00003357 // Write out identifiers if either the ID is local or the identifier has
3358 // changed since it was loaded.
3359 if (ID >= FirstIdentID || !Chain || !II->isFromAST()
3360 || II->hasChangedSinceDeserialization() ||
Richard Smithd79514e2016-02-05 19:03:40 +00003361 (Trait.needDecls() &&
3362 II->hasFETokenInfoChangedSinceDeserialization()))
Chandler Carruth885e78c2015-03-24 21:18:10 +00003363 Generator.insert(II, ID, Trait);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003364 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003365
Douglas Gregore84a9da2009-04-20 20:36:09 +00003366 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003367 SmallString<4096> IdentifierTable;
Douglas Gregora868bbd2009-04-21 22:25:48 +00003368 uint32_t BucketOffset;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003369 {
Justin Bognere1c147c2014-03-28 22:03:19 +00003370 using namespace llvm::support;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003371 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003372 // Make sure that no bucket is at offset 0
Justin Bognere1c147c2014-03-28 22:03:19 +00003373 endian::Writer<little>(Out).write<uint32_t>(0);
Douglas Gregora868bbd2009-04-21 22:25:48 +00003374 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003375 }
3376
3377 // Create a blob abbreviation
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003378 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00003379 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
Douglas Gregora868bbd2009-04-21 22:25:48 +00003380 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregore84a9da2009-04-20 20:36:09 +00003381 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregor8f45df52009-04-16 22:23:12 +00003382 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003383
3384 // Write the identifier table
Mehdi Amini57a41912015-09-10 01:46:39 +00003385 RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
Yaron Keren92e1b622015-03-18 10:17:07 +00003386 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003387 }
3388
3389 // Write the offsets table for identifier IDs.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003390 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00003391 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
Douglas Gregor0e149972009-04-25 19:10:14 +00003392 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
Douglas Gregor1ab036c2011-08-03 21:49:18 +00003393 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
Douglas Gregor0e149972009-04-25 19:10:14 +00003394 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3395 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
3396
Douglas Gregor8d7edce2013-02-08 21:30:59 +00003397#ifndef NDEBUG
3398 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3399 assert(IdentifierOffsets[I] && "Missing identifier offset?");
3400#endif
Mehdi Amini57a41912015-09-10 01:46:39 +00003401
3402 RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
3403 IdentifierOffsets.size(),
3404 FirstIdentID - NUM_PREDEF_IDENT_IDS};
Douglas Gregor0e149972009-04-25 19:10:14 +00003405 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00003406 bytes(IdentifierOffsets));
Richard Smith33e0f7e2015-07-22 02:08:40 +00003407
3408 // In C++, write the list of interesting identifiers (those that are
3409 // defined as macros, poisoned, or similar unusual things).
3410 if (!InterestingIdents.empty())
3411 Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003412}
3413
Douglas Gregorc5046832009-04-27 18:38:38 +00003414//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003415// DeclContext's Name Lookup Table Serialization
3416//===----------------------------------------------------------------------===//
3417
3418namespace {
3419// Trait used for the on-disk hash table used in the method pool.
3420class ASTDeclContextNameLookupTrait {
3421 ASTWriter &Writer;
Richard Smithd88a7f12015-09-01 20:35:42 +00003422 llvm::SmallVector<DeclID, 64> DeclIDs;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003423
3424public:
Richard Smitha06c7e62015-08-26 23:55:49 +00003425 typedef DeclarationNameKey key_type;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003426 typedef key_type key_type_ref;
3427
Richard Smithd88a7f12015-09-01 20:35:42 +00003428 /// A start and end index into DeclIDs, representing a sequence of decls.
3429 typedef std::pair<unsigned, unsigned> data_type;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003430 typedef const data_type& data_type_ref;
3431
Justin Bogner25463f12014-04-18 20:27:24 +00003432 typedef unsigned hash_value_type;
3433 typedef unsigned offset_type;
3434
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003435 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { }
3436
Richard Smithd88a7f12015-09-01 20:35:42 +00003437 template<typename Coll>
3438 data_type getData(const Coll &Decls) {
3439 unsigned Start = DeclIDs.size();
3440 for (NamedDecl *D : Decls) {
3441 DeclIDs.push_back(
3442 Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3443 }
3444 return std::make_pair(Start, DeclIDs.size());
3445 }
3446
3447 data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
3448 unsigned Start = DeclIDs.size();
3449 for (auto ID : FromReader)
3450 DeclIDs.push_back(ID);
3451 return std::make_pair(Start, DeclIDs.size());
3452 }
3453
3454 static bool EqualKey(key_type_ref a, key_type_ref b) {
3455 return a == b;
3456 }
3457
Richard Smitha06c7e62015-08-26 23:55:49 +00003458 hash_value_type ComputeHash(DeclarationNameKey Name) {
3459 return Name.getHash();
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003460 }
3461
Richard Smithd88a7f12015-09-01 20:35:42 +00003462 void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
3463 assert(Writer.hasChain() &&
3464 "have reference to loaded module file but no chain?");
3465
3466 using namespace llvm::support;
3467 endian::Writer<little>(Out)
3468 .write<uint32_t>(Writer.getChain()->getModuleFileID(F));
3469 }
3470
Richard Smitha06c7e62015-08-26 23:55:49 +00003471 std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
3472 DeclarationNameKey Name,
3473 data_type_ref Lookup) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003474 using namespace llvm::support;
3475 endian::Writer<little> LE(Out);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003476 unsigned KeyLen = 1;
Richard Smitha06c7e62015-08-26 23:55:49 +00003477 switch (Name.getKind()) {
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003478 case DeclarationName::Identifier:
3479 case DeclarationName::ObjCZeroArgSelector:
3480 case DeclarationName::ObjCOneArgSelector:
3481 case DeclarationName::ObjCMultiArgSelector:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003482 case DeclarationName::CXXLiteralOperatorName:
3483 KeyLen += 4;
3484 break;
3485 case DeclarationName::CXXOperatorName:
3486 KeyLen += 1;
3487 break;
Douglas Gregor3b65ed02011-08-02 18:32:54 +00003488 case DeclarationName::CXXConstructorName:
3489 case DeclarationName::CXXDestructorName:
3490 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003491 case DeclarationName::CXXUsingDirective:
3492 break;
3493 }
Justin Bognere1c147c2014-03-28 22:03:19 +00003494 LE.write<uint16_t>(KeyLen);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003495
Richard Smithf02662d2015-07-30 03:17:16 +00003496 // 4 bytes for each DeclID.
Richard Smithd88a7f12015-09-01 20:35:42 +00003497 unsigned DataLen = 4 * (Lookup.second - Lookup.first);
3498 assert(uint16_t(DataLen) == DataLen &&
3499 "too many decls for serialized lookup result");
Justin Bognere1c147c2014-03-28 22:03:19 +00003500 LE.write<uint16_t>(DataLen);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003501
3502 return std::make_pair(KeyLen, DataLen);
3503 }
3504
Richard Smitha06c7e62015-08-26 23:55:49 +00003505 void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003506 using namespace llvm::support;
3507 endian::Writer<little> LE(Out);
Richard Smitha06c7e62015-08-26 23:55:49 +00003508 LE.write<uint8_t>(Name.getKind());
3509 switch (Name.getKind()) {
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003510 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +00003511 case DeclarationName::CXXLiteralOperatorName:
3512 LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier()));
Benjamin Kramer53750b12012-09-19 13:40:40 +00003513 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003514 case DeclarationName::ObjCZeroArgSelector:
3515 case DeclarationName::ObjCOneArgSelector:
3516 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00003517 LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
Benjamin Kramer53750b12012-09-19 13:40:40 +00003518 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003519 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00003520 assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
Benjamin Kramer53750b12012-09-19 13:40:40 +00003521 "Invalid operator?");
Richard Smitha06c7e62015-08-26 23:55:49 +00003522 LE.write<uint8_t>(Name.getOperatorKind());
Benjamin Kramer53750b12012-09-19 13:40:40 +00003523 return;
Douglas Gregor3b65ed02011-08-02 18:32:54 +00003524 case DeclarationName::CXXConstructorName:
3525 case DeclarationName::CXXDestructorName:
3526 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003527 case DeclarationName::CXXUsingDirective:
Benjamin Kramer53750b12012-09-19 13:40:40 +00003528 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003529 }
Benjamin Kramer53750b12012-09-19 13:40:40 +00003530
3531 llvm_unreachable("Invalid name kind?");
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003532 }
3533
Richard Smitha06c7e62015-08-26 23:55:49 +00003534 void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
3535 unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003536 using namespace llvm::support;
3537 endian::Writer<little> LE(Out);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003538 uint64_t Start = Out.tell(); (void)Start;
Richard Smithd88a7f12015-09-01 20:35:42 +00003539 for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
3540 LE.write<uint32_t>(DeclIDs[I]);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003541 assert(Out.tell() - Start == DataLen && "Data length is wrong");
3542 }
3543};
3544} // end anonymous namespace
3545
Chandler Carruthe972c362015-03-26 03:11:40 +00003546bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
3547 DeclContext *DC) {
3548 return Result.hasExternalDecls() && DC->NeedToReconcileExternalVisibleStorage;
3549}
3550
3551bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
3552 DeclContext *DC) {
3553 for (auto *D : Result.getLookupResult())
3554 if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
3555 return false;
3556
3557 return true;
3558}
3559
Richard Smithd88a7f12015-09-01 20:35:42 +00003560void
Chandler Carruthe972c362015-03-26 03:11:40 +00003561ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
Richard Smithcd45dbc2014-04-19 03:48:30 +00003562 llvm::SmallVectorImpl<char> &LookupTable) {
Chandler Carruthe972c362015-03-26 03:11:40 +00003563 assert(!ConstDC->HasLazyLocalLexicalLookups &&
3564 !ConstDC->HasLazyExternalLexicalLookups &&
Richard Smith9e2341d2015-03-23 03:25:59 +00003565 "must call buildLookups first");
Richard Smithcd45dbc2014-04-19 03:48:30 +00003566
Chandler Carruthe972c362015-03-26 03:11:40 +00003567 // FIXME: We need to build the lookups table, which is logically const.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003568 auto *DC = const_cast<DeclContext*>(ConstDC);
Chandler Carruthe972c362015-03-26 03:11:40 +00003569 assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
3570
3571 // Create the on-disk hash table representation.
Richard Smithd88a7f12015-09-01 20:35:42 +00003572 MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait,
3573 ASTDeclContextNameLookupTrait> Generator;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003574 ASTDeclContextNameLookupTrait Trait(*this);
3575
Chandler Carruthe972c362015-03-26 03:11:40 +00003576 // The first step is to collect the declaration names which we need to
3577 // serialize into the name lookup table, and to collect them in a stable
3578 // order.
3579 SmallVector<DeclarationName, 16> Names;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003580
Chandler Carruthe972c362015-03-26 03:11:40 +00003581 // We also build up small sets of the constructor and conversion function
3582 // names which are visible.
3583 llvm::SmallSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003584
Chandler Carruthe972c362015-03-26 03:11:40 +00003585 for (auto &Lookup : *DC->buildLookup()) {
3586 auto &Name = Lookup.first;
3587 auto &Result = Lookup.second;
3588
Douglas Gregor7dd37e52015-11-03 01:20:54 +00003589 // If there are no local declarations in our lookup result, we
3590 // don't need to write an entry for the name at all. If we can't
3591 // write out a lookup set without performing more deserialization,
3592 // just skip this entry.
3593 if (isLookupResultExternal(Result, DC) &&
Chandler Carruthe972c362015-03-26 03:11:40 +00003594 isLookupResultEntirelyExternal(Result, DC))
3595 continue;
3596
3597 // We also skip empty results. If any of the results could be external and
3598 // the currently available results are empty, then all of the results are
3599 // external and we skip it above. So the only way we get here with an empty
3600 // results is when no results could have been external *and* we have
3601 // external results.
3602 //
3603 // FIXME: While we might want to start emitting on-disk entries for negative
3604 // lookups into a decl context as an optimization, today we *have* to skip
3605 // them because there are names with empty lookup results in decl contexts
3606 // which we can't emit in any stable ordering: we lookup constructors and
3607 // conversion functions in the enclosing namespace scope creating empty
3608 // results for them. This in almost certainly a bug in Clang's name lookup,
3609 // but that is likely to be hard or impossible to fix and so we tolerate it
3610 // here by omitting lookups with empty results.
3611 if (Lookup.second.getLookupResult().empty())
3612 continue;
3613
3614 switch (Lookup.first.getNameKind()) {
3615 default:
3616 Names.push_back(Lookup.first);
3617 break;
3618
Richard Smithcd45dbc2014-04-19 03:48:30 +00003619 case DeclarationName::CXXConstructorName:
Chandler Carruthe972c362015-03-26 03:11:40 +00003620 assert(isa<CXXRecordDecl>(DC) &&
3621 "Cannot have a constructor name outside of a class!");
3622 ConstructorNameSet.insert(Name);
3623 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003624
3625 case DeclarationName::CXXConversionFunctionName:
Chandler Carruthe972c362015-03-26 03:11:40 +00003626 assert(isa<CXXRecordDecl>(DC) &&
3627 "Cannot have a conversion function name outside of a class!");
3628 ConversionNameSet.insert(Name);
Rafael Espindolac606b3e2015-03-25 04:43:15 +00003629 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003630 }
Chandler Carruth75c9f132015-03-25 00:34:51 +00003631 }
Chandler Carruth75c9f132015-03-25 00:34:51 +00003632
Chandler Carruthe972c362015-03-26 03:11:40 +00003633 // Sort the names into a stable order.
3634 std::sort(Names.begin(), Names.end());
3635
Chandler Carruthffbf7052015-03-26 22:27:09 +00003636 if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
Chandler Carruthe972c362015-03-26 03:11:40 +00003637 // We need to establish an ordering of constructor and conversion function
Chandler Carruthffbf7052015-03-26 22:27:09 +00003638 // names, and they don't have an intrinsic ordering.
Chandler Carruthe972c362015-03-26 03:11:40 +00003639
Chandler Carruthffbf7052015-03-26 22:27:09 +00003640 // First we try the easy case by forming the current context's constructor
3641 // name and adding that name first. This is a very useful optimization to
3642 // avoid walking the lexical declarations in many cases, and it also
3643 // handles the only case where a constructor name can come from some other
3644 // lexical context -- when that name is an implicit constructor merged from
3645 // another declaration in the redecl chain. Any non-implicit constructor or
3646 // conversion function which doesn't occur in all the lexical contexts
3647 // would be an ODR violation.
3648 auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
3649 Context->getCanonicalType(Context->getRecordType(D)));
3650 if (ConstructorNameSet.erase(ImplicitCtorName))
3651 Names.push_back(ImplicitCtorName);
Chandler Carruthe972c362015-03-26 03:11:40 +00003652
Chandler Carruthffbf7052015-03-26 22:27:09 +00003653 // If we still have constructors or conversion functions, we walk all the
3654 // names in the decl and add the constructors and conversion functions
3655 // which are visible in the order they lexically occur within the context.
3656 if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
3657 for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
3658 if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
3659 auto Name = ChildND->getDeclName();
3660 switch (Name.getNameKind()) {
3661 default:
3662 continue;
3663
3664 case DeclarationName::CXXConstructorName:
3665 if (ConstructorNameSet.erase(Name))
3666 Names.push_back(Name);
3667 break;
3668
3669 case DeclarationName::CXXConversionFunctionName:
3670 if (ConversionNameSet.erase(Name))
3671 Names.push_back(Name);
3672 break;
3673 }
3674
3675 if (ConstructorNameSet.empty() && ConversionNameSet.empty())
3676 break;
Chandler Carruthe972c362015-03-26 03:11:40 +00003677 }
3678
Chandler Carruthe972c362015-03-26 03:11:40 +00003679 assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
3680 "constructors by walking all the "
3681 "lexical members of the context.");
3682 assert(ConversionNameSet.empty() && "Failed to find all of the visible "
3683 "conversion functions by walking all "
3684 "the lexical members of the context.");
Richard Smith961eae52014-03-25 01:14:22 +00003685 }
3686
Chandler Carruthe972c362015-03-26 03:11:40 +00003687 // Next we need to do a lookup with each name into this decl context to fully
3688 // populate any results from external sources. We don't actually use the
3689 // results of these lookups because we only want to use the results after all
3690 // results have been loaded and the pointers into them will be stable.
3691 for (auto &Name : Names)
3692 DC->lookup(Name);
3693
3694 // Now we need to insert the results for each name into the hash table. For
3695 // constructor names and conversion function names, we actually need to merge
3696 // all of the results for them into one list of results each and insert
3697 // those.
3698 SmallVector<NamedDecl *, 8> ConstructorDecls;
3699 SmallVector<NamedDecl *, 8> ConversionDecls;
3700
3701 // Now loop over the names, either inserting them or appending for the two
3702 // special cases.
3703 for (auto &Name : Names) {
3704 DeclContext::lookup_result Result = DC->noload_lookup(Name);
3705
3706 switch (Name.getNameKind()) {
3707 default:
Richard Smithd88a7f12015-09-01 20:35:42 +00003708 Generator.insert(Name, Trait.getData(Result), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00003709 break;
3710
3711 case DeclarationName::CXXConstructorName:
3712 ConstructorDecls.append(Result.begin(), Result.end());
3713 break;
3714
3715 case DeclarationName::CXXConversionFunctionName:
3716 ConversionDecls.append(Result.begin(), Result.end());
3717 break;
3718 }
3719 }
3720
3721 // Handle our two special cases if we ended up having any. We arbitrarily use
3722 // the first declaration's name here because the name itself isn't part of
3723 // the key, only the kind of name is used.
3724 if (!ConstructorDecls.empty())
3725 Generator.insert(ConstructorDecls.front()->getDeclName(),
Richard Smithd88a7f12015-09-01 20:35:42 +00003726 Trait.getData(ConstructorDecls), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00003727 if (!ConversionDecls.empty())
3728 Generator.insert(ConversionDecls.front()->getDeclName(),
Richard Smithd88a7f12015-09-01 20:35:42 +00003729 Trait.getData(ConversionDecls), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00003730
Richard Smithd88a7f12015-09-01 20:35:42 +00003731 // Create the on-disk hash table. Also emit the existing imported and
3732 // merged table if there is one.
3733 auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr;
3734 Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr);
Richard Smith961eae52014-03-25 01:14:22 +00003735}
3736
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003737/// \brief Write the block containing all of the declaration IDs
3738/// visible from the given DeclContext.
3739///
3740/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
Sebastian Redla4071b42010-08-24 00:50:09 +00003741/// bitstream, or 0 if no block was written.
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003742uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
3743 DeclContext *DC) {
Richard Smith5fc18a92015-07-12 23:43:21 +00003744 // If we imported a key declaration of this namespace, write the visible
3745 // lookup results as an update record for it rather than including them
3746 // on this declaration. We will only look at key declarations on reload.
3747 if (isa<NamespaceDecl>(DC) && Chain &&
3748 Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) {
3749 // Only do this once, for the first local declaration of the namespace.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003750 for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
Richard Smith5fc18a92015-07-12 23:43:21 +00003751 Prev = Prev->getPreviousDecl())
3752 if (!Prev->isFromASTFile())
3753 return 0;
3754
3755 // Note that we need to emit an update record for the primary context.
3756 UpdatedDeclContexts.insert(DC->getPrimaryContext());
3757
3758 // Make sure all visible decls are written. They will be recorded later. We
3759 // do this using a side data structure so we can sort the names into
3760 // a deterministic order.
3761 StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup();
3762 SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16>
3763 LookupResults;
3764 if (Map) {
3765 LookupResults.reserve(Map->size());
3766 for (auto &Entry : *Map)
3767 LookupResults.push_back(
3768 std::make_pair(Entry.first, Entry.second.getLookupResult()));
3769 }
3770
3771 std::sort(LookupResults.begin(), LookupResults.end(), llvm::less_first());
3772 for (auto &NameAndResult : LookupResults) {
3773 DeclarationName Name = NameAndResult.first;
3774 DeclContext::lookup_result Result = NameAndResult.second;
3775 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
3776 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
3777 // We have to work around a name lookup bug here where negative lookup
3778 // results for these names get cached in namespace lookup tables (these
3779 // names should never be looked up in a namespace).
3780 assert(Result.empty() && "Cannot have a constructor or conversion "
3781 "function name in a namespace!");
3782 continue;
3783 }
3784
3785 for (NamedDecl *ND : Result)
3786 if (!ND->isFromASTFile())
3787 GetDeclRef(ND);
3788 }
3789
3790 return 0;
3791 }
3792
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003793 if (DC->getPrimaryContext() != DC)
3794 return 0;
3795
Chandler Carruthe972c362015-03-26 03:11:40 +00003796 // Skip contexts which don't support name lookup.
3797 if (!DC->isLookupContext())
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003798 return 0;
3799
3800 // If not in C++, we perform name lookup for the translation unit via the
3801 // IdentifierInfo chains, don't bother to build a visible-declarations table.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003802 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003803 return 0;
3804
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003805 // Serialize the contents of the mapping used for lookup. Note that,
3806 // although we have two very different code paths, the serialized
3807 // representation is the same for both cases: a declaration name,
3808 // followed by a size, followed by references to the visible
3809 // declarations that have that name.
3810 uint64_t Offset = Stream.GetCurrentBitNo();
Richard Smithf634c902012-03-16 06:12:59 +00003811 StoredDeclsMap *Map = DC->buildLookup();
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003812 if (!Map || Map->empty())
3813 return 0;
3814
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +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);
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003818
3819 // Write the lookup table
Mehdi Amini57a41912015-09-10 01:46:39 +00003820 RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003821 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
Yaron Keren92e1b622015-03-18 10:17:07 +00003822 LookupTable);
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003823 ++NumVisibleDeclContexts;
3824 return Offset;
3825}
3826
Sebastian Redla4071b42010-08-24 00:50:09 +00003827/// \brief Write an UPDATE_VISIBLE block for the given context.
3828///
3829/// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
3830/// DeclContext in a dependent AST file. As such, they only exist for the TU
Richard Smithf634c902012-03-16 06:12:59 +00003831/// (in C++), for namespaces, and for classes with forward-declared unscoped
3832/// enumeration members (in C++11).
Sebastian Redla4071b42010-08-24 00:50:09 +00003833void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
Richard Smith961eae52014-03-25 01:14:22 +00003834 StoredDeclsMap *Map = DC->getLookupPtr();
Sebastian Redla4071b42010-08-24 00:50:09 +00003835 if (!Map || Map->empty())
3836 return;
3837
Sebastian Redla4071b42010-08-24 00:50:09 +00003838 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003839 SmallString<4096> LookupTable;
Richard Smithd88a7f12015-09-01 20:35:42 +00003840 GenerateNameLookupTable(DC, LookupTable);
Sebastian Redla4071b42010-08-24 00:50:09 +00003841
Richard Smith5fc18a92015-07-12 23:43:21 +00003842 // If we're updating a namespace, select a key declaration as the key for the
3843 // update record; those are the only ones that will be checked on reload.
3844 if (isa<NamespaceDecl>(DC))
3845 DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
3846
Sebastian Redla4071b42010-08-24 00:50:09 +00003847 // Write the lookup table
Mehdi Amini57a41912015-09-10 01:46:39 +00003848 RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))};
Yaron Keren92e1b622015-03-18 10:17:07 +00003849 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
Sebastian Redla4071b42010-08-24 00:50:09 +00003850}
3851
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003852/// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
3853void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
Mehdi Amini57a41912015-09-10 01:46:39 +00003854 RecordData::value_type Record[] = {Opts.fp_contract};
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003855 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
3856}
3857
3858/// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
3859void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003860 if (!SemaRef.Context.getLangOpts().OpenCL)
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003861 return;
3862
3863 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
3864 RecordData Record;
3865#define OPENCLEXT(nm) Record.push_back(Opts.nm);
3866#include "clang/Basic/OpenCLExtensions.def"
3867 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
3868}
3869
Douglas Gregor404cdde2012-01-27 01:47:08 +00003870void ASTWriter::WriteObjCCategories() {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003871 SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
Douglas Gregor404cdde2012-01-27 01:47:08 +00003872 RecordData Categories;
3873
3874 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
3875 unsigned Size = 0;
3876 unsigned StartIndex = Categories.size();
3877
3878 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
3879
3880 // Allocate space for the size.
3881 Categories.push_back(0);
3882
3883 // Add the categories.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003884 for (ObjCInterfaceDecl::known_categories_iterator
3885 Cat = Class->known_categories_begin(),
3886 CatEnd = Class->known_categories_end();
3887 Cat != CatEnd; ++Cat, ++Size) {
3888 assert(getDeclID(*Cat) != 0 && "Bogus category");
3889 AddDeclRef(*Cat, Categories);
Douglas Gregor404cdde2012-01-27 01:47:08 +00003890 }
3891
3892 // Update the size.
3893 Categories[StartIndex] = Size;
3894
3895 // Record this interface -> category map.
3896 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
3897 CategoriesMap.push_back(CatInfo);
3898 }
3899
3900 // Sort the categories map by the definition ID, since the reader will be
3901 // performing binary searches on this information.
3902 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
3903
3904 // Emit the categories map.
3905 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003906
3907 auto *Abbrev = new BitCodeAbbrev();
Douglas Gregor404cdde2012-01-27 01:47:08 +00003908 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
3909 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
3910 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3911 unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00003912
3913 RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
3914 Stream.EmitRecordWithBlob(AbbrevID, Record,
3915 reinterpret_cast<char *>(CategoriesMap.data()),
Douglas Gregor404cdde2012-01-27 01:47:08 +00003916 CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
Mehdi Amini57a41912015-09-10 01:46:39 +00003917
Douglas Gregor404cdde2012-01-27 01:47:08 +00003918 // Emit the category lists.
3919 Stream.EmitRecord(OBJC_CATEGORIES, Categories);
3920}
3921
Richard Smithe40f2ba2013-08-07 21:41:30 +00003922void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
3923 Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
3924
3925 if (LPTMap.empty())
3926 return;
3927
3928 RecordData Record;
Chandler Carruth52cee4d2015-03-26 09:08:15 +00003929 for (auto LPTMapEntry : LPTMap) {
3930 const FunctionDecl *FD = LPTMapEntry.first;
3931 LateParsedTemplate *LPT = LPTMapEntry.second;
3932 AddDeclRef(FD, Record);
Richard Smithe40f2ba2013-08-07 21:41:30 +00003933 AddDeclRef(LPT->D, Record);
3934 Record.push_back(LPT->Toks.size());
3935
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003936 for (const auto &Tok : LPT->Toks) {
3937 AddToken(Tok, Record);
Richard Smithe40f2ba2013-08-07 21:41:30 +00003938 }
3939 }
3940 Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
3941}
3942
Dario Domizioli13a0a382014-05-23 12:13:25 +00003943/// \brief Write the state of 'pragma clang optimize' at the end of the module.
3944void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
3945 RecordData Record;
3946 SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
3947 AddSourceLocation(PragmaLoc, Record);
3948 Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
3949}
3950
Nico Weber779355f2016-03-02 23:22:00 +00003951/// \brief Write the state of 'pragma ms_struct' at the end of the module.
3952void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
3953 RecordData Record;
3954 Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF);
3955 Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
3956}
3957
Nico Weber42932312016-03-03 00:17:35 +00003958/// \brief Write the state of 'pragma pointers_to_members' at the end of the
3959//module.
3960void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
3961 RecordData Record;
3962 Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod);
3963 AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record);
3964 Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
3965}
3966
Douglas Gregor8f64ca12015-12-08 22:43:32 +00003967void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
3968 ModuleFileExtensionWriter &Writer) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003969 // Enter the extension block.
3970 Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
3971
3972 // Emit the metadata record abbreviation.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003973 auto *Abv = new llvm::BitCodeAbbrev();
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003974 Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
3975 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3976 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3977 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3978 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3979 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
3980 unsigned Abbrev = Stream.EmitAbbrev(Abv);
3981
3982 // Emit the metadata record.
3983 RecordData Record;
3984 auto Metadata = Writer.getExtension()->getExtensionMetadata();
3985 Record.push_back(EXTENSION_METADATA);
3986 Record.push_back(Metadata.MajorVersion);
3987 Record.push_back(Metadata.MinorVersion);
3988 Record.push_back(Metadata.BlockName.size());
3989 Record.push_back(Metadata.UserInfo.size());
3990 SmallString<64> Buffer;
3991 Buffer += Metadata.BlockName;
3992 Buffer += Metadata.UserInfo;
3993 Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
3994
3995 // Emit the contents of the extension block.
Douglas Gregor8f64ca12015-12-08 22:43:32 +00003996 Writer.writeExtensionContents(SemaRef, Stream);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003997
3998 // Exit the extension block.
3999 Stream.ExitBlock();
4000}
4001
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00004002//===----------------------------------------------------------------------===//
Douglas Gregorc5046832009-04-27 18:38:38 +00004003// General Serialization Routines
4004//===----------------------------------------------------------------------===//
4005
Richard Smith69c82bf2016-04-01 22:52:03 +00004006/// \brief Emit the list of attributes to the specified record.
Richard Smith290d8012016-04-06 17:06:00 +00004007void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) {
4008 auto &Record = *this;
Argyrios Kyrtzidis9beef8e2010-10-18 19:20:11 +00004009 Record.push_back(Attrs.size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004010 for (const auto *A : Attrs) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00004011 Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
Richard Smith290d8012016-04-06 17:06:00 +00004012 Record.AddSourceRange(A->getRange());
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00004013
Alexis Huntdcfba7b2010-08-18 23:23:40 +00004014#include "clang/Serialization/AttrPCHWrite.inc"
Daniel Dunbarfc6507e2010-05-27 02:25:39 +00004015
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00004016 }
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00004017}
4018
John McCallf413f5e2013-05-03 00:10:13 +00004019void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
4020 AddSourceLocation(Tok.getLocation(), Record);
4021 Record.push_back(Tok.getLength());
4022
4023 // FIXME: When reading literal tokens, reconstruct the literal pointer
4024 // if it is needed.
4025 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
4026 // FIXME: Should translate token kind to a stable encoding.
4027 Record.push_back(Tok.getKind());
4028 // FIXME: Should translate token flags to a stable encoding.
4029 Record.push_back(Tok.getFlags());
4030}
4031
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004032void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00004033 Record.push_back(Str.size());
4034 Record.insert(Record.end(), Str.begin(), Str.end());
4035}
4036
Richard Smith7ed1bc92014-12-05 22:42:13 +00004037bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
Richard Smith54cc3c22014-12-11 20:50:24 +00004038 assert(Context && "should have context when outputting path");
Richard Smith7ed1bc92014-12-05 22:42:13 +00004039
Richard Smith54cc3c22014-12-11 20:50:24 +00004040 bool Changed =
4041 cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004042
4043 // Remove a prefix to make the path relative, if relevant.
4044 const char *PathBegin = Path.data();
4045 const char *PathPtr =
4046 adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
4047 if (PathPtr != PathBegin) {
4048 Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
4049 Changed = true;
4050 }
4051
4052 return Changed;
4053}
4054
4055void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
4056 SmallString<128> FilePath(Path);
4057 PreparePathForOutput(FilePath);
4058 AddString(FilePath, Record);
4059}
4060
Mehdi Amini57a41912015-09-10 01:46:39 +00004061void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
Richard Smith7ed1bc92014-12-05 22:42:13 +00004062 StringRef Path) {
4063 SmallString<128> FilePath(Path);
4064 PreparePathForOutput(FilePath);
4065 Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
4066}
4067
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004068void ASTWriter::AddVersionTuple(const VersionTuple &Version,
4069 RecordDataImpl &Record) {
4070 Record.push_back(Version.getMajor());
David Blaikie05785d12013-02-20 22:23:23 +00004071 if (Optional<unsigned> Minor = Version.getMinor())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004072 Record.push_back(*Minor + 1);
4073 else
4074 Record.push_back(0);
David Blaikie05785d12013-02-20 22:23:23 +00004075 if (Optional<unsigned> Subminor = Version.getSubminor())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004076 Record.push_back(*Subminor + 1);
4077 else
4078 Record.push_back(0);
4079}
4080
Douglas Gregore84a9da2009-04-20 20:36:09 +00004081/// \brief Note that the identifier II occurs at the given offset
4082/// within the identifier table.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004083void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Sebastian Redl539c5062010-08-18 23:57:32 +00004084 IdentID ID = IdentifierIDs[II];
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00004085 // Only store offsets new to this AST file. Other identifier names are looked
Sebastian Redlff4a2952010-07-23 23:49:55 +00004086 // up earlier in the chain and thus don't need an offset.
4087 if (ID >= FirstIdentID)
4088 IdentifierOffsets[ID - FirstIdentID] = Offset;
Douglas Gregore84a9da2009-04-20 20:36:09 +00004089}
4090
Douglas Gregor95c13f52009-04-25 17:48:32 +00004091/// \brief Note that the selector Sel occurs at the given offset
4092/// within the method pool/selector table.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004093void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
Douglas Gregor95c13f52009-04-25 17:48:32 +00004094 unsigned ID = SelectorIDs[Sel];
4095 assert(ID && "Unknown selector");
Sebastian Redld95a56e2010-08-04 18:21:41 +00004096 // Don't record offsets for selectors that are also available in a different
4097 // file.
4098 if (ID < FirstSelectorID)
4099 return;
4100 SelectorOffsets[ID - FirstSelectorID] = Offset;
Douglas Gregor95c13f52009-04-25 17:48:32 +00004101}
4102
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004103ASTWriter::ASTWriter(
4104 llvm::BitstreamWriter &Stream,
4105 ArrayRef<llvm::IntrusiveRefCntPtr<ModuleFileExtension>> Extensions,
4106 bool IncludeTimestamps)
Richard Smith01b2cb42014-07-26 06:37:51 +00004107 : Stream(Stream), Context(nullptr), PP(nullptr), Chain(nullptr),
Richard Smithe75ee0f2015-08-17 07:13:32 +00004108 WritingModule(nullptr), IncludeTimestamps(IncludeTimestamps),
4109 WritingAST(false), DoneWritingDeclsAndTypes(false),
4110 ASTHasCompilerErrors(false), FirstDeclID(NUM_PREDEF_DECL_IDS),
4111 NextDeclID(FirstDeclID), FirstTypeID(NUM_PREDEF_TYPE_IDS),
4112 NextTypeID(FirstTypeID), FirstIdentID(NUM_PREDEF_IDENT_IDS),
4113 NextIdentID(FirstIdentID), FirstMacroID(NUM_PREDEF_MACRO_IDS),
4114 NextMacroID(FirstMacroID), FirstSubmoduleID(NUM_PREDEF_SUBMODULE_IDS),
Richard Smith01b2cb42014-07-26 06:37:51 +00004115 NextSubmoduleID(FirstSubmoduleID),
4116 FirstSelectorID(NUM_PREDEF_SELECTOR_IDS), NextSelectorID(FirstSelectorID),
Richard Smith290d8012016-04-06 17:06:00 +00004117 NumStatements(0), NumMacros(0),
Richard Smith01b2cb42014-07-26 06:37:51 +00004118 NumLexicalDeclContexts(0), NumVisibleDeclContexts(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00004119 NextCXXBaseSpecifiersID(1), NextCXXCtorInitializersID(1),
Richard Smithe75ee0f2015-08-17 07:13:32 +00004120 TypeExtQualAbbrev(0), TypeFunctionProtoAbbrev(0), DeclParmVarAbbrev(0),
Richard Smith01b2cb42014-07-26 06:37:51 +00004121 DeclContextLexicalAbbrev(0), DeclContextVisibleLookupAbbrev(0),
Richard Smitha27c26e2014-07-27 04:19:32 +00004122 UpdateVisibleAbbrev(0), DeclRecordAbbrev(0), DeclTypedefAbbrev(0),
Richard Smith01b2cb42014-07-26 06:37:51 +00004123 DeclVarAbbrev(0), DeclFieldAbbrev(0), DeclEnumAbbrev(0),
Richard Smitha27c26e2014-07-27 04:19:32 +00004124 DeclObjCIvarAbbrev(0), DeclCXXMethodAbbrev(0), DeclRefExprAbbrev(0),
4125 CharacterLiteralAbbrev(0), IntegerLiteralAbbrev(0),
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004126 ExprImplicitCastAbbrev(0) {
4127 for (const auto &Ext : Extensions) {
4128 if (auto Writer = Ext->createExtensionWriter(*this))
4129 ModuleFileExtensionWriters.push_back(std::move(Writer));
4130 }
4131}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004132
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004133ASTWriter::~ASTWriter() {
Reid Kleckner588c9372014-02-19 23:44:52 +00004134 llvm::DeleteContainerSeconds(FileDeclIDs);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004135}
4136
Richard Smithb3761912015-02-05 23:08:52 +00004137const LangOptions &ASTWriter::getLangOpts() const {
4138 assert(WritingAST && "can't determine lang opts when not writing AST");
4139 return Context->getLangOpts();
4140}
4141
Richard Smithe75ee0f2015-08-17 07:13:32 +00004142time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const {
4143 return IncludeTimestamps ? E->getModificationTime() : 0;
4144}
4145
Adrian Prantladbd2b12015-09-22 23:26:31 +00004146uint64_t ASTWriter::WriteAST(Sema &SemaRef, const std::string &OutputFile,
4147 Module *WritingModule, StringRef isysroot,
4148 bool hasErrors) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00004149 WritingAST = true;
Adrian Prantladbd2b12015-09-22 23:26:31 +00004150
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00004151 ASTHasCompilerErrors = hasErrors;
4152
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004153 // Emit the file header.
Douglas Gregor8f45df52009-04-16 22:23:12 +00004154 Stream.Emit((unsigned)'C', 8);
4155 Stream.Emit((unsigned)'P', 8);
4156 Stream.Emit((unsigned)'C', 8);
4157 Stream.Emit((unsigned)'H', 8);
Mike Stump11289f42009-09-09 15:08:12 +00004158
Chris Lattner28fa4e62009-04-26 22:26:21 +00004159 WriteBlockInfoBlock();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004160
Douglas Gregoreda8e122011-08-09 15:13:55 +00004161 Context = &SemaRef.Context;
Douglas Gregora28bcdd2011-12-01 02:07:58 +00004162 PP = &SemaRef.PP;
Douglas Gregora89c5ac2011-12-06 01:10:29 +00004163 this->WritingModule = WritingModule;
Adrian Prantladbd2b12015-09-22 23:26:31 +00004164 ASTFileSignature Signature =
4165 WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
Craig Toppera13603a2014-05-22 05:54:18 +00004166 Context = nullptr;
4167 PP = nullptr;
4168 this->WritingModule = nullptr;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004169 this->BaseDirectory.clear();
Craig Toppera13603a2014-05-22 05:54:18 +00004170
Douglas Gregor2fd3d402011-09-17 00:05:03 +00004171 WritingAST = false;
Adrian Prantladbd2b12015-09-22 23:26:31 +00004172 return Signature;
Sebastian Redl143413f2010-07-12 22:02:52 +00004173}
4174
Douglas Gregora94a1542011-07-27 21:45:57 +00004175template<typename Vector>
4176static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4177 ASTWriter::RecordData &Record) {
Craig Toppera13603a2014-05-22 05:54:18 +00004178 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4179 I != E; ++I) {
Douglas Gregora94a1542011-07-27 21:45:57 +00004180 Writer.AddDeclRef(*I, Record);
4181 }
4182}
4183
Adrian Prantladbd2b12015-09-22 23:26:31 +00004184uint64_t ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
4185 const std::string &OutputFile,
4186 Module *WritingModule) {
Sebastian Redl143413f2010-07-12 22:02:52 +00004187 using namespace llvm;
4188
Craig Toppera13603a2014-05-22 05:54:18 +00004189 bool isModule = WritingModule != nullptr;
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004190
Douglas Gregorcf68c582011-12-01 22:20:10 +00004191 // Make sure that the AST reader knows to finalize itself.
4192 if (Chain)
4193 Chain->finalizeForWriting();
4194
Sebastian Redl143413f2010-07-12 22:02:52 +00004195 ASTContext &Context = SemaRef.Context;
4196 Preprocessor &PP = SemaRef.PP;
4197
Douglas Gregordab42432011-08-12 00:15:20 +00004198 // Set up predefined declaration IDs.
Richard Smith5fc18a92015-07-12 23:43:21 +00004199 auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
4200 if (D) {
4201 assert(D->isCanonicalDecl() && "predefined decl is not canonical");
4202 DeclIDs[D] = ID;
Richard Smith5fc18a92015-07-12 23:43:21 +00004203 }
4204 };
4205 RegisterPredefDecl(Context.getTranslationUnitDecl(),
4206 PREDEF_DECL_TRANSLATION_UNIT_ID);
4207 RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
4208 RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
4209 RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
4210 RegisterPredefDecl(Context.ObjCProtocolClassDecl,
4211 PREDEF_DECL_OBJC_PROTOCOL_ID);
4212 RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
4213 RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
4214 RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
4215 PREDEF_DECL_OBJC_INSTANCETYPE_ID);
4216 RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
Richard Smith9b88a4c2015-07-27 05:40:23 +00004217 RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
Charles Davisc7d5c942015-09-17 20:55:33 +00004218 RegisterPredefDecl(Context.BuiltinMSVaListDecl,
4219 PREDEF_DECL_BUILTIN_MS_VA_LIST_ID);
Richard Smith5fc18a92015-07-12 23:43:21 +00004220 RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
David Majnemerd9b1a4f2015-11-04 03:40:30 +00004221 RegisterPredefDecl(Context.MakeIntegerSeqDecl,
4222 PREDEF_DECL_MAKE_INTEGER_SEQ_ID);
Quentin Colombet043406b2016-02-03 22:41:00 +00004223 RegisterPredefDecl(Context.CFConstantStringTypeDecl,
4224 PREDEF_DECL_CF_CONSTANT_STRING_ID);
Ben Langmuirf5416742016-02-04 00:55:24 +00004225 RegisterPredefDecl(Context.CFConstantStringTagDecl,
4226 PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID);
Meador Inge5d3fb222012-06-16 03:34:49 +00004227
Chris Lattner0c797362009-09-08 18:19:27 +00004228 // Build a record containing all of the tentative definitions in this file, in
Sebastian Redl35351a92010-01-31 22:27:38 +00004229 // TentativeDefinitions order. Generally, this record will be empty for
Chris Lattner0c797362009-09-08 18:19:27 +00004230 // headers.
Douglas Gregord4df8652009-04-22 22:02:47 +00004231 RecordData TentativeDefinitions;
Douglas Gregora94a1542011-07-27 21:45:57 +00004232 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
Douglas Gregoreb08bd42011-07-27 20:58:46 +00004233
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00004234 // Build a record containing all of the file scoped decls in this file.
4235 RecordData UnusedFileScopedDecls;
Argyrios Kyrtzidis59852362013-03-14 04:45:00 +00004236 if (!isModule)
4237 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
4238 UnusedFileScopedDecls);
Sebastian Redl08aca90252010-08-05 18:21:25 +00004239
Douglas Gregor851443c2011-08-12 01:39:19 +00004240 // Build a record containing all of the delegating constructors we still need
4241 // to resolve.
Alexis Hunt27a761d2011-05-04 23:29:54 +00004242 RecordData DelegatingCtorDecls;
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004243 if (!isModule)
4244 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
Alexis Hunt27a761d2011-05-04 23:29:54 +00004245
Douglas Gregor851443c2011-08-12 01:39:19 +00004246 // Write the set of weak, undeclared identifiers. We always write the
4247 // entire table, since later PCH files in a PCH chain are only interested in
4248 // the results at the end of the chain.
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004249 RecordData WeakUndeclaredIdentifiers;
Chandler Carruthf85d9822015-03-26 08:32:49 +00004250 for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) {
4251 IdentifierInfo *II = WeakUndeclaredIdentifier.first;
4252 WeakInfo &WI = WeakUndeclaredIdentifier.second;
4253 AddIdentifierRef(II, WeakUndeclaredIdentifiers);
4254 AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
4255 AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
4256 WeakUndeclaredIdentifiers.push_back(WI.getUsed());
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004257 }
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00004258
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004259 // Build a record containing all of the ext_vector declarations.
4260 RecordData ExtVectorDecls;
Douglas Gregorb7098a32011-07-28 00:39:29 +00004261 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004262
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004263 // Build a record containing all of the VTable uses information.
4264 RecordData VTableUses;
Argyrios Kyrtzidisedee67f2010-08-03 17:29:52 +00004265 if (!SemaRef.VTableUses.empty()) {
Argyrios Kyrtzidisedee67f2010-08-03 17:29:52 +00004266 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4267 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4268 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4269 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4270 }
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004271 }
4272
Nico Weber72889432014-09-06 01:25:55 +00004273 // Build a record containing all of the UnusedLocalTypedefNameCandidates.
4274 RecordData UnusedLocalTypedefNameCandidates;
4275 for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4276 AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
4277
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004278 // Build a record containing all of pending implicit instantiations.
Chandler Carruth54080172010-08-25 08:44:16 +00004279 RecordData PendingInstantiations;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004280 for (const auto &I : SemaRef.PendingInstantiations) {
4281 AddDeclRef(I.first, PendingInstantiations);
4282 AddSourceLocation(I.second, PendingInstantiations);
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004283 }
4284 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4285 "There are local ones at end of translation unit!");
4286
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004287 // Build a record containing some declaration references.
4288 RecordData SemaDeclRefs;
4289 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
4290 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4291 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
4292 }
4293
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004294 RecordData CUDASpecialDeclRefs;
4295 if (Context.getcudaConfigureCallDecl()) {
4296 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4297 }
4298
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004299 // Build a record containing all of the known namespaces.
4300 RecordData KnownNamespaces;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004301 for (const auto &I : SemaRef.KnownNamespaces) {
4302 if (!I.second)
4303 AddDeclRef(I.first, KnownNamespaces);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004304 }
Douglas Gregor112b9072012-10-18 05:31:06 +00004305
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004306 // Build a record of all used, undefined objects that require definitions.
4307 RecordData UndefinedButUsed;
Nick Lewyckyf0f56162013-01-31 03:23:57 +00004308
4309 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004310 SemaRef.getUndefinedButUsed(Undefined);
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004311 for (const auto &I : Undefined) {
4312 AddDeclRef(I.first, UndefinedButUsed);
4313 AddSourceLocation(I.second, UndefinedButUsed);
Nick Lewycky8334af82013-01-26 00:35:08 +00004314 }
4315
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00004316 // Build a record containing all delete-expressions that we would like to
4317 // analyze later in AST.
4318 RecordData DeleteExprsToAnalyze;
4319
4320 for (const auto &DeleteExprsInfo :
4321 SemaRef.getMismatchingDeleteExpressions()) {
4322 AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
4323 DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
4324 for (const auto &DeleteLoc : DeleteExprsInfo.second) {
4325 AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
4326 DeleteExprsToAnalyze.push_back(DeleteLoc.second);
4327 }
4328 }
4329
Douglas Gregor112b9072012-10-18 05:31:06 +00004330 // Write the control block
Adrian Prantladbd2b12015-09-22 23:26:31 +00004331 uint64_t Signature = WriteControlBlock(PP, Context, isysroot, OutputFile);
Douglas Gregor112b9072012-10-18 05:31:06 +00004332
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00004333 // Write the remaining AST contents.
Sebastian Redl539c5062010-08-18 23:57:32 +00004334 Stream.EnterSubblock(AST_BLOCK_ID, 5);
Douglas Gregor851443c2011-08-12 01:39:19 +00004335
Argyrios Kyrtzidis39605402012-12-13 21:38:23 +00004336 // This is so that older clang versions, before the introduction
4337 // of the control block, can read and reject the newer PCH format.
Mehdi Amini57a41912015-09-10 01:46:39 +00004338 {
4339 RecordData Record = {VERSION_MAJOR};
4340 Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4341 }
Argyrios Kyrtzidis39605402012-12-13 21:38:23 +00004342
Douglas Gregor851443c2011-08-12 01:39:19 +00004343 // Create a lexical update block containing all of the declarations in the
4344 // translation unit that do not come from other AST files.
4345 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00004346 SmallVector<uint32_t, 128> NewGlobalKindDeclPairs;
4347 for (const auto *D : TU->noload_decls()) {
4348 if (!D->isFromASTFile()) {
4349 NewGlobalKindDeclPairs.push_back(D->getKind());
4350 NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
4351 }
Douglas Gregor851443c2011-08-12 01:39:19 +00004352 }
4353
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004354 auto *Abv = new llvm::BitCodeAbbrev();
Douglas Gregor851443c2011-08-12 01:39:19 +00004355 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4356 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4357 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv);
Mehdi Amini57a41912015-09-10 01:46:39 +00004358 {
4359 RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
4360 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4361 bytes(NewGlobalKindDeclPairs));
4362 }
4363
Douglas Gregor851443c2011-08-12 01:39:19 +00004364 // And a visible updates block for the translation unit.
4365 Abv = new llvm::BitCodeAbbrev();
4366 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4367 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
Douglas Gregor851443c2011-08-12 01:39:19 +00004368 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4369 UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv);
4370 WriteDeclContextVisibleUpdate(TU);
Richard Smithf19e1272015-03-07 00:04:49 +00004371
4372 // If we have any extern "C" names, write out a visible update for them.
4373 if (Context.ExternCContext)
4374 WriteDeclContextVisibleUpdate(Context.ExternCContext);
Douglas Gregor851443c2011-08-12 01:39:19 +00004375
4376 // If the translation unit has an anonymous namespace, and we don't already
4377 // have an update block for it, write it as an update block.
Richard Smith6ef42932014-03-20 21:02:00 +00004378 // FIXME: Why do we not do this if there's already an update block?
Douglas Gregor851443c2011-08-12 01:39:19 +00004379 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4380 ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
Richard Smith6ef42932014-03-20 21:02:00 +00004381 if (Record.empty())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004382 Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
Douglas Gregor851443c2011-08-12 01:39:19 +00004383 }
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004384
Richard Smith5652c0f2014-03-21 01:48:23 +00004385 // Add update records for all mangling numbers and static local numbers.
4386 // These aren't really update records, but this is a convenient way of
4387 // tagging this rare extra data onto the declarations.
4388 for (const auto &Number : Context.MangleNumbers)
4389 if (!Number.first->isFromASTFile())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004390 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4391 Number.second));
Richard Smith5652c0f2014-03-21 01:48:23 +00004392 for (const auto &Number : Context.StaticLocalNumbers)
4393 if (!Number.first->isFromASTFile())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004394 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4395 Number.second));
Richard Smith5652c0f2014-03-21 01:48:23 +00004396
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004397 // Make sure visible decls, added to DeclContexts previously loaded from
4398 // an AST file, are registered for serialization.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004399 for (const auto *I : UpdatingVisibleDecls) {
4400 GetDeclRef(I);
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004401 }
4402
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +00004403 // Make sure all decls associated with an identifier are registered for
Richard Smith79bf9202015-08-24 03:33:22 +00004404 // serialization, if we're storing decls with identifiers.
4405 if (!WritingModule || !getLangOpts().CPlusPlus) {
4406 llvm::SmallVector<const IdentifierInfo*, 256> IIs;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004407 for (const auto &ID : PP.getIdentifierTable()) {
4408 const IdentifierInfo *II = ID.second;
Richard Smith79bf9202015-08-24 03:33:22 +00004409 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
4410 IIs.push_back(II);
4411 }
4412 // Sort the identifiers to visit based on their name.
4413 std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
4414 for (const IdentifierInfo *II : IIs) {
4415 for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4416 DEnd = SemaRef.IdResolver.end();
4417 D != DEnd; ++D) {
4418 GetDeclRef(*D);
4419 }
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +00004420 }
4421 }
4422
Douglas Gregor5204bde2011-08-02 16:26:37 +00004423 // Form the record of special types.
4424 RecordData SpecialTypes;
Douglas Gregor5204bde2011-08-02 16:26:37 +00004425 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
Douglas Gregor5204bde2011-08-02 16:26:37 +00004426 AddTypeRef(Context.getFILEType(), SpecialTypes);
4427 AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4428 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4429 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4430 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
Douglas Gregor5204bde2011-08-02 16:26:37 +00004431 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00004432 AddTypeRef(Context.getucontext_tType(), SpecialTypes);
Douglas Gregora28bcdd2011-12-01 02:07:58 +00004433
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004434 if (Chain) {
4435 // Write the mapping information describing our module dependencies and how
4436 // each of those modules were mapped into our own offset/ID space, so that
4437 // the reader can build the appropriate mapping to its own offset/ID space.
4438 // The map consists solely of a blob with the following format:
4439 // *(module-name-len:i16 module-name:len*i8
4440 // source-location-offset:i32
4441 // identifier-id:i32
4442 // preprocessed-entity-id:i32
4443 // macro-definition-id:i32
Douglas Gregor253eefe2011-12-01 00:59:36 +00004444 // submodule-id:i32
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004445 // selector-id:i32
4446 // declaration-id:i32
4447 // c++-base-specifiers-id:i32
4448 // type-id:i32)
4449 //
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004450 auto *Abbrev = new BitCodeAbbrev();
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004451 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4452 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4453 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(Abbrev);
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004454 SmallString<2048> Buffer;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004455 {
4456 llvm::raw_svector_ostream Out(Buffer);
Ben Langmuir785180e2014-10-20 16:27:30 +00004457 for (ModuleFile *M : Chain->ModuleMgr) {
Justin Bognere1c147c2014-03-28 22:03:19 +00004458 using namespace llvm::support;
4459 endian::Writer<little> LE(Out);
Ben Langmuir785180e2014-10-20 16:27:30 +00004460 StringRef FileName = M->FileName;
Justin Bognere1c147c2014-03-28 22:03:19 +00004461 LE.write<uint16_t>(FileName.size());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004462 Out.write(FileName.data(), FileName.size());
Ben Langmuirfe971d92014-08-16 04:54:18 +00004463
Ben Langmuir785180e2014-10-20 16:27:30 +00004464 // Note: if a base ID was uint max, it would not be possible to load
4465 // another module after it or have more than one entity inside it.
4466 uint32_t None = std::numeric_limits<uint32_t>::max();
4467
4468 auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) {
4469 assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
4470 if (ShouldWrite)
4471 LE.write<uint32_t>(BaseID);
4472 else
4473 LE.write<uint32_t>(None);
4474 };
4475
Ben Langmuirfe971d92014-08-16 04:54:18 +00004476 // These values should be unique within a chain, since they will be read
4477 // as keys into ContinuousRangeMaps.
Ben Langmuir785180e2014-10-20 16:27:30 +00004478 writeBaseIDOrNone(M->SLocEntryBaseOffset, M->LocalNumSLocEntries);
4479 writeBaseIDOrNone(M->BaseIdentifierID, M->LocalNumIdentifiers);
4480 writeBaseIDOrNone(M->BaseMacroID, M->LocalNumMacros);
4481 writeBaseIDOrNone(M->BasePreprocessedEntityID,
4482 M->NumPreprocessedEntities);
4483 writeBaseIDOrNone(M->BaseSubmoduleID, M->LocalNumSubmodules);
4484 writeBaseIDOrNone(M->BaseSelectorID, M->LocalNumSelectors);
4485 writeBaseIDOrNone(M->BaseDeclID, M->LocalNumDecls);
4486 writeBaseIDOrNone(M->BaseTypeIndex, M->LocalNumTypes);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004487 }
4488 }
Mehdi Amini57a41912015-09-10 01:46:39 +00004489 RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004490 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4491 Buffer.data(), Buffer.size());
4492 }
Richard Smithb9eab6d2014-03-20 19:44:17 +00004493
Richard Smithb9eab6d2014-03-20 19:44:17 +00004494 RecordData DeclUpdatesOffsetsRecord;
4495
Richard Smith59442b42014-03-20 20:07:19 +00004496 // Keep writing types, declarations, and declaration update records
4497 // until we've emitted all of them.
Richard Smith01b2cb42014-07-26 06:37:51 +00004498 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
4499 WriteTypeAbbrevs();
4500 WriteDeclAbbrevs();
Richard Smith59442b42014-03-20 20:07:19 +00004501 do {
4502 WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
4503 while (!DeclTypesToEmit.empty()) {
4504 DeclOrType DOT = DeclTypesToEmit.front();
4505 DeclTypesToEmit.pop();
4506 if (DOT.isType())
4507 WriteType(DOT.getType());
4508 else
4509 WriteDecl(Context, DOT.getDecl());
4510 }
4511 } while (!DeclUpdates.empty());
Richard Smithb9eab6d2014-03-20 19:44:17 +00004512 Stream.ExitBlock();
4513
Richard Smithb9eab6d2014-03-20 19:44:17 +00004514 DoneWritingDeclsAndTypes = true;
4515
4516 // These things can only be done once we've written out decls and types.
4517 WriteTypeDeclOffsets();
Richard Smith5652c0f2014-03-21 01:48:23 +00004518 if (!DeclUpdatesOffsetsRecord.empty())
4519 Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
Richard Smithb9eab6d2014-03-20 19:44:17 +00004520 WriteCXXBaseSpecifiersOffsets();
Richard Smithc2bb8182015-03-24 06:36:48 +00004521 WriteCXXCtorInitializersOffsets();
Richard Smithb9eab6d2014-03-20 19:44:17 +00004522 WriteFileDeclIDsMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00004523 WriteSourceManagerBlock(Context.getSourceManager(), PP);
Richard Smithb9eab6d2014-03-20 19:44:17 +00004524 WriteComments();
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004525 WritePreprocessor(PP, isModule);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004526 WriteHeaderSearch(PP.getHeaderSearchInfo());
Sebastian Redla19a67f2010-08-03 21:58:15 +00004527 WriteSelectors(SemaRef);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00004528 WriteReferencedSelectorsPool(SemaRef);
Richard Smith9c254182015-07-19 21:41:12 +00004529 WriteLateParsedTemplates(SemaRef);
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004530 WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
Peter Collingbourne5df20e02011-02-15 19:46:30 +00004531 WriteFPPragmaOptions(SemaRef.getFPOptions());
4532 WriteOpenCLExtensions(SemaRef);
Argyrios Kyrtzidis0f06b982013-03-27 17:17:23 +00004533 WritePragmaDiagnosticMappings(Context.getDiagnostics(), isModule);
Douglas Gregor652d82a2009-04-18 05:55:16 +00004534
Douglas Gregora89c5ac2011-12-06 01:10:29 +00004535 // If we're emitting a module, write out the submodule information.
4536 if (WritingModule)
4537 WriteSubmodules(WritingModule);
4538
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 Smithcd45dbc2014-04-19 03:48:30 +00004705 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
4706 auto *RD = cast<CXXRecordDecl>(D);
Chandler Carruth8a3d24d2015-03-26 04:27:10 +00004707 UpdatedDeclContexts.insert(RD->getPrimaryContext());
Richard Smith69c82bf2016-04-01 22:52:03 +00004708 Record.AddCXXDefinitionData(RD);
Richard Smithf1c23dc2016-04-13 02:12:03 +00004709 // FIXME: Use AddOffset here.
Richard Smithcd45dbc2014-04-19 03:48:30 +00004710 Record.push_back(WriteDeclContextLexicalBlock(
4711 *Context, const_cast<CXXRecordDecl *>(RD)));
4712
4713 // This state is sometimes updated by template instantiation, when we
4714 // switch from the specialization referring to the template declaration
4715 // to it referring to the template definition.
4716 if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
4717 Record.push_back(MSInfo->getTemplateSpecializationKind());
Richard Smith69c82bf2016-04-01 22:52:03 +00004718 Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
Richard Smithcd45dbc2014-04-19 03:48:30 +00004719 } else {
4720 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
4721 Record.push_back(Spec->getTemplateSpecializationKind());
Richard Smith69c82bf2016-04-01 22:52:03 +00004722 Record.AddSourceLocation(Spec->getPointOfInstantiation());
Richard Smithdf352052014-05-22 20:59:29 +00004723
4724 // The instantiation might have been resolved to a partial
4725 // specialization. If so, record which one.
4726 auto From = Spec->getInstantiatedFrom();
4727 if (auto PartialSpec =
4728 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
4729 Record.push_back(true);
Richard Smith69c82bf2016-04-01 22:52:03 +00004730 Record.AddDeclRef(PartialSpec);
4731 Record.AddTemplateArgumentList(
4732 &Spec->getTemplateInstantiationArgs());
Richard Smithdf352052014-05-22 20:59:29 +00004733 } else {
4734 Record.push_back(false);
4735 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00004736 }
4737 Record.push_back(RD->getTagKind());
Richard Smith69c82bf2016-04-01 22:52:03 +00004738 Record.AddSourceLocation(RD->getLocation());
4739 Record.AddSourceLocation(RD->getLocStart());
4740 Record.AddSourceLocation(RD->getRBraceLoc());
Richard Smithcd45dbc2014-04-19 03:48:30 +00004741
4742 // Instantiation may change attributes; write them all out afresh.
4743 Record.push_back(D->hasAttrs());
Richard Smith69c82bf2016-04-01 22:52:03 +00004744 if (D->hasAttrs())
4745 Record.AddAttributes(D->getAttrs());
Richard Smithcd45dbc2014-04-19 03:48:30 +00004746
4747 // FIXME: Ensure we don't get here for explicit instantiations.
4748 break;
4749 }
4750
Richard Smithf8134002015-03-10 01:41:22 +00004751 case UPD_CXX_RESOLVED_DTOR_DELETE:
Richard Smith69c82bf2016-04-01 22:52:03 +00004752 Record.AddDeclRef(Update.getDecl());
Richard Smithf8134002015-03-10 01:41:22 +00004753 break;
4754
Richard Smith564417a2014-03-20 21:47:22 +00004755 case UPD_CXX_RESOLVED_EXCEPTION_SPEC:
4756 addExceptionSpec(
Richard Smith564417a2014-03-20 21:47:22 +00004757 cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>(),
4758 Record);
4759 break;
4760
Richard Smith6ef42932014-03-20 21:02:00 +00004761 case UPD_CXX_DEDUCED_RETURN_TYPE:
4762 Record.push_back(GetOrCreateTypeID(Update.getType()));
4763 break;
4764
4765 case UPD_DECL_MARKED_USED:
4766 break;
Richard Smith5652c0f2014-03-21 01:48:23 +00004767
4768 case UPD_MANGLING_NUMBER:
4769 case UPD_STATIC_LOCAL_NUMBER:
4770 Record.push_back(Update.getNumber());
4771 break;
Richard Smith65ebb4a2015-03-26 04:09:53 +00004772
Alexey Bataev97720002014-11-11 04:05:39 +00004773 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
Richard Smith69c82bf2016-04-01 22:52:03 +00004774 Record.AddSourceRange(
4775 D->getAttr<OMPThreadPrivateDeclAttr>()->getRange());
Alexey Bataev97720002014-11-11 04:05:39 +00004776 break;
Richard Smith65ebb4a2015-03-26 04:09:53 +00004777
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00004778 case UPD_DECL_MARKED_OPENMP_DECLARETARGET:
4779 Record.AddSourceRange(
4780 D->getAttr<OMPDeclareTargetDeclAttr>()->getRange());
4781 break;
4782
Richard Smith65ebb4a2015-03-26 04:09:53 +00004783 case UPD_DECL_EXPORTED:
Richard Smith4caa4492015-05-15 02:34:32 +00004784 Record.push_back(getSubmoduleID(Update.getModule()));
Richard Smith65ebb4a2015-03-26 04:09:53 +00004785 break;
Alex Denisovfde64952015-06-26 05:28:36 +00004786
4787 case UPD_ADDED_ATTR_TO_RECORD:
Richard Smith69c82bf2016-04-01 22:52:03 +00004788 Record.AddAttributes(llvm::makeArrayRef(Update.getAttr()));
Alex Denisovfde64952015-06-26 05:28:36 +00004789 break;
Richard Smith6ef42932014-03-20 21:02:00 +00004790 }
4791 }
4792
Richard Smithd28ac5b2014-03-22 23:33:22 +00004793 if (HasUpdatedBody) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004794 const auto *Def = cast<FunctionDecl>(D);
Richard Smith4d235792014-08-07 18:53:08 +00004795 Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
Richard Smithd28ac5b2014-03-22 23:33:22 +00004796 Record.push_back(Def->isInlined());
Richard Smith69c82bf2016-04-01 22:52:03 +00004797 Record.AddSourceLocation(Def->getInnerLocStart());
Richard Smith290d8012016-04-06 17:06:00 +00004798 Record.AddFunctionDefinition(Def);
Richard Smithd28ac5b2014-03-22 23:33:22 +00004799 }
4800
Richard Smithcd45dbc2014-04-19 03:48:30 +00004801 OffsetsRecord.push_back(GetDeclRef(D));
Richard Smith69c82bf2016-04-01 22:52:03 +00004802 OffsetsRecord.push_back(Record.Emit(DECL_UPDATES));
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00004803
Richard Smithc2bb8182015-03-24 06:36:48 +00004804 FlushPendingAfterDecl();
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00004805 }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00004806}
4807
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004808void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
Richard Smithb22a1d12016-03-27 20:13:24 +00004809 uint32_t Raw = Loc.getRawEncoding();
4810 Record.push_back((Raw << 1) | (Raw >> 31));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004811}
4812
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004813void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
Chris Lattnerca025db2010-05-07 21:43:38 +00004814 AddSourceLocation(Range.getBegin(), Record);
4815 AddSourceLocation(Range.getEnd(), Record);
4816}
4817
Richard Smithf144b542016-04-08 21:54:32 +00004818void ASTRecordWriter::AddAPInt(const llvm::APInt &Value) {
4819 Record->push_back(Value.getBitWidth());
Benjamin Kramer25f9ea62010-09-06 23:43:28 +00004820 const uint64_t *Words = Value.getRawData();
Richard Smithf144b542016-04-08 21:54:32 +00004821 Record->append(Words, Words + Value.getNumWords());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004822}
4823
Richard Smithf144b542016-04-08 21:54:32 +00004824void ASTRecordWriter::AddAPSInt(const llvm::APSInt &Value) {
4825 Record->push_back(Value.isUnsigned());
4826 AddAPInt(Value);
Douglas Gregor1daeb692009-04-13 18:14:40 +00004827}
4828
Richard Smithf144b542016-04-08 21:54:32 +00004829void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) {
4830 AddAPInt(Value.bitcastToAPInt());
Douglas Gregore0a3a512009-04-14 21:55:33 +00004831}
4832
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004833void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
Douglas Gregor4621c6a2009-04-22 18:49:13 +00004834 Record.push_back(getIdentifierRef(II));
4835}
4836
Sebastian Redl539c5062010-08-18 23:57:32 +00004837IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
Craig Toppera13603a2014-05-22 05:54:18 +00004838 if (!II)
Douglas Gregor4621c6a2009-04-22 18:49:13 +00004839 return 0;
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00004840
Sebastian Redl539c5062010-08-18 23:57:32 +00004841 IdentID &ID = IdentifierIDs[II];
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00004842 if (ID == 0)
Sebastian Redlff4a2952010-07-23 23:49:55 +00004843 ID = NextIdentID++;
Douglas Gregor4621c6a2009-04-22 18:49:13 +00004844 return ID;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004845}
4846
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004847MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004848 // Don't emit builtin macros like __LINE__ to the AST file unless they
4849 // have been redefined by the header (in which case they are not
4850 // isBuiltinMacro).
Craig Toppera13603a2014-05-22 05:54:18 +00004851 if (!MI || MI->isBuiltinMacro())
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004852 return 0;
4853
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004854 MacroID &ID = MacroIDs[MI];
4855 if (ID == 0) {
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004856 ID = NextMacroID++;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004857 MacroInfoToEmitData Info = { Name, MI, ID };
4858 MacroInfosToEmit.push_back(Info);
4859 }
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004860 return ID;
4861}
4862
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004863MacroID ASTWriter::getMacroID(MacroInfo *MI) {
Craig Toppera13603a2014-05-22 05:54:18 +00004864 if (!MI || MI->isBuiltinMacro())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004865 return 0;
4866
4867 assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
4868 return MacroIDs[MI];
4869}
4870
4871uint64_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
Richard Smithd7329392015-04-21 21:46:32 +00004872 return IdentMacroDirectivesOffsetMap.lookup(Name);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004873}
4874
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004875void ASTWriter::AddSelectorRef(const Selector SelRef, RecordDataImpl &Record) {
Sebastian Redl834bb972010-08-04 17:20:04 +00004876 Record.push_back(getSelectorRef(SelRef));
4877}
4878
Sebastian Redl539c5062010-08-18 23:57:32 +00004879SelectorID ASTWriter::getSelectorRef(Selector Sel) {
Craig Toppera13603a2014-05-22 05:54:18 +00004880 if (Sel.getAsOpaquePtr() == nullptr) {
Sebastian Redl834bb972010-08-04 17:20:04 +00004881 return 0;
Steve Naroff2ddea052009-04-23 10:39:46 +00004882 }
4883
Douglas Gregor8d7edce2013-02-08 21:30:59 +00004884 SelectorID SID = SelectorIDs[Sel];
Sebastian Redld95a56e2010-08-04 18:21:41 +00004885 if (SID == 0 && Chain) {
4886 // This might trigger a ReadSelector callback, which will set the ID for
4887 // this selector.
4888 Chain->LoadSelector(Sel);
Douglas Gregor8d7edce2013-02-08 21:30:59 +00004889 SID = SelectorIDs[Sel];
Sebastian Redld95a56e2010-08-04 18:21:41 +00004890 }
Steve Naroff2ddea052009-04-23 10:39:46 +00004891 if (SID == 0) {
Sebastian Redld95a56e2010-08-04 18:21:41 +00004892 SID = NextSelectorID++;
Douglas Gregor8d7edce2013-02-08 21:30:59 +00004893 SelectorIDs[Sel] = SID;
Steve Naroff2ddea052009-04-23 10:39:46 +00004894 }
Sebastian Redl834bb972010-08-04 17:20:04 +00004895 return SID;
Steve Naroff2ddea052009-04-23 10:39:46 +00004896}
4897
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004898void ASTWriter::AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record) {
Chris Lattnercba86142010-05-10 00:25:06 +00004899 AddDeclRef(Temp->getDestructor(), Record);
4900}
4901
Richard Smithc2bb8182015-03-24 06:36:48 +00004902void ASTWriter::AddCXXCtorInitializersRef(ArrayRef<CXXCtorInitializer *> Inits,
4903 RecordDataImpl &Record) {
4904 assert(!Inits.empty() && "Empty ctor initializer sets are not recorded");
4905 CXXCtorInitializersToWrite.push_back(
4906 QueuedCXXCtorInitializers(NextCXXCtorInitializersID, Inits));
4907 Record.push_back(NextCXXCtorInitializersID++);
4908}
4909
Douglas Gregord4c5ed02010-10-29 22:39:52 +00004910void ASTWriter::AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases,
Richard Smithc2bb8182015-03-24 06:36:48 +00004911 CXXBaseSpecifier const *BasesEnd,
Douglas Gregord4c5ed02010-10-29 22:39:52 +00004912 RecordDataImpl &Record) {
4913 assert(Bases != BasesEnd && "Empty base-specifier sets are not recorded");
4914 CXXBaseSpecifiersToWrite.push_back(
4915 QueuedCXXBaseSpecifiers(NextCXXBaseSpecifiersID,
4916 Bases, BasesEnd));
4917 Record.push_back(NextCXXBaseSpecifiersID++);
4918}
4919
Richard Smith290d8012016-04-06 17:06:00 +00004920void ASTRecordWriter::AddTemplateArgumentLocInfo(
4921 TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg) {
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004922 switch (Kind) {
John McCall0ad16662009-10-29 08:12:44 +00004923 case TemplateArgument::Expression:
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004924 AddStmt(Arg.getAsExpr());
John McCall0ad16662009-10-29 08:12:44 +00004925 break;
4926 case TemplateArgument::Type:
Richard Smith290d8012016-04-06 17:06:00 +00004927 AddTypeSourceInfo(Arg.getAsTypeSourceInfo());
John McCall0ad16662009-10-29 08:12:44 +00004928 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004929 case TemplateArgument::Template:
Richard Smith290d8012016-04-06 17:06:00 +00004930 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
4931 AddSourceLocation(Arg.getTemplateNameLoc());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004932 break;
4933 case TemplateArgument::TemplateExpansion:
Richard Smith290d8012016-04-06 17:06:00 +00004934 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
4935 AddSourceLocation(Arg.getTemplateNameLoc());
4936 AddSourceLocation(Arg.getTemplateEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004937 break;
John McCall0ad16662009-10-29 08:12:44 +00004938 case TemplateArgument::Null:
4939 case TemplateArgument::Integral:
4940 case TemplateArgument::Declaration:
Eli Friedmanb826a002012-09-26 02:36:12 +00004941 case TemplateArgument::NullPtr:
John McCall0ad16662009-10-29 08:12:44 +00004942 case TemplateArgument::Pack:
Eli Friedmanb826a002012-09-26 02:36:12 +00004943 // FIXME: Is this right?
John McCall0ad16662009-10-29 08:12:44 +00004944 break;
4945 }
4946}
4947
Richard Smith290d8012016-04-06 17:06:00 +00004948void ASTRecordWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg) {
4949 AddTemplateArgument(Arg.getArgument());
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00004950
4951 if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
4952 bool InfoHasSameExpr
4953 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
Richard Smith290d8012016-04-06 17:06:00 +00004954 Record->push_back(InfoHasSameExpr);
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00004955 if (InfoHasSameExpr)
4956 return; // Avoid storing the same expr twice.
4957 }
Richard Smith290d8012016-04-06 17:06:00 +00004958 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo());
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004959}
4960
Richard Smith290d8012016-04-06 17:06:00 +00004961void ASTRecordWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo) {
Craig Toppera13603a2014-05-22 05:54:18 +00004962 if (!TInfo) {
Richard Smith290d8012016-04-06 17:06:00 +00004963 AddTypeRef(QualType());
John McCall8f115c62009-10-16 21:56:05 +00004964 return;
4965 }
4966
Richard Smith290d8012016-04-06 17:06:00 +00004967 AddTypeLoc(TInfo->getTypeLoc());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004968}
4969
Richard Smith290d8012016-04-06 17:06:00 +00004970void ASTRecordWriter::AddTypeLoc(TypeLoc TL) {
4971 AddTypeRef(TL.getType());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004972
Richard Smith290d8012016-04-06 17:06:00 +00004973 TypeLocWriter TLW(*this);
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004974 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00004975 TLW.Visit(TL);
John McCall8f115c62009-10-16 21:56:05 +00004976}
4977
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004978void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
Argyrios Kyrtzidis9ab44ea2010-08-20 16:04:14 +00004979 Record.push_back(GetOrCreateTypeID(T));
4980}
4981
Richard Smith2095ffe2015-03-16 20:11:03 +00004982TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
Richard Smith1fa5d642013-05-11 05:45:24 +00004983 assert(Context);
Richard Smith2095ffe2015-03-16 20:11:03 +00004984 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
4985 if (T.isNull())
4986 return TypeIdx();
4987 assert(!T.getLocalFastQualifiers());
4988
4989 TypeIdx &Idx = TypeIdxs[T];
4990 if (Idx.getIndex() == 0) {
4991 if (DoneWritingDeclsAndTypes) {
4992 assert(0 && "New type seen after serializing all the types to emit!");
4993 return TypeIdx();
4994 }
4995
4996 // We haven't seen this type before. Assign it a new ID and put it
4997 // into the queue of types to emit.
4998 Idx = TypeIdx(NextTypeID++);
4999 DeclTypesToEmit.push(T);
5000 }
5001 return Idx;
5002 });
Argyrios Kyrtzidis082e4612010-08-20 16:04:20 +00005003}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005004
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00005005TypeID ASTWriter::getTypeID(QualType T) const {
Richard Smith1fa5d642013-05-11 05:45:24 +00005006 assert(Context);
Richard Smith2095ffe2015-03-16 20:11:03 +00005007 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5008 if (T.isNull())
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005009 return TypeIdx();
Richard Smith2095ffe2015-03-16 20:11:03 +00005010 assert(!T.getLocalFastQualifiers());
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005011
Richard Smith2095ffe2015-03-16 20:11:03 +00005012 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
5013 assert(I != TypeIdxs.end() && "Type not emitted!");
5014 return I->second;
5015 });
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005016}
5017
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005018void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005019 Record.push_back(GetDeclRef(D));
5020}
5021
Sebastian Redl539c5062010-08-18 23:57:32 +00005022DeclID ASTWriter::GetDeclRef(const Decl *D) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005023 assert(WritingAST && "Cannot request a declaration ID before AST writing");
Craig Toppera13603a2014-05-22 05:54:18 +00005024
5025 if (!D) {
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005026 return 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005027 }
Douglas Gregorb3163e52012-01-05 22:33:30 +00005028
5029 // If D comes from an AST file, its declaration ID is already known and
5030 // fixed.
5031 if (D->isFromASTFile())
5032 return D->getGlobalID();
5033
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005034 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
Sebastian Redl539c5062010-08-18 23:57:32 +00005035 DeclID &ID = DeclIDs[D];
Mike Stump11289f42009-09-09 15:08:12 +00005036 if (ID == 0) {
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005037 if (DoneWritingDeclsAndTypes) {
5038 assert(0 && "New decl seen after serializing all the decls to emit!");
5039 return 0;
5040 }
5041
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005042 // We haven't seen this declaration before. Give it a new ID and
5043 // enqueue it in the list of declarations to emit.
Sebastian Redlff4a2952010-07-23 23:49:55 +00005044 ID = NextDeclID++;
Douglas Gregor12bfa382009-10-17 00:13:19 +00005045 DeclTypesToEmit.push(const_cast<Decl *>(D));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005046 }
5047
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005048 return ID;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005049}
5050
Sebastian Redl539c5062010-08-18 23:57:32 +00005051DeclID ASTWriter::getDeclID(const Decl *D) {
Craig Toppera13603a2014-05-22 05:54:18 +00005052 if (!D)
Douglas Gregore84a9da2009-04-20 20:36:09 +00005053 return 0;
5054
Douglas Gregorb3163e52012-01-05 22:33:30 +00005055 // If D comes from an AST file, its declaration ID is already known and
5056 // fixed.
5057 if (D->isFromASTFile())
5058 return D->getGlobalID();
5059
Douglas Gregore84a9da2009-04-20 20:36:09 +00005060 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
5061 return DeclIDs[D];
5062}
5063
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005064void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005065 assert(ID);
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005066 assert(D);
5067
5068 SourceLocation Loc = D->getLocation();
5069 if (Loc.isInvalid())
5070 return;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005071
5072 // We only keep track of the file-level declarations of each file.
5073 if (!D->getLexicalDeclContext()->isFileContext())
5074 return;
Argyrios Kyrtzidise1bc99e2012-02-24 19:45:46 +00005075 // FIXME: ParmVarDecls that are part of a function type of a parameter of
5076 // a function/objc method, should not have TU as lexical context.
Argyrios Kyrtzidisffe055a82012-02-24 01:12:38 +00005077 if (isa<ParmVarDecl>(D))
5078 return;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005079
5080 SourceManager &SM = Context->getSourceManager();
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005081 SourceLocation FileLoc = SM.getFileLoc(Loc);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005082 assert(SM.isLocalSourceLocation(FileLoc));
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005083 FileID FID;
5084 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00005085 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005086 if (FID.isInvalid())
5087 return;
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00005088 assert(SM.getSLocEntry(FID).isFile());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005089
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00005090 DeclIDInFileInfo *&Info = FileDeclIDs[FID];
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005091 if (!Info)
5092 Info = new DeclIDInFileInfo();
5093
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005094 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005095 LocDeclIDsTy &Decls = Info->DeclIDs;
5096
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005097 if (Decls.empty() || Decls.back().first <= Offset) {
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005098 Decls.push_back(LocDecl);
5099 return;
5100 }
5101
Benjamin Kramer45025c02013-08-24 13:22:59 +00005102 LocDeclIDsTy::iterator I =
5103 std::upper_bound(Decls.begin(), Decls.end(), LocDecl, llvm::less_first());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005104
5105 Decls.insert(I, LocDecl);
5106}
5107
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005108void ASTWriter::AddDeclarationName(DeclarationName Name, RecordDataImpl &Record) {
Chris Lattner258172e2009-04-27 07:35:58 +00005109 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005110 Record.push_back(Name.getNameKind());
5111 switch (Name.getNameKind()) {
5112 case DeclarationName::Identifier:
5113 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
5114 break;
5115
5116 case DeclarationName::ObjCZeroArgSelector:
5117 case DeclarationName::ObjCOneArgSelector:
5118 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff2ddea052009-04-23 10:39:46 +00005119 AddSelectorRef(Name.getObjCSelector(), Record);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005120 break;
5121
5122 case DeclarationName::CXXConstructorName:
5123 case DeclarationName::CXXDestructorName:
5124 case DeclarationName::CXXConversionFunctionName:
5125 AddTypeRef(Name.getCXXNameType(), Record);
5126 break;
5127
5128 case DeclarationName::CXXOperatorName:
5129 Record.push_back(Name.getCXXOverloadedOperator());
5130 break;
5131
Alexis Hunt3d221f22009-11-29 07:34:05 +00005132 case DeclarationName::CXXLiteralOperatorName:
5133 AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record);
5134 break;
5135
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005136 case DeclarationName::CXXUsingDirective:
5137 // No extra data to emit
5138 break;
5139 }
5140}
Chris Lattnerca025db2010-05-07 21:43:38 +00005141
Richard Smithd08aeb62014-08-28 01:33:39 +00005142unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
5143 assert(needsAnonymousDeclarationNumber(D) &&
5144 "expected an anonymous declaration");
5145
5146 // Number the anonymous declarations within this context, if we've not
5147 // already done so.
5148 auto It = AnonymousDeclarationNumbers.find(D);
5149 if (It == AnonymousDeclarationNumbers.end()) {
Richard Smith2b560572015-02-07 03:11:11 +00005150 auto *DC = D->getLexicalDeclContext();
5151 numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
5152 AnonymousDeclarationNumbers[ND] = Number;
5153 });
Richard Smithd08aeb62014-08-28 01:33:39 +00005154
5155 It = AnonymousDeclarationNumbers.find(D);
5156 assert(It != AnonymousDeclarationNumbers.end() &&
5157 "declaration not found within its lexical context");
5158 }
5159
5160 return It->second;
5161}
5162
Richard Smith290d8012016-04-06 17:06:00 +00005163void ASTRecordWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
5164 DeclarationName Name) {
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005165 switch (Name.getNameKind()) {
5166 case DeclarationName::CXXConstructorName:
5167 case DeclarationName::CXXDestructorName:
5168 case DeclarationName::CXXConversionFunctionName:
Richard Smith290d8012016-04-06 17:06:00 +00005169 AddTypeSourceInfo(DNLoc.NamedType.TInfo);
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005170 break;
5171
5172 case DeclarationName::CXXOperatorName:
Richard Smith290d8012016-04-06 17:06:00 +00005173 AddSourceLocation(SourceLocation::getFromRawEncoding(
5174 DNLoc.CXXOperatorName.BeginOpNameLoc));
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005175 AddSourceLocation(
Richard Smith290d8012016-04-06 17:06:00 +00005176 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc));
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005177 break;
5178
5179 case DeclarationName::CXXLiteralOperatorName:
Richard Smith290d8012016-04-06 17:06:00 +00005180 AddSourceLocation(SourceLocation::getFromRawEncoding(
5181 DNLoc.CXXLiteralOperatorName.OpNameLoc));
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005182 break;
5183
5184 case DeclarationName::Identifier:
5185 case DeclarationName::ObjCZeroArgSelector:
5186 case DeclarationName::ObjCOneArgSelector:
5187 case DeclarationName::ObjCMultiArgSelector:
5188 case DeclarationName::CXXUsingDirective:
5189 break;
5190 }
5191}
5192
Richard Smith290d8012016-04-06 17:06:00 +00005193void ASTRecordWriter::AddDeclarationNameInfo(
5194 const DeclarationNameInfo &NameInfo) {
5195 AddDeclarationName(NameInfo.getName());
5196 AddSourceLocation(NameInfo.getLoc());
5197 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName());
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005198}
5199
Richard Smith290d8012016-04-06 17:06:00 +00005200void ASTRecordWriter::AddQualifierInfo(const QualifierInfo &Info) {
5201 AddNestedNameSpecifierLoc(Info.QualifierLoc);
5202 Record->push_back(Info.NumTemplParamLists);
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005203 for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i)
Richard Smith290d8012016-04-06 17:06:00 +00005204 AddTemplateParameterList(Info.TemplParamLists[i]);
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005205}
5206
Sebastian Redl55c0ad52010-08-18 23:56:21 +00005207void ASTWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005208 RecordDataImpl &Record) {
Chris Lattnerca025db2010-05-07 21:43:38 +00005209 // Nested name specifiers usually aren't too long. I think that 8 would
Chris Lattner57540c52011-04-15 05:22:18 +00005210 // typically accommodate the vast majority.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005211 SmallVector<NestedNameSpecifier *, 8> NestedNames;
Chris Lattnerca025db2010-05-07 21:43:38 +00005212
5213 // Push each of the NNS's onto a stack for serialization in reverse order.
5214 while (NNS) {
5215 NestedNames.push_back(NNS);
5216 NNS = NNS->getPrefix();
5217 }
5218
5219 Record.push_back(NestedNames.size());
5220 while(!NestedNames.empty()) {
5221 NNS = NestedNames.pop_back_val();
5222 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
5223 Record.push_back(Kind);
5224 switch (Kind) {
5225 case NestedNameSpecifier::Identifier:
5226 AddIdentifierRef(NNS->getAsIdentifier(), Record);
5227 break;
5228
5229 case NestedNameSpecifier::Namespace:
5230 AddDeclRef(NNS->getAsNamespace(), Record);
5231 break;
5232
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005233 case NestedNameSpecifier::NamespaceAlias:
5234 AddDeclRef(NNS->getAsNamespaceAlias(), Record);
5235 break;
5236
Chris Lattnerca025db2010-05-07 21:43:38 +00005237 case NestedNameSpecifier::TypeSpec:
5238 case NestedNameSpecifier::TypeSpecWithTemplate:
5239 AddTypeRef(QualType(NNS->getAsType(), 0), Record);
5240 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5241 break;
5242
5243 case NestedNameSpecifier::Global:
5244 // Don't need to write an associated value.
5245 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00005246
5247 case NestedNameSpecifier::Super:
5248 AddDeclRef(NNS->getAsRecordDecl(), Record);
5249 break;
Chris Lattnerca025db2010-05-07 21:43:38 +00005250 }
5251 }
5252}
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005253
Richard Smith290d8012016-04-06 17:06:00 +00005254void ASTRecordWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005255 // Nested name specifiers usually aren't too long. I think that 8 would
Chris Lattner57540c52011-04-15 05:22:18 +00005256 // typically accommodate the vast majority.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005257 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005258
5259 // Push each of the nested-name-specifiers's onto a stack for
5260 // serialization in reverse order.
5261 while (NNS) {
5262 NestedNames.push_back(NNS);
5263 NNS = NNS.getPrefix();
5264 }
5265
Richard Smith290d8012016-04-06 17:06:00 +00005266 Record->push_back(NestedNames.size());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005267 while(!NestedNames.empty()) {
5268 NNS = NestedNames.pop_back_val();
5269 NestedNameSpecifier::SpecifierKind Kind
5270 = NNS.getNestedNameSpecifier()->getKind();
Richard Smith290d8012016-04-06 17:06:00 +00005271 Record->push_back(Kind);
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005272 switch (Kind) {
5273 case NestedNameSpecifier::Identifier:
Richard Smith290d8012016-04-06 17:06:00 +00005274 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier());
5275 AddSourceRange(NNS.getLocalSourceRange());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005276 break;
5277
5278 case NestedNameSpecifier::Namespace:
Richard Smith290d8012016-04-06 17:06:00 +00005279 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace());
5280 AddSourceRange(NNS.getLocalSourceRange());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005281 break;
5282
5283 case NestedNameSpecifier::NamespaceAlias:
Richard Smith290d8012016-04-06 17:06:00 +00005284 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias());
5285 AddSourceRange(NNS.getLocalSourceRange());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005286 break;
5287
5288 case NestedNameSpecifier::TypeSpec:
5289 case NestedNameSpecifier::TypeSpecWithTemplate:
Richard Smith290d8012016-04-06 17:06:00 +00005290 Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5291 AddTypeLoc(NNS.getTypeLoc());
5292 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005293 break;
5294
5295 case NestedNameSpecifier::Global:
Richard Smith290d8012016-04-06 17:06:00 +00005296 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005297 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00005298
5299 case NestedNameSpecifier::Super:
Richard Smith290d8012016-04-06 17:06:00 +00005300 AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl());
5301 AddSourceRange(NNS.getLocalSourceRange());
Nikola Smiljanic67860242014-09-26 00:28:20 +00005302 break;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005303 }
5304 }
5305}
5306
Richard Smith290d8012016-04-06 17:06:00 +00005307void ASTRecordWriter::AddTemplateName(TemplateName Name) {
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005308 TemplateName::NameKind Kind = Name.getKind();
Richard Smith290d8012016-04-06 17:06:00 +00005309 Record->push_back(Kind);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005310 switch (Kind) {
5311 case TemplateName::Template:
Richard Smith290d8012016-04-06 17:06:00 +00005312 AddDeclRef(Name.getAsTemplateDecl());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005313 break;
5314
5315 case TemplateName::OverloadedTemplate: {
5316 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
Richard Smith290d8012016-04-06 17:06:00 +00005317 Record->push_back(OvT->size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005318 for (const auto &I : *OvT)
Richard Smith290d8012016-04-06 17:06:00 +00005319 AddDeclRef(I);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005320 break;
5321 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005322
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005323 case TemplateName::QualifiedTemplate: {
5324 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
Richard Smith290d8012016-04-06 17:06:00 +00005325 AddNestedNameSpecifier(QualT->getQualifier());
5326 Record->push_back(QualT->hasTemplateKeyword());
5327 AddDeclRef(QualT->getTemplateDecl());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005328 break;
5329 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005330
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005331 case TemplateName::DependentTemplate: {
5332 DependentTemplateName *DepT = Name.getAsDependentTemplateName();
Richard Smith290d8012016-04-06 17:06:00 +00005333 AddNestedNameSpecifier(DepT->getQualifier());
5334 Record->push_back(DepT->isIdentifier());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005335 if (DepT->isIdentifier())
Richard Smith290d8012016-04-06 17:06:00 +00005336 AddIdentifierRef(DepT->getIdentifier());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005337 else
Richard Smith290d8012016-04-06 17:06:00 +00005338 Record->push_back(DepT->getOperator());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005339 break;
5340 }
John McCalld9dfe3a2011-06-30 08:33:18 +00005341
5342 case TemplateName::SubstTemplateTemplateParm: {
5343 SubstTemplateTemplateParmStorage *subst
5344 = Name.getAsSubstTemplateTemplateParm();
Richard Smith290d8012016-04-06 17:06:00 +00005345 AddDeclRef(subst->getParameter());
5346 AddTemplateName(subst->getReplacement());
John McCalld9dfe3a2011-06-30 08:33:18 +00005347 break;
5348 }
Douglas Gregor5590be02011-01-15 06:45:20 +00005349
5350 case TemplateName::SubstTemplateTemplateParmPack: {
5351 SubstTemplateTemplateParmPackStorage *SubstPack
5352 = Name.getAsSubstTemplateTemplateParmPack();
Richard Smith290d8012016-04-06 17:06:00 +00005353 AddDeclRef(SubstPack->getParameterPack());
5354 AddTemplateArgument(SubstPack->getArgumentPack());
Douglas Gregor5590be02011-01-15 06:45:20 +00005355 break;
5356 }
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005357 }
5358}
5359
Richard Smith290d8012016-04-06 17:06:00 +00005360void ASTRecordWriter::AddTemplateArgument(const TemplateArgument &Arg) {
5361 Record->push_back(Arg.getKind());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005362 switch (Arg.getKind()) {
5363 case TemplateArgument::Null:
5364 break;
5365 case TemplateArgument::Type:
Richard Smith290d8012016-04-06 17:06:00 +00005366 AddTypeRef(Arg.getAsType());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005367 break;
5368 case TemplateArgument::Declaration:
Richard Smith290d8012016-04-06 17:06:00 +00005369 AddDeclRef(Arg.getAsDecl());
5370 AddTypeRef(Arg.getParamTypeForDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00005371 break;
5372 case TemplateArgument::NullPtr:
Richard Smith290d8012016-04-06 17:06:00 +00005373 AddTypeRef(Arg.getNullPtrType());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005374 break;
5375 case TemplateArgument::Integral:
Richard Smith290d8012016-04-06 17:06:00 +00005376 AddAPSInt(Arg.getAsIntegral());
5377 AddTypeRef(Arg.getIntegralType());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005378 break;
5379 case TemplateArgument::Template:
Richard Smith290d8012016-04-06 17:06:00 +00005380 AddTemplateName(Arg.getAsTemplateOrTemplatePattern());
Douglas Gregore1d60df2011-01-14 23:41:42 +00005381 break;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005382 case TemplateArgument::TemplateExpansion:
Richard Smith290d8012016-04-06 17:06:00 +00005383 AddTemplateName(Arg.getAsTemplateOrTemplatePattern());
David Blaikie05785d12013-02-20 22:23:23 +00005384 if (Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
Richard Smith290d8012016-04-06 17:06:00 +00005385 Record->push_back(*NumExpansions + 1);
Douglas Gregore1d60df2011-01-14 23:41:42 +00005386 else
Richard Smith290d8012016-04-06 17:06:00 +00005387 Record->push_back(0);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005388 break;
5389 case TemplateArgument::Expression:
5390 AddStmt(Arg.getAsExpr());
5391 break;
5392 case TemplateArgument::Pack:
Richard Smith290d8012016-04-06 17:06:00 +00005393 Record->push_back(Arg.pack_size());
Aaron Ballman2a89e852014-07-15 21:32:31 +00005394 for (const auto &P : Arg.pack_elements())
Richard Smith290d8012016-04-06 17:06:00 +00005395 AddTemplateArgument(P);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005396 break;
5397 }
5398}
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005399
5400void
Sebastian Redl55c0ad52010-08-18 23:56:21 +00005401ASTWriter::AddTemplateParameterList(const TemplateParameterList *TemplateParams,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005402 RecordDataImpl &Record) {
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005403 assert(TemplateParams && "No TemplateParams!");
5404 AddSourceLocation(TemplateParams->getTemplateLoc(), Record);
5405 AddSourceLocation(TemplateParams->getLAngleLoc(), Record);
5406 AddSourceLocation(TemplateParams->getRAngleLoc(), Record);
5407 Record.push_back(TemplateParams->size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005408 for (const auto &P : *TemplateParams)
5409 AddDeclRef(P, Record);
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005410}
5411
5412/// \brief Emit a template argument list.
Richard Smith290d8012016-04-06 17:06:00 +00005413void ASTRecordWriter::AddTemplateArgumentList(
5414 const TemplateArgumentList *TemplateArgs) {
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005415 assert(TemplateArgs && "No TemplateArgs!");
Richard Smith290d8012016-04-06 17:06:00 +00005416 Record->push_back(TemplateArgs->size());
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005417 for (int i=0, e = TemplateArgs->size(); i != e; ++i)
Richard Smith290d8012016-04-06 17:06:00 +00005418 AddTemplateArgument(TemplateArgs->get(i));
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005419}
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005420
Richard Smith290d8012016-04-06 17:06:00 +00005421void ASTRecordWriter::AddASTTemplateArgumentListInfo(
5422 const ASTTemplateArgumentListInfo *ASTTemplArgList) {
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005423 assert(ASTTemplArgList && "No ASTTemplArgList!");
Richard Smith290d8012016-04-06 17:06:00 +00005424 AddSourceLocation(ASTTemplArgList->LAngleLoc);
5425 AddSourceLocation(ASTTemplArgList->RAngleLoc);
5426 Record->push_back(ASTTemplArgList->NumTemplateArgs);
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005427 const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
5428 for (int i=0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
Richard Smith290d8012016-04-06 17:06:00 +00005429 AddTemplateArgumentLoc(TemplArgs[i]);
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005430}
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005431
5432void
Argyrios Kyrtzidis0f05fb92012-11-28 03:56:16 +00005433ASTWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set, RecordDataImpl &Record) {
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005434 Record.push_back(Set.size());
Argyrios Kyrtzidis0f05fb92012-11-28 03:56:16 +00005435 for (ASTUnresolvedSet::const_iterator
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005436 I = Set.begin(), E = Set.end(); I != E; ++I) {
5437 AddDeclRef(I.getDecl(), Record);
5438 Record.push_back(I.getAccess());
5439 }
5440}
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005441
Richard Smith290d8012016-04-06 17:06:00 +00005442// FIXME: Move this out of the main ASTRecordWriter interface.
5443void ASTRecordWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
5444 Record->push_back(Base.isVirtual());
5445 Record->push_back(Base.isBaseOfClass());
5446 Record->push_back(Base.getAccessSpecifierAsWritten());
5447 Record->push_back(Base.getInheritConstructors());
5448 AddTypeSourceInfo(Base.getTypeSourceInfo());
5449 AddSourceRange(Base.getSourceRange());
Douglas Gregor752a5952011-01-03 22:36:02 +00005450 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
Richard Smith290d8012016-04-06 17:06:00 +00005451 : SourceLocation());
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005452}
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00005453
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005454void ASTWriter::FlushCXXBaseSpecifiers() {
5455 RecordData Record;
Richard Smithc2bb8182015-03-24 06:36:48 +00005456 unsigned N = CXXBaseSpecifiersToWrite.size();
5457 for (unsigned I = 0; I != N; ++I) {
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005458 Record.clear();
Dmitry Polukhin790b5402016-04-06 10:01:46 +00005459
5460 const CXXBaseSpecifier *B = CXXBaseSpecifiersToWrite[I].Bases,
5461 *BEnd = CXXBaseSpecifiersToWrite[I].BasesEnd;
Richard Smith290d8012016-04-06 17:06:00 +00005462
5463 // Write the base specifier set.
5464 ASTRecordWriter Writer(*this, Record);
5465 Writer.push_back(BEnd - B);
Dmitry Polukhin790b5402016-04-06 10:01:46 +00005466 for (; B != BEnd; ++B)
Richard Smith290d8012016-04-06 17:06:00 +00005467 Writer.AddCXXBaseSpecifier(*B);
5468 uint64_t Offset = Writer.Emit(serialization::DECL_CXX_BASE_SPECIFIERS);
Dmitry Polukhin790b5402016-04-06 10:01:46 +00005469
Richard Smith290d8012016-04-06 17:06:00 +00005470 // Record the offset of this base-specifier set.
5471 //
5472 // FIXME: We don't need an indirect lookup table for these; instead, write
5473 // the base specifier record prior to the decl record and store its offset
5474 // from the decl record rather than its ID.
5475 unsigned Index = CXXBaseSpecifiersToWrite[I].ID - 1;
5476 if (Index == CXXBaseSpecifiersOffsets.size())
5477 CXXBaseSpecifiersOffsets.push_back(Offset);
5478 else {
5479 if (Index > CXXBaseSpecifiersOffsets.size())
5480 CXXBaseSpecifiersOffsets.resize(Index + 1);
5481 CXXBaseSpecifiersOffsets[Index] = Offset;
5482 }
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005483 }
5484
Richard Smithc2bb8182015-03-24 06:36:48 +00005485 assert(N == CXXBaseSpecifiersToWrite.size() &&
5486 "added more base specifiers while writing base specifiers");
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005487 CXXBaseSpecifiersToWrite.clear();
5488}
5489
Richard Smith290d8012016-04-06 17:06:00 +00005490// FIXME: Move this out of the main ASTRecordWriter interface.
5491void ASTRecordWriter::AddCXXCtorInitializers(
5492 const CXXCtorInitializer *const *CtorInitializers,
5493 unsigned NumCtorInitializers) {
5494 Record->push_back(NumCtorInitializers);
Alexis Hunt1d792652011-01-08 20:30:50 +00005495 for (unsigned i=0; i != NumCtorInitializers; ++i) {
5496 const CXXCtorInitializer *Init = CtorInitializers[i];
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005497
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005498 if (Init->isBaseInitializer()) {
Richard Smith290d8012016-04-06 17:06:00 +00005499 Record->push_back(CTOR_INITIALIZER_BASE);
5500 AddTypeSourceInfo(Init->getTypeSourceInfo());
5501 Record->push_back(Init->isBaseVirtual());
Alexis Hunt37a477f2011-05-04 01:19:08 +00005502 } else if (Init->isDelegatingInitializer()) {
Richard Smith290d8012016-04-06 17:06:00 +00005503 Record->push_back(CTOR_INITIALIZER_DELEGATING);
5504 AddTypeSourceInfo(Init->getTypeSourceInfo());
Alexis Hunt37a477f2011-05-04 01:19:08 +00005505 } else if (Init->isMemberInitializer()){
Richard Smith290d8012016-04-06 17:06:00 +00005506 Record->push_back(CTOR_INITIALIZER_MEMBER);
5507 AddDeclRef(Init->getMember());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005508 } else {
Richard Smith290d8012016-04-06 17:06:00 +00005509 Record->push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
5510 AddDeclRef(Init->getIndirectMember());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005511 }
Francois Pichetd583da02010-12-04 09:14:42 +00005512
Richard Smith290d8012016-04-06 17:06:00 +00005513 AddSourceLocation(Init->getMemberLocation());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005514 AddStmt(Init->getInit());
Richard Smith290d8012016-04-06 17:06:00 +00005515 AddSourceLocation(Init->getLParenLoc());
5516 AddSourceLocation(Init->getRParenLoc());
5517 Record->push_back(Init->isWritten());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005518 if (Init->isWritten()) {
Richard Smith290d8012016-04-06 17:06:00 +00005519 Record->push_back(Init->getSourceOrder());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005520 } else {
Richard Smith290d8012016-04-06 17:06:00 +00005521 Record->push_back(Init->getNumArrayIndices());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005522 for (unsigned i=0, e=Init->getNumArrayIndices(); i != e; ++i)
Richard Smith290d8012016-04-06 17:06:00 +00005523 AddDeclRef(Init->getArrayIndex(i));
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005524 }
5525 }
5526}
5527
Richard Smithc2bb8182015-03-24 06:36:48 +00005528void ASTWriter::FlushCXXCtorInitializers() {
5529 RecordData Record;
5530
5531 unsigned N = CXXCtorInitializersToWrite.size();
Daniel Jasperc77b0a12015-03-24 08:06:38 +00005532 (void)N; // Silence unused warning in non-assert builds.
Richard Smithc2bb8182015-03-24 06:36:48 +00005533 for (auto &Init : CXXCtorInitializersToWrite) {
5534 Record.clear();
5535
Richard Smith290d8012016-04-06 17:06:00 +00005536 ASTRecordWriter Writer(*this, Record);
5537 Writer.AddCXXCtorInitializers(Init.Inits.data(), Init.Inits.size());
5538 uint64_t Offset = Writer.Emit(serialization::DECL_CXX_CTOR_INITIALIZERS);
5539
Richard Smithc2bb8182015-03-24 06:36:48 +00005540 // Record the offset of this mem-initializer list.
5541 unsigned Index = Init.ID - 1;
5542 if (Index == CXXCtorInitializersOffsets.size())
Richard Smith290d8012016-04-06 17:06:00 +00005543 CXXCtorInitializersOffsets.push_back(Offset);
Richard Smithc2bb8182015-03-24 06:36:48 +00005544 else {
5545 if (Index > CXXCtorInitializersOffsets.size())
5546 CXXCtorInitializersOffsets.resize(Index + 1);
Richard Smith290d8012016-04-06 17:06:00 +00005547 CXXCtorInitializersOffsets[Index] = Offset;
Richard Smithc2bb8182015-03-24 06:36:48 +00005548 }
Richard Smithc2bb8182015-03-24 06:36:48 +00005549 }
5550
5551 assert(N == CXXCtorInitializersToWrite.size() &&
5552 "added more ctor initializers while writing ctor initializers");
5553 CXXCtorInitializersToWrite.clear();
5554}
5555
Richard Smith290d8012016-04-06 17:06:00 +00005556void ASTRecordWriter::AddCXXDefinitionData(const CXXRecordDecl *D) {
Richard Smith053f6c62014-05-16 23:01:30 +00005557 auto &Data = D->data();
Richard Smith290d8012016-04-06 17:06:00 +00005558 Record->push_back(Data.IsLambda);
5559 Record->push_back(Data.UserDeclaredConstructor);
5560 Record->push_back(Data.UserDeclaredSpecialMembers);
5561 Record->push_back(Data.Aggregate);
5562 Record->push_back(Data.PlainOldData);
5563 Record->push_back(Data.Empty);
5564 Record->push_back(Data.Polymorphic);
5565 Record->push_back(Data.Abstract);
5566 Record->push_back(Data.IsStandardLayout);
5567 Record->push_back(Data.HasNoNonEmptyBases);
5568 Record->push_back(Data.HasPrivateFields);
5569 Record->push_back(Data.HasProtectedFields);
5570 Record->push_back(Data.HasPublicFields);
5571 Record->push_back(Data.HasMutableFields);
5572 Record->push_back(Data.HasVariantMembers);
5573 Record->push_back(Data.HasOnlyCMembers);
5574 Record->push_back(Data.HasInClassInitializer);
5575 Record->push_back(Data.HasUninitializedReferenceMember);
5576 Record->push_back(Data.HasUninitializedFields);
5577 Record->push_back(Data.NeedOverloadResolutionForMoveConstructor);
5578 Record->push_back(Data.NeedOverloadResolutionForMoveAssignment);
5579 Record->push_back(Data.NeedOverloadResolutionForDestructor);
5580 Record->push_back(Data.DefaultedMoveConstructorIsDeleted);
5581 Record->push_back(Data.DefaultedMoveAssignmentIsDeleted);
5582 Record->push_back(Data.DefaultedDestructorIsDeleted);
5583 Record->push_back(Data.HasTrivialSpecialMembers);
5584 Record->push_back(Data.DeclaredNonTrivialSpecialMembers);
5585 Record->push_back(Data.HasIrrelevantDestructor);
5586 Record->push_back(Data.HasConstexprNonCopyMoveConstructor);
5587 Record->push_back(Data.HasDefaultedDefaultConstructor);
5588 Record->push_back(Data.DefaultedDefaultConstructorIsConstexpr);
5589 Record->push_back(Data.HasConstexprDefaultConstructor);
5590 Record->push_back(Data.HasNonLiteralTypeFieldsOrBases);
5591 Record->push_back(Data.ComputedVisibleConversions);
5592 Record->push_back(Data.UserProvidedDefaultConstructor);
5593 Record->push_back(Data.DeclaredSpecialMembers);
5594 Record->push_back(Data.ImplicitCopyConstructorHasConstParam);
5595 Record->push_back(Data.ImplicitCopyAssignmentHasConstParam);
5596 Record->push_back(Data.HasDeclaredCopyConstructorWithConstParam);
5597 Record->push_back(Data.HasDeclaredCopyAssignmentWithConstParam);
Richard Smith561fb152012-02-25 07:33:38 +00005598 // IsLambda bit is already saved.
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005599
Richard Smith290d8012016-04-06 17:06:00 +00005600 Record->push_back(Data.NumBases);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005601 if (Data.NumBases > 0)
Richard Smith290d8012016-04-06 17:06:00 +00005602 AddCXXBaseSpecifiersRef(Data.getBases(), Data.getBases() + Data.NumBases);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005603
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005604 // FIXME: Make VBases lazily computed when needed to avoid storing them.
Richard Smith290d8012016-04-06 17:06:00 +00005605 Record->push_back(Data.NumVBases);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005606 if (Data.NumVBases > 0)
Richard Smith290d8012016-04-06 17:06:00 +00005607 AddCXXBaseSpecifiersRef(Data.getVBases(),
5608 Data.getVBases() + Data.NumVBases);
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005609
Richard Smith290d8012016-04-06 17:06:00 +00005610 AddUnresolvedSet(Data.Conversions.get(*Writer->Context));
5611 AddUnresolvedSet(Data.VisibleConversions.get(*Writer->Context));
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005612 // Data.Definition is the owning decl, no need to write it.
Richard Smith290d8012016-04-06 17:06:00 +00005613 AddDeclRef(D->getFirstFriend());
Douglas Gregor99ae8062012-02-14 17:54:36 +00005614
5615 // Add lambda-specific data.
5616 if (Data.IsLambda) {
Richard Smith053f6c62014-05-16 23:01:30 +00005617 auto &Lambda = D->getLambdaData();
Richard Smith290d8012016-04-06 17:06:00 +00005618 Record->push_back(Lambda.Dependent);
5619 Record->push_back(Lambda.IsGenericLambda);
5620 Record->push_back(Lambda.CaptureDefault);
5621 Record->push_back(Lambda.NumCaptures);
5622 Record->push_back(Lambda.NumExplicitCaptures);
5623 Record->push_back(Lambda.ManglingNumber);
5624 AddDeclRef(Lambda.ContextDecl);
5625 AddTypeSourceInfo(Lambda.MethodTyInfo);
Douglas Gregor99ae8062012-02-14 17:54:36 +00005626 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00005627 const LambdaCapture &Capture = Lambda.Captures[I];
Richard Smith290d8012016-04-06 17:06:00 +00005628 AddSourceLocation(Capture.getLocation());
5629 Record->push_back(Capture.isImplicit());
5630 Record->push_back(Capture.getCaptureKind());
Richard Smithba71c082013-05-16 06:20:58 +00005631 switch (Capture.getCaptureKind()) {
Faisal Validc6b5962016-03-21 09:25:37 +00005632 case LCK_StarThis:
Richard Smithba71c082013-05-16 06:20:58 +00005633 case LCK_This:
Alexey Bataev39c81e22014-08-28 04:28:19 +00005634 case LCK_VLAType:
Richard Smithba71c082013-05-16 06:20:58 +00005635 break;
5636 case LCK_ByCopy:
Richard Smithbb13c9a2013-09-28 04:02:39 +00005637 case LCK_ByRef:
Richard Smithba71c082013-05-16 06:20:58 +00005638 VarDecl *Var =
Craig Toppera13603a2014-05-22 05:54:18 +00005639 Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
Richard Smith290d8012016-04-06 17:06:00 +00005640 AddDeclRef(Var);
Richard Smithba71c082013-05-16 06:20:58 +00005641 AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
Richard Smith290d8012016-04-06 17:06:00 +00005642 : SourceLocation());
Richard Smithba71c082013-05-16 06:20:58 +00005643 break;
5644 }
Douglas Gregor99ae8062012-02-14 17:54:36 +00005645 }
5646 }
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005647}
5648
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005649void ASTWriter::ReaderInitialized(ASTReader *Reader) {
Sebastian Redl07a89a82010-07-30 00:29:29 +00005650 assert(Reader && "Cannot remove chain");
Douglas Gregordf0c1512011-08-18 04:12:04 +00005651 assert((!Chain || Chain == Reader) && "Cannot replace chain");
Sebastian Redl07a89a82010-07-30 00:29:29 +00005652 assert(FirstDeclID == NextDeclID &&
5653 FirstTypeID == NextTypeID &&
5654 FirstIdentID == NextIdentID &&
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005655 FirstMacroID == NextMacroID &&
Douglas Gregor253eefe2011-12-01 00:59:36 +00005656 FirstSubmoduleID == NextSubmoduleID &&
Sebastian Redld95a56e2010-08-04 18:21:41 +00005657 FirstSelectorID == NextSelectorID &&
Sebastian Redl07a89a82010-07-30 00:29:29 +00005658 "Setting chain after writing has started.");
Douglas Gregor925296b2011-07-19 16:10:42 +00005659
Sebastian Redl07a89a82010-07-30 00:29:29 +00005660 Chain = Reader;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005661
Richard Smith7f330cd2015-03-18 01:42:29 +00005662 // Note, this will get called multiple times, once one the reader starts up
5663 // and again each time it's done reading a PCH or module.
Douglas Gregordf0c1512011-08-18 04:12:04 +00005664 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
5665 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
5666 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005667 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
Douglas Gregor253eefe2011-12-01 00:59:36 +00005668 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
Douglas Gregordf0c1512011-08-18 04:12:04 +00005669 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005670 NextDeclID = FirstDeclID;
5671 NextTypeID = FirstTypeID;
5672 NextIdentID = FirstIdentID;
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005673 NextMacroID = FirstMacroID;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005674 NextSelectorID = FirstSelectorID;
Douglas Gregor253eefe2011-12-01 00:59:36 +00005675 NextSubmoduleID = FirstSubmoduleID;
Sebastian Redl07a89a82010-07-30 00:29:29 +00005676}
5677
Sebastian Redl539c5062010-08-18 23:57:32 +00005678void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005679 // Always keep the highest ID. See \p TypeRead() for more information.
5680 IdentID &StoredID = IdentifierIDs[II];
5681 if (ID > StoredID)
5682 StoredID = ID;
Sebastian Redlff4a2952010-07-23 23:49:55 +00005683}
5684
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005685void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005686 // Always keep the highest ID. See \p TypeRead() for more information.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005687 MacroID &StoredID = MacroIDs[MI];
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005688 if (ID > StoredID)
5689 StoredID = ID;
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005690}
5691
Argyrios Kyrtzidisbb5c7eae2010-08-20 16:03:59 +00005692void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005693 // Always take the highest-numbered type index. This copes with an interesting
5694 // case for chained AST writing where we schedule writing the type and then,
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005695 // later, deserialize the type from another AST. In this case, we want to
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005696 // keep the higher-numbered entry so that we can properly write it out to
5697 // the AST file.
5698 TypeIdx &StoredIdx = TypeIdxs[T];
5699 if (Idx.getIndex() >= StoredIdx.getIndex())
5700 StoredIdx = Idx;
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00005701}
5702
Sebastian Redl539c5062010-08-18 23:57:32 +00005703void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005704 // Always keep the highest ID. See \p TypeRead() for more information.
5705 SelectorID &StoredID = SelectorIDs[S];
5706 if (ID > StoredID)
5707 StoredID = ID;
Sebastian Redl834bb972010-08-04 17:20:04 +00005708}
Douglas Gregor91096292010-10-02 19:29:26 +00005709
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00005710void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
Richard Smith66a81862015-05-04 02:25:31 +00005711 MacroDefinitionRecord *MD) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00005712 assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
Douglas Gregor91096292010-10-02 19:29:26 +00005713 MacroDefinitions[MD] = ID;
5714}
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005715
Douglas Gregore37a85a2011-12-02 17:30:13 +00005716void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
5717 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
5718 SubmoduleIDs[Mod] = ID;
5719}
5720
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005721void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
John McCallf937c022011-10-07 06:10:15 +00005722 assert(D->isCompleteDefinition());
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005723 assert(!WritingAST && "Already writing the AST!");
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005724 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005725 // We are interested when a PCH decl is modified.
Douglas Gregorb3722e22011-09-09 23:01:35 +00005726 if (RD->isFromASTFile()) {
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005727 // A forward reference was mutated into a definition. Rewrite it.
5728 // FIXME: This happens during template instantiation, should we
5729 // have created a new definition decl instead ?
Richard Smithcd45dbc2014-04-19 03:48:30 +00005730 assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
5731 "completed a tag from another module but not by instantiation?");
5732 DeclUpdates[RD].push_back(
5733 DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION));
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005734 }
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005735 }
5736}
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005737
Richard Smithf983f7f2015-10-13 00:23:25 +00005738static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) {
5739 if (D->isFromASTFile())
5740 return true;
5741
5742 // If we've not loaded any modules, this can't be imported.
5743 if (!Chain || !Chain->getModuleManager().size())
5744 return false;
5745
5746 // The predefined __va_list_tag struct is imported if we imported any decls.
5747 // FIXME: This is a gross hack.
5748 return D == D->getASTContext().getVaListTagDecl();
5749}
5750
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005751void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
Vassil Vassilev71eafde2016-04-06 20:56:03 +00005752 assert(DC->isLookupContext() &&
5753 "Should not add lookup results to non-lookup contexts!");
5754
Vassil Vassilev632eac32016-03-16 11:17:04 +00005755 // TU is handled elsewhere.
5756 if (isa<TranslationUnitDecl>(DC))
5757 return;
5758
5759 // Namespaces are handled elsewhere, except for template instantiations of
5760 // FunctionTemplateDecls in namespaces. We are interested in cases where the
5761 // local instantiations are added to an imported context. Only happens when
5762 // adding ADL lookup candidates, for example templated friends.
5763 if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None &&
5764 !isa<FunctionTemplateDecl>(D))
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005765 return;
5766
Richard Smithf983f7f2015-10-13 00:23:25 +00005767 // We're only interested in cases where a local declaration is added to an
5768 // imported context.
5769 if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC)))
5770 return;
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005771
Richard Smith0f4e2c42015-08-06 04:23:48 +00005772 assert(DC == DC->getPrimaryContext() && "added to non-primary context");
Douglas Gregor9f782892013-01-21 15:25:38 +00005773 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
Richard Smithe9a8bc32014-09-30 00:45:29 +00005774 assert(!WritingAST && "Already writing the AST!");
Richard Smithf983f7f2015-10-13 00:23:25 +00005775 if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) {
5776 // We're adding a visible declaration to a predefined decl context. Ensure
5777 // that we write out all of its lookup results so we don't get a nasty
5778 // surprise when we try to emit its lookup table.
5779 for (auto *Child : DC->decls())
5780 UpdatingVisibleDecls.push_back(Child);
5781 }
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005782 UpdatingVisibleDecls.push_back(D);
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005783}
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005784
5785void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
5786 assert(D->isImplicit());
Richard Smithf983f7f2015-10-13 00:23:25 +00005787
5788 // We're only interested in cases where a local declaration is added to an
5789 // imported context.
5790 if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD))
5791 return;
5792
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005793 if (!isa<CXXMethodDecl>(D))
Richard Smithf983f7f2015-10-13 00:23:25 +00005794 return;
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005795
5796 // A decl coming from PCH was modified.
John McCallf937c022011-10-07 06:10:15 +00005797 assert(RD->isCompleteDefinition());
Richard Smithe9a8bc32014-09-30 00:45:29 +00005798 assert(!WritingAST && "Already writing the AST!");
Aaron Ballman4f45b712014-03-21 15:22:56 +00005799 DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005800}
Argyrios Kyrtzidis402dbbb2010-10-28 07:38:42 +00005801
Richard Smith564417a2014-03-20 21:47:22 +00005802void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005803 assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
5804 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00005805 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005806 // If we don't already know the exception specification for this redecl
5807 // chain, add an update record for it.
5808 if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
5809 ->getType()
5810 ->castAs<FunctionProtoType>()
5811 ->getExceptionSpecType()))
5812 DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
5813 });
Richard Smith564417a2014-03-20 21:47:22 +00005814}
5815
Richard Smith1fa5d642013-05-11 05:45:24 +00005816void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
5817 assert(!WritingAST && "Already writing the AST!");
Richard Smith9e2341d2015-03-23 03:25:59 +00005818 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00005819 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005820 DeclUpdates[D].push_back(
5821 DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
5822 });
Richard Smith1fa5d642013-05-11 05:45:24 +00005823}
5824
Richard Smithf8134002015-03-10 01:41:22 +00005825void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
5826 const FunctionDecl *Delete) {
5827 assert(!WritingAST && "Already writing the AST!");
5828 assert(Delete && "Not given an operator delete");
Richard Smith9e2341d2015-03-23 03:25:59 +00005829 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00005830 Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005831 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete));
5832 });
Richard Smithf8134002015-03-10 01:41:22 +00005833}
5834
Sebastian Redlab238a72011-04-24 16:28:06 +00005835void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005836 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005837 if (!D->isFromASTFile())
Sebastian Redlab238a72011-04-24 16:28:06 +00005838 return; // Declaration not imported from PCH.
5839
Richard Smith4d235792014-08-07 18:53:08 +00005840 // Implicit function decl from a PCH was defined.
5841 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
Sebastian Redlab238a72011-04-24 16:28:06 +00005842}
5843
Richard Smithd28ac5b2014-03-22 23:33:22 +00005844void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
5845 assert(!WritingAST && "Already writing the AST!");
5846 if (!D->isFromASTFile())
5847 return;
5848
Richard Smith9e2341d2015-03-23 03:25:59 +00005849 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
Richard Smithd28ac5b2014-03-22 23:33:22 +00005850}
5851
Sebastian Redl2ac2c722011-04-29 08:19:30 +00005852void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005853 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005854 if (!D->isFromASTFile())
Sebastian Redl2ac2c722011-04-29 08:19:30 +00005855 return;
5856
5857 // Since the actual instantiation is delayed, this really means that we need
5858 // to update the instantiation location.
Richard Smith6ef42932014-03-20 21:02:00 +00005859 DeclUpdates[D].push_back(
Aaron Ballman4f45b712014-03-21 15:22:56 +00005860 DeclUpdate(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER,
5861 D->getMemberSpecializationInfo()->getPointOfInstantiation()));
Sebastian Redl2ac2c722011-04-29 08:19:30 +00005862}
5863
John McCall32791cc2016-01-06 22:34:54 +00005864void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) {
5865 assert(!WritingAST && "Already writing the AST!");
5866 if (!D->isFromASTFile())
5867 return;
5868
5869 DeclUpdates[D].push_back(
5870 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D));
5871}
5872
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00005873void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
5874 const ObjCInterfaceDecl *IFD) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005875 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005876 if (!IFD->isFromASTFile())
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00005877 return; // Declaration not imported from PCH.
Douglas Gregor404cdde2012-01-27 01:47:08 +00005878
5879 assert(IFD->getDefinition() && "Category on a class without a definition?");
5880 ObjCClassesWithCategories.insert(
5881 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00005882}
Argyrios Kyrtzidisb97a4022011-11-12 21:07:46 +00005883
Eli Friedman276dd182013-09-05 00:02:25 +00005884void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
5885 assert(!WritingAST && "Already writing the AST!");
5886 if (!D->isFromASTFile())
5887 return;
5888
Aaron Ballman4f45b712014-03-21 15:22:56 +00005889 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
Eli Friedman276dd182013-09-05 00:02:25 +00005890}
Alexey Bataev97720002014-11-11 04:05:39 +00005891
5892void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
5893 assert(!WritingAST && "Already writing the AST!");
5894 if (!D->isFromASTFile())
5895 return;
5896
5897 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE));
5898}
Richard Smith65ebb4a2015-03-26 04:09:53 +00005899
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00005900void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D) {
5901 assert(!WritingAST && "Already writing the AST!");
5902 if (!D->isFromASTFile())
5903 return;
5904
5905 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_DECLARETARGET));
5906}
5907
Richard Smith4caa4492015-05-15 02:34:32 +00005908void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
Richard Smith65ebb4a2015-03-26 04:09:53 +00005909 assert(!WritingAST && "Already writing the AST!");
5910 assert(D->isHidden() && "expected a hidden declaration");
Richard Smith4caa4492015-05-15 02:34:32 +00005911 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M));
Richard Smith65ebb4a2015-03-26 04:09:53 +00005912}
Alex Denisovfde64952015-06-26 05:28:36 +00005913
5914void ASTWriter::AddedAttributeToRecord(const Attr *Attr,
5915 const RecordDecl *Record) {
5916 assert(!WritingAST && "Already writing the AST!");
5917 if (!Record->isFromASTFile())
5918 return;
5919 DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr));
5920}