blob: c77a7099642dbf6c21af18ee305eaeb83ab13e66 [file] [log] [blame]
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001//===--- ASTWriter.cpp - AST File Writer ------------------------*- C++ -*-===//
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Sebastian Redl55c0ad52010-08-18 23:56:21 +000010// This file defines the ASTWriter class, which writes AST files.
Douglas Gregoref84c4b2009-04-09 22:27:44 +000011//
12//===----------------------------------------------------------------------===//
13
Sebastian Redl1914c6f2010-08-18 23:56:37 +000014#include "clang/Serialization/ASTWriter.h"
Douglas Gregor6623e1f2015-11-03 18:33:07 +000015#include "clang/Serialization/ModuleFileExtension.h"
Argyrios Kyrtzidis4bd97102010-08-20 16:03:52 +000016#include "ASTCommon.h"
Richard Smithd88a7f12015-09-01 20:35:42 +000017#include "ASTReaderInternals.h"
18#include "MultiOnDiskHashTable.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000019#include "clang/AST/ASTContext.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/DeclContextInternals.h"
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +000022#include "clang/AST/DeclFriend.h"
Richard Smith961eae52014-03-25 01:14:22 +000023#include "clang/AST/DeclLookups.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/AST/DeclTemplate.h"
Douglas Gregorfeb84b02009-04-14 21:18:50 +000025#include "clang/AST/Expr.h"
John McCallbfd822c2010-08-24 07:32:53 +000026#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000027#include "clang/AST/Type.h"
John McCall8f115c62009-10-16 21:56:05 +000028#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000029#include "clang/Basic/DiagnosticOptions.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000030#include "clang/Basic/FileManager.h"
Chris Lattner226efd32010-11-23 19:19:34 +000031#include "clang/Basic/FileSystemStatCache.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000032#include "clang/Basic/SourceManager.h"
Douglas Gregor4c7626e2009-04-13 16:31:14 +000033#include "clang/Basic/SourceManagerInternals.h"
Douglas Gregorbfbde532009-04-10 21:16:55 +000034#include "clang/Basic/TargetInfo.h"
Douglas Gregorcb177f12012-10-16 23:40:58 +000035#include "clang/Basic/TargetOptions.h"
Douglas Gregor7b71e632009-04-27 22:23:34 +000036#include "clang/Basic/Version.h"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000037#include "clang/Basic/VersionTuple.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "clang/Lex/HeaderSearch.h"
39#include "clang/Lex/HeaderSearchOptions.h"
40#include "clang/Lex/MacroInfo.h"
41#include "clang/Lex/PreprocessingRecord.h"
42#include "clang/Lex/Preprocessor.h"
43#include "clang/Lex/PreprocessorOptions.h"
44#include "clang/Sema/IdentifierResolver.h"
45#include "clang/Sema/Sema.h"
46#include "clang/Serialization/ASTReader.h"
Richard Smithb5aaf5a2015-09-01 02:35:58 +000047#include "clang/Serialization/SerializationDiagnostic.h"
Douglas Gregore0a3a512009-04-14 21:55:33 +000048#include "llvm/ADT/APFloat.h"
49#include "llvm/ADT/APInt.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000050#include "llvm/ADT/Hashing.h"
Daniel Dunbarf8502d52009-10-17 23:52:28 +000051#include "llvm/ADT/StringExtras.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000052#include "llvm/Bitcode/BitstreamWriter.h"
Richard Smithaada85c2016-02-06 02:06:43 +000053#include "llvm/Support/Compression.h"
Justin Bognere1c147c2014-03-28 22:03:19 +000054#include "llvm/Support/EndianStream.h"
Michael J. Spencer740857f2010-12-21 16:45:57 +000055#include "llvm/Support/FileSystem.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000056#include "llvm/Support/MemoryBuffer.h"
Justin Bognerbb094f02014-04-18 19:57:06 +000057#include "llvm/Support/OnDiskHashTable.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000058#include "llvm/Support/Path.h"
Ben Langmuir487ea142014-10-23 18:05:36 +000059#include "llvm/Support/Process.h"
Douglas Gregor925296b2011-07-19 16:10:42 +000060#include <algorithm>
Chris Lattner225dd6c2009-04-11 18:40:46 +000061#include <cstdio>
Douglas Gregor09b69892011-02-10 17:09:37 +000062#include <string.h>
Douglas Gregor925296b2011-07-19 16:10:42 +000063#include <utility>
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +000064
Douglas Gregoref84c4b2009-04-09 22:27:44 +000065using namespace clang;
Sebastian Redl539c5062010-08-18 23:57:32 +000066using namespace clang::serialization;
Douglas Gregoref84c4b2009-04-09 22:27:44 +000067
Sebastian Redl3df5a082010-07-30 17:03:48 +000068template <typename T, typename Allocator>
Reid Kleckner012665e2015-05-21 00:13:09 +000069static StringRef bytes(const std::vector<T, Allocator> &v) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000070 if (v.empty()) return StringRef();
71 return StringRef(reinterpret_cast<const char*>(&v[0]),
Benjamin Kramerd47a12a2011-04-24 17:44:50 +000072 sizeof(T) * v.size());
Sebastian Redl3df5a082010-07-30 17:03:48 +000073}
Benjamin Kramerd47a12a2011-04-24 17:44:50 +000074
75template <typename T>
Reid Kleckner012665e2015-05-21 00:13:09 +000076static StringRef bytes(const SmallVectorImpl<T> &v) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000077 return StringRef(reinterpret_cast<const char*>(v.data()),
Benjamin Kramerd47a12a2011-04-24 17:44:50 +000078 sizeof(T) * v.size());
Sebastian Redl3df5a082010-07-30 17:03:48 +000079}
80
Douglas Gregoref84c4b2009-04-09 22:27:44 +000081//===----------------------------------------------------------------------===//
82// Type serialization
83//===----------------------------------------------------------------------===//
Chris Lattner7099dbc2009-04-27 06:16:06 +000084
Douglas Gregoref84c4b2009-04-09 22:27:44 +000085namespace {
Sebastian Redl42a0f6a2010-08-18 23:56:27 +000086 class ASTTypeWriter {
Sebastian Redl55c0ad52010-08-18 23:56:21 +000087 ASTWriter &Writer;
Richard Smith69c82bf2016-04-01 22:52:03 +000088 ASTRecordWriter Record;
Douglas Gregoref84c4b2009-04-09 22:27:44 +000089
90 public:
91 /// \brief Type code that corresponds to the record generated.
Sebastian Redl539c5062010-08-18 23:57:32 +000092 TypeCode Code;
Richard Smith01b2cb42014-07-26 06:37:51 +000093 /// \brief Abbreviation to use for the record, if any.
94 unsigned AbbrevToUse;
Douglas Gregoref84c4b2009-04-09 22:27:44 +000095
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +000096 ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
Richard Smith69c82bf2016-04-01 22:52:03 +000097 : Writer(Writer), Record(Writer, Record), Code(TYPE_EXT_QUAL) { }
Douglas Gregoref84c4b2009-04-09 22:27:44 +000098
99 void VisitArrayType(const ArrayType *T);
100 void VisitFunctionType(const FunctionType *T);
101 void VisitTagType(const TagType *T);
102
103#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
104#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000105#include "clang/AST/TypeNodes.def"
106 };
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +0000107} // end anonymous namespace
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000108
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000109void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
David Blaikie83d382b2011-09-23 05:06:16 +0000110 llvm_unreachable("Built-in types are never serialized");
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000111}
112
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000113void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000114 Record.AddTypeRef(T->getElementType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000115 Code = TYPE_COMPLEX;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000116}
117
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000118void ASTTypeWriter::VisitPointerType(const PointerType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000119 Record.AddTypeRef(T->getPointeeType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000120 Code = TYPE_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000121}
122
Reid Kleckner8a365022013-06-24 17:51:48 +0000123void ASTTypeWriter::VisitDecayedType(const DecayedType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000124 Record.AddTypeRef(T->getOriginalType());
Reid Kleckner8a365022013-06-24 17:51:48 +0000125 Code = TYPE_DECAYED;
126}
127
Reid Kleckner0503a872013-12-05 01:23:43 +0000128void ASTTypeWriter::VisitAdjustedType(const AdjustedType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000129 Record.AddTypeRef(T->getOriginalType());
130 Record.AddTypeRef(T->getAdjustedType());
Reid Kleckner0503a872013-12-05 01:23:43 +0000131 Code = TYPE_ADJUSTED;
132}
133
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000134void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000135 Record.AddTypeRef(T->getPointeeType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000136 Code = TYPE_BLOCK_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000137}
138
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000139void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000140 Record.AddTypeRef(T->getPointeeTypeAsWritten());
Richard Smith0f538462011-04-12 10:38:03 +0000141 Record.push_back(T->isSpelledAsLValue());
Sebastian Redl539c5062010-08-18 23:57:32 +0000142 Code = TYPE_LVALUE_REFERENCE;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000143}
144
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000145void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000146 Record.AddTypeRef(T->getPointeeTypeAsWritten());
Sebastian Redl539c5062010-08-18 23:57:32 +0000147 Code = TYPE_RVALUE_REFERENCE;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000148}
149
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000150void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000151 Record.AddTypeRef(T->getPointeeType());
152 Record.AddTypeRef(QualType(T->getClass(), 0));
Sebastian Redl539c5062010-08-18 23:57:32 +0000153 Code = TYPE_MEMBER_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000154}
155
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000156void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000157 Record.AddTypeRef(T->getElementType());
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000158 Record.push_back(T->getSizeModifier()); // FIXME: stable values
John McCall8ccfcb52009-09-24 19:53:00 +0000159 Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000160}
161
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000162void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000163 VisitArrayType(T);
Richard Smith69c82bf2016-04-01 22:52:03 +0000164 Record.AddAPInt(T->getSize());
Sebastian Redl539c5062010-08-18 23:57:32 +0000165 Code = TYPE_CONSTANT_ARRAY;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000166}
167
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000168void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000169 VisitArrayType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000170 Code = TYPE_INCOMPLETE_ARRAY;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000171}
172
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000173void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000174 VisitArrayType(T);
Richard Smith69c82bf2016-04-01 22:52:03 +0000175 Record.AddSourceLocation(T->getLBracketLoc());
176 Record.AddSourceLocation(T->getRBracketLoc());
Douglas Gregor8f45df52009-04-16 22:23:12 +0000177 Writer.AddStmt(T->getSizeExpr());
Sebastian Redl539c5062010-08-18 23:57:32 +0000178 Code = TYPE_VARIABLE_ARRAY;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000179}
180
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000181void ASTTypeWriter::VisitVectorType(const VectorType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000182 Record.AddTypeRef(T->getElementType());
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000183 Record.push_back(T->getNumElements());
Bob Wilsonaeb56442010-11-10 21:56:12 +0000184 Record.push_back(T->getVectorKind());
Sebastian Redl539c5062010-08-18 23:57:32 +0000185 Code = TYPE_VECTOR;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000186}
187
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000188void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000189 VisitVectorType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000190 Code = TYPE_EXT_VECTOR;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000191}
192
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000193void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000194 Record.AddTypeRef(T->getReturnType());
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000195 FunctionType::ExtInfo C = T->getExtInfo();
196 Record.push_back(C.getNoReturn());
Eli Friedmanc5b20b52011-04-09 08:18:08 +0000197 Record.push_back(C.getHasRegParm());
Rafael Espindola49b85ab2010-03-30 22:15:11 +0000198 Record.push_back(C.getRegParm());
Douglas Gregor8c940862010-01-18 17:14:39 +0000199 // FIXME: need to stabilize encoding of calling convention...
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000200 Record.push_back(C.getCC());
John McCall31168b02011-06-15 23:02:42 +0000201 Record.push_back(C.getProducesResult());
Richard Smith01b2cb42014-07-26 06:37:51 +0000202
203 if (C.getHasRegParm() || C.getRegParm() || C.getProducesResult())
204 AbbrevToUse = 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000205}
206
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000207void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000208 VisitFunctionType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000209 Code = TYPE_FUNCTION_NO_PROTO;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000210}
211
Richard Smith564417a2014-03-20 21:47:22 +0000212static void addExceptionSpec(ASTWriter &Writer, const FunctionProtoType *T,
Richard Smith69c82bf2016-04-01 22:52:03 +0000213 ASTRecordWriter Record) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000214 Record.push_back(T->getExceptionSpecType());
215 if (T->getExceptionSpecType() == EST_Dynamic) {
216 Record.push_back(T->getNumExceptions());
217 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
Richard Smith69c82bf2016-04-01 22:52:03 +0000218 Record.AddTypeRef(T->getExceptionType(I));
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000219 } else if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
220 Writer.AddStmt(T->getNoexceptExpr());
Richard Smith8b987a92012-04-21 17:47:47 +0000221 } else if (T->getExceptionSpecType() == EST_Uninstantiated) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000222 Record.AddDeclRef(T->getExceptionSpecDecl());
223 Record.AddDeclRef(T->getExceptionSpecTemplate());
Richard Smithd3b5c9082012-07-27 04:22:15 +0000224 } else if (T->getExceptionSpecType() == EST_Unevaluated) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000225 Record.AddDeclRef(T->getExceptionSpecDecl());
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000226 }
Richard Smith564417a2014-03-20 21:47:22 +0000227}
228
229void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
230 VisitFunctionType(T);
Richard Smith01b2cb42014-07-26 06:37:51 +0000231
Richard Smith564417a2014-03-20 21:47:22 +0000232 Record.push_back(T->isVariadic());
233 Record.push_back(T->hasTrailingReturn());
234 Record.push_back(T->getTypeQuals());
235 Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
236 addExceptionSpec(Writer, T, Record);
Richard Smith01b2cb42014-07-26 06:37:51 +0000237
238 Record.push_back(T->getNumParams());
239 for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
Richard Smith69c82bf2016-04-01 22:52:03 +0000240 Record.AddTypeRef(T->getParamType(I));
Richard Smith01b2cb42014-07-26 06:37:51 +0000241
John McCall18afab72016-03-01 00:49:02 +0000242 if (T->hasExtParameterInfos()) {
243 for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
244 Record.push_back(T->getExtParameterInfo(I).getOpaqueValue());
245 }
246
Richard Smith01b2cb42014-07-26 06:37:51 +0000247 if (T->isVariadic() || T->hasTrailingReturn() || T->getTypeQuals() ||
John McCall18afab72016-03-01 00:49:02 +0000248 T->getRefQualifier() || T->getExceptionSpecType() != EST_None ||
249 T->hasExtParameterInfos())
Richard Smith01b2cb42014-07-26 06:37:51 +0000250 AbbrevToUse = 0;
251
Sebastian Redl539c5062010-08-18 23:57:32 +0000252 Code = TYPE_FUNCTION_PROTO;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000253}
254
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000255void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000256 Record.AddDeclRef(T->getDecl());
Sebastian Redl539c5062010-08-18 23:57:32 +0000257 Code = TYPE_UNRESOLVED_USING;
John McCallb96ec562009-12-04 22:46:56 +0000258}
John McCallb96ec562009-12-04 22:46:56 +0000259
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000260void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000261 Record.AddDeclRef(T->getDecl());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +0000262 assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
Richard Smith69c82bf2016-04-01 22:52:03 +0000263 Record.AddTypeRef(T->getCanonicalTypeInternal());
Sebastian Redl539c5062010-08-18 23:57:32 +0000264 Code = TYPE_TYPEDEF;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000265}
266
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000267void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
Douglas Gregor8f45df52009-04-16 22:23:12 +0000268 Writer.AddStmt(T->getUnderlyingExpr());
Sebastian Redl539c5062010-08-18 23:57:32 +0000269 Code = TYPE_TYPEOF_EXPR;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000270}
271
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000272void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000273 Record.AddTypeRef(T->getUnderlyingType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000274 Code = TYPE_TYPEOF;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000275}
276
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000277void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000278 Record.AddTypeRef(T->getUnderlyingType());
Anders Carlsson81df7b82009-06-24 19:06:50 +0000279 Writer.AddStmt(T->getUnderlyingExpr());
Sebastian Redl539c5062010-08-18 23:57:32 +0000280 Code = TYPE_DECLTYPE;
Anders Carlsson81df7b82009-06-24 19:06:50 +0000281}
282
Alexis Hunte852b102011-05-24 22:41:36 +0000283void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000284 Record.AddTypeRef(T->getBaseType());
285 Record.AddTypeRef(T->getUnderlyingType());
Alexis Hunte852b102011-05-24 22:41:36 +0000286 Record.push_back(T->getUTTKind());
287 Code = TYPE_UNARY_TRANSFORM;
288}
289
Richard Smith30482bc2011-02-20 03:19:35 +0000290void ASTTypeWriter::VisitAutoType(const AutoType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000291 Record.AddTypeRef(T->getDeducedType());
Richard Smithe301ba22015-11-11 02:02:15 +0000292 Record.push_back((unsigned)T->getKeyword());
Richard Smith27d807c2013-04-30 13:56:41 +0000293 if (T->getDeducedType().isNull())
294 Record.push_back(T->isDependentType());
Richard Smith30482bc2011-02-20 03:19:35 +0000295 Code = TYPE_AUTO;
296}
297
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000298void ASTTypeWriter::VisitTagType(const TagType *T) {
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +0000299 Record.push_back(T->isDependentType());
Richard Smith69c82bf2016-04-01 22:52:03 +0000300 Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +0000301 assert(!T->isBeingDefined() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000302 "Cannot serialize in the middle of a type definition");
303}
304
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000305void ASTTypeWriter::VisitRecordType(const RecordType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000306 VisitTagType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000307 Code = TYPE_RECORD;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000308}
309
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000310void ASTTypeWriter::VisitEnumType(const EnumType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000311 VisitTagType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000312 Code = TYPE_ENUM;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000313}
314
John McCall81904512011-01-06 01:58:22 +0000315void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000316 Record.AddTypeRef(T->getModifiedType());
317 Record.AddTypeRef(T->getEquivalentType());
John McCall81904512011-01-06 01:58:22 +0000318 Record.push_back(T->getAttrKind());
319 Code = TYPE_ATTRIBUTED;
320}
321
Mike Stump11289f42009-09-09 15:08:12 +0000322void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000323ASTTypeWriter::VisitSubstTemplateTypeParmType(
John McCallcebee162009-10-18 09:09:24 +0000324 const SubstTemplateTypeParmType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000325 Record.AddTypeRef(QualType(T->getReplacedParameter(), 0));
326 Record.AddTypeRef(T->getReplacementType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000327 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
John McCallcebee162009-10-18 09:09:24 +0000328}
329
330void
Douglas Gregorada4b792011-01-14 02:55:32 +0000331ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
332 const SubstTemplateTypeParmPackType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000333 Record.AddTypeRef(QualType(T->getReplacedParameter(), 0));
334 Record.AddTemplateArgument(T->getArgumentPack());
Douglas Gregorada4b792011-01-14 02:55:32 +0000335 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK;
336}
337
338void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000339ASTTypeWriter::VisitTemplateSpecializationType(
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000340 const TemplateSpecializationType *T) {
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +0000341 Record.push_back(T->isDependentType());
Richard Smith69c82bf2016-04-01 22:52:03 +0000342 Record.AddTemplateName(T->getTemplateName());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000343 Record.push_back(T->getNumArgs());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +0000344 for (const auto &ArgI : *T)
Richard Smith69c82bf2016-04-01 22:52:03 +0000345 Record.AddTemplateArgument(ArgI);
346 Record.AddTypeRef(T->isTypeAlias() ? T->getAliasedType()
347 : T->isCanonicalUnqualified()
348 ? QualType()
349 : T->getCanonicalTypeInternal());
Sebastian Redl539c5062010-08-18 23:57:32 +0000350 Code = TYPE_TEMPLATE_SPECIALIZATION;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000351}
352
353void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000354ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
Argyrios Kyrtzidis4a57bd02010-06-30 08:49:25 +0000355 VisitArrayType(T);
356 Writer.AddStmt(T->getSizeExpr());
Richard Smith69c82bf2016-04-01 22:52:03 +0000357 Record.AddSourceRange(T->getBracketsRange());
Sebastian Redl539c5062010-08-18 23:57:32 +0000358 Code = TYPE_DEPENDENT_SIZED_ARRAY;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000359}
360
361void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000362ASTTypeWriter::VisitDependentSizedExtVectorType(
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000363 const DependentSizedExtVectorType *T) {
364 // FIXME: Serialize this type (C++ only)
David Blaikie83d382b2011-09-23 05:06:16 +0000365 llvm_unreachable("Cannot serialize dependent sized extended vector types");
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000366}
367
368void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000369ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000370 Record.push_back(T->getDepth());
371 Record.push_back(T->getIndex());
372 Record.push_back(T->isParameterPack());
Richard Smith69c82bf2016-04-01 22:52:03 +0000373 Record.AddDeclRef(T->getDecl());
Sebastian Redl539c5062010-08-18 23:57:32 +0000374 Code = TYPE_TEMPLATE_TYPE_PARM;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000375}
376
377void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000378ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
Argyrios Kyrtzidisbfcacee2010-06-24 08:57:31 +0000379 Record.push_back(T->getKeyword());
Richard Smith69c82bf2016-04-01 22:52:03 +0000380 Record.AddNestedNameSpecifier(T->getQualifier());
381 Record.AddIdentifierRef(T->getIdentifier());
382 Record.AddTypeRef(
383 T->isCanonicalUnqualified() ? QualType() : T->getCanonicalTypeInternal());
Sebastian Redl539c5062010-08-18 23:57:32 +0000384 Code = TYPE_DEPENDENT_NAME;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000385}
386
387void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000388ASTTypeWriter::VisitDependentTemplateSpecializationType(
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000389 const DependentTemplateSpecializationType *T) {
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +0000390 Record.push_back(T->getKeyword());
Richard Smith69c82bf2016-04-01 22:52:03 +0000391 Record.AddNestedNameSpecifier(T->getQualifier());
392 Record.AddIdentifierRef(T->getIdentifier());
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +0000393 Record.push_back(T->getNumArgs());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +0000394 for (const auto &I : *T)
Richard Smith69c82bf2016-04-01 22:52:03 +0000395 Record.AddTemplateArgument(I);
Sebastian Redl539c5062010-08-18 23:57:32 +0000396 Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000397}
398
Douglas Gregord2fa7662010-12-20 02:24:11 +0000399void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000400 Record.AddTypeRef(T->getPattern());
David Blaikie05785d12013-02-20 22:23:23 +0000401 if (Optional<unsigned> NumExpansions = T->getNumExpansions())
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000402 Record.push_back(*NumExpansions + 1);
403 else
404 Record.push_back(0);
Douglas Gregord2fa7662010-12-20 02:24:11 +0000405 Code = TYPE_PACK_EXPANSION;
406}
407
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000408void ASTTypeWriter::VisitParenType(const ParenType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000409 Record.AddTypeRef(T->getInnerType());
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000410 Code = TYPE_PAREN;
411}
412
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000413void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000414 Record.push_back(T->getKeyword());
Richard Smith69c82bf2016-04-01 22:52:03 +0000415 Record.AddNestedNameSpecifier(T->getQualifier());
416 Record.AddTypeRef(T->getNamedType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000417 Code = TYPE_ELABORATED;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000418}
419
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000420void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000421 Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
422 Record.AddTypeRef(T->getInjectedSpecializationType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000423 Code = TYPE_INJECTED_CLASS_NAME;
John McCalle78aac42010-03-10 03:28:59 +0000424}
425
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000426void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000427 Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
Sebastian Redl539c5062010-08-18 23:57:32 +0000428 Code = TYPE_OBJC_INTERFACE;
John McCall8b07ec22010-05-15 11:32:37 +0000429}
430
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000431void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000432 Record.AddTypeRef(T->getBaseType());
Douglas Gregore83b9562015-07-07 03:57:53 +0000433 Record.push_back(T->getTypeArgsAsWritten().size());
434 for (auto TypeArg : T->getTypeArgsAsWritten())
Richard Smith69c82bf2016-04-01 22:52:03 +0000435 Record.AddTypeRef(TypeArg);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000436 Record.push_back(T->getNumProtocols());
Aaron Ballman1683f7b2014-03-17 15:55:30 +0000437 for (const auto *I : T->quals())
Richard Smith69c82bf2016-04-01 22:52:03 +0000438 Record.AddDeclRef(I);
Douglas Gregorab209d82015-07-07 03:58:42 +0000439 Record.push_back(T->isKindOfTypeAsWritten());
Sebastian Redl539c5062010-08-18 23:57:32 +0000440 Code = TYPE_OBJC_OBJECT;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000441}
442
Steve Narofffb4330f2009-06-17 22:40:22 +0000443void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000444ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000445 Record.AddTypeRef(T->getPointeeType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000446 Code = TYPE_OBJC_OBJECT_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000447}
448
Eli Friedman0dfb8892011-10-06 23:00:33 +0000449void
450ASTTypeWriter::VisitAtomicType(const AtomicType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000451 Record.AddTypeRef(T->getValueType());
Eli Friedman0dfb8892011-10-06 23:00:33 +0000452 Code = TYPE_ATOMIC;
453}
454
Xiuli Pan9c14e282016-01-09 12:53:17 +0000455void
456ASTTypeWriter::VisitPipeType(const PipeType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000457 Record.AddTypeRef(T->getElementType());
Xiuli Pan9c14e282016-01-09 12:53:17 +0000458 Code = TYPE_PIPE;
459}
460
John McCall8f115c62009-10-16 21:56:05 +0000461namespace {
462
463class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
Sebastian Redl55c0ad52010-08-18 23:56:21 +0000464 ASTWriter &Writer;
Richard Smith69c82bf2016-04-01 22:52:03 +0000465 ASTRecordWriter Record;
John McCall8f115c62009-10-16 21:56:05 +0000466
467public:
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000468 TypeLocWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
Richard Smith69c82bf2016-04-01 22:52:03 +0000469 : Writer(Writer), Record(Writer, Record) { }
John McCall8f115c62009-10-16 21:56:05 +0000470
John McCall17001972009-10-18 01:05:36 +0000471#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCall8f115c62009-10-16 21:56:05 +0000472#define TYPELOC(CLASS, PARENT) \
John McCall17001972009-10-18 01:05:36 +0000473 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +0000474#include "clang/AST/TypeLocNodes.def"
475
John McCall17001972009-10-18 01:05:36 +0000476 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
477 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +0000478};
479
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +0000480} // end anonymous namespace
John McCall8f115c62009-10-16 21:56:05 +0000481
John McCall17001972009-10-18 01:05:36 +0000482void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
483 // nothing to do
John McCall8f115c62009-10-16 21:56:05 +0000484}
John McCall17001972009-10-18 01:05:36 +0000485void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000486 Record.AddSourceLocation(TL.getBuiltinLoc());
Douglas Gregorc9b7a592010-01-18 18:04:31 +0000487 if (TL.needsExtraLocalData()) {
488 Record.push_back(TL.getWrittenTypeSpec());
489 Record.push_back(TL.getWrittenSignSpec());
490 Record.push_back(TL.getWrittenWidthSpec());
491 Record.push_back(TL.hasModeAttr());
492 }
John McCall8f115c62009-10-16 21:56:05 +0000493}
John McCall17001972009-10-18 01:05:36 +0000494void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000495 Record.AddSourceLocation(TL.getNameLoc());
John McCall8f115c62009-10-16 21:56:05 +0000496}
John McCall17001972009-10-18 01:05:36 +0000497void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000498 Record.AddSourceLocation(TL.getStarLoc());
John McCall8f115c62009-10-16 21:56:05 +0000499}
Reid Kleckner8a365022013-06-24 17:51:48 +0000500void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
501 // nothing to do
502}
Reid Kleckner0503a872013-12-05 01:23:43 +0000503void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
504 // nothing to do
505}
John McCall17001972009-10-18 01:05:36 +0000506void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000507 Record.AddSourceLocation(TL.getCaretLoc());
John McCall8f115c62009-10-16 21:56:05 +0000508}
John McCall17001972009-10-18 01:05:36 +0000509void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000510 Record.AddSourceLocation(TL.getAmpLoc());
John McCall8f115c62009-10-16 21:56:05 +0000511}
John McCall17001972009-10-18 01:05:36 +0000512void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000513 Record.AddSourceLocation(TL.getAmpAmpLoc());
John McCall8f115c62009-10-16 21:56:05 +0000514}
John McCall17001972009-10-18 01:05:36 +0000515void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000516 Record.AddSourceLocation(TL.getStarLoc());
517 Record.AddTypeSourceInfo(TL.getClassTInfo());
John McCall8f115c62009-10-16 21:56:05 +0000518}
John McCall17001972009-10-18 01:05:36 +0000519void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000520 Record.AddSourceLocation(TL.getLBracketLoc());
521 Record.AddSourceLocation(TL.getRBracketLoc());
John McCall17001972009-10-18 01:05:36 +0000522 Record.push_back(TL.getSizeExpr() ? 1 : 0);
523 if (TL.getSizeExpr())
524 Writer.AddStmt(TL.getSizeExpr());
John McCall8f115c62009-10-16 21:56:05 +0000525}
John McCall17001972009-10-18 01:05:36 +0000526void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
527 VisitArrayTypeLoc(TL);
528}
529void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
530 VisitArrayTypeLoc(TL);
531}
532void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
533 VisitArrayTypeLoc(TL);
534}
535void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
536 DependentSizedArrayTypeLoc TL) {
537 VisitArrayTypeLoc(TL);
538}
539void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
540 DependentSizedExtVectorTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000541 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000542}
543void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000544 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000545}
546void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000547 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000548}
549void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000550 Record.AddSourceLocation(TL.getLocalRangeBegin());
551 Record.AddSourceLocation(TL.getLParenLoc());
552 Record.AddSourceLocation(TL.getRParenLoc());
553 Record.AddSourceLocation(TL.getLocalRangeEnd());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +0000554 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000555 Record.AddDeclRef(TL.getParam(i));
John McCall17001972009-10-18 01:05:36 +0000556}
557void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
558 VisitFunctionTypeLoc(TL);
559}
560void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
561 VisitFunctionTypeLoc(TL);
562}
John McCallb96ec562009-12-04 22:46:56 +0000563void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000564 Record.AddSourceLocation(TL.getNameLoc());
John McCallb96ec562009-12-04 22:46:56 +0000565}
John McCall17001972009-10-18 01:05:36 +0000566void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000567 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000568}
569void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000570 Record.AddSourceLocation(TL.getTypeofLoc());
571 Record.AddSourceLocation(TL.getLParenLoc());
572 Record.AddSourceLocation(TL.getRParenLoc());
John McCall17001972009-10-18 01:05:36 +0000573}
574void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000575 Record.AddSourceLocation(TL.getTypeofLoc());
576 Record.AddSourceLocation(TL.getLParenLoc());
577 Record.AddSourceLocation(TL.getRParenLoc());
578 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
John McCall17001972009-10-18 01:05:36 +0000579}
580void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000581 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000582}
Alexis Hunte852b102011-05-24 22:41:36 +0000583void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000584 Record.AddSourceLocation(TL.getKWLoc());
585 Record.AddSourceLocation(TL.getLParenLoc());
586 Record.AddSourceLocation(TL.getRParenLoc());
587 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
Alexis Hunte852b102011-05-24 22:41:36 +0000588}
Richard Smith30482bc2011-02-20 03:19:35 +0000589void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000590 Record.AddSourceLocation(TL.getNameLoc());
Richard Smith30482bc2011-02-20 03:19:35 +0000591}
John McCall17001972009-10-18 01:05:36 +0000592void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000593 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000594}
595void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000596 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000597}
John McCall81904512011-01-06 01:58:22 +0000598void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000599 Record.AddSourceLocation(TL.getAttrNameLoc());
John McCall81904512011-01-06 01:58:22 +0000600 if (TL.hasAttrOperand()) {
601 SourceRange range = TL.getAttrOperandParensRange();
Richard Smith69c82bf2016-04-01 22:52:03 +0000602 Record.AddSourceLocation(range.getBegin());
603 Record.AddSourceLocation(range.getEnd());
John McCall81904512011-01-06 01:58:22 +0000604 }
605 if (TL.hasAttrExprOperand()) {
606 Expr *operand = TL.getAttrExprOperand();
607 Record.push_back(operand ? 1 : 0);
608 if (operand) Writer.AddStmt(operand);
609 } else if (TL.hasAttrEnumOperand()) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000610 Record.AddSourceLocation(TL.getAttrEnumOperandLoc());
John McCall81904512011-01-06 01:58:22 +0000611 }
612}
John McCall17001972009-10-18 01:05:36 +0000613void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000614 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000615}
John McCallcebee162009-10-18 09:09:24 +0000616void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
617 SubstTemplateTypeParmTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000618 Record.AddSourceLocation(TL.getNameLoc());
John McCallcebee162009-10-18 09:09:24 +0000619}
Douglas Gregorada4b792011-01-14 02:55:32 +0000620void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
621 SubstTemplateTypeParmPackTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000622 Record.AddSourceLocation(TL.getNameLoc());
Douglas Gregorada4b792011-01-14 02:55:32 +0000623}
John McCall17001972009-10-18 01:05:36 +0000624void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
625 TemplateSpecializationTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000626 Record.AddSourceLocation(TL.getTemplateKeywordLoc());
627 Record.AddSourceLocation(TL.getTemplateNameLoc());
628 Record.AddSourceLocation(TL.getLAngleLoc());
629 Record.AddSourceLocation(TL.getRAngleLoc());
John McCall0ad16662009-10-29 08:12:44 +0000630 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000631 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
632 TL.getArgLoc(i).getLocInfo());
John McCall17001972009-10-18 01:05:36 +0000633}
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000634void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000635 Record.AddSourceLocation(TL.getLParenLoc());
636 Record.AddSourceLocation(TL.getRParenLoc());
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000637}
Abramo Bagnara6150c882010-05-11 21:36:43 +0000638void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000639 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
640 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
John McCall17001972009-10-18 01:05:36 +0000641}
John McCalle78aac42010-03-10 03:28:59 +0000642void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000643 Record.AddSourceLocation(TL.getNameLoc());
John McCalle78aac42010-03-10 03:28:59 +0000644}
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +0000645void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000646 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
647 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
648 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000649}
John McCallc392f372010-06-11 00:33:02 +0000650void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
651 DependentTemplateSpecializationTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000652 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
653 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
654 Record.AddSourceLocation(TL.getTemplateKeywordLoc());
655 Record.AddSourceLocation(TL.getTemplateNameLoc());
656 Record.AddSourceLocation(TL.getLAngleLoc());
657 Record.AddSourceLocation(TL.getRAngleLoc());
John McCallc392f372010-06-11 00:33:02 +0000658 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
Richard Smith69c82bf2016-04-01 22:52:03 +0000659 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
660 TL.getArgLoc(I).getLocInfo());
John McCallc392f372010-06-11 00:33:02 +0000661}
Douglas Gregord2fa7662010-12-20 02:24:11 +0000662void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000663 Record.AddSourceLocation(TL.getEllipsisLoc());
Douglas Gregord2fa7662010-12-20 02:24:11 +0000664}
John McCall17001972009-10-18 01:05:36 +0000665void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000666 Record.AddSourceLocation(TL.getNameLoc());
John McCall8b07ec22010-05-15 11:32:37 +0000667}
668void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
669 Record.push_back(TL.hasBaseTypeAsWritten());
Richard Smith69c82bf2016-04-01 22:52:03 +0000670 Record.AddSourceLocation(TL.getTypeArgsLAngleLoc());
671 Record.AddSourceLocation(TL.getTypeArgsRAngleLoc());
Douglas Gregore9d95f12015-07-07 03:57:35 +0000672 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000673 Record.AddTypeSourceInfo(TL.getTypeArgTInfo(i));
674 Record.AddSourceLocation(TL.getProtocolLAngleLoc());
675 Record.AddSourceLocation(TL.getProtocolRAngleLoc());
John McCall17001972009-10-18 01:05:36 +0000676 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000677 Record.AddSourceLocation(TL.getProtocolLoc(i));
John McCall8f115c62009-10-16 21:56:05 +0000678}
John McCallfc93cf92009-10-22 22:37:11 +0000679void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000680 Record.AddSourceLocation(TL.getStarLoc());
John McCallfc93cf92009-10-22 22:37:11 +0000681}
Eli Friedman0dfb8892011-10-06 23:00:33 +0000682void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000683 Record.AddSourceLocation(TL.getKWLoc());
684 Record.AddSourceLocation(TL.getLParenLoc());
685 Record.AddSourceLocation(TL.getRParenLoc());
Eli Friedman0dfb8892011-10-06 23:00:33 +0000686}
Xiuli Pan9c14e282016-01-09 12:53:17 +0000687void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000688 Record.AddSourceLocation(TL.getKWLoc());
Xiuli Pan9c14e282016-01-09 12:53:17 +0000689}
John McCall8f115c62009-10-16 21:56:05 +0000690
Richard Smith01b2cb42014-07-26 06:37:51 +0000691void ASTWriter::WriteTypeAbbrevs() {
692 using namespace llvm;
693
694 BitCodeAbbrev *Abv;
695
696 // Abbreviation for TYPE_EXT_QUAL
697 Abv = new BitCodeAbbrev();
698 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
699 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
700 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals
701 TypeExtQualAbbrev = Stream.EmitAbbrev(Abv);
702
703 // Abbreviation for TYPE_FUNCTION_PROTO
704 Abv = new BitCodeAbbrev();
705 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_FUNCTION_PROTO));
706 // FunctionType
707 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ReturnType
708 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NoReturn
709 Abv->Add(BitCodeAbbrevOp(0)); // HasRegParm
710 Abv->Add(BitCodeAbbrevOp(0)); // RegParm
711 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // CC
712 Abv->Add(BitCodeAbbrevOp(0)); // ProducesResult
713 // FunctionProtoType
714 Abv->Add(BitCodeAbbrevOp(0)); // IsVariadic
715 Abv->Add(BitCodeAbbrevOp(0)); // HasTrailingReturn
716 Abv->Add(BitCodeAbbrevOp(0)); // TypeQuals
717 Abv->Add(BitCodeAbbrevOp(0)); // RefQualifier
718 Abv->Add(BitCodeAbbrevOp(EST_None)); // ExceptionSpec
719 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // NumParams
720 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
721 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Params
722 TypeFunctionProtoAbbrev = Stream.EmitAbbrev(Abv);
723}
724
Chris Lattner19cea4e2009-04-22 05:57:30 +0000725//===----------------------------------------------------------------------===//
Sebastian Redl55c0ad52010-08-18 23:56:21 +0000726// ASTWriter Implementation
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000727//===----------------------------------------------------------------------===//
728
Chris Lattner28fa4e62009-04-26 22:26:21 +0000729static void EmitBlockID(unsigned ID, const char *Name,
730 llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000731 ASTWriter::RecordDataImpl &Record) {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000732 Record.clear();
733 Record.push_back(ID);
734 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
735
736 // Emit the block name if present.
Craig Toppera13603a2014-05-22 05:54:18 +0000737 if (!Name || Name[0] == 0)
738 return;
Chris Lattner28fa4e62009-04-26 22:26:21 +0000739 Record.clear();
740 while (*Name)
741 Record.push_back(*Name++);
742 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
743}
744
745static void EmitRecordID(unsigned ID, const char *Name,
746 llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000747 ASTWriter::RecordDataImpl &Record) {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000748 Record.clear();
749 Record.push_back(ID);
750 while (*Name)
751 Record.push_back(*Name++);
752 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000753}
754
755static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000756 ASTWriter::RecordDataImpl &Record) {
Sebastian Redl539c5062010-08-18 23:57:32 +0000757#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
Chris Lattnerccac3a62009-04-27 00:49:53 +0000758 RECORD(STMT_STOP);
759 RECORD(STMT_NULL_PTR);
Richard Smith01b2cb42014-07-26 06:37:51 +0000760 RECORD(STMT_REF_PTR);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000761 RECORD(STMT_NULL);
762 RECORD(STMT_COMPOUND);
763 RECORD(STMT_CASE);
764 RECORD(STMT_DEFAULT);
765 RECORD(STMT_LABEL);
Richard Smithc202b282012-04-14 00:33:13 +0000766 RECORD(STMT_ATTRIBUTED);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000767 RECORD(STMT_IF);
768 RECORD(STMT_SWITCH);
769 RECORD(STMT_WHILE);
770 RECORD(STMT_DO);
771 RECORD(STMT_FOR);
772 RECORD(STMT_GOTO);
773 RECORD(STMT_INDIRECT_GOTO);
774 RECORD(STMT_CONTINUE);
775 RECORD(STMT_BREAK);
776 RECORD(STMT_RETURN);
777 RECORD(STMT_DECL);
Chad Rosierde70e0e2012-08-25 00:11:56 +0000778 RECORD(STMT_GCCASM);
Chad Rosiere30d4992012-08-24 23:51:02 +0000779 RECORD(STMT_MSASM);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000780 RECORD(EXPR_PREDEFINED);
781 RECORD(EXPR_DECL_REF);
782 RECORD(EXPR_INTEGER_LITERAL);
783 RECORD(EXPR_FLOATING_LITERAL);
784 RECORD(EXPR_IMAGINARY_LITERAL);
785 RECORD(EXPR_STRING_LITERAL);
786 RECORD(EXPR_CHARACTER_LITERAL);
787 RECORD(EXPR_PAREN);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000788 RECORD(EXPR_PAREN_LIST);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000789 RECORD(EXPR_UNARY_OPERATOR);
790 RECORD(EXPR_SIZEOF_ALIGN_OF);
791 RECORD(EXPR_ARRAY_SUBSCRIPT);
792 RECORD(EXPR_CALL);
793 RECORD(EXPR_MEMBER);
794 RECORD(EXPR_BINARY_OPERATOR);
795 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
796 RECORD(EXPR_CONDITIONAL_OPERATOR);
797 RECORD(EXPR_IMPLICIT_CAST);
798 RECORD(EXPR_CSTYLE_CAST);
799 RECORD(EXPR_COMPOUND_LITERAL);
800 RECORD(EXPR_EXT_VECTOR_ELEMENT);
801 RECORD(EXPR_INIT_LIST);
802 RECORD(EXPR_DESIGNATED_INIT);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000803 RECORD(EXPR_DESIGNATED_INIT_UPDATE);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000804 RECORD(EXPR_IMPLICIT_VALUE_INIT);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000805 RECORD(EXPR_NO_INIT);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000806 RECORD(EXPR_VA_ARG);
807 RECORD(EXPR_ADDR_LABEL);
808 RECORD(EXPR_STMT);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000809 RECORD(EXPR_CHOOSE);
810 RECORD(EXPR_GNU_NULL);
811 RECORD(EXPR_SHUFFLE_VECTOR);
812 RECORD(EXPR_BLOCK);
Peter Collingbourne91147592011-04-15 00:35:48 +0000813 RECORD(EXPR_GENERIC_SELECTION);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000814 RECORD(EXPR_OBJC_STRING_LITERAL);
Patrick Beard0caa3942012-04-19 00:25:12 +0000815 RECORD(EXPR_OBJC_BOXED_EXPRESSION);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000816 RECORD(EXPR_OBJC_ARRAY_LITERAL);
817 RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000818 RECORD(EXPR_OBJC_ENCODE);
819 RECORD(EXPR_OBJC_SELECTOR_EXPR);
820 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
821 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
822 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
823 RECORD(EXPR_OBJC_KVC_REF_EXPR);
824 RECORD(EXPR_OBJC_MESSAGE_EXPR);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000825 RECORD(STMT_OBJC_FOR_COLLECTION);
826 RECORD(STMT_OBJC_CATCH);
827 RECORD(STMT_OBJC_FINALLY);
828 RECORD(STMT_OBJC_AT_TRY);
829 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
830 RECORD(STMT_OBJC_AT_THROW);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000831 RECORD(EXPR_OBJC_BOOL_LITERAL);
Richard Smith01b2cb42014-07-26 06:37:51 +0000832 RECORD(STMT_CXX_CATCH);
833 RECORD(STMT_CXX_TRY);
834 RECORD(STMT_CXX_FOR_RANGE);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000835 RECORD(EXPR_CXX_OPERATOR_CALL);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000836 RECORD(EXPR_CXX_MEMBER_CALL);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000837 RECORD(EXPR_CXX_CONSTRUCT);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000838 RECORD(EXPR_CXX_TEMPORARY_OBJECT);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000839 RECORD(EXPR_CXX_STATIC_CAST);
840 RECORD(EXPR_CXX_DYNAMIC_CAST);
841 RECORD(EXPR_CXX_REINTERPRET_CAST);
842 RECORD(EXPR_CXX_CONST_CAST);
843 RECORD(EXPR_CXX_FUNCTIONAL_CAST);
Richard Smithc67fdd42012-03-07 08:35:16 +0000844 RECORD(EXPR_USER_DEFINED_LITERAL);
Richard Smithcc1b96d2013-06-12 22:31:48 +0000845 RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000846 RECORD(EXPR_CXX_BOOL_LITERAL);
847 RECORD(EXPR_CXX_NULL_PTR_LITERAL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000848 RECORD(EXPR_CXX_TYPEID_EXPR);
849 RECORD(EXPR_CXX_TYPEID_TYPE);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000850 RECORD(EXPR_CXX_THIS);
851 RECORD(EXPR_CXX_THROW);
852 RECORD(EXPR_CXX_DEFAULT_ARG);
Richard Smith01b2cb42014-07-26 06:37:51 +0000853 RECORD(EXPR_CXX_DEFAULT_INIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000854 RECORD(EXPR_CXX_BIND_TEMPORARY);
855 RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
856 RECORD(EXPR_CXX_NEW);
857 RECORD(EXPR_CXX_DELETE);
858 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
859 RECORD(EXPR_EXPR_WITH_CLEANUPS);
860 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
861 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
862 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
863 RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
864 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
Richard Smith01b2cb42014-07-26 06:37:51 +0000865 RECORD(EXPR_CXX_EXPRESSION_TRAIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000866 RECORD(EXPR_CXX_NOEXCEPT);
867 RECORD(EXPR_OPAQUE_VALUE);
Richard Smith01b2cb42014-07-26 06:37:51 +0000868 RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR);
869 RECORD(EXPR_TYPE_TRAIT);
870 RECORD(EXPR_ARRAY_TYPE_TRAIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000871 RECORD(EXPR_PACK_EXPANSION);
872 RECORD(EXPR_SIZEOF_PACK);
Richard Smith01b2cb42014-07-26 06:37:51 +0000873 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000874 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
Richard Smith01b2cb42014-07-26 06:37:51 +0000875 RECORD(EXPR_FUNCTION_PARM_PACK);
876 RECORD(EXPR_MATERIALIZE_TEMPORARY);
Peter Collingbourne41f85462011-02-09 21:07:24 +0000877 RECORD(EXPR_CUDA_KERNEL_CALL);
Richard Smith01b2cb42014-07-26 06:37:51 +0000878 RECORD(EXPR_CXX_UUIDOF_EXPR);
879 RECORD(EXPR_CXX_UUIDOF_TYPE);
880 RECORD(EXPR_LAMBDA);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000881#undef RECORD
Chris Lattner28fa4e62009-04-26 22:26:21 +0000882}
Mike Stump11289f42009-09-09 15:08:12 +0000883
Sebastian Redl55c0ad52010-08-18 23:56:21 +0000884void ASTWriter::WriteBlockInfoBlock() {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000885 RecordData Record;
886 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
Mike Stump11289f42009-09-09 15:08:12 +0000887
Sebastian Redl539c5062010-08-18 23:57:32 +0000888#define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
889#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
Mike Stump11289f42009-09-09 15:08:12 +0000890
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000891 // Control Block.
892 BLOCK(CONTROL_BLOCK);
893 RECORD(METADATA);
Ben Langmuir487ea142014-10-23 18:05:36 +0000894 RECORD(SIGNATURE);
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000895 RECORD(MODULE_NAME);
Richard Smithfa715652015-08-31 22:43:10 +0000896 RECORD(MODULE_DIRECTORY);
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000897 RECORD(MODULE_MAP_FILE);
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000898 RECORD(IMPORTS);
Douglas Gregorfad10d82012-10-18 18:36:53 +0000899 RECORD(ORIGINAL_FILE);
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000900 RECORD(ORIGINAL_PCH_DIR);
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +0000901 RECORD(ORIGINAL_FILE_ID);
Douglas Gregor3120d2c2012-10-22 18:42:04 +0000902 RECORD(INPUT_FILE_OFFSETS);
Richard Smith0516b182015-09-08 19:40:14 +0000903
904 BLOCK(OPTIONS_BLOCK);
905 RECORD(LANGUAGE_OPTIONS);
906 RECORD(TARGET_OPTIONS);
Douglas Gregor8263ffb2012-10-24 15:17:15 +0000907 RECORD(DIAGNOSTIC_OPTIONS);
Douglas Gregorc6317db2012-10-24 15:49:58 +0000908 RECORD(FILE_SYSTEM_OPTIONS);
Douglas Gregor2d302362012-10-24 16:50:34 +0000909 RECORD(HEADER_SEARCH_OPTIONS);
Douglas Gregorb6af6c22012-10-24 20:05:57 +0000910 RECORD(PREPROCESSOR_OPTIONS);
911
Douglas Gregor108cb222012-10-19 00:45:00 +0000912 BLOCK(INPUT_FILES_BLOCK);
913 RECORD(INPUT_FILE);
914
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000915 // AST Top-Level Block.
916 BLOCK(AST_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000917 RECORD(TYPE_OFFSET);
918 RECORD(DECL_OFFSET);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000919 RECORD(IDENTIFIER_OFFSET);
920 RECORD(IDENTIFIER_TABLE);
Ben Langmuir332aafe2014-01-31 01:06:56 +0000921 RECORD(EAGERLY_DESERIALIZED_DECLS);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000922 RECORD(SPECIAL_TYPES);
923 RECORD(STATISTICS);
924 RECORD(TENTATIVE_DEFINITIONS);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000925 RECORD(SELECTOR_OFFSETS);
926 RECORD(METHOD_POOL);
927 RECORD(PP_COUNTER_VALUE);
Douglas Gregor258ae542009-04-27 06:38:32 +0000928 RECORD(SOURCE_LOCATION_OFFSETS);
929 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor61cac2b2009-04-27 20:06:05 +0000930 RECORD(EXT_VECTOR_DECLS);
Richard Smithfa715652015-08-31 22:43:10 +0000931 RECORD(UNUSED_FILESCOPED_DECLS);
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +0000932 RECORD(PPD_ENTITIES_OFFSETS);
Richard Smithfa715652015-08-31 22:43:10 +0000933 RECORD(VTABLE_USES);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +0000934 RECORD(REFERENCED_SELECTOR_POOL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000935 RECORD(TU_UPDATE_LEXICAL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000936 RECORD(SEMA_DECL_REFS);
937 RECORD(WEAK_UNDECLARED_IDENTIFIERS);
938 RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000939 RECORD(UPDATE_VISIBLE);
940 RECORD(DECL_UPDATE_OFFSETS);
941 RECORD(DECL_UPDATES);
942 RECORD(CXX_BASE_SPECIFIER_OFFSETS);
943 RECORD(DIAG_PRAGMA_MAPPINGS);
Peter Collingbourne5df20e02011-02-15 19:46:30 +0000944 RECORD(CUDA_SPECIAL_DECL_REFS);
Douglas Gregor09b69892011-02-10 17:09:37 +0000945 RECORD(HEADER_SEARCH_TABLE);
Peter Collingbourne5df20e02011-02-15 19:46:30 +0000946 RECORD(FP_PRAGMA_OPTIONS);
947 RECORD(OPENCL_EXTENSIONS);
Alexis Hunt27a761d2011-05-04 23:29:54 +0000948 RECORD(DELEGATING_CTORS);
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000949 RECORD(KNOWN_NAMESPACES);
Douglas Gregor78d0b572011-08-04 16:39:39 +0000950 RECORD(MODULE_OFFSET_MAP);
951 RECORD(SOURCE_MANAGER_LINE_TABLE);
Douglas Gregor404cdde2012-01-27 01:47:08 +0000952 RECORD(OBJC_CATEGORIES_MAP);
Douglas Gregor66e4add2011-12-19 21:09:25 +0000953 RECORD(FILE_SORTED_DECLS);
954 RECORD(IMPORTED_MODULES);
Douglas Gregor404cdde2012-01-27 01:47:08 +0000955 RECORD(OBJC_CATEGORIES);
Douglas Gregorcb28f9d2012-10-09 23:05:51 +0000956 RECORD(MACRO_OFFSET);
Richard Smithfa715652015-08-31 22:43:10 +0000957 RECORD(INTERESTING_IDENTIFIERS);
958 RECORD(UNDEFINED_BUT_USED);
Richard Smithe40f2ba2013-08-07 21:41:30 +0000959 RECORD(LATE_PARSED_TEMPLATE);
Dario Domizioli13a0a382014-05-23 12:13:25 +0000960 RECORD(OPTIMIZE_PRAGMA_OPTIONS);
Nico Weber779355f2016-03-02 23:22:00 +0000961 RECORD(MSSTRUCT_PRAGMA_OPTIONS);
Nico Weber42932312016-03-03 00:17:35 +0000962 RECORD(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS);
Richard Smithfa715652015-08-31 22:43:10 +0000963 RECORD(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES);
964 RECORD(CXX_CTOR_INITIALIZERS_OFFSETS);
965 RECORD(DELETE_EXPRS_TO_ANALYZE);
Douglas Gregor358cd442012-01-15 16:58:34 +0000966
Chris Lattner28fa4e62009-04-26 22:26:21 +0000967 // SourceManager Block.
Chris Lattner64031982009-04-27 00:40:25 +0000968 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000969 RECORD(SM_SLOC_FILE_ENTRY);
970 RECORD(SM_SLOC_BUFFER_ENTRY);
971 RECORD(SM_SLOC_BUFFER_BLOB);
Richard Smithaada85c2016-02-06 02:06:43 +0000972 RECORD(SM_SLOC_BUFFER_BLOB_COMPRESSED);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +0000973 RECORD(SM_SLOC_EXPANSION_ENTRY);
Mike Stump11289f42009-09-09 15:08:12 +0000974
Chris Lattner28fa4e62009-04-26 22:26:21 +0000975 // Preprocessor Block.
Chris Lattner64031982009-04-27 00:40:25 +0000976 BLOCK(PREPROCESSOR_BLOCK);
Richard Smithec216502015-02-13 19:48:37 +0000977 RECORD(PP_MACRO_DIRECTIVE_HISTORY);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000978 RECORD(PP_MACRO_FUNCTION_LIKE);
Richard Smithd7329392015-04-21 21:46:32 +0000979 RECORD(PP_MACRO_OBJECT_LIKE);
980 RECORD(PP_MODULE_MACRO);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000981 RECORD(PP_TOKEN);
Richard Smithec216502015-02-13 19:48:37 +0000982
Richard Smithfa715652015-08-31 22:43:10 +0000983 // Submodule Block.
984 BLOCK(SUBMODULE_BLOCK);
985 RECORD(SUBMODULE_METADATA);
986 RECORD(SUBMODULE_DEFINITION);
987 RECORD(SUBMODULE_UMBRELLA_HEADER);
988 RECORD(SUBMODULE_HEADER);
989 RECORD(SUBMODULE_TOPHEADER);
990 RECORD(SUBMODULE_UMBRELLA_DIR);
991 RECORD(SUBMODULE_IMPORTS);
992 RECORD(SUBMODULE_EXPORTS);
993 RECORD(SUBMODULE_REQUIRES);
994 RECORD(SUBMODULE_EXCLUDED_HEADER);
995 RECORD(SUBMODULE_LINK_LIBRARY);
996 RECORD(SUBMODULE_CONFIG_MACRO);
997 RECORD(SUBMODULE_CONFLICT);
998 RECORD(SUBMODULE_PRIVATE_HEADER);
999 RECORD(SUBMODULE_TEXTUAL_HEADER);
1000 RECORD(SUBMODULE_PRIVATE_TEXTUAL_HEADER);
1001
1002 // Comments Block.
1003 BLOCK(COMMENTS_BLOCK);
1004 RECORD(COMMENTS_RAW_COMMENT);
1005
Douglas Gregor12bfa382009-10-17 00:13:19 +00001006 // Decls and Types block.
1007 BLOCK(DECLTYPES_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001008 RECORD(TYPE_EXT_QUAL);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001009 RECORD(TYPE_COMPLEX);
1010 RECORD(TYPE_POINTER);
1011 RECORD(TYPE_BLOCK_POINTER);
1012 RECORD(TYPE_LVALUE_REFERENCE);
1013 RECORD(TYPE_RVALUE_REFERENCE);
1014 RECORD(TYPE_MEMBER_POINTER);
1015 RECORD(TYPE_CONSTANT_ARRAY);
1016 RECORD(TYPE_INCOMPLETE_ARRAY);
1017 RECORD(TYPE_VARIABLE_ARRAY);
1018 RECORD(TYPE_VECTOR);
1019 RECORD(TYPE_EXT_VECTOR);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001020 RECORD(TYPE_FUNCTION_NO_PROTO);
Richard Smithf1b4b8b2014-07-27 04:29:04 +00001021 RECORD(TYPE_FUNCTION_PROTO);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001022 RECORD(TYPE_TYPEDEF);
1023 RECORD(TYPE_TYPEOF_EXPR);
1024 RECORD(TYPE_TYPEOF);
1025 RECORD(TYPE_RECORD);
1026 RECORD(TYPE_ENUM);
1027 RECORD(TYPE_OBJC_INTERFACE);
Steve Narofffb4330f2009-06-17 22:40:22 +00001028 RECORD(TYPE_OBJC_OBJECT_POINTER);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001029 RECORD(TYPE_DECLTYPE);
1030 RECORD(TYPE_ELABORATED);
1031 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
1032 RECORD(TYPE_UNRESOLVED_USING);
1033 RECORD(TYPE_INJECTED_CLASS_NAME);
1034 RECORD(TYPE_OBJC_OBJECT);
1035 RECORD(TYPE_TEMPLATE_TYPE_PARM);
1036 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
1037 RECORD(TYPE_DEPENDENT_NAME);
1038 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
1039 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
1040 RECORD(TYPE_PAREN);
1041 RECORD(TYPE_PACK_EXPANSION);
1042 RECORD(TYPE_ATTRIBUTED);
1043 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
Richard Smithf1b4b8b2014-07-27 04:29:04 +00001044 RECORD(TYPE_AUTO);
1045 RECORD(TYPE_UNARY_TRANSFORM);
Eli Friedman0dfb8892011-10-06 23:00:33 +00001046 RECORD(TYPE_ATOMIC);
Richard Smithf1b4b8b2014-07-27 04:29:04 +00001047 RECORD(TYPE_DECAYED);
1048 RECORD(TYPE_ADJUSTED);
Richard Smithd61d4ac2015-08-22 20:13:39 +00001049 RECORD(LOCAL_REDECLARATIONS);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001050 RECORD(DECL_TYPEDEF);
Richard Smith01b2cb42014-07-26 06:37:51 +00001051 RECORD(DECL_TYPEALIAS);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001052 RECORD(DECL_ENUM);
1053 RECORD(DECL_RECORD);
1054 RECORD(DECL_ENUM_CONSTANT);
1055 RECORD(DECL_FUNCTION);
1056 RECORD(DECL_OBJC_METHOD);
1057 RECORD(DECL_OBJC_INTERFACE);
1058 RECORD(DECL_OBJC_PROTOCOL);
1059 RECORD(DECL_OBJC_IVAR);
1060 RECORD(DECL_OBJC_AT_DEFS_FIELD);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001061 RECORD(DECL_OBJC_CATEGORY);
1062 RECORD(DECL_OBJC_CATEGORY_IMPL);
1063 RECORD(DECL_OBJC_IMPLEMENTATION);
1064 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
1065 RECORD(DECL_OBJC_PROPERTY);
1066 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001067 RECORD(DECL_FIELD);
John McCall5e77d762013-04-16 07:28:30 +00001068 RECORD(DECL_MS_PROPERTY);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001069 RECORD(DECL_VAR);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001070 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001071 RECORD(DECL_PARM_VAR);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001072 RECORD(DECL_FILE_SCOPE_ASM);
1073 RECORD(DECL_BLOCK);
1074 RECORD(DECL_CONTEXT_LEXICAL);
1075 RECORD(DECL_CONTEXT_VISIBLE);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001076 RECORD(DECL_NAMESPACE);
1077 RECORD(DECL_NAMESPACE_ALIAS);
1078 RECORD(DECL_USING);
1079 RECORD(DECL_USING_SHADOW);
1080 RECORD(DECL_USING_DIRECTIVE);
1081 RECORD(DECL_UNRESOLVED_USING_VALUE);
1082 RECORD(DECL_UNRESOLVED_USING_TYPENAME);
1083 RECORD(DECL_LINKAGE_SPEC);
1084 RECORD(DECL_CXX_RECORD);
1085 RECORD(DECL_CXX_METHOD);
1086 RECORD(DECL_CXX_CONSTRUCTOR);
1087 RECORD(DECL_CXX_DESTRUCTOR);
1088 RECORD(DECL_CXX_CONVERSION);
1089 RECORD(DECL_ACCESS_SPEC);
1090 RECORD(DECL_FRIEND);
1091 RECORD(DECL_FRIEND_TEMPLATE);
1092 RECORD(DECL_CLASS_TEMPLATE);
1093 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
1094 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001095 RECORD(DECL_VAR_TEMPLATE);
1096 RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
1097 RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001098 RECORD(DECL_FUNCTION_TEMPLATE);
1099 RECORD(DECL_TEMPLATE_TYPE_PARM);
1100 RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
1101 RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
1102 RECORD(DECL_STATIC_ASSERT);
1103 RECORD(DECL_CXX_BASE_SPECIFIERS);
1104 RECORD(DECL_INDIRECTFIELD);
1105 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
1106
Douglas Gregor03412ba2011-06-03 02:27:19 +00001107 // Statements and Exprs can occur in the Decls and Types block.
1108 AddStmtsExprs(Stream, Record);
1109
Douglas Gregor92a96f52011-02-08 21:58:10 +00001110 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001111 RECORD(PPD_MACRO_EXPANSION);
Douglas Gregor92a96f52011-02-08 21:58:10 +00001112 RECORD(PPD_MACRO_DEFINITION);
1113 RECORD(PPD_INCLUSION_DIRECTIVE);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00001114
1115 // Decls and Types block.
1116 BLOCK(EXTENSION_BLOCK);
1117 RECORD(EXTENSION_METADATA);
1118
Chris Lattner28fa4e62009-04-26 22:26:21 +00001119#undef RECORD
1120#undef BLOCK
1121 Stream.ExitBlock();
1122}
1123
Richard Smith54cc3c22014-12-11 20:50:24 +00001124/// \brief Prepares a path for being written to an AST file by converting it
1125/// to an absolute path and removing nested './'s.
1126///
1127/// \return \c true if the path was changed.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001128static bool cleanPathForOutput(FileManager &FileMgr,
1129 SmallVectorImpl<char> &Path) {
Argyrios Kyrtzidis403cbcb2015-07-31 01:39:23 +00001130 bool Changed = FileMgr.makeAbsolutePath(Path);
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +00001131 return Changed | llvm::sys::path::remove_dots(Path);
Richard Smith54cc3c22014-12-11 20:50:24 +00001132}
1133
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001134/// \brief Adjusts the given filename to only write out the portion of the
1135/// filename that is not part of the system root directory.
Mike Stump11289f42009-09-09 15:08:12 +00001136///
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001137/// \param Filename the file name to adjust.
1138///
Richard Smith7ed1bc92014-12-05 22:42:13 +00001139/// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
1140/// the returned filename will be adjusted by this root directory.
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001141///
1142/// \returns either the original filename (if it needs no adjustment) or the
1143/// adjusted filename (which points into the @p Filename parameter).
Mike Stump11289f42009-09-09 15:08:12 +00001144static const char *
Richard Smith7ed1bc92014-12-05 22:42:13 +00001145adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001146 assert(Filename && "No file name to adjust?");
Mike Stump11289f42009-09-09 15:08:12 +00001147
Richard Smith7ed1bc92014-12-05 22:42:13 +00001148 if (BaseDir.empty())
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001149 return Filename;
Mike Stump11289f42009-09-09 15:08:12 +00001150
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001151 // Verify that the filename and the system root have the same prefix.
1152 unsigned Pos = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001153 for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
1154 if (Filename[Pos] != BaseDir[Pos])
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001155 return Filename; // Prefixes don't match.
Mike Stump11289f42009-09-09 15:08:12 +00001156
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001157 // We hit the end of the filename before we hit the end of the system root.
1158 if (!Filename[Pos])
1159 return Filename;
Mike Stump11289f42009-09-09 15:08:12 +00001160
Richard Smith7ed1bc92014-12-05 22:42:13 +00001161 // If there's not a path separator at the end of the base directory nor
1162 // immediately after it, then this isn't within the base directory.
1163 if (!llvm::sys::path::is_separator(Filename[Pos])) {
1164 if (!llvm::sys::path::is_separator(BaseDir.back()))
1165 return Filename;
1166 } else {
1167 // If the file name has a '/' at the current position, skip over the '/'.
1168 // We distinguish relative paths from absolute paths by the
1169 // absence of '/' at the beginning of relative paths.
1170 //
1171 // FIXME: This is wrong. We distinguish them by asking if the path is
1172 // absolute, which isn't the same thing. And there might be multiple '/'s
1173 // in a row. Use a better mechanism to indicate whether we have emitted an
1174 // absolute or relative path.
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001175 ++Pos;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001176 }
Mike Stump11289f42009-09-09 15:08:12 +00001177
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001178 return Filename + Pos;
1179}
Chris Lattner28fa4e62009-04-26 22:26:21 +00001180
Ben Langmuir487ea142014-10-23 18:05:36 +00001181static ASTFileSignature getSignature() {
1182 while (1) {
1183 if (ASTFileSignature S = llvm::sys::Process::GetRandomNumber())
1184 return S;
1185 // Rely on GetRandomNumber to eventually return non-zero...
1186 }
1187}
1188
Douglas Gregor112b9072012-10-18 05:31:06 +00001189/// \brief Write the control block.
Adrian Prantladbd2b12015-09-22 23:26:31 +00001190uint64_t ASTWriter::WriteControlBlock(Preprocessor &PP,
1191 ASTContext &Context,
1192 StringRef isysroot,
1193 const std::string &OutputFile) {
1194 ASTFileSignature Signature = 0;
1195
Douglas Gregorbfbde532009-04-10 21:16:55 +00001196 using namespace llvm;
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001197 Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001198 RecordData Record;
1199
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001200 // Metadata
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001201 auto *MetadataAbbrev = new BitCodeAbbrev();
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001202 MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1203 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1204 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1205 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1206 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1207 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
Richard Smithe75ee0f2015-08-17 07:13:32 +00001208 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001209 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1210 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1211 unsigned MetadataAbbrevCode = Stream.EmitAbbrev(MetadataAbbrev);
Richard Smith7ed1bc92014-12-05 22:42:13 +00001212 assert((!WritingModule || isysroot.empty()) &&
1213 "writing module as a relocatable PCH?");
Mehdi Amini57a41912015-09-10 01:46:39 +00001214 {
1215 RecordData::value_type Record[] = {METADATA, VERSION_MAJOR, VERSION_MINOR,
1216 CLANG_VERSION_MAJOR, CLANG_VERSION_MINOR,
1217 !isysroot.empty(), IncludeTimestamps,
1218 ASTHasCompilerErrors};
1219 Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1220 getClangFullRepositoryVersion());
1221 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001222 if (WritingModule) {
Chandler Carruth885e78c2015-03-24 21:18:10 +00001223 // For implicit modules we output a signature that we can use to ensure
1224 // duplicate module builds don't collide in the cache as their output order
1225 // is non-deterministic.
1226 // FIXME: Remove this when output is deterministic.
1227 if (Context.getLangOpts().ImplicitModules) {
Adrian Prantladbd2b12015-09-22 23:26:31 +00001228 Signature = getSignature();
1229 RecordData::value_type Record[] = {Signature};
Chandler Carruth885e78c2015-03-24 21:18:10 +00001230 Stream.EmitRecord(SIGNATURE, Record);
1231 }
1232
Richard Smith7ed1bc92014-12-05 22:42:13 +00001233 // Module name
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001234 auto *Abbrev = new BitCodeAbbrev();
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001235 Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1236 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1237 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00001238 RecordData::value_type Record[] = {MODULE_NAME};
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001239 Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1240 }
1241
Richard Smith7ed1bc92014-12-05 22:42:13 +00001242 if (WritingModule && WritingModule->Directory) {
Richard Smith7ed1bc92014-12-05 22:42:13 +00001243 SmallString<128> BaseDir(WritingModule->Directory->getName());
Richard Smith54cc3c22014-12-11 20:50:24 +00001244 cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
Richard Smithf7b41372015-08-13 23:47:44 +00001245
1246 // If the home of the module is the current working directory, then we
1247 // want to pick up the cwd of the build process loading the module, not
1248 // our cwd, when we load this module.
1249 if (!PP.getHeaderSearchInfo()
1250 .getHeaderSearchOpts()
1251 .ModuleMapFileHomeIsCwd ||
1252 WritingModule->Directory->getName() != StringRef(".")) {
1253 // Module directory.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001254 auto *Abbrev = new BitCodeAbbrev();
Richard Smithf7b41372015-08-13 23:47:44 +00001255 Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1256 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
1257 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1258
Mehdi Amini57a41912015-09-10 01:46:39 +00001259 RecordData::value_type Record[] = {MODULE_DIRECTORY};
Richard Smithf7b41372015-08-13 23:47:44 +00001260 Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
1261 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001262
1263 // Write out all other paths relative to the base directory if possible.
1264 BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1265 } else if (!isysroot.empty()) {
1266 // Write out paths relative to the sysroot if possible.
1267 BaseDirectory = isysroot;
1268 }
1269
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001270 // Module map file
1271 if (WritingModule) {
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001272 Record.clear();
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001273
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001274 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
1275
1276 // Primary module map file.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001277 AddPath(Map.getModuleMapFileForUniquing(WritingModule)->getName(), Record);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001278
1279 // Additional module map files.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001280 if (auto *AdditionalModMaps =
1281 Map.getAdditionalModuleMapFiles(WritingModule)) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001282 Record.push_back(AdditionalModMaps->size());
1283 for (const FileEntry *F : *AdditionalModMaps)
Richard Smith7ed1bc92014-12-05 22:42:13 +00001284 AddPath(F->getName(), Record);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001285 } else {
1286 Record.push_back(0);
1287 }
1288
1289 Stream.EmitRecord(MODULE_MAP_FILE, Record);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001290 }
1291
Douglas Gregor112b9072012-10-18 05:31:06 +00001292 // Imports
Douglas Gregor29cc6422011-08-17 21:07:30 +00001293 if (Chain) {
Douglas Gregor29cc6422011-08-17 21:07:30 +00001294 serialization::ModuleManager &Mgr = Chain->getModuleManager();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001295 Record.clear();
Douglas Gregordf0c1512011-08-18 04:12:04 +00001296
Richard Smith7f330cd2015-03-18 01:42:29 +00001297 for (auto *M : Mgr) {
Douglas Gregordf0c1512011-08-18 04:12:04 +00001298 // Skip modules that weren't directly imported.
Richard Smith7f330cd2015-03-18 01:42:29 +00001299 if (!M->isDirectlyImported())
Douglas Gregordf0c1512011-08-18 04:12:04 +00001300 continue;
1301
Richard Smith7f330cd2015-03-18 01:42:29 +00001302 Record.push_back((unsigned)M->Kind); // FIXME: Stable encoding
1303 AddSourceLocation(M->ImportLoc, Record);
1304 Record.push_back(M->File->getSize());
Richard Smithe75ee0f2015-08-17 07:13:32 +00001305 Record.push_back(getTimestampForOutput(M->File));
Richard Smith7f330cd2015-03-18 01:42:29 +00001306 Record.push_back(M->Signature);
1307 AddPath(M->FileName, Record);
Douglas Gregordf0c1512011-08-18 04:12:04 +00001308 }
Douglas Gregor29cc6422011-08-17 21:07:30 +00001309 Stream.EmitRecord(IMPORTS, Record);
1310 }
Mike Stump11289f42009-09-09 15:08:12 +00001311
Richard Smith0516b182015-09-08 19:40:14 +00001312 // Write the options block.
1313 Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
1314
Douglas Gregor112b9072012-10-18 05:31:06 +00001315 // Language options.
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001316 Record.clear();
Douglas Gregor112b9072012-10-18 05:31:06 +00001317 const LangOptions &LangOpts = Context.getLangOpts();
1318#define LANGOPT(Name, Bits, Default, Description) \
1319 Record.push_back(LangOpts.Name);
1320#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1321 Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001322#include "clang/Basic/LangOptions.def"
1323#define SANITIZER(NAME, ID) \
1324 Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
Will Dietzf54319c2013-01-18 11:30:38 +00001325#include "clang/Basic/Sanitizers.def"
Douglas Gregor112b9072012-10-18 05:31:06 +00001326
Ben Langmuircd98cb72015-06-23 18:20:18 +00001327 Record.push_back(LangOpts.ModuleFeatures.size());
1328 for (StringRef Feature : LangOpts.ModuleFeatures)
1329 AddString(Feature, Record);
1330
Douglas Gregor112b9072012-10-18 05:31:06 +00001331 Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1332 AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
Ben Langmuird4a667a2015-06-23 18:20:23 +00001333
1334 AddString(LangOpts.CurrentModule, Record);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001335
1336 // Comment options.
1337 Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001338 for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1339 AddString(I, Record);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001340 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00001341 Record.push_back(LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001342
Samuel Antaoee8fb302016-01-06 13:42:12 +00001343 // OpenMP offloading options.
1344 Record.push_back(LangOpts.OMPTargetTriples.size());
1345 for (auto &T : LangOpts.OMPTargetTriples)
1346 AddString(T.getTriple(), Record);
1347
1348 AddString(LangOpts.OMPHostIRFile, Record);
1349
Douglas Gregor112b9072012-10-18 05:31:06 +00001350 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1351
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001352 // Target options.
1353 Record.clear();
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001354 const TargetInfo &Target = Context.getTargetInfo();
1355 const TargetOptions &TargetOpts = Target.getTargetOpts();
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001356 AddString(TargetOpts.Triple, Record);
1357 AddString(TargetOpts.CPU, Record);
1358 AddString(TargetOpts.ABI, Record);
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001359 Record.push_back(TargetOpts.FeaturesAsWritten.size());
1360 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1361 AddString(TargetOpts.FeaturesAsWritten[I], Record);
1362 }
1363 Record.push_back(TargetOpts.Features.size());
1364 for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1365 AddString(TargetOpts.Features[I], Record);
1366 }
1367 Stream.EmitRecord(TARGET_OPTIONS, Record);
1368
Douglas Gregor8263ffb2012-10-24 15:17:15 +00001369 // Diagnostic options.
1370 Record.clear();
1371 const DiagnosticOptions &DiagOpts
1372 = Context.getDiagnostics().getDiagnosticOptions();
1373#define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1374#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1375 Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1376#include "clang/Basic/DiagnosticOptions.def"
1377 Record.push_back(DiagOpts.Warnings.size());
1378 for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1379 AddString(DiagOpts.Warnings[I], Record);
Richard Smith3be1cb22014-08-07 00:24:21 +00001380 Record.push_back(DiagOpts.Remarks.size());
1381 for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1382 AddString(DiagOpts.Remarks[I], Record);
Douglas Gregor8263ffb2012-10-24 15:17:15 +00001383 // Note: we don't serialize the log or serialization file names, because they
1384 // are generally transient files and will almost always be overridden.
1385 Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1386
Douglas Gregorc6317db2012-10-24 15:49:58 +00001387 // File system options.
1388 Record.clear();
Yaron Keren8dec46c2015-08-26 08:10:22 +00001389 const FileSystemOptions &FSOpts =
1390 Context.getSourceManager().getFileManager().getFileSystemOpts();
Douglas Gregorc6317db2012-10-24 15:49:58 +00001391 AddString(FSOpts.WorkingDir, Record);
1392 Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1393
Douglas Gregor2d302362012-10-24 16:50:34 +00001394 // Header search options.
1395 Record.clear();
1396 const HeaderSearchOptions &HSOpts
1397 = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1398 AddString(HSOpts.Sysroot, Record);
1399
1400 // Include entries.
1401 Record.push_back(HSOpts.UserEntries.size());
1402 for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1403 const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1404 AddString(Entry.Path, Record);
1405 Record.push_back(static_cast<unsigned>(Entry.Group));
Douglas Gregor2d302362012-10-24 16:50:34 +00001406 Record.push_back(Entry.IsFramework);
1407 Record.push_back(Entry.IgnoreSysRoot);
Douglas Gregor2d302362012-10-24 16:50:34 +00001408 }
1409
1410 // System header prefixes.
1411 Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1412 for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1413 AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1414 Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1415 }
1416
1417 AddString(HSOpts.ResourceDir, Record);
1418 AddString(HSOpts.ModuleCachePath, Record);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00001419 AddString(HSOpts.ModuleUserBuildPath, Record);
Douglas Gregor2d302362012-10-24 16:50:34 +00001420 Record.push_back(HSOpts.DisableModuleHash);
1421 Record.push_back(HSOpts.UseBuiltinIncludes);
1422 Record.push_back(HSOpts.UseStandardSystemIncludes);
1423 Record.push_back(HSOpts.UseStandardCXXIncludes);
1424 Record.push_back(HSOpts.UseLibcxx);
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00001425 // Write out the specific module cache path that contains the module files.
1426 AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
Douglas Gregor2d302362012-10-24 16:50:34 +00001427 Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1428
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001429 // Preprocessor options.
1430 Record.clear();
1431 const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1432
1433 // Macro definitions.
1434 Record.push_back(PPOpts.Macros.size());
1435 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1436 AddString(PPOpts.Macros[I].first, Record);
1437 Record.push_back(PPOpts.Macros[I].second);
1438 }
1439
1440 // Includes
1441 Record.push_back(PPOpts.Includes.size());
1442 for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1443 AddString(PPOpts.Includes[I], Record);
1444
1445 // Macro includes
1446 Record.push_back(PPOpts.MacroIncludes.size());
1447 for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1448 AddString(PPOpts.MacroIncludes[I], Record);
1449
Douglas Gregorb6368752012-10-24 23:41:50 +00001450 Record.push_back(PPOpts.UsePredefines);
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00001451 // Detailed record is important since it is used for the module cache hash.
1452 Record.push_back(PPOpts.DetailedRecord);
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001453 AddString(PPOpts.ImplicitPCHInclude, Record);
1454 AddString(PPOpts.ImplicitPTHInclude, Record);
1455 Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1456 Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1457
Richard Smith0516b182015-09-08 19:40:14 +00001458 // Leave the options block.
1459 Stream.ExitBlock();
1460
Douglas Gregora3b20262011-05-06 21:43:30 +00001461 // Original file name and file ID
Douglas Gregor45fe0362009-05-12 01:31:05 +00001462 SourceManager &SM = Context.getSourceManager();
1463 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001464 auto *FileAbbrev = new BitCodeAbbrev();
Douglas Gregorfad10d82012-10-18 18:36:53 +00001465 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1466 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
Douglas Gregor45fe0362009-05-12 01:31:05 +00001467 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1468 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
1469
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001470 Record.clear();
Douglas Gregorfad10d82012-10-18 18:36:53 +00001471 Record.push_back(ORIGINAL_FILE);
Douglas Gregora3b20262011-05-06 21:43:30 +00001472 Record.push_back(SM.getMainFileID().getOpaqueValue());
Richard Smith7ed1bc92014-12-05 22:42:13 +00001473 EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
Douglas Gregor45fe0362009-05-12 01:31:05 +00001474 }
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00001475
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +00001476 Record.clear();
1477 Record.push_back(SM.getMainFileID().getOpaqueValue());
1478 Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1479
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001480 // Original PCH directory
1481 if (!OutputFile.empty() && OutputFile != "-") {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001482 auto *Abbrev = new BitCodeAbbrev();
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001483 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1484 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1485 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1486
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001487 SmallString<128> OutputPath(OutputFile);
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001488
Argyrios Kyrtzidisc56419e2015-07-31 00:58:32 +00001489 SM.getFileManager().makeAbsolutePath(OutputPath);
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001490 StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1491
Mehdi Amini57a41912015-09-10 01:46:39 +00001492 RecordData::value_type Record[] = {ORIGINAL_PCH_DIR};
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001493 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1494 }
1495
Douglas Gregor49491f72013-03-15 22:15:07 +00001496 WriteInputFiles(Context.SourceMgr,
1497 PP.getHeaderSearchInfo().getHeaderSearchOpts(),
Douglas Gregora3dd9002013-07-22 20:48:33 +00001498 PP.getLangOpts().Modules);
Douglas Gregor72be3902012-10-19 00:38:02 +00001499 Stream.ExitBlock();
Adrian Prantladbd2b12015-09-22 23:26:31 +00001500 return Signature;
Douglas Gregor72be3902012-10-19 00:38:02 +00001501}
1502
Douglas Gregor49491f72013-03-15 22:15:07 +00001503namespace {
1504 /// \brief An input file.
1505 struct InputFileEntry {
1506 const FileEntry *File;
1507 bool IsSystemFile;
Richard Smitha8cfffa2015-11-26 02:04:16 +00001508 bool IsTransient;
Douglas Gregor49491f72013-03-15 22:15:07 +00001509 bool BufferOverridden;
1510 };
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001511} // end anonymous namespace
Douglas Gregor49491f72013-03-15 22:15:07 +00001512
1513void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1514 HeaderSearchOptions &HSOpts,
Douglas Gregora3dd9002013-07-22 20:48:33 +00001515 bool Modules) {
Douglas Gregor72be3902012-10-19 00:38:02 +00001516 using namespace llvm;
1517 Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
Mehdi Amini57a41912015-09-10 01:46:39 +00001518
Douglas Gregor72be3902012-10-19 00:38:02 +00001519 // Create input-file abbreviation.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001520 auto *IFAbbrev = new BitCodeAbbrev();
Douglas Gregor72be3902012-10-19 00:38:02 +00001521 IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001522 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
Douglas Gregor72be3902012-10-19 00:38:02 +00001523 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1524 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001525 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
Richard Smitha8cfffa2015-11-26 02:04:16 +00001526 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
Douglas Gregor72be3902012-10-19 00:38:02 +00001527 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1528 unsigned IFAbbrevCode = Stream.EmitAbbrev(IFAbbrev);
1529
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001530 // Get all ContentCache objects for files, sorted by whether the file is a
1531 // system one or not. System files go at the back, users files at the front.
Douglas Gregor49491f72013-03-15 22:15:07 +00001532 std::deque<InputFileEntry> SortedFiles;
Douglas Gregor72be3902012-10-19 00:38:02 +00001533 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1534 // Get this source location entry.
1535 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
NAKAMURA Takumideca50f2012-10-19 01:53:57 +00001536 assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
Douglas Gregor72be3902012-10-19 00:38:02 +00001537
1538 // We only care about file entries that were not overridden.
1539 if (!SLoc->isFile())
1540 continue;
1541 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001542 if (!Cache->OrigEntry)
Douglas Gregor72be3902012-10-19 00:38:02 +00001543 continue;
1544
Douglas Gregor49491f72013-03-15 22:15:07 +00001545 InputFileEntry Entry;
1546 Entry.File = Cache->OrigEntry;
1547 Entry.IsSystemFile = Cache->IsSystemFile;
Richard Smitha8cfffa2015-11-26 02:04:16 +00001548 Entry.IsTransient = Cache->IsTransient;
Douglas Gregor49491f72013-03-15 22:15:07 +00001549 Entry.BufferOverridden = Cache->BufferOverridden;
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001550 if (Cache->IsSystemFile)
Douglas Gregor49491f72013-03-15 22:15:07 +00001551 SortedFiles.push_back(Entry);
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001552 else
Douglas Gregor49491f72013-03-15 22:15:07 +00001553 SortedFiles.push_front(Entry);
1554 }
1555
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001556 unsigned UserFilesNum = 0;
1557 // Write out all of the input files.
Richard Smithec216502015-02-13 19:48:37 +00001558 std::vector<uint64_t> InputFileOffsets;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001559 for (const auto &Entry : SortedFiles) {
Douglas Gregor49491f72013-03-15 22:15:07 +00001560 uint32_t &InputFileID = InputFileIDs[Entry.File];
Argyrios Kyrtzidise65856f2012-12-11 07:48:08 +00001561 if (InputFileID != 0)
1562 continue; // already recorded this file.
1563
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001564 // Record this entry's offset.
1565 InputFileOffsets.push_back(Stream.GetCurrentBitNo());
Argyrios Kyrtzidise65856f2012-12-11 07:48:08 +00001566
1567 InputFileID = InputFileOffsets.size();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001568
Douglas Gregor49491f72013-03-15 22:15:07 +00001569 if (!Entry.IsSystemFile)
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001570 ++UserFilesNum;
1571
Douglas Gregor72be3902012-10-19 00:38:02 +00001572 // Emit size/modification time for this file.
Mehdi Amini57a41912015-09-10 01:46:39 +00001573 // And whether this file was overridden.
1574 RecordData::value_type Record[] = {
Richard Smitha8cfffa2015-11-26 02:04:16 +00001575 INPUT_FILE,
1576 InputFileOffsets.size(),
1577 (uint64_t)Entry.File->getSize(),
1578 (uint64_t)getTimestampForOutput(Entry.File),
1579 Entry.BufferOverridden,
1580 Entry.IsTransient};
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001581
Richard Smith7ed1bc92014-12-05 22:42:13 +00001582 EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
1583 }
Douglas Gregor49491f72013-03-15 22:15:07 +00001584
Douglas Gregor112b9072012-10-18 05:31:06 +00001585 Stream.ExitBlock();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001586
1587 // Create input file offsets abbreviation.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001588 auto *OffsetsAbbrev = new BitCodeAbbrev();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001589 OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1590 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001591 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1592 // input files
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001593 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
1594 unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(OffsetsAbbrev);
1595
1596 // Write input file offsets.
Mehdi Amini57a41912015-09-10 01:46:39 +00001597 RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
1598 InputFileOffsets.size(), UserFilesNum};
Reid Kleckner012665e2015-05-21 00:13:09 +00001599 Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
Douglas Gregor55abb232009-04-10 20:39:37 +00001600}
1601
Douglas Gregora7f71a92009-04-10 03:52:48 +00001602//===----------------------------------------------------------------------===//
1603// Source Manager Serialization
1604//===----------------------------------------------------------------------===//
1605
1606/// \brief Create an abbreviation for the SLocEntry that refers to a
1607/// file.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001608static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001609 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001610
1611 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00001612 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001613 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1614 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1615 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1616 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregorb41ca8f2010-03-21 22:49:54 +00001617 // FileEntry fields.
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001618 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001619 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00001620 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1621 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
Douglas Gregor8f45df52009-04-16 22:23:12 +00001622 return Stream.EmitAbbrev(Abbrev);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001623}
1624
1625/// \brief Create an abbreviation for the SLocEntry that refers to a
1626/// buffer.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001627static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001628 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001629
1630 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00001631 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001632 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1633 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1634 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1635 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1636 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
Douglas Gregor8f45df52009-04-16 22:23:12 +00001637 return Stream.EmitAbbrev(Abbrev);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001638}
1639
1640/// \brief Create an abbreviation for the SLocEntry that refers to a
1641/// buffer's blob.
Richard Smithaada85c2016-02-06 02:06:43 +00001642static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
1643 bool Compressed) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001644 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001645
1646 auto *Abbrev = new BitCodeAbbrev();
Richard Smithaada85c2016-02-06 02:06:43 +00001647 Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED
1648 : SM_SLOC_BUFFER_BLOB));
1649 if (Compressed)
1650 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
Douglas Gregora7f71a92009-04-10 03:52:48 +00001651 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
Douglas Gregor8f45df52009-04-16 22:23:12 +00001652 return Stream.EmitAbbrev(Abbrev);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001653}
1654
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001655/// \brief Create an abbreviation for the SLocEntry that refers to a macro
1656/// expansion.
1657static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001658 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001659
1660 auto *Abbrev = new BitCodeAbbrev();
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001661 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001662 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1663 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1664 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1665 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregor83243272009-04-15 18:05:10 +00001666 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
Douglas Gregor8f45df52009-04-16 22:23:12 +00001667 return Stream.EmitAbbrev(Abbrev);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001668}
1669
Douglas Gregor09b69892011-02-10 17:09:37 +00001670namespace {
1671 // Trait used for the on-disk hash table of header search information.
1672 class HeaderFileInfoTrait {
1673 ASTWriter &Writer;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001674 const HeaderSearch &HS;
Douglas Gregor09b69892011-02-10 17:09:37 +00001675
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001676 // Keep track of the framework names we've used during serialization.
1677 SmallVector<char, 128> FrameworkStringData;
1678 llvm::StringMap<unsigned> FrameworkNameOffset;
1679
Douglas Gregor09b69892011-02-10 17:09:37 +00001680 public:
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001681 HeaderFileInfoTrait(ASTWriter &Writer, const HeaderSearch &HS)
1682 : Writer(Writer), HS(HS) { }
Douglas Gregor09b69892011-02-10 17:09:37 +00001683
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001684 struct key_type {
1685 const FileEntry *FE;
1686 const char *Filename;
1687 };
1688 typedef const key_type &key_type_ref;
Douglas Gregor09b69892011-02-10 17:09:37 +00001689
1690 typedef HeaderFileInfo data_type;
1691 typedef const data_type &data_type_ref;
Justin Bogner25463f12014-04-18 20:27:24 +00001692 typedef unsigned hash_value_type;
1693 typedef unsigned offset_type;
Douglas Gregor09b69892011-02-10 17:09:37 +00001694
Richard Smithe75ee0f2015-08-17 07:13:32 +00001695 hash_value_type ComputeHash(key_type_ref key) {
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001696 // The hash is based only on size/time of the file, so that the reader can
1697 // match even when symlinking or excess path elements ("foo/../", "../")
1698 // change the form of the name. However, complete path is still the key.
1699 return llvm::hash_combine(key.FE->getSize(),
Richard Smithe75ee0f2015-08-17 07:13:32 +00001700 Writer.getTimestampForOutput(key.FE));
Douglas Gregor09b69892011-02-10 17:09:37 +00001701 }
1702
1703 std::pair<unsigned,unsigned>
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001704 EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001705 using namespace llvm::support;
Richard Smith386bb072015-08-18 23:42:23 +00001706 endian::Writer<little> LE(Out);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001707 unsigned KeyLen = strlen(key.Filename) + 1 + 8 + 8;
Richard Smith386bb072015-08-18 23:42:23 +00001708 LE.write<uint16_t>(KeyLen);
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001709 unsigned DataLen = 1 + 2 + 4 + 4;
Richard Smith386bb072015-08-18 23:42:23 +00001710 for (auto ModInfo : HS.getModuleMap().findAllModulesForHeader(key.FE))
1711 if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
1712 DataLen += 4;
1713 LE.write<uint8_t>(DataLen);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001714 return std::make_pair(KeyLen, DataLen);
Douglas Gregor09b69892011-02-10 17:09:37 +00001715 }
1716
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001717 void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001718 using namespace llvm::support;
1719 endian::Writer<little> LE(Out);
1720 LE.write<uint64_t>(key.FE->getSize());
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001721 KeyLen -= 8;
Richard Smithe75ee0f2015-08-17 07:13:32 +00001722 LE.write<uint64_t>(Writer.getTimestampForOutput(key.FE));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001723 KeyLen -= 8;
1724 Out.write(key.Filename, KeyLen);
Douglas Gregor09b69892011-02-10 17:09:37 +00001725 }
1726
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001727 void EmitData(raw_ostream &Out, key_type_ref key,
Douglas Gregor09b69892011-02-10 17:09:37 +00001728 data_type_ref Data, unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001729 using namespace llvm::support;
1730 endian::Writer<little> LE(Out);
Douglas Gregor09b69892011-02-10 17:09:37 +00001731 uint64_t Start = Out.tell(); (void)Start;
1732
Richard Smith386bb072015-08-18 23:42:23 +00001733 unsigned char Flags = (Data.isImport << 4)
1734 | (Data.isPragmaOnce << 3)
1735 | (Data.DirInfo << 1)
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001736 | Data.IndexHeaderMapHeader;
Justin Bognere1c147c2014-03-28 22:03:19 +00001737 LE.write<uint8_t>(Flags);
1738 LE.write<uint16_t>(Data.NumIncludes);
Douglas Gregor09b69892011-02-10 17:09:37 +00001739
1740 if (!Data.ControllingMacro)
Justin Bognere1c147c2014-03-28 22:03:19 +00001741 LE.write<uint32_t>(Data.ControllingMacroID);
Douglas Gregor09b69892011-02-10 17:09:37 +00001742 else
Justin Bognere1c147c2014-03-28 22:03:19 +00001743 LE.write<uint32_t>(Writer.getIdentifierRef(Data.ControllingMacro));
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001744
1745 unsigned Offset = 0;
1746 if (!Data.Framework.empty()) {
1747 // If this header refers into a framework, save the framework name.
1748 llvm::StringMap<unsigned>::iterator Pos
1749 = FrameworkNameOffset.find(Data.Framework);
1750 if (Pos == FrameworkNameOffset.end()) {
1751 Offset = FrameworkStringData.size() + 1;
1752 FrameworkStringData.append(Data.Framework.begin(),
1753 Data.Framework.end());
1754 FrameworkStringData.push_back(0);
1755
1756 FrameworkNameOffset[Data.Framework] = Offset;
1757 } else
1758 Offset = Pos->second;
1759 }
Justin Bognere1c147c2014-03-28 22:03:19 +00001760 LE.write<uint32_t>(Offset);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001761
Richard Smith386bb072015-08-18 23:42:23 +00001762 // FIXME: If the header is excluded, we should write out some
1763 // record of that fact.
1764 for (auto ModInfo : HS.getModuleMap().findAllModulesForHeader(key.FE)) {
1765 if (uint32_t ModID =
1766 Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule())) {
1767 uint32_t Value = (ModID << 2) | (unsigned)ModInfo.getRole();
1768 assert((Value >> 2) == ModID && "overflow in header module info");
1769 LE.write<uint32_t>(Value);
1770 }
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001771 }
1772
Douglas Gregor09b69892011-02-10 17:09:37 +00001773 assert(Out.tell() - Start == DataLen && "Wrong data length");
1774 }
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001775
1776 const char *strings_begin() const { return FrameworkStringData.begin(); }
1777 const char *strings_end() const { return FrameworkStringData.end(); }
Douglas Gregor09b69892011-02-10 17:09:37 +00001778 };
1779} // end anonymous namespace
1780
1781/// \brief Write the header search block for the list of files that
1782///
1783/// \param HS The header search structure to save.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001784void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001785 SmallVector<const FileEntry *, 16> FilesByUID;
Douglas Gregor09b69892011-02-10 17:09:37 +00001786 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
1787
1788 if (FilesByUID.size() > HS.header_file_size())
1789 FilesByUID.resize(HS.header_file_size());
1790
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001791 HeaderFileInfoTrait GeneratorTrait(*this, HS);
Justin Bognerbb094f02014-04-18 19:57:06 +00001792 llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001793 SmallVector<const char *, 4> SavedStrings;
Douglas Gregor09b69892011-02-10 17:09:37 +00001794 unsigned NumHeaderSearchEntries = 0;
1795 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1796 const FileEntry *File = FilesByUID[UID];
1797 if (!File)
1798 continue;
1799
Richard Smith386bb072015-08-18 23:42:23 +00001800 // Get the file info. This will load info from the external source if
1801 // necessary. Skip emitting this file if we have no information on it
1802 // as a header file (in which case HFI will be null) or if it hasn't
1803 // changed since it was loaded. Also skip it if it's for a modular header
1804 // from a different module; in that case, we rely on the module(s)
1805 // containing the header to provide this information.
Richard Smithd8879c82015-08-24 21:59:32 +00001806 const HeaderFileInfo *HFI =
1807 HS.getExistingFileInfo(File, /*WantExternal*/!Chain);
1808 if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001809 continue;
Douglas Gregor09b69892011-02-10 17:09:37 +00001810
Richard Smith7ed1bc92014-12-05 22:42:13 +00001811 // Massage the file path into an appropriate form.
Douglas Gregor09b69892011-02-10 17:09:37 +00001812 const char *Filename = File->getName();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001813 SmallString<128> FilenameTmp(Filename);
1814 if (PreparePathForOutput(FilenameTmp)) {
1815 // If we performed any translation on the file name at all, we need to
1816 // save this string, since the generator will refer to it later.
1817 Filename = strdup(FilenameTmp.c_str());
Douglas Gregor09b69892011-02-10 17:09:37 +00001818 SavedStrings.push_back(Filename);
1819 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001820
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001821 HeaderFileInfoTrait::key_type key = { File, Filename };
Richard Smith386bb072015-08-18 23:42:23 +00001822 Generator.insert(key, *HFI, GeneratorTrait);
Douglas Gregor09b69892011-02-10 17:09:37 +00001823 ++NumHeaderSearchEntries;
1824 }
1825
1826 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001827 SmallString<4096> TableData;
Douglas Gregor09b69892011-02-10 17:09:37 +00001828 uint32_t BucketOffset;
1829 {
Justin Bognere1c147c2014-03-28 22:03:19 +00001830 using namespace llvm::support;
Douglas Gregor09b69892011-02-10 17:09:37 +00001831 llvm::raw_svector_ostream Out(TableData);
1832 // Make sure that no bucket is at offset 0
Justin Bognere1c147c2014-03-28 22:03:19 +00001833 endian::Writer<little>(Out).write<uint32_t>(0);
Douglas Gregor09b69892011-02-10 17:09:37 +00001834 BucketOffset = Generator.Emit(Out, GeneratorTrait);
1835 }
1836
1837 // Create a blob abbreviation
1838 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001839
1840 auto *Abbrev = new BitCodeAbbrev();
Douglas Gregor09b69892011-02-10 17:09:37 +00001841 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1842 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1843 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001844 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor09b69892011-02-10 17:09:37 +00001845 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1846 unsigned TableAbbrev = Stream.EmitAbbrev(Abbrev);
1847
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001848 // Write the header search table
Mehdi Amini57a41912015-09-10 01:46:39 +00001849 RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
1850 NumHeaderSearchEntries, TableData.size()};
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001851 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
Yaron Keren92e1b622015-03-18 10:17:07 +00001852 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
Douglas Gregor09b69892011-02-10 17:09:37 +00001853
1854 // Free all of the strings we had to duplicate.
1855 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
David Greenebae0e352013-01-15 22:09:43 +00001856 free(const_cast<char *>(SavedStrings[I]));
Douglas Gregor09b69892011-02-10 17:09:37 +00001857}
1858
Douglas Gregora7f71a92009-04-10 03:52:48 +00001859/// \brief Writes the block containing the serialized form of the
1860/// source manager.
1861///
1862/// TODO: We should probably use an on-disk hash table (stored in a
1863/// blob), indexed based on the file name, so that we only create
1864/// entries for files that we actually need. In the common case (no
1865/// errors), we probably won't have to create file entries for any of
1866/// the files in the AST.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00001867void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001868 const Preprocessor &PP) {
Douglas Gregor258ae542009-04-27 06:38:32 +00001869 RecordData Record;
1870
Chris Lattner0910e3b2009-04-10 17:16:57 +00001871 // Enter the source manager block.
Richard Smithaada85c2016-02-06 02:06:43 +00001872 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001873
1874 // Abbreviations for the various kinds of source-location entries.
Chris Lattnerc4976c732009-04-27 19:03:22 +00001875 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
1876 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
Richard Smithaada85c2016-02-06 02:06:43 +00001877 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
1878 unsigned SLocBufferBlobCompressedAbbrv =
1879 CreateSLocBufferBlobAbbrev(Stream, true);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001880 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001881
Douglas Gregor258ae542009-04-27 06:38:32 +00001882 // Write out the source location entry table. We skip the first
1883 // entry, which is always the same dummy entry.
Chris Lattner12d61d32009-04-27 19:01:47 +00001884 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor258ae542009-04-27 06:38:32 +00001885 RecordData PreloadSLocs;
Douglas Gregor925296b2011-07-19 16:10:42 +00001886 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
1887 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
Sebastian Redl5c415f32010-07-22 17:01:13 +00001888 I != N; ++I) {
Douglas Gregor8655e882009-10-16 22:46:09 +00001889 // Get this source location entry.
Douglas Gregor925296b2011-07-19 16:10:42 +00001890 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00001891 FileID FID = FileID::get(I);
1892 assert(&SourceMgr.getSLocEntry(FID) == SLoc);
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00001893
Douglas Gregor258ae542009-04-27 06:38:32 +00001894 // Record the offset of this source-location entry.
1895 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
1896
1897 // Figure out which record code to use.
1898 unsigned Code;
1899 if (SLoc->isFile()) {
Douglas Gregor9dc32122011-11-16 20:05:18 +00001900 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1901 if (Cache->OrigEntry) {
Sebastian Redl539c5062010-08-18 23:57:32 +00001902 Code = SM_SLOC_FILE_ENTRY;
Argyrios Kyrtzidis92dd4662011-06-02 20:01:46 +00001903 } else
Sebastian Redl539c5062010-08-18 23:57:32 +00001904 Code = SM_SLOC_BUFFER_ENTRY;
Douglas Gregor258ae542009-04-27 06:38:32 +00001905 } else
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001906 Code = SM_SLOC_EXPANSION_ENTRY;
Douglas Gregor258ae542009-04-27 06:38:32 +00001907 Record.clear();
1908 Record.push_back(Code);
1909
Douglas Gregor925296b2011-07-19 16:10:42 +00001910 // Starting offset of this entry within this module, so skip the dummy.
1911 Record.push_back(SLoc->getOffset() - 2);
Douglas Gregor258ae542009-04-27 06:38:32 +00001912 if (SLoc->isFile()) {
1913 const SrcMgr::FileInfo &File = SLoc->getFile();
Richard Smithb22a1d12016-03-27 20:13:24 +00001914 AddSourceLocation(File.getIncludeLoc(), Record);
Douglas Gregor258ae542009-04-27 06:38:32 +00001915 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
1916 Record.push_back(File.hasLineDirectives());
1917
1918 const SrcMgr::ContentCache *Content = File.getContentCache();
Richard Smithaada85c2016-02-06 02:06:43 +00001919 bool EmitBlob = false;
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001920 if (Content->OrigEntry) {
1921 assert(Content->OrigEntry == Content->ContentsEntry &&
Douglas Gregor9dc32122011-11-16 20:05:18 +00001922 "Writing to AST an overridden file is not supported");
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001923
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001924 // The source location entry is a file. Emit input file ID.
1925 assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
1926 Record.push_back(InputFileIDs[Content->OrigEntry]);
Mike Stump11289f42009-09-09 15:08:12 +00001927
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001928 Record.push_back(File.NumCreatedFIDs);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00001929
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00001930 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00001931 if (FDI != FileDeclIDs.end()) {
1932 Record.push_back(FDI->second->FirstDeclIndex);
1933 Record.push_back(FDI->second->DeclIDs.size());
1934 } else {
1935 Record.push_back(0);
1936 Record.push_back(0);
1937 }
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001938
1939 Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
1940
Richard Smithaada85c2016-02-06 02:06:43 +00001941 if (Content->BufferOverridden || Content->IsTransient)
1942 EmitBlob = true;
Douglas Gregor258ae542009-04-27 06:38:32 +00001943 } else {
1944 // The source location entry is a buffer. The blob associated
1945 // with this entry contains the contents of the buffer.
1946
1947 // We add one to the size so that we capture the trailing NULL
1948 // that is required by llvm::MemoryBuffer::getMemBuffer (on
1949 // the reader side).
Douglas Gregor874cc622010-03-16 00:35:39 +00001950 const llvm::MemoryBuffer *Buffer
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00001951 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
Douglas Gregor258ae542009-04-27 06:38:32 +00001952 const char *Name = Buffer->getBufferIdentifier();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001953 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001954 StringRef(Name, strlen(Name) + 1));
Richard Smithaada85c2016-02-06 02:06:43 +00001955 EmitBlob = true;
Douglas Gregor258ae542009-04-27 06:38:32 +00001956
Douglas Gregor925296b2011-07-19 16:10:42 +00001957 if (strcmp(Name, "<built-in>") == 0) {
1958 PreloadSLocs.push_back(SLocEntryOffsets.size());
1959 }
Douglas Gregor258ae542009-04-27 06:38:32 +00001960 }
Richard Smithaada85c2016-02-06 02:06:43 +00001961
1962 if (EmitBlob) {
1963 // Include the implicit terminating null character in the on-disk buffer
1964 // if we're writing it uncompressed.
1965 const llvm::MemoryBuffer *Buffer =
1966 Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
1967 StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
1968
1969 // Compress the buffer if possible. We expect that almost all PCM
1970 // consumers will not want its contents.
1971 SmallString<0> CompressedBuffer;
1972 if (llvm::zlib::compress(Blob.drop_back(1), CompressedBuffer) ==
1973 llvm::zlib::StatusOK) {
1974 RecordData::value_type Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED,
1975 Blob.size() - 1};
1976 Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
1977 CompressedBuffer);
1978 } else {
1979 RecordData::value_type Record[] = {SM_SLOC_BUFFER_BLOB};
1980 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob);
1981 }
1982 }
Douglas Gregor258ae542009-04-27 06:38:32 +00001983 } else {
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001984 // The source location entry is a macro expansion.
Chandler Carruthee4c1d12011-07-26 04:56:51 +00001985 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
Richard Smithb22a1d12016-03-27 20:13:24 +00001986 AddSourceLocation(Expansion.getSpellingLoc(), Record);
1987 AddSourceLocation(Expansion.getExpansionLocStart(), Record);
1988 AddSourceLocation(Expansion.isMacroArgExpansion()
1989 ? SourceLocation()
1990 : Expansion.getExpansionLocEnd(),
1991 Record);
Douglas Gregor258ae542009-04-27 06:38:32 +00001992
1993 // Compute the token length for this macro expansion.
Douglas Gregor925296b2011-07-19 16:10:42 +00001994 unsigned NextOffset = SourceMgr.getNextLocalOffset();
Douglas Gregor8655e882009-10-16 22:46:09 +00001995 if (I + 1 != N)
Douglas Gregor925296b2011-07-19 16:10:42 +00001996 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
Douglas Gregor258ae542009-04-27 06:38:32 +00001997 Record.push_back(NextOffset - SLoc->getOffset() - 1);
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001998 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
Douglas Gregor258ae542009-04-27 06:38:32 +00001999 }
2000 }
2001
Douglas Gregor8f45df52009-04-16 22:23:12 +00002002 Stream.ExitBlock();
Douglas Gregor258ae542009-04-27 06:38:32 +00002003
2004 if (SLocEntryOffsets.empty())
2005 return;
2006
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002007 // Write the source-location offsets table into the AST block. This
Douglas Gregor258ae542009-04-27 06:38:32 +00002008 // table is used for lazily loading source-location information.
2009 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002010
2011 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00002012 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
Douglas Gregor258ae542009-04-27 06:38:32 +00002013 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
Douglas Gregor925296b2011-07-19 16:10:42 +00002014 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
Douglas Gregor258ae542009-04-27 06:38:32 +00002015 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
2016 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00002017 {
2018 RecordData::value_type Record[] = {
2019 SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
2020 SourceMgr.getNextLocalOffset() - 1 /* skip dummy */};
2021 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
2022 bytes(SLocEntryOffsets));
2023 }
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002024 // Write the source location entry preloads array, telling the AST
Douglas Gregor258ae542009-04-27 06:38:32 +00002025 // reader which source locations entries it should load eagerly.
Sebastian Redl539c5062010-08-18 23:57:32 +00002026 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregor925296b2011-07-19 16:10:42 +00002027
2028 // Write the line table. It depends on remapping working, so it must come
2029 // after the source location offsets.
2030 if (SourceMgr.hasLineTable()) {
2031 LineTableInfo &LineTable = SourceMgr.getLineTable();
2032
2033 Record.clear();
Richard Smith63078492015-09-01 07:41:55 +00002034
2035 // Emit the needed file names.
2036 llvm::DenseMap<int, int> FilenameMap;
2037 for (const auto &L : LineTable) {
2038 if (L.first.ID < 0)
2039 continue;
2040 for (auto &LE : L.second) {
2041 if (FilenameMap.insert(std::make_pair(LE.FilenameID,
2042 FilenameMap.size())).second)
2043 AddPath(LineTable.getFilename(LE.FilenameID), Record);
2044 }
2045 }
2046 Record.push_back(0);
Douglas Gregor925296b2011-07-19 16:10:42 +00002047
2048 // Emit the line entries
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002049 for (const auto &L : LineTable) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002050 // Only emit entries for local files.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002051 if (L.first.ID < 0)
Douglas Gregor925296b2011-07-19 16:10:42 +00002052 continue;
2053
2054 // Emit the file ID
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002055 Record.push_back(L.first.ID);
Douglas Gregor925296b2011-07-19 16:10:42 +00002056
2057 // Emit the line entries
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002058 Record.push_back(L.second.size());
2059 for (const auto &LE : L.second) {
2060 Record.push_back(LE.FileOffset);
2061 Record.push_back(LE.LineNo);
2062 Record.push_back(FilenameMap[LE.FilenameID]);
2063 Record.push_back((unsigned)LE.FileKind);
2064 Record.push_back(LE.IncludeOffset);
Douglas Gregor925296b2011-07-19 16:10:42 +00002065 }
2066 }
Richard Smith63078492015-09-01 07:41:55 +00002067
Douglas Gregor925296b2011-07-19 16:10:42 +00002068 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
2069 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00002070}
2071
Douglas Gregorc5046832009-04-27 18:38:38 +00002072//===----------------------------------------------------------------------===//
2073// Preprocessor Serialization
2074//===----------------------------------------------------------------------===//
2075
Argyrios Kyrtzidis0aef0f02013-03-15 22:43:10 +00002076static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
2077 const Preprocessor &PP) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002078 if (MacroInfo *MI = MD->getMacroInfo())
2079 if (MI->isBuiltinMacro())
2080 return true;
Argyrios Kyrtzidis0aef0f02013-03-15 22:43:10 +00002081
2082 if (IsModule) {
2083 SourceLocation Loc = MD->getLocation();
2084 if (Loc.isInvalid())
2085 return true;
2086 if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
2087 return true;
2088 }
2089
2090 return false;
2091}
2092
Chris Lattnereeffaef2009-04-10 17:15:23 +00002093/// \brief Writes the block containing the serialized form of the
2094/// preprocessor.
2095///
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00002096void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002097 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
2098 if (PPRec)
2099 WritePreprocessorDetail(*PPRec);
2100
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002101 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00002102 RecordData ModuleMacroRecord;
Chris Lattner0910e3b2009-04-10 17:16:57 +00002103
Chris Lattner0af3ba12009-04-13 01:29:17 +00002104 // If the preprocessor __COUNTER__ value has been bumped, remember it.
2105 if (PP.getCounterValue() != 0) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002106 RecordData::value_type Record[] = {PP.getCounterValue()};
Sebastian Redl539c5062010-08-18 23:57:32 +00002107 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
Douglas Gregoreda6a892009-04-26 00:07:37 +00002108 }
2109
2110 // Enter the preprocessor block.
Douglas Gregor796d76a2010-10-20 22:00:55 +00002111 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
Mike Stump11289f42009-09-09 15:08:12 +00002112
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002113 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
Richard Smithb5aaf5a2015-09-01 02:35:58 +00002114 // FIXME: Include a location for the use, and say which one was used.
Douglas Gregoreda6a892009-04-26 00:07:37 +00002115 if (PP.SawDateOrTime())
Richard Smithb5aaf5a2015-09-01 02:35:58 +00002116 PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
Douglas Gregor796d76a2010-10-20 22:00:55 +00002117
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002118 // Loop over all the macro directives that are live at the end of the file,
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002119 // emitting each to the PP section.
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002120
Richard Smithee977932015-05-01 21:22:17 +00002121 // Construct the list of identifiers with macro directives that need to be
2122 // serialized.
2123 SmallVector<const IdentifierInfo *, 128> MacroIdentifiers;
2124 for (auto &Id : PP.getIdentifierTable())
2125 if (Id.second->hadMacroDefinition() &&
2126 (!Id.second->isFromAST() ||
2127 Id.second->hasChangedSinceDeserialization()))
2128 MacroIdentifiers.push_back(Id.second);
Douglas Gregor2e5571d2011-02-10 18:20:09 +00002129 // Sort the set of macro definitions that need to be serialized by the
2130 // name of the macro, to provide a stable ordering.
Richard Smithee977932015-05-01 21:22:17 +00002131 std::sort(MacroIdentifiers.begin(), MacroIdentifiers.end(),
2132 llvm::less_ptr<IdentifierInfo>());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002133
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002134 // Emit the macro directives as a list and associate the offset with the
2135 // identifier they belong to.
Richard Smithee977932015-05-01 21:22:17 +00002136 for (const IdentifierInfo *Name : MacroIdentifiers) {
2137 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name);
Richard Smithd7329392015-04-21 21:46:32 +00002138 auto StartOffset = Stream.GetCurrentBitNo();
2139
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002140 // Emit the macro directives in reverse source order.
2141 for (; MD; MD = MD->getPrevious()) {
Richard Smithd7329392015-04-21 21:46:32 +00002142 // Once we hit an ignored macro, we're done: the rest of the chain
2143 // will all be ignored macros.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002144 if (shouldIgnoreMacro(MD, IsModule, PP))
Richard Smithd7329392015-04-21 21:46:32 +00002145 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002146
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002147 AddSourceLocation(MD->getLocation(), Record);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002148 Record.push_back(MD->getKind());
Richard Smithdaa69e02014-07-25 04:40:03 +00002149 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
Richard Smith3981b172015-04-30 02:16:23 +00002150 Record.push_back(getMacroRef(DefMD->getInfo(), Name));
Richard Smith713369b2015-04-23 20:40:50 +00002151 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002152 Record.push_back(VisMD->isPublic());
2153 }
Richard Smithb8b2ed62015-04-23 18:18:26 +00002154 }
Richard Smithd7329392015-04-21 21:46:32 +00002155
Richard Smithb8b2ed62015-04-23 18:18:26 +00002156 // Write out any exported module macros.
Richard Smithee977932015-05-01 21:22:17 +00002157 bool EmittedModuleMacros = false;
Richard Smithb8b2ed62015-04-23 18:18:26 +00002158 if (IsModule) {
2159 auto Leafs = PP.getLeafModuleMacros(Name);
2160 SmallVector<ModuleMacro*, 8> Worklist(Leafs.begin(), Leafs.end());
2161 llvm::DenseMap<ModuleMacro*, unsigned> Visits;
2162 while (!Worklist.empty()) {
2163 auto *Macro = Worklist.pop_back_val();
Richard Smithd7329392015-04-21 21:46:32 +00002164
Richard Smithb8b2ed62015-04-23 18:18:26 +00002165 // Emit a record indicating this submodule exports this macro.
2166 ModuleMacroRecord.push_back(
2167 getSubmoduleID(Macro->getOwningModule()));
Richard Smithee977932015-05-01 21:22:17 +00002168 ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
Richard Smithb8b2ed62015-04-23 18:18:26 +00002169 for (auto *M : Macro->overrides())
2170 ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
Richard Smithd7329392015-04-21 21:46:32 +00002171
Richard Smithb8b2ed62015-04-23 18:18:26 +00002172 Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2173 ModuleMacroRecord.clear();
Richard Smithd7329392015-04-21 21:46:32 +00002174
Richard Smithb8b2ed62015-04-23 18:18:26 +00002175 // Enqueue overridden macros once we've visited all their ancestors.
2176 for (auto *M : Macro->overrides())
2177 if (++Visits[M] == M->getNumOverridingMacros())
2178 Worklist.push_back(M);
Richard Smithee977932015-05-01 21:22:17 +00002179
2180 EmittedModuleMacros = true;
Richard Smithd7329392015-04-21 21:46:32 +00002181 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002182 }
Richard Smithd7329392015-04-21 21:46:32 +00002183
Richard Smithee977932015-05-01 21:22:17 +00002184 if (Record.empty() && !EmittedModuleMacros)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002185 continue;
2186
Richard Smithd7329392015-04-21 21:46:32 +00002187 IdentMacroDirectivesOffsetMap[Name] = StartOffset;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002188 Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2189 Record.clear();
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002190 }
Alexander Kornienko1d26c022012-09-25 17:18:14 +00002191
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002192 /// \brief Offsets of each of the macros into the bitstream, indexed by
2193 /// the local macro ID
2194 ///
2195 /// For each identifier that is associated with a macro, this map
2196 /// provides the offset into the bitstream where that macro is
2197 /// defined.
2198 std::vector<uint32_t> MacroOffsets;
2199
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002200 for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2201 const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2202 MacroInfo *MI = MacroInfosToEmit[I].MI;
2203 MacroID ID = MacroInfosToEmit[I].ID;
Douglas Gregoreb114da2010-10-01 01:03:07 +00002204
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002205 if (ID < FirstMacroID) {
2206 assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2207 continue;
Chris Lattner2199f5b2009-04-10 18:08:30 +00002208 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002209
2210 // Record the local offset of this macro.
2211 unsigned Index = ID - FirstMacroID;
2212 if (Index == MacroOffsets.size())
2213 MacroOffsets.push_back(Stream.GetCurrentBitNo());
2214 else {
2215 if (Index > MacroOffsets.size())
2216 MacroOffsets.resize(Index + 1);
2217
2218 MacroOffsets[Index] = Stream.GetCurrentBitNo();
2219 }
2220
2221 AddIdentifierRef(Name, Record);
2222 Record.push_back(inferSubmoduleIDFromLocation(MI->getDefinitionLoc()));
2223 AddSourceLocation(MI->getDefinitionLoc(), Record);
2224 AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2225 Record.push_back(MI->isUsed());
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00002226 Record.push_back(MI->isUsedForHeaderGuard());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002227 unsigned Code;
2228 if (MI->isObjectLike()) {
2229 Code = PP_MACRO_OBJECT_LIKE;
2230 } else {
2231 Code = PP_MACRO_FUNCTION_LIKE;
2232
2233 Record.push_back(MI->isC99Varargs());
2234 Record.push_back(MI->isGNUVarargs());
2235 Record.push_back(MI->hasCommaPasting());
2236 Record.push_back(MI->getNumArgs());
Daniel Marjamakie4770da2015-05-29 09:15:24 +00002237 for (const IdentifierInfo *Arg : MI->args())
2238 AddIdentifierRef(Arg, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002239 }
2240
2241 // If we have a detailed preprocessing record, record the macro definition
2242 // ID that corresponds to this macro.
2243 if (PPRec)
2244 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2245
2246 Stream.EmitRecord(Code, Record);
2247 Record.clear();
2248
2249 // Emit the tokens array.
2250 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2251 // Note that we know that the preprocessor does not have any annotation
2252 // tokens in it because they are created by the parser, and thus can't
2253 // be in a macro definition.
2254 const Token &Tok = MI->getReplacementToken(TokNo);
John McCallf413f5e2013-05-03 00:10:13 +00002255 AddToken(Tok, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002256 Stream.EmitRecord(PP_TOKEN, Record);
2257 Record.clear();
2258 }
2259 ++NumMacros;
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002260 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002261
Douglas Gregor92a96f52011-02-08 21:58:10 +00002262 Stream.ExitBlock();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002263
2264 // Write the offsets table for macro IDs.
2265 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002266
Richard Smith13090a22015-04-10 02:02:24 +00002267 auto *Abbrev = new BitCodeAbbrev();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002268 Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2269 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2270 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2271 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2272
2273 unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00002274 {
2275 RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
2276 FirstMacroID - NUM_PREDEF_MACRO_IDS};
2277 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
2278 }
Douglas Gregor92a96f52011-02-08 21:58:10 +00002279}
2280
2281void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
Argyrios Kyrtzidis7f448362011-09-19 20:40:42 +00002282 if (PPRec.local_begin() == PPRec.local_end())
Douglas Gregor92a96f52011-02-08 21:58:10 +00002283 return;
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002284
Argyrios Kyrtzidis64f63812011-09-19 20:40:25 +00002285 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002286
Douglas Gregor92a96f52011-02-08 21:58:10 +00002287 // Enter the preprocessor block.
2288 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002289
Douglas Gregoraae92242010-03-19 21:51:54 +00002290 // If the preprocessor has a preprocessing record, emit it.
2291 unsigned NumPreprocessingRecords = 0;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002292 using namespace llvm;
2293
2294 // Set up the abbreviation for
2295 unsigned InclusionAbbrev = 0;
2296 {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002297 auto *Abbrev = new BitCodeAbbrev();
Douglas Gregor92a96f52011-02-08 21:58:10 +00002298 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
Douglas Gregor92a96f52011-02-08 21:58:10 +00002299 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2300 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2301 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
Argyrios Kyrtzidisf590e092012-10-02 16:10:46 +00002302 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
Douglas Gregor92a96f52011-02-08 21:58:10 +00002303 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2304 InclusionAbbrev = Stream.EmitAbbrev(Abbrev);
2305 }
2306
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002307 unsigned FirstPreprocessorEntityID
2308 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
2309 + NUM_PREDEF_PP_ENTITY_IDS;
2310 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002311 RecordData Record;
Argyrios Kyrtzidis7f448362011-09-19 20:40:42 +00002312 for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2313 EEnd = PPRec.local_end();
Douglas Gregor0d4b4312011-08-04 17:06:18 +00002314 E != EEnd;
2315 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
Douglas Gregor92a96f52011-02-08 21:58:10 +00002316 Record.clear();
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002317
Richard Smith66a81862015-05-04 02:25:31 +00002318 PreprocessedEntityOffsets.push_back(
2319 PPEntityOffset((*E)->getSourceRange(), Stream.GetCurrentBitNo()));
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002320
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002321 if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002322 // Record this macro definition's ID.
2323 MacroDefinitions[MD] = NextPreprocessorEntityID;
Richard Smith66a81862015-05-04 02:25:31 +00002324
Douglas Gregor92a96f52011-02-08 21:58:10 +00002325 AddIdentifierRef(MD->getName(), Record);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002326 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2327 continue;
Douglas Gregoraae92242010-03-19 21:51:54 +00002328 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002329
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002330 if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
Argyrios Kyrtzidis80f78b92011-09-08 17:18:41 +00002331 Record.push_back(ME->isBuiltinMacro());
2332 if (ME->isBuiltinMacro())
2333 AddIdentifierRef(ME->getName(), Record);
2334 else
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002335 Record.push_back(MacroDefinitions[ME->getDefinition()]);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00002336 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002337 continue;
2338 }
2339
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002340 if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
Douglas Gregor92a96f52011-02-08 21:58:10 +00002341 Record.push_back(PPD_INCLUSION_DIRECTIVE);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002342 Record.push_back(ID->getFileName().size());
2343 Record.push_back(ID->wasInQuotes());
2344 Record.push_back(static_cast<unsigned>(ID->getKind()));
Argyrios Kyrtzidisf590e092012-10-02 16:10:46 +00002345 Record.push_back(ID->importedModule());
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002346 SmallString<64> Buffer;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002347 Buffer += ID->getFileName();
Argyrios Kyrtzidis8dbcfc32012-03-08 01:08:28 +00002348 // Check that the FileEntry is not null because it was not resolved and
2349 // we create a PCH even with compiler errors.
2350 if (ID->getFile())
2351 Buffer += ID->getFile()->getName();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00002352 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002353 continue;
2354 }
2355
2356 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2357 }
Douglas Gregor8f45df52009-04-16 22:23:12 +00002358 Stream.ExitBlock();
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002359
Douglas Gregoraae92242010-03-19 21:51:54 +00002360 // Write the offsets table for the preprocessing record.
2361 if (NumPreprocessingRecords > 0) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002362 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2363
Douglas Gregoraae92242010-03-19 21:51:54 +00002364 // Write the offsets table for identifier IDs.
2365 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002366
2367 auto *Abbrev = new BitCodeAbbrev();
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002368 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002369 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
Douglas Gregoraae92242010-03-19 21:51:54 +00002370 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002371 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002372
Mehdi Amini57a41912015-09-10 01:46:39 +00002373 RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
2374 FirstPreprocessorEntityID -
2375 NUM_PREDEF_PP_ENTITY_IDS};
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002376 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00002377 bytes(PreprocessedEntityOffsets));
Douglas Gregoraae92242010-03-19 21:51:54 +00002378 }
Chris Lattnereeffaef2009-04-10 17:15:23 +00002379}
2380
Richard Smith386bb072015-08-18 23:42:23 +00002381unsigned ASTWriter::getLocalOrImportedSubmoduleID(Module *Mod) {
Richard Smith080056b2015-08-18 21:53:42 +00002382 if (!Mod)
2383 return 0;
2384
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002385 llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
2386 if (Known != SubmoduleIDs.end())
2387 return Known->second;
Richard Smith386bb072015-08-18 23:42:23 +00002388
2389 if (Mod->getTopLevelModule() != WritingModule)
2390 return 0;
2391
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002392 return SubmoduleIDs[Mod] = NextSubmoduleID++;
2393}
2394
Richard Smith386bb072015-08-18 23:42:23 +00002395unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2396 // FIXME: This can easily happen, if we have a reference to a submodule that
2397 // did not result in us loading a module file for that submodule. For
2398 // instance, a cross-top-level-module 'conflict' declaration will hit this.
2399 unsigned ID = getLocalOrImportedSubmoduleID(Mod);
2400 assert((ID || !Mod) &&
2401 "asked for module ID for non-local, non-imported module");
2402 return ID;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00002403}
2404
Douglas Gregor253eefe2011-12-01 00:59:36 +00002405/// \brief Compute the number of modules within the given tree (including the
2406/// given module).
2407static unsigned getNumberOfModules(Module *Mod) {
2408 unsigned ChildModules = 0;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002409 for (auto Sub = Mod->submodule_begin(), SubEnd = Mod->submodule_end();
Douglas Gregor253eefe2011-12-01 00:59:36 +00002410 Sub != SubEnd; ++Sub)
Douglas Gregoreb90e832012-01-04 23:32:19 +00002411 ChildModules += getNumberOfModules(*Sub);
Douglas Gregor253eefe2011-12-01 00:59:36 +00002412
2413 return ChildModules + 1;
2414}
2415
Douglas Gregorde3ef502011-11-30 23:21:26 +00002416void ASTWriter::WriteSubmodules(Module *WritingModule) {
Douglas Gregor69021972011-11-30 17:33:56 +00002417 // Enter the submodule description block.
Richard Smith202210b2014-10-24 20:23:01 +00002418 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
Douglas Gregor69021972011-11-30 17:33:56 +00002419
2420 // Write the abbreviations needed for the submodules block.
2421 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002422
2423 auto *Abbrev = new BitCodeAbbrev();
Douglas Gregor69021972011-11-30 17:33:56 +00002424 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002425 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
Douglas Gregor69021972011-11-30 17:33:56 +00002426 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
2427 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2428 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
Richard Smith9bca2982014-03-08 00:03:56 +00002429 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2430 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
Douglas Gregora686e1b2012-01-27 19:52:33 +00002431 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
Douglas Gregor73441092011-12-05 22:27:44 +00002432 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
Douglas Gregor73441092011-12-05 22:27:44 +00002433 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002434 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
Douglas Gregor69021972011-11-30 17:33:56 +00002435 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2436 unsigned DefinitionAbbrev = Stream.EmitAbbrev(Abbrev);
2437
2438 Abbrev = new BitCodeAbbrev();
Douglas Gregor524e33e2011-12-08 19:11:24 +00002439 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
Douglas Gregor69021972011-11-30 17:33:56 +00002440 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2441 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(Abbrev);
2442
2443 Abbrev = new BitCodeAbbrev();
2444 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2445 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2446 unsigned HeaderAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregor524e33e2011-12-08 19:11:24 +00002447
2448 Abbrev = new BitCodeAbbrev();
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +00002449 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2450 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2451 unsigned TopHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2452
2453 Abbrev = new BitCodeAbbrev();
Douglas Gregor524e33e2011-12-08 19:11:24 +00002454 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2455 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2456 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(Abbrev);
2457
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002458 Abbrev = new BitCodeAbbrev();
2459 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
Richard Smitha3feee22013-10-28 22:18:19 +00002460 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2461 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002462 unsigned RequiresAbbrev = Stream.EmitAbbrev(Abbrev);
2463
Douglas Gregor59527662012-10-15 06:28:11 +00002464 Abbrev = new BitCodeAbbrev();
2465 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2466 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2467 unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2468
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002469 Abbrev = new BitCodeAbbrev();
Richard Smith306d8922014-10-22 23:50:56 +00002470 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
2471 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2472 unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2473
2474 Abbrev = new BitCodeAbbrev();
Lawrence Crowlb53e5482013-06-20 21:14:14 +00002475 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2476 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2477 unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2478
2479 Abbrev = new BitCodeAbbrev();
Richard Smith202210b2014-10-24 20:23:01 +00002480 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
2481 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2482 unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2483
2484 Abbrev = new BitCodeAbbrev();
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002485 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2486 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2487 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2488 unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(Abbrev);
2489
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002490 Abbrev = new BitCodeAbbrev();
2491 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2492 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2493 unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(Abbrev);
2494
Douglas Gregorfb912652013-03-20 21:10:35 +00002495 Abbrev = new BitCodeAbbrev();
2496 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2497 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
2498 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
2499 unsigned ConflictAbbrev = Stream.EmitAbbrev(Abbrev);
2500
Douglas Gregor253eefe2011-12-01 00:59:36 +00002501 // Write the submodule metadata block.
Mehdi Amini57a41912015-09-10 01:46:39 +00002502 RecordData::value_type Record[] = {getNumberOfModules(WritingModule),
2503 FirstSubmoduleID -
2504 NUM_PREDEF_SUBMODULE_IDS};
Douglas Gregor253eefe2011-12-01 00:59:36 +00002505 Stream.EmitRecord(SUBMODULE_METADATA, Record);
2506
Douglas Gregor69021972011-11-30 17:33:56 +00002507 // Write all of the submodules.
Douglas Gregorde3ef502011-11-30 23:21:26 +00002508 std::queue<Module *> Q;
Douglas Gregor69021972011-11-30 17:33:56 +00002509 Q.push(WritingModule);
Douglas Gregor69021972011-11-30 17:33:56 +00002510 while (!Q.empty()) {
Douglas Gregorde3ef502011-11-30 23:21:26 +00002511 Module *Mod = Q.front();
Douglas Gregor69021972011-11-30 17:33:56 +00002512 Q.pop();
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002513 unsigned ID = getSubmoduleID(Mod);
Mehdi Amini57a41912015-09-10 01:46:39 +00002514
2515 uint64_t ParentID = 0;
Douglas Gregor69021972011-11-30 17:33:56 +00002516 if (Mod->Parent) {
2517 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
Mehdi Amini57a41912015-09-10 01:46:39 +00002518 ParentID = SubmoduleIDs[Mod->Parent];
Douglas Gregor69021972011-11-30 17:33:56 +00002519 }
Mehdi Amini57a41912015-09-10 01:46:39 +00002520
2521 // Emit the definition of the block.
2522 {
2523 RecordData::value_type Record[] = {
2524 SUBMODULE_DEFINITION, ID, ParentID, Mod->IsFramework, Mod->IsExplicit,
2525 Mod->IsSystem, Mod->IsExternC, Mod->InferSubmodules,
2526 Mod->InferExplicitSubmodules, Mod->InferExportWildcard,
2527 Mod->ConfigMacrosExhaustive};
2528 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2529 }
2530
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002531 // Emit the requirements.
Richard Smith080056b2015-08-18 21:53:42 +00002532 for (const auto &R : Mod->Requirements) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002533 RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.second};
Richard Smith080056b2015-08-18 21:53:42 +00002534 Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.first);
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002535 }
2536
Douglas Gregor69021972011-11-30 17:33:56 +00002537 // Emit the umbrella header, if there is one.
Richard Smith2b63d152015-05-16 02:28:53 +00002538 if (auto UmbrellaHeader = Mod->getUmbrellaHeader()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002539 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
Richard Smith2b63d152015-05-16 02:28:53 +00002540 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2541 UmbrellaHeader.NameAsWritten);
2542 } else if (auto UmbrellaDir = Mod->getUmbrellaDir()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002543 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
2544 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
Richard Smith2b63d152015-05-16 02:28:53 +00002545 UmbrellaDir.NameAsWritten);
Douglas Gregor69021972011-11-30 17:33:56 +00002546 }
Richard Smith306d8922014-10-22 23:50:56 +00002547
Douglas Gregor69021972011-11-30 17:33:56 +00002548 // Emit the headers.
Richard Smith202210b2014-10-24 20:23:01 +00002549 struct {
Richard Smith3c1a41a2014-12-02 00:08:08 +00002550 unsigned RecordKind;
Richard Smith202210b2014-10-24 20:23:01 +00002551 unsigned Abbrev;
Richard Smith3c1a41a2014-12-02 00:08:08 +00002552 Module::HeaderKind HeaderKind;
Richard Smith202210b2014-10-24 20:23:01 +00002553 } HeaderLists[] = {
Richard Smith3c1a41a2014-12-02 00:08:08 +00002554 {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
2555 {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
2556 {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
Richard Smith202210b2014-10-24 20:23:01 +00002557 {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
Richard Smith3c1a41a2014-12-02 00:08:08 +00002558 Module::HK_PrivateTextual},
2559 {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
Richard Smith202210b2014-10-24 20:23:01 +00002560 };
2561 for (auto &HL : HeaderLists) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002562 RecordData::value_type Record[] = {HL.RecordKind};
Richard Smith3c1a41a2014-12-02 00:08:08 +00002563 for (auto &H : Mod->Headers[HL.HeaderKind])
2564 Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
2565 }
2566
2567 // Emit the top headers.
2568 {
2569 auto TopHeaders = Mod->getTopHeaders(PP->getFileManager());
Mehdi Amini57a41912015-09-10 01:46:39 +00002570 RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
Richard Smith3c1a41a2014-12-02 00:08:08 +00002571 for (auto *H : TopHeaders)
2572 Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, H->getName());
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +00002573 }
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002574
2575 // Emit the imports.
2576 if (!Mod->Imports.empty()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002577 RecordData Record;
Richard Smith080056b2015-08-18 21:53:42 +00002578 for (auto *I : Mod->Imports)
2579 Record.push_back(getSubmoduleID(I));
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002580 Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2581 }
2582
Douglas Gregor24bb9232011-12-02 18:58:38 +00002583 // Emit the exports.
2584 if (!Mod->Exports.empty()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002585 RecordData Record;
Richard Smith080056b2015-08-18 21:53:42 +00002586 for (const auto &E : Mod->Exports) {
2587 // FIXME: This may fail; we don't require that all exported modules
2588 // are local or imported.
2589 Record.push_back(getSubmoduleID(E.getPointer()));
2590 Record.push_back(E.getInt());
Douglas Gregor24bb9232011-12-02 18:58:38 +00002591 }
2592 Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2593 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002594
Daniel Jasperba7f2f72013-09-24 09:14:14 +00002595 //FIXME: How do we emit the 'use'd modules? They may not be submodules.
2596 // Might be unnecessary as use declarations are only used to build the
2597 // module itself.
2598
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002599 // Emit the link libraries.
Richard Smith080056b2015-08-18 21:53:42 +00002600 for (const auto &LL : Mod->LinkLibraries) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002601 RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
2602 LL.IsFramework};
Richard Smith080056b2015-08-18 21:53:42 +00002603 Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002604 }
2605
Douglas Gregorfb912652013-03-20 21:10:35 +00002606 // Emit the conflicts.
Richard Smith080056b2015-08-18 21:53:42 +00002607 for (const auto &C : Mod->Conflicts) {
Richard Smith080056b2015-08-18 21:53:42 +00002608 // FIXME: This may fail; we don't require that all conflicting modules
2609 // are local or imported.
Mehdi Amini57a41912015-09-10 01:46:39 +00002610 RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
2611 getSubmoduleID(C.Other)};
Richard Smith080056b2015-08-18 21:53:42 +00002612 Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message);
Douglas Gregorfb912652013-03-20 21:10:35 +00002613 }
2614
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002615 // Emit the configuration macros.
Richard Smith080056b2015-08-18 21:53:42 +00002616 for (const auto &CM : Mod->ConfigMacros) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002617 RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
Richard Smith080056b2015-08-18 21:53:42 +00002618 Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM);
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002619 }
2620
Douglas Gregor69021972011-11-30 17:33:56 +00002621 // Queue up the submodules of this module.
Richard Smith080056b2015-08-18 21:53:42 +00002622 for (auto *M : Mod->submodules())
2623 Q.push(M);
Douglas Gregor69021972011-11-30 17:33:56 +00002624 }
2625
2626 Stream.ExitBlock();
Richard Smith23d8d032015-05-14 00:45:20 +00002627
Richard Smith23d8d032015-05-14 00:45:20 +00002628 assert((NextSubmoduleID - FirstSubmoduleID ==
2629 getNumberOfModules(WritingModule)) &&
2630 "Wrong # of submodules; found a reference to a non-local, "
2631 "non-imported submodule?");
Douglas Gregor69021972011-11-30 17:33:56 +00002632}
2633
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002634serialization::SubmoduleID
2635ASTWriter::inferSubmoduleIDFromLocation(SourceLocation Loc) {
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002636 if (Loc.isInvalid() || !WritingModule)
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002637 return 0; // No submodule
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002638
2639 // Find the module that owns this location.
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002640 ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002641 Module *OwningMod
2642 = ModMap.inferModuleFromLocation(FullSourceLoc(Loc,PP->getSourceManager()));
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002643 if (!OwningMod)
2644 return 0;
2645
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002646 // Check whether this submodule is part of our own module.
2647 if (WritingModule != OwningMod && !OwningMod->isSubModuleOf(WritingModule))
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002648 return 0;
2649
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002650 return getSubmoduleID(OwningMod);
Douglas Gregora28bcdd2011-12-01 02:07:58 +00002651}
2652
Argyrios Kyrtzidis0f06b982013-03-27 17:17:23 +00002653void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
2654 bool isModule) {
2655 // Make sure set diagnostic pragmas don't affect the translation unit that
2656 // imports the module.
2657 // FIXME: Make diagnostic pragma sections work properly with modules.
2658 if (isModule)
2659 return;
2660
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002661 llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
2662 DiagStateIDMap;
2663 unsigned CurrID = 0;
2664 DiagStateIDMap[&Diag.DiagStates.front()] = ++CurrID; // the command-line one.
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002665 RecordData Record;
David Blaikie9c902b52011-09-25 23:23:43 +00002666 for (DiagnosticsEngine::DiagStatePointsTy::const_iterator
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002667 I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end();
2668 I != E; ++I) {
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002669 const DiagnosticsEngine::DiagStatePoint &point = *I;
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002670 if (point.Loc.isInvalid())
2671 continue;
2672
Richard Smithb22a1d12016-03-27 20:13:24 +00002673 AddSourceLocation(point.Loc, Record);
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002674 unsigned &DiagStateID = DiagStateIDMap[point.State];
2675 Record.push_back(DiagStateID);
2676
2677 if (DiagStateID == 0) {
2678 DiagStateID = ++CurrID;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002679 for (const auto &I : *(point.State)) {
2680 if (I.second.isPragma()) {
2681 Record.push_back(I.first);
2682 Record.push_back((unsigned)I.second.getSeverity());
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002683 }
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002684 }
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002685 Record.push_back(-1); // mark the end of the diag/map pairs for this
2686 // location.
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002687 }
2688 }
2689
Argyrios Kyrtzidisb0ca9eb2010-11-05 22:20:49 +00002690 if (!Record.empty())
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002691 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002692}
2693
Richard Smithc2bb8182015-03-24 06:36:48 +00002694void ASTWriter::WriteCXXCtorInitializersOffsets() {
2695 if (CXXCtorInitializersOffsets.empty())
2696 return;
2697
Richard Smithc2bb8182015-03-24 06:36:48 +00002698 // Create a blob abbreviation for the C++ ctor initializer offsets.
2699 using namespace llvm;
2700
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002701 auto *Abbrev = new BitCodeAbbrev();
Richard Smithc2bb8182015-03-24 06:36:48 +00002702 Abbrev->Add(BitCodeAbbrevOp(CXX_CTOR_INITIALIZERS_OFFSETS));
2703 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2704 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2705 unsigned CtorInitializersOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2706
2707 // Write the base specifier offsets table.
Mehdi Amini57a41912015-09-10 01:46:39 +00002708 RecordData::value_type Record[] = {CXX_CTOR_INITIALIZERS_OFFSETS,
2709 CXXCtorInitializersOffsets.size()};
Richard Smithc2bb8182015-03-24 06:36:48 +00002710 Stream.EmitRecordWithBlob(CtorInitializersOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00002711 bytes(CXXCtorInitializersOffsets));
Richard Smithc2bb8182015-03-24 06:36:48 +00002712}
2713
Anders Carlsson9bb83e82011-03-06 18:41:18 +00002714void ASTWriter::WriteCXXBaseSpecifiersOffsets() {
2715 if (CXXBaseSpecifiersOffsets.empty())
2716 return;
2717
Anders Carlsson9bb83e82011-03-06 18:41:18 +00002718 // Create a blob abbreviation for the C++ base specifiers offsets.
2719 using namespace llvm;
2720
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002721 auto *Abbrev = new BitCodeAbbrev();
Anders Carlsson9bb83e82011-03-06 18:41:18 +00002722 Abbrev->Add(BitCodeAbbrevOp(CXX_BASE_SPECIFIER_OFFSETS));
2723 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2724 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2725 unsigned BaseSpecifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2726
Douglas Gregorc27b2872011-08-04 00:01:48 +00002727 // Write the base specifier offsets table.
Mehdi Amini57a41912015-09-10 01:46:39 +00002728 RecordData::value_type Record[] = {CXX_BASE_SPECIFIER_OFFSETS,
2729 CXXBaseSpecifiersOffsets.size()};
Anders Carlsson9bb83e82011-03-06 18:41:18 +00002730 Stream.EmitRecordWithBlob(BaseSpecifierOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00002731 bytes(CXXBaseSpecifiersOffsets));
Anders Carlsson9bb83e82011-03-06 18:41:18 +00002732}
2733
Douglas Gregorc5046832009-04-27 18:38:38 +00002734//===----------------------------------------------------------------------===//
2735// Type Serialization
2736//===----------------------------------------------------------------------===//
Chris Lattnereeffaef2009-04-10 17:15:23 +00002737
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002738/// \brief Write the representation of a type to the AST stream.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002739void ASTWriter::WriteType(QualType T) {
Argyrios Kyrtzidisa7fbbb02010-08-20 16:04:04 +00002740 TypeIdx &Idx = TypeIdxs[T];
Argyrios Kyrtzidisbb5c7eae2010-08-20 16:03:59 +00002741 if (Idx.getIndex() == 0) // we haven't seen this type before.
2742 Idx = TypeIdx(NextTypeID++);
Mike Stump11289f42009-09-09 15:08:12 +00002743
Douglas Gregor9b3932c2010-10-05 18:37:06 +00002744 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
Douglas Gregordc72caa2010-10-04 18:21:45 +00002745
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002746 // Record the offset for this type.
Argyrios Kyrtzidisbb5c7eae2010-08-20 16:03:59 +00002747 unsigned Index = Idx.getIndex() - FirstTypeID;
Sebastian Redl66c5eef2010-07-27 00:17:23 +00002748 if (TypeOffsets.size() == Index)
Douglas Gregor8f45df52009-04-16 22:23:12 +00002749 TypeOffsets.push_back(Stream.GetCurrentBitNo());
Sebastian Redl66c5eef2010-07-27 00:17:23 +00002750 else if (TypeOffsets.size() < Index) {
2751 TypeOffsets.resize(Index + 1);
2752 TypeOffsets[Index] = Stream.GetCurrentBitNo();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002753 }
2754
2755 RecordData Record;
Mike Stump11289f42009-09-09 15:08:12 +00002756
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002757 // Emit the type's representation.
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002758 ASTTypeWriter W(*this, Record);
Richard Smith01b2cb42014-07-26 06:37:51 +00002759 W.AbbrevToUse = 0;
John McCall8ccfcb52009-09-24 19:53:00 +00002760
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002761 if (T.hasLocalNonFastQualifiers()) {
2762 Qualifiers Qs = T.getLocalQualifiers();
2763 AddTypeRef(T.getLocalUnqualifiedType(), Record);
John McCall8ccfcb52009-09-24 19:53:00 +00002764 Record.push_back(Qs.getAsOpaqueValue());
Sebastian Redl539c5062010-08-18 23:57:32 +00002765 W.Code = TYPE_EXT_QUAL;
Richard Smith01b2cb42014-07-26 06:37:51 +00002766 W.AbbrevToUse = TypeExtQualAbbrev;
John McCall8ccfcb52009-09-24 19:53:00 +00002767 } else {
2768 switch (T->getTypeClass()) {
2769 // For all of the concrete, non-dependent types, call the
2770 // appropriate visitor function.
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002771#define TYPE(Class, Base) \
Mike Stump281d6d72010-01-20 02:03:14 +00002772 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002773#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002774#include "clang/AST/TypeNodes.def"
John McCall8ccfcb52009-09-24 19:53:00 +00002775 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002776 }
2777
2778 // Emit the serialized record.
Richard Smith01b2cb42014-07-26 06:37:51 +00002779 Stream.EmitRecord(W.Code, Record, W.AbbrevToUse);
Douglas Gregorfeb84b02009-04-14 21:18:50 +00002780
2781 // Flush any expressions that were written as part of this type.
Douglas Gregor8f45df52009-04-16 22:23:12 +00002782 FlushStmts();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002783}
2784
Douglas Gregorc5046832009-04-27 18:38:38 +00002785//===----------------------------------------------------------------------===//
2786// Declaration Serialization
2787//===----------------------------------------------------------------------===//
2788
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002789/// \brief Write the block containing all of the declaration IDs
2790/// lexically declared within the given DeclContext.
2791///
2792/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
2793/// bistream, or 0 if no block was written.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002794uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002795 DeclContext *DC) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002796 if (DC->decls_empty())
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002797 return 0;
2798
Douglas Gregor8f45df52009-04-16 22:23:12 +00002799 uint64_t Offset = Stream.GetCurrentBitNo();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002800 SmallVector<uint32_t, 128> KindDeclPairs;
2801 for (const auto *D : DC->decls()) {
2802 KindDeclPairs.push_back(D->getKind());
2803 KindDeclPairs.push_back(GetDeclRef(D));
2804 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002805
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002806 ++NumLexicalDeclContexts;
Mehdi Amini57a41912015-09-10 01:46:39 +00002807 RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
Richard Smith82f8fcd2015-08-06 22:07:25 +00002808 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
2809 bytes(KindDeclPairs));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002810 return Offset;
2811}
2812
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002813void ASTWriter::WriteTypeDeclOffsets() {
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002814 using namespace llvm;
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002815
2816 // Write the type offsets array
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002817 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00002818 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002819 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
Douglas Gregor5204bde2011-08-02 16:26:37 +00002820 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002821 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
2822 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00002823 {
2824 RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(),
2825 FirstTypeID - NUM_PREDEF_TYPE_IDS};
2826 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
2827 }
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002828
2829 // Write the declaration offsets array
2830 Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00002831 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002832 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
Douglas Gregorf7180622011-08-03 15:48:04 +00002833 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002834 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
2835 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00002836 {
2837 RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(),
2838 FirstDeclID - NUM_PREDEF_DECL_IDS};
2839 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
2840 }
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002841}
2842
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002843void ASTWriter::WriteFileDeclIDsMap() {
2844 using namespace llvm;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002845
Chandler Carruthb306d732015-03-27 00:31:20 +00002846 SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs(
2847 FileDeclIDs.begin(), FileDeclIDs.end());
2848 std::sort(SortedFileDeclIDs.begin(), SortedFileDeclIDs.end(),
2849 llvm::less_first());
2850
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002851 // Join the vectors of DeclIDs from all files.
Chandler Carruthb306d732015-03-27 00:31:20 +00002852 SmallVector<DeclID, 256> FileGroupedDeclIDs;
2853 for (auto &FileDeclEntry : SortedFileDeclIDs) {
2854 DeclIDInFileInfo &Info = *FileDeclEntry.second;
2855 Info.FirstDeclIndex = FileGroupedDeclIDs.size();
2856 for (auto &LocDeclEntry : Info.DeclIDs)
2857 FileGroupedDeclIDs.push_back(LocDeclEntry.second);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002858 }
2859
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002860 auto *Abbrev = new BitCodeAbbrev();
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002861 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002862 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002863 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2864 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00002865 RecordData::value_type Record[] = {FILE_SORTED_DECLS,
2866 FileGroupedDeclIDs.size()};
Reid Kleckner012665e2015-05-21 00:13:09 +00002867 Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002868}
2869
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002870void ASTWriter::WriteComments() {
2871 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +00002872 ArrayRef<RawComment *> RawComments = Context->Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002873 RecordData Record;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002874 for (const auto *I : RawComments) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002875 Record.clear();
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002876 AddSourceRange(I->getSourceRange(), Record);
2877 Record.push_back(I->getKind());
2878 Record.push_back(I->isTrailingComment());
2879 Record.push_back(I->isAlmostTrailingComment());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002880 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
2881 }
2882 Stream.ExitBlock();
2883}
2884
Douglas Gregorc5046832009-04-27 18:38:38 +00002885//===----------------------------------------------------------------------===//
2886// Global Method Pool and Selector Serialization
2887//===----------------------------------------------------------------------===//
2888
Douglas Gregore84a9da2009-04-20 20:36:09 +00002889namespace {
Douglas Gregorc78d3462009-04-24 21:10:55 +00002890// Trait used for the on-disk hash table used in the method pool.
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002891class ASTMethodPoolTrait {
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002892 ASTWriter &Writer;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002893
2894public:
2895 typedef Selector key_type;
2896 typedef key_type key_type_ref;
Mike Stump11289f42009-09-09 15:08:12 +00002897
Sebastian Redl834bb972010-08-04 17:20:04 +00002898 struct data_type {
Sebastian Redl539c5062010-08-18 23:57:32 +00002899 SelectorID ID;
Sebastian Redl834bb972010-08-04 17:20:04 +00002900 ObjCMethodList Instance, Factory;
2901 };
Douglas Gregorc78d3462009-04-24 21:10:55 +00002902 typedef const data_type& data_type_ref;
2903
Justin Bogner25463f12014-04-18 20:27:24 +00002904 typedef unsigned hash_value_type;
2905 typedef unsigned offset_type;
2906
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002907 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { }
Mike Stump11289f42009-09-09 15:08:12 +00002908
Justin Bogner25463f12014-04-18 20:27:24 +00002909 static hash_value_type ComputeHash(Selector Sel) {
Argyrios Kyrtzidis4bd97102010-08-20 16:03:52 +00002910 return serialization::ComputeHash(Sel);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002911 }
Mike Stump11289f42009-09-09 15:08:12 +00002912
2913 std::pair<unsigned,unsigned>
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002914 EmitKeyDataLength(raw_ostream& Out, Selector Sel,
Douglas Gregorc78d3462009-04-24 21:10:55 +00002915 data_type_ref Methods) {
Justin Bognere1c147c2014-03-28 22:03:19 +00002916 using namespace llvm::support;
2917 endian::Writer<little> LE(Out);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002918 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
Justin Bognere1c147c2014-03-28 22:03:19 +00002919 LE.write<uint16_t>(KeyLen);
Sebastian Redl834bb972010-08-04 17:20:04 +00002920 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
2921 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002922 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002923 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002924 DataLen += 4;
Sebastian Redl834bb972010-08-04 17:20:04 +00002925 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002926 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002927 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002928 DataLen += 4;
Justin Bognere1c147c2014-03-28 22:03:19 +00002929 LE.write<uint16_t>(DataLen);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002930 return std::make_pair(KeyLen, DataLen);
2931 }
Mike Stump11289f42009-09-09 15:08:12 +00002932
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002933 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00002934 using namespace llvm::support;
2935 endian::Writer<little> LE(Out);
Mike Stump11289f42009-09-09 15:08:12 +00002936 uint64_t Start = Out.tell();
Douglas Gregor95c13f52009-04-25 17:48:32 +00002937 assert((Start >> 32) == 0 && "Selector key offset too large");
2938 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002939 unsigned N = Sel.getNumArgs();
Justin Bognere1c147c2014-03-28 22:03:19 +00002940 LE.write<uint16_t>(N);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002941 if (N == 0)
2942 N = 1;
2943 for (unsigned I = 0; I != N; ++I)
Justin Bognere1c147c2014-03-28 22:03:19 +00002944 LE.write<uint32_t>(
2945 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
Douglas Gregorc78d3462009-04-24 21:10:55 +00002946 }
Mike Stump11289f42009-09-09 15:08:12 +00002947
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002948 void EmitData(raw_ostream& Out, key_type_ref,
Douglas Gregor4647cfa2009-04-24 21:49:02 +00002949 data_type_ref Methods, unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00002950 using namespace llvm::support;
2951 endian::Writer<little> LE(Out);
Douglas Gregor4647cfa2009-04-24 21:49:02 +00002952 uint64_t Start = Out.tell(); (void)Start;
Justin Bognere1c147c2014-03-28 22:03:19 +00002953 LE.write<uint32_t>(Methods.ID);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002954 unsigned NumInstanceMethods = 0;
Sebastian Redl834bb972010-08-04 17:20:04 +00002955 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002956 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002957 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002958 ++NumInstanceMethods;
2959
2960 unsigned NumFactoryMethods = 0;
Sebastian Redl834bb972010-08-04 17:20:04 +00002961 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002962 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002963 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002964 ++NumFactoryMethods;
2965
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002966 unsigned InstanceBits = Methods.Instance.getBits();
2967 assert(InstanceBits < 4);
Nico Weberff4b35e2014-12-27 22:14:15 +00002968 unsigned InstanceHasMoreThanOneDeclBit =
2969 Methods.Instance.hasMoreThanOneDecl();
2970 unsigned FullInstanceBits = (NumInstanceMethods << 3) |
2971 (InstanceHasMoreThanOneDeclBit << 2) |
2972 InstanceBits;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002973 unsigned FactoryBits = Methods.Factory.getBits();
2974 assert(FactoryBits < 4);
Nico Weberff4b35e2014-12-27 22:14:15 +00002975 unsigned FactoryHasMoreThanOneDeclBit =
2976 Methods.Factory.hasMoreThanOneDecl();
2977 unsigned FullFactoryBits = (NumFactoryMethods << 3) |
2978 (FactoryHasMoreThanOneDeclBit << 2) |
2979 FactoryBits;
2980 LE.write<uint16_t>(FullInstanceBits);
2981 LE.write<uint16_t>(FullFactoryBits);
Sebastian Redl834bb972010-08-04 17:20:04 +00002982 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002983 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002984 if (Method->getMethod())
2985 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
Sebastian Redl834bb972010-08-04 17:20:04 +00002986 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002987 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002988 if (Method->getMethod())
2989 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
Douglas Gregor4647cfa2009-04-24 21:49:02 +00002990
2991 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorc78d3462009-04-24 21:10:55 +00002992 }
2993};
2994} // end anonymous namespace
2995
Sebastian Redla19a67f2010-08-03 21:58:15 +00002996/// \brief Write ObjC data: selectors and the method pool.
Douglas Gregorc78d3462009-04-24 21:10:55 +00002997///
2998/// The method pool contains both instance and factory methods, stored
Sebastian Redla19a67f2010-08-03 21:58:15 +00002999/// in an on-disk hash table indexed by the selector. The hash table also
3000/// contains an empty entry for every other selector known to Sema.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003001void ASTWriter::WriteSelectors(Sema &SemaRef) {
Douglas Gregorc78d3462009-04-24 21:10:55 +00003002 using namespace llvm;
3003
Sebastian Redla19a67f2010-08-03 21:58:15 +00003004 // Do we have to do anything at all?
Sebastian Redl834bb972010-08-04 17:20:04 +00003005 if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
Sebastian Redla19a67f2010-08-03 21:58:15 +00003006 return;
Sebastian Redld95a56e2010-08-04 18:21:41 +00003007 unsigned NumTableEntries = 0;
Sebastian Redla19a67f2010-08-03 21:58:15 +00003008 // Create and write out the blob that contains selectors and the method pool.
Douglas Gregorc78d3462009-04-24 21:10:55 +00003009 {
Justin Bognerbb094f02014-04-18 19:57:06 +00003010 llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003011 ASTMethodPoolTrait Trait(*this);
Mike Stump11289f42009-09-09 15:08:12 +00003012
Sebastian Redla19a67f2010-08-03 21:58:15 +00003013 // Create the on-disk hash table representation. We walk through every
3014 // selector we've seen and look it up in the method pool.
Sebastian Redld95a56e2010-08-04 18:21:41 +00003015 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003016 for (auto &SelectorAndID : SelectorIDs) {
3017 Selector S = SelectorAndID.first;
3018 SelectorID ID = SelectorAndID.second;
Sebastian Redla19a67f2010-08-03 21:58:15 +00003019 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003020 ASTMethodPoolTrait::data_type Data = {
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003021 ID,
Sebastian Redl834bb972010-08-04 17:20:04 +00003022 ObjCMethodList(),
3023 ObjCMethodList()
3024 };
3025 if (F != SemaRef.MethodPool.end()) {
3026 Data.Instance = F->second.first;
3027 Data.Factory = F->second.second;
3028 }
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003029 // Only write this selector if it's not in an existing AST or something
Sebastian Redld95a56e2010-08-04 18:21:41 +00003030 // changed.
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003031 if (Chain && ID < FirstSelectorID) {
Sebastian Redld95a56e2010-08-04 18:21:41 +00003032 // Selector already exists. Did it change?
3033 bool changed = false;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003034 for (ObjCMethodList *M = &Data.Instance;
3035 !changed && M && M->getMethod(); M = M->getNext()) {
3036 if (!M->getMethod()->isFromASTFile())
Sebastian Redld95a56e2010-08-04 18:21:41 +00003037 changed = true;
3038 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003039 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003040 M = M->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003041 if (!M->getMethod()->isFromASTFile())
Sebastian Redld95a56e2010-08-04 18:21:41 +00003042 changed = true;
3043 }
3044 if (!changed)
3045 continue;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003046 } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
Sebastian Redl6e1a2a02010-08-04 21:22:45 +00003047 // A new method pool entry.
3048 ++NumTableEntries;
Sebastian Redld95a56e2010-08-04 18:21:41 +00003049 }
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003050 Generator.insert(S, Data, Trait);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003051 }
3052
Douglas Gregorc78d3462009-04-24 21:10:55 +00003053 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003054 SmallString<4096> MethodPool;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003055 uint32_t BucketOffset;
3056 {
Justin Bognere1c147c2014-03-28 22:03:19 +00003057 using namespace llvm::support;
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003058 ASTMethodPoolTrait Trait(*this);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003059 llvm::raw_svector_ostream Out(MethodPool);
3060 // Make sure that no bucket is at offset 0
Justin Bognere1c147c2014-03-28 22:03:19 +00003061 endian::Writer<little>(Out).write<uint32_t>(0);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003062 BucketOffset = Generator.Emit(Out, Trait);
3063 }
3064
3065 // Create a blob abbreviation
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003066 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00003067 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003068 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor95c13f52009-04-25 17:48:32 +00003069 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003070 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3071 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
3072
Douglas Gregor95c13f52009-04-25 17:48:32 +00003073 // Write the method pool
Mehdi Amini57a41912015-09-10 01:46:39 +00003074 {
3075 RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3076 NumTableEntries};
3077 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3078 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00003079
3080 // Create a blob abbreviation for the selector table offsets.
3081 Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00003082 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
Douglas Gregord4c5ed02010-10-29 22:39:52 +00003083 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
Douglas Gregor8f364fb2011-08-03 23:28:44 +00003084 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
Douglas Gregor95c13f52009-04-25 17:48:32 +00003085 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3086 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
3087
3088 // Write the selector offsets table.
Mehdi Amini57a41912015-09-10 01:46:39 +00003089 {
3090 RecordData::value_type Record[] = {
3091 SELECTOR_OFFSETS, SelectorOffsets.size(),
3092 FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3093 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3094 bytes(SelectorOffsets));
3095 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00003096 }
3097}
3098
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003099/// \brief Write the selectors referenced in @selector expression into AST file.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003100void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003101 using namespace llvm;
3102 if (SemaRef.ReferencedSelectors.empty())
3103 return;
Sebastian Redlada023c2010-08-04 20:40:17 +00003104
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003105 RecordData Record;
Sebastian Redlada023c2010-08-04 20:40:17 +00003106
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003107 // Note: this writes out all references even for a dependent AST. But it is
Sebastian Redl51c79d82010-08-04 22:21:29 +00003108 // very tricky to fix, and given that @selector shouldn't really appear in
3109 // headers, probably not worth it. It's not a correctness issue.
Chandler Carruth12c8f652015-03-27 00:55:05 +00003110 for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
3111 Selector Sel = SelectorAndLocation.first;
3112 SourceLocation Loc = SelectorAndLocation.second;
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003113 AddSelectorRef(Sel, Record);
3114 AddSourceLocation(Loc, Record);
3115 }
Sebastian Redl539c5062010-08-18 23:57:32 +00003116 Stream.EmitRecord(REFERENCED_SELECTOR_POOL, Record);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003117}
3118
Douglas Gregorc5046832009-04-27 18:38:38 +00003119//===----------------------------------------------------------------------===//
3120// Identifier Table Serialization
3121//===----------------------------------------------------------------------===//
3122
Richard Smithb3761912015-02-05 23:08:52 +00003123/// Determine the declaration that should be put into the name lookup table to
3124/// represent the given declaration in this module. This is usually D itself,
3125/// but if D was imported and merged into a local declaration, we want the most
3126/// recent local declaration instead. The chosen declaration will be the most
3127/// recent declaration in any module that imports this one.
3128static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
3129 NamedDecl *D) {
3130 if (!LangOpts.Modules || !D->isFromASTFile())
3131 return D;
3132
3133 if (Decl *Redecl = D->getPreviousDecl()) {
3134 // For Redeclarable decls, a prior declaration might be local.
3135 for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
3136 if (!Redecl->isFromASTFile())
3137 return cast<NamedDecl>(Redecl);
Richard Smithfe620d22015-03-05 23:24:12 +00003138 // If we find a decl from a (chained-)PCH stop since we won't find a
Richard Smithb3761912015-02-05 23:08:52 +00003139 // local one.
3140 if (D->getOwningModuleID() == 0)
3141 break;
3142 }
3143 } else if (Decl *First = D->getCanonicalDecl()) {
3144 // For Mergeable decls, the first decl might be local.
3145 if (!First->isFromASTFile())
3146 return cast<NamedDecl>(First);
3147 }
3148
3149 // All declarations are imported. Our most recent declaration will also be
3150 // the most recent one in anyone who imports us.
3151 return D;
3152}
3153
Douglas Gregorc78d3462009-04-24 21:10:55 +00003154namespace {
Richard Smithcf97cf62015-04-19 01:34:23 +00003155class ASTIdentifierTableTrait {
3156 ASTWriter &Writer;
3157 Preprocessor &PP;
3158 IdentifierResolver &IdResolver;
Richard Smith9c254182015-07-19 21:41:12 +00003159 bool IsModule;
Richard Smitha534a312015-07-21 23:54:07 +00003160 bool NeedDecls;
Richard Smith33e0f7e2015-07-22 02:08:40 +00003161 ASTWriter::RecordData *InterestingIdentifierOffsets;
Richard Smithcf97cf62015-04-19 01:34:23 +00003162
3163 /// \brief Determines whether this is an "interesting" identifier that needs a
3164 /// full IdentifierInfo structure written into the hash table. Notably, this
3165 /// doesn't check whether the name has macros defined; use PublicMacroIterator
3166 /// to check that.
Richard Smith9c254182015-07-19 21:41:12 +00003167 bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
Richard Smithd7329392015-04-21 21:46:32 +00003168 if (MacroOffset ||
3169 II->isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +00003170 (IsModule ? II->hasRevertedBuiltin() : II->getObjCOrBuiltinID()) ||
Richard Smithcf97cf62015-04-19 01:34:23 +00003171 II->hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +00003172 (NeedDecls && II->getFETokenInfo<void>()))
Richard Smithcf97cf62015-04-19 01:34:23 +00003173 return true;
3174
3175 return false;
3176 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003177
Douglas Gregore84a9da2009-04-20 20:36:09 +00003178public:
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00003179 typedef IdentifierInfo* key_type;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003180 typedef key_type key_type_ref;
Mike Stump11289f42009-09-09 15:08:12 +00003181
Sebastian Redl539c5062010-08-18 23:57:32 +00003182 typedef IdentID data_type;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003183 typedef data_type data_type_ref;
Mike Stump11289f42009-09-09 15:08:12 +00003184
Justin Bogner25463f12014-04-18 20:27:24 +00003185 typedef unsigned hash_value_type;
3186 typedef unsigned offset_type;
3187
Richard Smithd7329392015-04-21 21:46:32 +00003188 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
Richard Smith33e0f7e2015-07-22 02:08:40 +00003189 IdentifierResolver &IdResolver, bool IsModule,
3190 ASTWriter::RecordData *InterestingIdentifierOffsets)
Richard Smitha534a312015-07-21 23:54:07 +00003191 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
Richard Smith33e0f7e2015-07-22 02:08:40 +00003192 NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3193 InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
Douglas Gregore84a9da2009-04-20 20:36:09 +00003194
Richard Smithd79514e2016-02-05 19:03:40 +00003195 bool needDecls() const { return NeedDecls; }
3196
Justin Bogner25463f12014-04-18 20:27:24 +00003197 static hash_value_type ComputeHash(const IdentifierInfo* II) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +00003198 return llvm::HashString(II->getName());
Douglas Gregore84a9da2009-04-20 20:36:09 +00003199 }
Mike Stump11289f42009-09-09 15:08:12 +00003200
Richard Smith33e0f7e2015-07-22 02:08:40 +00003201 bool isInterestingIdentifier(const IdentifierInfo *II) {
3202 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3203 return isInterestingIdentifier(II, MacroOffset);
3204 }
Richard Smith9c254182015-07-19 21:41:12 +00003205 bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) {
3206 return isInterestingIdentifier(II, 0);
3207 }
3208
Mike Stump11289f42009-09-09 15:08:12 +00003209 std::pair<unsigned,unsigned>
Douglas Gregor935bc7a22011-10-27 09:33:13 +00003210 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003211 unsigned KeyLen = II->getLength() + 1;
Douglas Gregor1d583f22009-04-28 21:18:29 +00003212 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
Richard Smithd7329392015-04-21 21:46:32 +00003213 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3214 if (isInterestingIdentifier(II, MacroOffset)) {
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003215 DataLen += 2; // 2 bytes for builtin ID
3216 DataLen += 2; // 2 bytes for flags
Richard Smithd7329392015-04-21 21:46:32 +00003217 if (MacroOffset)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003218 DataLen += 4; // MacroDirectives offset.
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003219
Richard Smitha534a312015-07-21 23:54:07 +00003220 if (NeedDecls) {
3221 for (IdentifierResolver::iterator D = IdResolver.begin(II),
3222 DEnd = IdResolver.end();
3223 D != DEnd; ++D)
3224 DataLen += 4;
3225 }
Douglas Gregor1d583f22009-04-28 21:18:29 +00003226 }
Justin Bognere1c147c2014-03-28 22:03:19 +00003227 using namespace llvm::support;
3228 endian::Writer<little> LE(Out);
3229
Richard Smithdf8a8312015-03-13 04:05:01 +00003230 assert((uint16_t)DataLen == DataLen && (uint16_t)KeyLen == KeyLen);
Justin Bognere1c147c2014-03-28 22:03:19 +00003231 LE.write<uint16_t>(DataLen);
Douglas Gregorab4df582009-04-28 20:01:51 +00003232 // We emit the key length after the data length so that every
3233 // string is preceded by a 16-bit length. This matches the PTH
3234 // format for storing identifiers.
Justin Bognere1c147c2014-03-28 22:03:19 +00003235 LE.write<uint16_t>(KeyLen);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003236 return std::make_pair(KeyLen, DataLen);
3237 }
Mike Stump11289f42009-09-09 15:08:12 +00003238
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003239 void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
Douglas Gregore84a9da2009-04-20 20:36:09 +00003240 unsigned KeyLen) {
3241 // Record the location of the key data. This is used when generating
3242 // the mapping from persistent IDs to strings.
3243 Writer.SetIdentifierOffset(II, Out.tell());
Richard Smith33e0f7e2015-07-22 02:08:40 +00003244
3245 // Emit the offset of the key/data length information to the interesting
3246 // identifiers table if necessary.
3247 if (InterestingIdentifierOffsets && isInterestingIdentifier(II))
3248 InterestingIdentifierOffsets->push_back(Out.tell() - 4);
3249
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003250 Out.write(II->getNameStart(), KeyLen);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003251 }
Mike Stump11289f42009-09-09 15:08:12 +00003252
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00003253 void EmitData(raw_ostream& Out, IdentifierInfo* II,
Sebastian Redl539c5062010-08-18 23:57:32 +00003254 IdentID ID, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003255 using namespace llvm::support;
3256 endian::Writer<little> LE(Out);
Richard Smithcf97cf62015-04-19 01:34:23 +00003257
Richard Smithd7329392015-04-21 21:46:32 +00003258 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3259 if (!isInterestingIdentifier(II, MacroOffset)) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003260 LE.write<uint32_t>(ID << 1);
Douglas Gregor1d583f22009-04-28 21:18:29 +00003261 return;
3262 }
Douglas Gregorb9256522009-04-28 21:32:13 +00003263
Justin Bognere1c147c2014-03-28 22:03:19 +00003264 LE.write<uint32_t>((ID << 1) | 0x01);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003265 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3266 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
Justin Bognere1c147c2014-03-28 22:03:19 +00003267 LE.write<uint16_t>(Bits);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003268 Bits = 0;
Richard Smithd7329392015-04-21 21:46:32 +00003269 bool HadMacroDefinition = MacroOffset != 0;
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003270 Bits = (Bits << 1) | unsigned(HadMacroDefinition);
Daniel Dunbar91b640a2009-12-18 20:58:47 +00003271 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3272 Bits = (Bits << 1) | unsigned(II->isPoisoned());
Richard Smith9c254182015-07-19 21:41:12 +00003273 Bits = (Bits << 1) | unsigned(II->hasRevertedBuiltin());
Argyrios Kyrtzidis3084a612010-08-11 22:55:12 +00003274 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
Daniel Dunbar91b640a2009-12-18 20:58:47 +00003275 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
Justin Bognere1c147c2014-03-28 22:03:19 +00003276 LE.write<uint16_t>(Bits);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003277
Richard Smithd7329392015-04-21 21:46:32 +00003278 if (HadMacroDefinition)
3279 LE.write<uint32_t>(MacroOffset);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003280
Richard Smitha534a312015-07-21 23:54:07 +00003281 if (NeedDecls) {
3282 // Emit the declaration IDs in reverse order, because the
3283 // IdentifierResolver provides the declarations as they would be
3284 // visible (e.g., the function "stat" would come before the struct
3285 // "stat"), but the ASTReader adds declarations to the end of the list
3286 // (so we need to see the struct "stat" before the function "stat").
3287 // Only emit declarations that aren't from a chained PCH, though.
3288 SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II),
3289 IdResolver.end());
3290 for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(),
3291 DEnd = Decls.rend();
3292 D != DEnd; ++D)
3293 LE.write<uint32_t>(
3294 Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D)));
3295 }
Douglas Gregore84a9da2009-04-20 20:36:09 +00003296 }
3297};
3298} // end anonymous namespace
3299
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003300/// \brief Write the identifier table into the AST file.
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003301///
3302/// The identifier table consists of a blob containing string data
3303/// (the actual identifiers themselves) and a separate "offsets" index
3304/// that maps identifier IDs to locations within the blob.
Douglas Gregor935bc7a22011-10-27 09:33:13 +00003305void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3306 IdentifierResolver &IdResolver,
3307 bool IsModule) {
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003308 using namespace llvm;
3309
Richard Smith33e0f7e2015-07-22 02:08:40 +00003310 RecordData InterestingIdents;
3311
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003312 // Create and write out the blob that contains the identifier
3313 // strings.
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003314 {
Justin Bognerbb094f02014-04-18 19:57:06 +00003315 llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
Richard Smith33e0f7e2015-07-22 02:08:40 +00003316 ASTIdentifierTableTrait Trait(
3317 *this, PP, IdResolver, IsModule,
3318 (getLangOpts().CPlusPlus && IsModule) ? &InterestingIdents : nullptr);
Mike Stump11289f42009-09-09 15:08:12 +00003319
Douglas Gregore6648fb2009-04-28 20:33:11 +00003320 // Look for any identifiers that were named while processing the
3321 // headers, but are otherwise not needed. We add these to the hash
3322 // table to enable checking of the predefines buffer in the case
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003323 // where the user adds new macro definitions when building the AST
Douglas Gregore6648fb2009-04-28 20:33:11 +00003324 // file.
Chandler Carruth8440c982015-03-26 23:54:15 +00003325 SmallVector<const IdentifierInfo *, 128> IIs;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003326 for (const auto &ID : PP.getIdentifierTable())
3327 IIs.push_back(ID.second);
Chandler Carruth8440c982015-03-26 23:54:15 +00003328 // Sort the identifiers lexicographically before getting them references so
3329 // that their order is stable.
3330 std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
3331 for (const IdentifierInfo *II : IIs)
Richard Smith9c254182015-07-19 21:41:12 +00003332 if (Trait.isInterestingNonMacroIdentifier(II))
3333 getIdentifierRef(II);
Douglas Gregore6648fb2009-04-28 20:33:11 +00003334
Sebastian Redlff4a2952010-07-23 23:49:55 +00003335 // Create the on-disk hash table representation. We only store offsets
3336 // for identifiers that appear here for the first time.
3337 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
Chandler Carruth885e78c2015-03-24 21:18:10 +00003338 for (auto IdentIDPair : IdentifierIDs) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003339 auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
Chandler Carruth885e78c2015-03-24 21:18:10 +00003340 IdentID ID = IdentIDPair.second;
3341 assert(II && "NULL identifier in identifier table");
Vassil Vassilev262f41e2016-03-30 20:16:03 +00003342 // Write out identifiers if either the ID is local or the identifier has
3343 // changed since it was loaded.
3344 if (ID >= FirstIdentID || !Chain || !II->isFromAST()
3345 || II->hasChangedSinceDeserialization() ||
Richard Smithd79514e2016-02-05 19:03:40 +00003346 (Trait.needDecls() &&
3347 II->hasFETokenInfoChangedSinceDeserialization()))
Chandler Carruth885e78c2015-03-24 21:18:10 +00003348 Generator.insert(II, ID, Trait);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003349 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003350
Douglas Gregore84a9da2009-04-20 20:36:09 +00003351 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003352 SmallString<4096> IdentifierTable;
Douglas Gregora868bbd2009-04-21 22:25:48 +00003353 uint32_t BucketOffset;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003354 {
Justin Bognere1c147c2014-03-28 22:03:19 +00003355 using namespace llvm::support;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003356 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003357 // Make sure that no bucket is at offset 0
Justin Bognere1c147c2014-03-28 22:03:19 +00003358 endian::Writer<little>(Out).write<uint32_t>(0);
Douglas Gregora868bbd2009-04-21 22:25:48 +00003359 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003360 }
3361
3362 // Create a blob abbreviation
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003363 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00003364 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
Douglas Gregora868bbd2009-04-21 22:25:48 +00003365 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregore84a9da2009-04-20 20:36:09 +00003366 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
Douglas Gregor8f45df52009-04-16 22:23:12 +00003367 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003368
3369 // Write the identifier table
Mehdi Amini57a41912015-09-10 01:46:39 +00003370 RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
Yaron Keren92e1b622015-03-18 10:17:07 +00003371 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003372 }
3373
3374 // Write the offsets table for identifier IDs.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003375 auto *Abbrev = new BitCodeAbbrev();
Sebastian Redl539c5062010-08-18 23:57:32 +00003376 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
Douglas Gregor0e149972009-04-25 19:10:14 +00003377 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
Douglas Gregor1ab036c2011-08-03 21:49:18 +00003378 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
Douglas Gregor0e149972009-04-25 19:10:14 +00003379 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3380 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
3381
Douglas Gregor8d7edce2013-02-08 21:30:59 +00003382#ifndef NDEBUG
3383 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3384 assert(IdentifierOffsets[I] && "Missing identifier offset?");
3385#endif
Mehdi Amini57a41912015-09-10 01:46:39 +00003386
3387 RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
3388 IdentifierOffsets.size(),
3389 FirstIdentID - NUM_PREDEF_IDENT_IDS};
Douglas Gregor0e149972009-04-25 19:10:14 +00003390 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00003391 bytes(IdentifierOffsets));
Richard Smith33e0f7e2015-07-22 02:08:40 +00003392
3393 // In C++, write the list of interesting identifiers (those that are
3394 // defined as macros, poisoned, or similar unusual things).
3395 if (!InterestingIdents.empty())
3396 Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003397}
3398
Douglas Gregorc5046832009-04-27 18:38:38 +00003399//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003400// DeclContext's Name Lookup Table Serialization
3401//===----------------------------------------------------------------------===//
3402
3403namespace {
3404// Trait used for the on-disk hash table used in the method pool.
3405class ASTDeclContextNameLookupTrait {
3406 ASTWriter &Writer;
Richard Smithd88a7f12015-09-01 20:35:42 +00003407 llvm::SmallVector<DeclID, 64> DeclIDs;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003408
3409public:
Richard Smitha06c7e62015-08-26 23:55:49 +00003410 typedef DeclarationNameKey key_type;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003411 typedef key_type key_type_ref;
3412
Richard Smithd88a7f12015-09-01 20:35:42 +00003413 /// A start and end index into DeclIDs, representing a sequence of decls.
3414 typedef std::pair<unsigned, unsigned> data_type;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003415 typedef const data_type& data_type_ref;
3416
Justin Bogner25463f12014-04-18 20:27:24 +00003417 typedef unsigned hash_value_type;
3418 typedef unsigned offset_type;
3419
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003420 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { }
3421
Richard Smithd88a7f12015-09-01 20:35:42 +00003422 template<typename Coll>
3423 data_type getData(const Coll &Decls) {
3424 unsigned Start = DeclIDs.size();
3425 for (NamedDecl *D : Decls) {
3426 DeclIDs.push_back(
3427 Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3428 }
3429 return std::make_pair(Start, DeclIDs.size());
3430 }
3431
3432 data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
3433 unsigned Start = DeclIDs.size();
3434 for (auto ID : FromReader)
3435 DeclIDs.push_back(ID);
3436 return std::make_pair(Start, DeclIDs.size());
3437 }
3438
3439 static bool EqualKey(key_type_ref a, key_type_ref b) {
3440 return a == b;
3441 }
3442
Richard Smitha06c7e62015-08-26 23:55:49 +00003443 hash_value_type ComputeHash(DeclarationNameKey Name) {
3444 return Name.getHash();
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003445 }
3446
Richard Smithd88a7f12015-09-01 20:35:42 +00003447 void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
3448 assert(Writer.hasChain() &&
3449 "have reference to loaded module file but no chain?");
3450
3451 using namespace llvm::support;
3452 endian::Writer<little>(Out)
3453 .write<uint32_t>(Writer.getChain()->getModuleFileID(F));
3454 }
3455
Richard Smitha06c7e62015-08-26 23:55:49 +00003456 std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
3457 DeclarationNameKey Name,
3458 data_type_ref Lookup) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003459 using namespace llvm::support;
3460 endian::Writer<little> LE(Out);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003461 unsigned KeyLen = 1;
Richard Smitha06c7e62015-08-26 23:55:49 +00003462 switch (Name.getKind()) {
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003463 case DeclarationName::Identifier:
3464 case DeclarationName::ObjCZeroArgSelector:
3465 case DeclarationName::ObjCOneArgSelector:
3466 case DeclarationName::ObjCMultiArgSelector:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003467 case DeclarationName::CXXLiteralOperatorName:
3468 KeyLen += 4;
3469 break;
3470 case DeclarationName::CXXOperatorName:
3471 KeyLen += 1;
3472 break;
Douglas Gregor3b65ed02011-08-02 18:32:54 +00003473 case DeclarationName::CXXConstructorName:
3474 case DeclarationName::CXXDestructorName:
3475 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003476 case DeclarationName::CXXUsingDirective:
3477 break;
3478 }
Justin Bognere1c147c2014-03-28 22:03:19 +00003479 LE.write<uint16_t>(KeyLen);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003480
Richard Smithf02662d2015-07-30 03:17:16 +00003481 // 4 bytes for each DeclID.
Richard Smithd88a7f12015-09-01 20:35:42 +00003482 unsigned DataLen = 4 * (Lookup.second - Lookup.first);
3483 assert(uint16_t(DataLen) == DataLen &&
3484 "too many decls for serialized lookup result");
Justin Bognere1c147c2014-03-28 22:03:19 +00003485 LE.write<uint16_t>(DataLen);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003486
3487 return std::make_pair(KeyLen, DataLen);
3488 }
3489
Richard Smitha06c7e62015-08-26 23:55:49 +00003490 void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003491 using namespace llvm::support;
3492 endian::Writer<little> LE(Out);
Richard Smitha06c7e62015-08-26 23:55:49 +00003493 LE.write<uint8_t>(Name.getKind());
3494 switch (Name.getKind()) {
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003495 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +00003496 case DeclarationName::CXXLiteralOperatorName:
3497 LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier()));
Benjamin Kramer53750b12012-09-19 13:40:40 +00003498 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003499 case DeclarationName::ObjCZeroArgSelector:
3500 case DeclarationName::ObjCOneArgSelector:
3501 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00003502 LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
Benjamin Kramer53750b12012-09-19 13:40:40 +00003503 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003504 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00003505 assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
Benjamin Kramer53750b12012-09-19 13:40:40 +00003506 "Invalid operator?");
Richard Smitha06c7e62015-08-26 23:55:49 +00003507 LE.write<uint8_t>(Name.getOperatorKind());
Benjamin Kramer53750b12012-09-19 13:40:40 +00003508 return;
Douglas Gregor3b65ed02011-08-02 18:32:54 +00003509 case DeclarationName::CXXConstructorName:
3510 case DeclarationName::CXXDestructorName:
3511 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003512 case DeclarationName::CXXUsingDirective:
Benjamin Kramer53750b12012-09-19 13:40:40 +00003513 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003514 }
Benjamin Kramer53750b12012-09-19 13:40:40 +00003515
3516 llvm_unreachable("Invalid name kind?");
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003517 }
3518
Richard Smitha06c7e62015-08-26 23:55:49 +00003519 void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
3520 unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003521 using namespace llvm::support;
3522 endian::Writer<little> LE(Out);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003523 uint64_t Start = Out.tell(); (void)Start;
Richard Smithd88a7f12015-09-01 20:35:42 +00003524 for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
3525 LE.write<uint32_t>(DeclIDs[I]);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003526 assert(Out.tell() - Start == DataLen && "Data length is wrong");
3527 }
3528};
3529} // end anonymous namespace
3530
Chandler Carruthe972c362015-03-26 03:11:40 +00003531bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
3532 DeclContext *DC) {
3533 return Result.hasExternalDecls() && DC->NeedToReconcileExternalVisibleStorage;
3534}
3535
3536bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
3537 DeclContext *DC) {
3538 for (auto *D : Result.getLookupResult())
3539 if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
3540 return false;
3541
3542 return true;
3543}
3544
Richard Smithd88a7f12015-09-01 20:35:42 +00003545void
Chandler Carruthe972c362015-03-26 03:11:40 +00003546ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
Richard Smithcd45dbc2014-04-19 03:48:30 +00003547 llvm::SmallVectorImpl<char> &LookupTable) {
Chandler Carruthe972c362015-03-26 03:11:40 +00003548 assert(!ConstDC->HasLazyLocalLexicalLookups &&
3549 !ConstDC->HasLazyExternalLexicalLookups &&
Richard Smith9e2341d2015-03-23 03:25:59 +00003550 "must call buildLookups first");
Richard Smithcd45dbc2014-04-19 03:48:30 +00003551
Chandler Carruthe972c362015-03-26 03:11:40 +00003552 // FIXME: We need to build the lookups table, which is logically const.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003553 auto *DC = const_cast<DeclContext*>(ConstDC);
Chandler Carruthe972c362015-03-26 03:11:40 +00003554 assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
3555
3556 // Create the on-disk hash table representation.
Richard Smithd88a7f12015-09-01 20:35:42 +00003557 MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait,
3558 ASTDeclContextNameLookupTrait> Generator;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003559 ASTDeclContextNameLookupTrait Trait(*this);
3560
Chandler Carruthe972c362015-03-26 03:11:40 +00003561 // The first step is to collect the declaration names which we need to
3562 // serialize into the name lookup table, and to collect them in a stable
3563 // order.
3564 SmallVector<DeclarationName, 16> Names;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003565
Chandler Carruthe972c362015-03-26 03:11:40 +00003566 // We also build up small sets of the constructor and conversion function
3567 // names which are visible.
3568 llvm::SmallSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003569
Chandler Carruthe972c362015-03-26 03:11:40 +00003570 for (auto &Lookup : *DC->buildLookup()) {
3571 auto &Name = Lookup.first;
3572 auto &Result = Lookup.second;
3573
Douglas Gregor7dd37e52015-11-03 01:20:54 +00003574 // If there are no local declarations in our lookup result, we
3575 // don't need to write an entry for the name at all. If we can't
3576 // write out a lookup set without performing more deserialization,
3577 // just skip this entry.
3578 if (isLookupResultExternal(Result, DC) &&
Chandler Carruthe972c362015-03-26 03:11:40 +00003579 isLookupResultEntirelyExternal(Result, DC))
3580 continue;
3581
3582 // We also skip empty results. If any of the results could be external and
3583 // the currently available results are empty, then all of the results are
3584 // external and we skip it above. So the only way we get here with an empty
3585 // results is when no results could have been external *and* we have
3586 // external results.
3587 //
3588 // FIXME: While we might want to start emitting on-disk entries for negative
3589 // lookups into a decl context as an optimization, today we *have* to skip
3590 // them because there are names with empty lookup results in decl contexts
3591 // which we can't emit in any stable ordering: we lookup constructors and
3592 // conversion functions in the enclosing namespace scope creating empty
3593 // results for them. This in almost certainly a bug in Clang's name lookup,
3594 // but that is likely to be hard or impossible to fix and so we tolerate it
3595 // here by omitting lookups with empty results.
3596 if (Lookup.second.getLookupResult().empty())
3597 continue;
3598
3599 switch (Lookup.first.getNameKind()) {
3600 default:
3601 Names.push_back(Lookup.first);
3602 break;
3603
Richard Smithcd45dbc2014-04-19 03:48:30 +00003604 case DeclarationName::CXXConstructorName:
Chandler Carruthe972c362015-03-26 03:11:40 +00003605 assert(isa<CXXRecordDecl>(DC) &&
3606 "Cannot have a constructor name outside of a class!");
3607 ConstructorNameSet.insert(Name);
3608 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003609
3610 case DeclarationName::CXXConversionFunctionName:
Chandler Carruthe972c362015-03-26 03:11:40 +00003611 assert(isa<CXXRecordDecl>(DC) &&
3612 "Cannot have a conversion function name outside of a class!");
3613 ConversionNameSet.insert(Name);
Rafael Espindolac606b3e2015-03-25 04:43:15 +00003614 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003615 }
Chandler Carruth75c9f132015-03-25 00:34:51 +00003616 }
Chandler Carruth75c9f132015-03-25 00:34:51 +00003617
Chandler Carruthe972c362015-03-26 03:11:40 +00003618 // Sort the names into a stable order.
3619 std::sort(Names.begin(), Names.end());
3620
Chandler Carruthffbf7052015-03-26 22:27:09 +00003621 if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
Chandler Carruthe972c362015-03-26 03:11:40 +00003622 // We need to establish an ordering of constructor and conversion function
Chandler Carruthffbf7052015-03-26 22:27:09 +00003623 // names, and they don't have an intrinsic ordering.
Chandler Carruthe972c362015-03-26 03:11:40 +00003624
Chandler Carruthffbf7052015-03-26 22:27:09 +00003625 // First we try the easy case by forming the current context's constructor
3626 // name and adding that name first. This is a very useful optimization to
3627 // avoid walking the lexical declarations in many cases, and it also
3628 // handles the only case where a constructor name can come from some other
3629 // lexical context -- when that name is an implicit constructor merged from
3630 // another declaration in the redecl chain. Any non-implicit constructor or
3631 // conversion function which doesn't occur in all the lexical contexts
3632 // would be an ODR violation.
3633 auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
3634 Context->getCanonicalType(Context->getRecordType(D)));
3635 if (ConstructorNameSet.erase(ImplicitCtorName))
3636 Names.push_back(ImplicitCtorName);
Chandler Carruthe972c362015-03-26 03:11:40 +00003637
Chandler Carruthffbf7052015-03-26 22:27:09 +00003638 // If we still have constructors or conversion functions, we walk all the
3639 // names in the decl and add the constructors and conversion functions
3640 // which are visible in the order they lexically occur within the context.
3641 if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
3642 for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
3643 if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
3644 auto Name = ChildND->getDeclName();
3645 switch (Name.getNameKind()) {
3646 default:
3647 continue;
3648
3649 case DeclarationName::CXXConstructorName:
3650 if (ConstructorNameSet.erase(Name))
3651 Names.push_back(Name);
3652 break;
3653
3654 case DeclarationName::CXXConversionFunctionName:
3655 if (ConversionNameSet.erase(Name))
3656 Names.push_back(Name);
3657 break;
3658 }
3659
3660 if (ConstructorNameSet.empty() && ConversionNameSet.empty())
3661 break;
Chandler Carruthe972c362015-03-26 03:11:40 +00003662 }
3663
Chandler Carruthe972c362015-03-26 03:11:40 +00003664 assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
3665 "constructors by walking all the "
3666 "lexical members of the context.");
3667 assert(ConversionNameSet.empty() && "Failed to find all of the visible "
3668 "conversion functions by walking all "
3669 "the lexical members of the context.");
Richard Smith961eae52014-03-25 01:14:22 +00003670 }
3671
Chandler Carruthe972c362015-03-26 03:11:40 +00003672 // Next we need to do a lookup with each name into this decl context to fully
3673 // populate any results from external sources. We don't actually use the
3674 // results of these lookups because we only want to use the results after all
3675 // results have been loaded and the pointers into them will be stable.
3676 for (auto &Name : Names)
3677 DC->lookup(Name);
3678
3679 // Now we need to insert the results for each name into the hash table. For
3680 // constructor names and conversion function names, we actually need to merge
3681 // all of the results for them into one list of results each and insert
3682 // those.
3683 SmallVector<NamedDecl *, 8> ConstructorDecls;
3684 SmallVector<NamedDecl *, 8> ConversionDecls;
3685
3686 // Now loop over the names, either inserting them or appending for the two
3687 // special cases.
3688 for (auto &Name : Names) {
3689 DeclContext::lookup_result Result = DC->noload_lookup(Name);
3690
3691 switch (Name.getNameKind()) {
3692 default:
Richard Smithd88a7f12015-09-01 20:35:42 +00003693 Generator.insert(Name, Trait.getData(Result), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00003694 break;
3695
3696 case DeclarationName::CXXConstructorName:
3697 ConstructorDecls.append(Result.begin(), Result.end());
3698 break;
3699
3700 case DeclarationName::CXXConversionFunctionName:
3701 ConversionDecls.append(Result.begin(), Result.end());
3702 break;
3703 }
3704 }
3705
3706 // Handle our two special cases if we ended up having any. We arbitrarily use
3707 // the first declaration's name here because the name itself isn't part of
3708 // the key, only the kind of name is used.
3709 if (!ConstructorDecls.empty())
3710 Generator.insert(ConstructorDecls.front()->getDeclName(),
Richard Smithd88a7f12015-09-01 20:35:42 +00003711 Trait.getData(ConstructorDecls), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00003712 if (!ConversionDecls.empty())
3713 Generator.insert(ConversionDecls.front()->getDeclName(),
Richard Smithd88a7f12015-09-01 20:35:42 +00003714 Trait.getData(ConversionDecls), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00003715
Richard Smithd88a7f12015-09-01 20:35:42 +00003716 // Create the on-disk hash table. Also emit the existing imported and
3717 // merged table if there is one.
3718 auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr;
3719 Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr);
Richard Smith961eae52014-03-25 01:14:22 +00003720}
3721
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003722/// \brief Write the block containing all of the declaration IDs
3723/// visible from the given DeclContext.
3724///
3725/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
Sebastian Redla4071b42010-08-24 00:50:09 +00003726/// bitstream, or 0 if no block was written.
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003727uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
3728 DeclContext *DC) {
Richard Smith5fc18a92015-07-12 23:43:21 +00003729 // If we imported a key declaration of this namespace, write the visible
3730 // lookup results as an update record for it rather than including them
3731 // on this declaration. We will only look at key declarations on reload.
3732 if (isa<NamespaceDecl>(DC) && Chain &&
3733 Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) {
3734 // Only do this once, for the first local declaration of the namespace.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003735 for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
Richard Smith5fc18a92015-07-12 23:43:21 +00003736 Prev = Prev->getPreviousDecl())
3737 if (!Prev->isFromASTFile())
3738 return 0;
3739
3740 // Note that we need to emit an update record for the primary context.
3741 UpdatedDeclContexts.insert(DC->getPrimaryContext());
3742
3743 // Make sure all visible decls are written. They will be recorded later. We
3744 // do this using a side data structure so we can sort the names into
3745 // a deterministic order.
3746 StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup();
3747 SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16>
3748 LookupResults;
3749 if (Map) {
3750 LookupResults.reserve(Map->size());
3751 for (auto &Entry : *Map)
3752 LookupResults.push_back(
3753 std::make_pair(Entry.first, Entry.second.getLookupResult()));
3754 }
3755
3756 std::sort(LookupResults.begin(), LookupResults.end(), llvm::less_first());
3757 for (auto &NameAndResult : LookupResults) {
3758 DeclarationName Name = NameAndResult.first;
3759 DeclContext::lookup_result Result = NameAndResult.second;
3760 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
3761 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
3762 // We have to work around a name lookup bug here where negative lookup
3763 // results for these names get cached in namespace lookup tables (these
3764 // names should never be looked up in a namespace).
3765 assert(Result.empty() && "Cannot have a constructor or conversion "
3766 "function name in a namespace!");
3767 continue;
3768 }
3769
3770 for (NamedDecl *ND : Result)
3771 if (!ND->isFromASTFile())
3772 GetDeclRef(ND);
3773 }
3774
3775 return 0;
3776 }
3777
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003778 if (DC->getPrimaryContext() != DC)
3779 return 0;
3780
Chandler Carruthe972c362015-03-26 03:11:40 +00003781 // Skip contexts which don't support name lookup.
3782 if (!DC->isLookupContext())
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003783 return 0;
3784
3785 // If not in C++, we perform name lookup for the translation unit via the
3786 // IdentifierInfo chains, don't bother to build a visible-declarations table.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003787 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003788 return 0;
3789
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003790 // Serialize the contents of the mapping used for lookup. Note that,
3791 // although we have two very different code paths, the serialized
3792 // representation is the same for both cases: a declaration name,
3793 // followed by a size, followed by references to the visible
3794 // declarations that have that name.
3795 uint64_t Offset = Stream.GetCurrentBitNo();
Richard Smithf634c902012-03-16 06:12:59 +00003796 StoredDeclsMap *Map = DC->buildLookup();
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003797 if (!Map || Map->empty())
3798 return 0;
3799
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003800 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003801 SmallString<4096> LookupTable;
Richard Smithd88a7f12015-09-01 20:35:42 +00003802 GenerateNameLookupTable(DC, LookupTable);
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003803
3804 // Write the lookup table
Mehdi Amini57a41912015-09-10 01:46:39 +00003805 RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003806 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
Yaron Keren92e1b622015-03-18 10:17:07 +00003807 LookupTable);
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003808 ++NumVisibleDeclContexts;
3809 return Offset;
3810}
3811
Sebastian Redla4071b42010-08-24 00:50:09 +00003812/// \brief Write an UPDATE_VISIBLE block for the given context.
3813///
3814/// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
3815/// DeclContext in a dependent AST file. As such, they only exist for the TU
Richard Smithf634c902012-03-16 06:12:59 +00003816/// (in C++), for namespaces, and for classes with forward-declared unscoped
3817/// enumeration members (in C++11).
Sebastian Redla4071b42010-08-24 00:50:09 +00003818void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
Richard Smith961eae52014-03-25 01:14:22 +00003819 StoredDeclsMap *Map = DC->getLookupPtr();
Sebastian Redla4071b42010-08-24 00:50:09 +00003820 if (!Map || Map->empty())
3821 return;
3822
Sebastian Redla4071b42010-08-24 00:50:09 +00003823 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003824 SmallString<4096> LookupTable;
Richard Smithd88a7f12015-09-01 20:35:42 +00003825 GenerateNameLookupTable(DC, LookupTable);
Sebastian Redla4071b42010-08-24 00:50:09 +00003826
Richard Smith5fc18a92015-07-12 23:43:21 +00003827 // If we're updating a namespace, select a key declaration as the key for the
3828 // update record; those are the only ones that will be checked on reload.
3829 if (isa<NamespaceDecl>(DC))
3830 DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
3831
Sebastian Redla4071b42010-08-24 00:50:09 +00003832 // Write the lookup table
Mehdi Amini57a41912015-09-10 01:46:39 +00003833 RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))};
Yaron Keren92e1b622015-03-18 10:17:07 +00003834 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
Sebastian Redla4071b42010-08-24 00:50:09 +00003835}
3836
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003837/// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
3838void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
Mehdi Amini57a41912015-09-10 01:46:39 +00003839 RecordData::value_type Record[] = {Opts.fp_contract};
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003840 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
3841}
3842
3843/// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
3844void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003845 if (!SemaRef.Context.getLangOpts().OpenCL)
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003846 return;
3847
3848 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
3849 RecordData Record;
3850#define OPENCLEXT(nm) Record.push_back(Opts.nm);
3851#include "clang/Basic/OpenCLExtensions.def"
3852 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
3853}
3854
Douglas Gregor404cdde2012-01-27 01:47:08 +00003855void ASTWriter::WriteObjCCategories() {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003856 SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
Douglas Gregor404cdde2012-01-27 01:47:08 +00003857 RecordData Categories;
3858
3859 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
3860 unsigned Size = 0;
3861 unsigned StartIndex = Categories.size();
3862
3863 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
3864
3865 // Allocate space for the size.
3866 Categories.push_back(0);
3867
3868 // Add the categories.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003869 for (ObjCInterfaceDecl::known_categories_iterator
3870 Cat = Class->known_categories_begin(),
3871 CatEnd = Class->known_categories_end();
3872 Cat != CatEnd; ++Cat, ++Size) {
3873 assert(getDeclID(*Cat) != 0 && "Bogus category");
3874 AddDeclRef(*Cat, Categories);
Douglas Gregor404cdde2012-01-27 01:47:08 +00003875 }
3876
3877 // Update the size.
3878 Categories[StartIndex] = Size;
3879
3880 // Record this interface -> category map.
3881 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
3882 CategoriesMap.push_back(CatInfo);
3883 }
3884
3885 // Sort the categories map by the definition ID, since the reader will be
3886 // performing binary searches on this information.
3887 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
3888
3889 // Emit the categories map.
3890 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003891
3892 auto *Abbrev = new BitCodeAbbrev();
Douglas Gregor404cdde2012-01-27 01:47:08 +00003893 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
3894 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
3895 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3896 unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
Mehdi Amini57a41912015-09-10 01:46:39 +00003897
3898 RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
3899 Stream.EmitRecordWithBlob(AbbrevID, Record,
3900 reinterpret_cast<char *>(CategoriesMap.data()),
Douglas Gregor404cdde2012-01-27 01:47:08 +00003901 CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
Mehdi Amini57a41912015-09-10 01:46:39 +00003902
Douglas Gregor404cdde2012-01-27 01:47:08 +00003903 // Emit the category lists.
3904 Stream.EmitRecord(OBJC_CATEGORIES, Categories);
3905}
3906
Richard Smithe40f2ba2013-08-07 21:41:30 +00003907void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
3908 Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
3909
3910 if (LPTMap.empty())
3911 return;
3912
3913 RecordData Record;
Chandler Carruth52cee4d2015-03-26 09:08:15 +00003914 for (auto LPTMapEntry : LPTMap) {
3915 const FunctionDecl *FD = LPTMapEntry.first;
3916 LateParsedTemplate *LPT = LPTMapEntry.second;
3917 AddDeclRef(FD, Record);
Richard Smithe40f2ba2013-08-07 21:41:30 +00003918 AddDeclRef(LPT->D, Record);
3919 Record.push_back(LPT->Toks.size());
3920
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003921 for (const auto &Tok : LPT->Toks) {
3922 AddToken(Tok, Record);
Richard Smithe40f2ba2013-08-07 21:41:30 +00003923 }
3924 }
3925 Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
3926}
3927
Dario Domizioli13a0a382014-05-23 12:13:25 +00003928/// \brief Write the state of 'pragma clang optimize' at the end of the module.
3929void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
3930 RecordData Record;
3931 SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
3932 AddSourceLocation(PragmaLoc, Record);
3933 Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
3934}
3935
Nico Weber779355f2016-03-02 23:22:00 +00003936/// \brief Write the state of 'pragma ms_struct' at the end of the module.
3937void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
3938 RecordData Record;
3939 Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF);
3940 Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
3941}
3942
Nico Weber42932312016-03-03 00:17:35 +00003943/// \brief Write the state of 'pragma pointers_to_members' at the end of the
3944//module.
3945void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
3946 RecordData Record;
3947 Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod);
3948 AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record);
3949 Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
3950}
3951
Douglas Gregor8f64ca12015-12-08 22:43:32 +00003952void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
3953 ModuleFileExtensionWriter &Writer) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003954 // Enter the extension block.
3955 Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
3956
3957 // Emit the metadata record abbreviation.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003958 auto *Abv = new llvm::BitCodeAbbrev();
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003959 Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
3960 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3961 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3962 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3963 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3964 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
3965 unsigned Abbrev = Stream.EmitAbbrev(Abv);
3966
3967 // Emit the metadata record.
3968 RecordData Record;
3969 auto Metadata = Writer.getExtension()->getExtensionMetadata();
3970 Record.push_back(EXTENSION_METADATA);
3971 Record.push_back(Metadata.MajorVersion);
3972 Record.push_back(Metadata.MinorVersion);
3973 Record.push_back(Metadata.BlockName.size());
3974 Record.push_back(Metadata.UserInfo.size());
3975 SmallString<64> Buffer;
3976 Buffer += Metadata.BlockName;
3977 Buffer += Metadata.UserInfo;
3978 Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
3979
3980 // Emit the contents of the extension block.
Douglas Gregor8f64ca12015-12-08 22:43:32 +00003981 Writer.writeExtensionContents(SemaRef, Stream);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003982
3983 // Exit the extension block.
3984 Stream.ExitBlock();
3985}
3986
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003987//===----------------------------------------------------------------------===//
Douglas Gregorc5046832009-04-27 18:38:38 +00003988// General Serialization Routines
3989//===----------------------------------------------------------------------===//
3990
Richard Smith69c82bf2016-04-01 22:52:03 +00003991/// \brief Emit the list of attributes to the specified record.
3992void ASTWriter::AddAttributes(ArrayRef<const Attr *> Attrs,
3993 RecordDataImpl &Record) {
Argyrios Kyrtzidis9beef8e2010-10-18 19:20:11 +00003994 Record.push_back(Attrs.size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003995 for (const auto *A : Attrs) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003996 Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
Argyrios Kyrtzidis309b4c42011-09-13 16:05:58 +00003997 AddSourceRange(A->getRange(), Record);
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00003998
Alexis Huntdcfba7b2010-08-18 23:23:40 +00003999#include "clang/Serialization/AttrPCHWrite.inc"
Daniel Dunbarfc6507e2010-05-27 02:25:39 +00004000
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00004001 }
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00004002}
4003
John McCallf413f5e2013-05-03 00:10:13 +00004004void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
4005 AddSourceLocation(Tok.getLocation(), Record);
4006 Record.push_back(Tok.getLength());
4007
4008 // FIXME: When reading literal tokens, reconstruct the literal pointer
4009 // if it is needed.
4010 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
4011 // FIXME: Should translate token kind to a stable encoding.
4012 Record.push_back(Tok.getKind());
4013 // FIXME: Should translate token flags to a stable encoding.
4014 Record.push_back(Tok.getFlags());
4015}
4016
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004017void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00004018 Record.push_back(Str.size());
4019 Record.insert(Record.end(), Str.begin(), Str.end());
4020}
4021
Richard Smith7ed1bc92014-12-05 22:42:13 +00004022bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
Richard Smith54cc3c22014-12-11 20:50:24 +00004023 assert(Context && "should have context when outputting path");
Richard Smith7ed1bc92014-12-05 22:42:13 +00004024
Richard Smith54cc3c22014-12-11 20:50:24 +00004025 bool Changed =
4026 cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004027
4028 // Remove a prefix to make the path relative, if relevant.
4029 const char *PathBegin = Path.data();
4030 const char *PathPtr =
4031 adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
4032 if (PathPtr != PathBegin) {
4033 Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
4034 Changed = true;
4035 }
4036
4037 return Changed;
4038}
4039
4040void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
4041 SmallString<128> FilePath(Path);
4042 PreparePathForOutput(FilePath);
4043 AddString(FilePath, Record);
4044}
4045
Mehdi Amini57a41912015-09-10 01:46:39 +00004046void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
Richard Smith7ed1bc92014-12-05 22:42:13 +00004047 StringRef Path) {
4048 SmallString<128> FilePath(Path);
4049 PreparePathForOutput(FilePath);
4050 Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
4051}
4052
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004053void ASTWriter::AddVersionTuple(const VersionTuple &Version,
4054 RecordDataImpl &Record) {
4055 Record.push_back(Version.getMajor());
David Blaikie05785d12013-02-20 22:23:23 +00004056 if (Optional<unsigned> Minor = Version.getMinor())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004057 Record.push_back(*Minor + 1);
4058 else
4059 Record.push_back(0);
David Blaikie05785d12013-02-20 22:23:23 +00004060 if (Optional<unsigned> Subminor = Version.getSubminor())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004061 Record.push_back(*Subminor + 1);
4062 else
4063 Record.push_back(0);
4064}
4065
Douglas Gregore84a9da2009-04-20 20:36:09 +00004066/// \brief Note that the identifier II occurs at the given offset
4067/// within the identifier table.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004068void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Sebastian Redl539c5062010-08-18 23:57:32 +00004069 IdentID ID = IdentifierIDs[II];
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00004070 // Only store offsets new to this AST file. Other identifier names are looked
Sebastian Redlff4a2952010-07-23 23:49:55 +00004071 // up earlier in the chain and thus don't need an offset.
4072 if (ID >= FirstIdentID)
4073 IdentifierOffsets[ID - FirstIdentID] = Offset;
Douglas Gregore84a9da2009-04-20 20:36:09 +00004074}
4075
Douglas Gregor95c13f52009-04-25 17:48:32 +00004076/// \brief Note that the selector Sel occurs at the given offset
4077/// within the method pool/selector table.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004078void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
Douglas Gregor95c13f52009-04-25 17:48:32 +00004079 unsigned ID = SelectorIDs[Sel];
4080 assert(ID && "Unknown selector");
Sebastian Redld95a56e2010-08-04 18:21:41 +00004081 // Don't record offsets for selectors that are also available in a different
4082 // file.
4083 if (ID < FirstSelectorID)
4084 return;
4085 SelectorOffsets[ID - FirstSelectorID] = Offset;
Douglas Gregor95c13f52009-04-25 17:48:32 +00004086}
4087
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004088ASTWriter::ASTWriter(
4089 llvm::BitstreamWriter &Stream,
4090 ArrayRef<llvm::IntrusiveRefCntPtr<ModuleFileExtension>> Extensions,
4091 bool IncludeTimestamps)
Richard Smith01b2cb42014-07-26 06:37:51 +00004092 : Stream(Stream), Context(nullptr), PP(nullptr), Chain(nullptr),
Richard Smithe75ee0f2015-08-17 07:13:32 +00004093 WritingModule(nullptr), IncludeTimestamps(IncludeTimestamps),
4094 WritingAST(false), DoneWritingDeclsAndTypes(false),
4095 ASTHasCompilerErrors(false), FirstDeclID(NUM_PREDEF_DECL_IDS),
4096 NextDeclID(FirstDeclID), FirstTypeID(NUM_PREDEF_TYPE_IDS),
4097 NextTypeID(FirstTypeID), FirstIdentID(NUM_PREDEF_IDENT_IDS),
4098 NextIdentID(FirstIdentID), FirstMacroID(NUM_PREDEF_MACRO_IDS),
4099 NextMacroID(FirstMacroID), FirstSubmoduleID(NUM_PREDEF_SUBMODULE_IDS),
Richard Smith01b2cb42014-07-26 06:37:51 +00004100 NextSubmoduleID(FirstSubmoduleID),
4101 FirstSelectorID(NUM_PREDEF_SELECTOR_IDS), NextSelectorID(FirstSelectorID),
4102 CollectedStmts(&StmtsToEmit), NumStatements(0), NumMacros(0),
4103 NumLexicalDeclContexts(0), NumVisibleDeclContexts(0),
Richard Smithc2bb8182015-03-24 06:36:48 +00004104 NextCXXBaseSpecifiersID(1), NextCXXCtorInitializersID(1),
Richard Smithe75ee0f2015-08-17 07:13:32 +00004105 TypeExtQualAbbrev(0), TypeFunctionProtoAbbrev(0), DeclParmVarAbbrev(0),
Richard Smith01b2cb42014-07-26 06:37:51 +00004106 DeclContextLexicalAbbrev(0), DeclContextVisibleLookupAbbrev(0),
Richard Smitha27c26e2014-07-27 04:19:32 +00004107 UpdateVisibleAbbrev(0), DeclRecordAbbrev(0), DeclTypedefAbbrev(0),
Richard Smith01b2cb42014-07-26 06:37:51 +00004108 DeclVarAbbrev(0), DeclFieldAbbrev(0), DeclEnumAbbrev(0),
Richard Smitha27c26e2014-07-27 04:19:32 +00004109 DeclObjCIvarAbbrev(0), DeclCXXMethodAbbrev(0), DeclRefExprAbbrev(0),
4110 CharacterLiteralAbbrev(0), IntegerLiteralAbbrev(0),
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004111 ExprImplicitCastAbbrev(0) {
4112 for (const auto &Ext : Extensions) {
4113 if (auto Writer = Ext->createExtensionWriter(*this))
4114 ModuleFileExtensionWriters.push_back(std::move(Writer));
4115 }
4116}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004117
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004118ASTWriter::~ASTWriter() {
Reid Kleckner588c9372014-02-19 23:44:52 +00004119 llvm::DeleteContainerSeconds(FileDeclIDs);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004120}
4121
Richard Smithb3761912015-02-05 23:08:52 +00004122const LangOptions &ASTWriter::getLangOpts() const {
4123 assert(WritingAST && "can't determine lang opts when not writing AST");
4124 return Context->getLangOpts();
4125}
4126
Richard Smithe75ee0f2015-08-17 07:13:32 +00004127time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const {
4128 return IncludeTimestamps ? E->getModificationTime() : 0;
4129}
4130
Adrian Prantladbd2b12015-09-22 23:26:31 +00004131uint64_t ASTWriter::WriteAST(Sema &SemaRef, const std::string &OutputFile,
4132 Module *WritingModule, StringRef isysroot,
4133 bool hasErrors) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00004134 WritingAST = true;
Adrian Prantladbd2b12015-09-22 23:26:31 +00004135
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00004136 ASTHasCompilerErrors = hasErrors;
4137
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004138 // Emit the file header.
Douglas Gregor8f45df52009-04-16 22:23:12 +00004139 Stream.Emit((unsigned)'C', 8);
4140 Stream.Emit((unsigned)'P', 8);
4141 Stream.Emit((unsigned)'C', 8);
4142 Stream.Emit((unsigned)'H', 8);
Mike Stump11289f42009-09-09 15:08:12 +00004143
Chris Lattner28fa4e62009-04-26 22:26:21 +00004144 WriteBlockInfoBlock();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004145
Douglas Gregoreda8e122011-08-09 15:13:55 +00004146 Context = &SemaRef.Context;
Douglas Gregora28bcdd2011-12-01 02:07:58 +00004147 PP = &SemaRef.PP;
Douglas Gregora89c5ac2011-12-06 01:10:29 +00004148 this->WritingModule = WritingModule;
Adrian Prantladbd2b12015-09-22 23:26:31 +00004149 ASTFileSignature Signature =
4150 WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
Craig Toppera13603a2014-05-22 05:54:18 +00004151 Context = nullptr;
4152 PP = nullptr;
4153 this->WritingModule = nullptr;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004154 this->BaseDirectory.clear();
Craig Toppera13603a2014-05-22 05:54:18 +00004155
Douglas Gregor2fd3d402011-09-17 00:05:03 +00004156 WritingAST = false;
Adrian Prantladbd2b12015-09-22 23:26:31 +00004157 return Signature;
Sebastian Redl143413f2010-07-12 22:02:52 +00004158}
4159
Douglas Gregora94a1542011-07-27 21:45:57 +00004160template<typename Vector>
4161static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4162 ASTWriter::RecordData &Record) {
Craig Toppera13603a2014-05-22 05:54:18 +00004163 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4164 I != E; ++I) {
Douglas Gregora94a1542011-07-27 21:45:57 +00004165 Writer.AddDeclRef(*I, Record);
4166 }
4167}
4168
Adrian Prantladbd2b12015-09-22 23:26:31 +00004169uint64_t ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
4170 const std::string &OutputFile,
4171 Module *WritingModule) {
Sebastian Redl143413f2010-07-12 22:02:52 +00004172 using namespace llvm;
4173
Craig Toppera13603a2014-05-22 05:54:18 +00004174 bool isModule = WritingModule != nullptr;
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004175
Douglas Gregorcf68c582011-12-01 22:20:10 +00004176 // Make sure that the AST reader knows to finalize itself.
4177 if (Chain)
4178 Chain->finalizeForWriting();
4179
Sebastian Redl143413f2010-07-12 22:02:52 +00004180 ASTContext &Context = SemaRef.Context;
4181 Preprocessor &PP = SemaRef.PP;
4182
Douglas Gregordab42432011-08-12 00:15:20 +00004183 // Set up predefined declaration IDs.
Richard Smith5fc18a92015-07-12 23:43:21 +00004184 auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
4185 if (D) {
4186 assert(D->isCanonicalDecl() && "predefined decl is not canonical");
4187 DeclIDs[D] = ID;
Richard Smith5fc18a92015-07-12 23:43:21 +00004188 }
4189 };
4190 RegisterPredefDecl(Context.getTranslationUnitDecl(),
4191 PREDEF_DECL_TRANSLATION_UNIT_ID);
4192 RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
4193 RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
4194 RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
4195 RegisterPredefDecl(Context.ObjCProtocolClassDecl,
4196 PREDEF_DECL_OBJC_PROTOCOL_ID);
4197 RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
4198 RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
4199 RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
4200 PREDEF_DECL_OBJC_INSTANCETYPE_ID);
4201 RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
Richard Smith9b88a4c2015-07-27 05:40:23 +00004202 RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
Charles Davisc7d5c942015-09-17 20:55:33 +00004203 RegisterPredefDecl(Context.BuiltinMSVaListDecl,
4204 PREDEF_DECL_BUILTIN_MS_VA_LIST_ID);
Richard Smith5fc18a92015-07-12 23:43:21 +00004205 RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
David Majnemerd9b1a4f2015-11-04 03:40:30 +00004206 RegisterPredefDecl(Context.MakeIntegerSeqDecl,
4207 PREDEF_DECL_MAKE_INTEGER_SEQ_ID);
Quentin Colombet043406b2016-02-03 22:41:00 +00004208 RegisterPredefDecl(Context.CFConstantStringTypeDecl,
4209 PREDEF_DECL_CF_CONSTANT_STRING_ID);
Ben Langmuirf5416742016-02-04 00:55:24 +00004210 RegisterPredefDecl(Context.CFConstantStringTagDecl,
4211 PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID);
Meador Inge5d3fb222012-06-16 03:34:49 +00004212
Chris Lattner0c797362009-09-08 18:19:27 +00004213 // Build a record containing all of the tentative definitions in this file, in
Sebastian Redl35351a92010-01-31 22:27:38 +00004214 // TentativeDefinitions order. Generally, this record will be empty for
Chris Lattner0c797362009-09-08 18:19:27 +00004215 // headers.
Douglas Gregord4df8652009-04-22 22:02:47 +00004216 RecordData TentativeDefinitions;
Douglas Gregora94a1542011-07-27 21:45:57 +00004217 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
Douglas Gregoreb08bd42011-07-27 20:58:46 +00004218
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00004219 // Build a record containing all of the file scoped decls in this file.
4220 RecordData UnusedFileScopedDecls;
Argyrios Kyrtzidis59852362013-03-14 04:45:00 +00004221 if (!isModule)
4222 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
4223 UnusedFileScopedDecls);
Sebastian Redl08aca90252010-08-05 18:21:25 +00004224
Douglas Gregor851443c2011-08-12 01:39:19 +00004225 // Build a record containing all of the delegating constructors we still need
4226 // to resolve.
Alexis Hunt27a761d2011-05-04 23:29:54 +00004227 RecordData DelegatingCtorDecls;
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004228 if (!isModule)
4229 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
Alexis Hunt27a761d2011-05-04 23:29:54 +00004230
Douglas Gregor851443c2011-08-12 01:39:19 +00004231 // Write the set of weak, undeclared identifiers. We always write the
4232 // entire table, since later PCH files in a PCH chain are only interested in
4233 // the results at the end of the chain.
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004234 RecordData WeakUndeclaredIdentifiers;
Chandler Carruthf85d9822015-03-26 08:32:49 +00004235 for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) {
4236 IdentifierInfo *II = WeakUndeclaredIdentifier.first;
4237 WeakInfo &WI = WeakUndeclaredIdentifier.second;
4238 AddIdentifierRef(II, WeakUndeclaredIdentifiers);
4239 AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
4240 AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
4241 WeakUndeclaredIdentifiers.push_back(WI.getUsed());
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004242 }
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00004243
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004244 // Build a record containing all of the ext_vector declarations.
4245 RecordData ExtVectorDecls;
Douglas Gregorb7098a32011-07-28 00:39:29 +00004246 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004247
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004248 // Build a record containing all of the VTable uses information.
4249 RecordData VTableUses;
Argyrios Kyrtzidisedee67f2010-08-03 17:29:52 +00004250 if (!SemaRef.VTableUses.empty()) {
Argyrios Kyrtzidisedee67f2010-08-03 17:29:52 +00004251 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4252 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4253 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4254 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4255 }
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004256 }
4257
Nico Weber72889432014-09-06 01:25:55 +00004258 // Build a record containing all of the UnusedLocalTypedefNameCandidates.
4259 RecordData UnusedLocalTypedefNameCandidates;
4260 for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4261 AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
4262
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004263 // Build a record containing all of pending implicit instantiations.
Chandler Carruth54080172010-08-25 08:44:16 +00004264 RecordData PendingInstantiations;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004265 for (const auto &I : SemaRef.PendingInstantiations) {
4266 AddDeclRef(I.first, PendingInstantiations);
4267 AddSourceLocation(I.second, PendingInstantiations);
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004268 }
4269 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4270 "There are local ones at end of translation unit!");
4271
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004272 // Build a record containing some declaration references.
4273 RecordData SemaDeclRefs;
4274 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
4275 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4276 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
4277 }
4278
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004279 RecordData CUDASpecialDeclRefs;
4280 if (Context.getcudaConfigureCallDecl()) {
4281 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4282 }
4283
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004284 // Build a record containing all of the known namespaces.
4285 RecordData KnownNamespaces;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004286 for (const auto &I : SemaRef.KnownNamespaces) {
4287 if (!I.second)
4288 AddDeclRef(I.first, KnownNamespaces);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004289 }
Douglas Gregor112b9072012-10-18 05:31:06 +00004290
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004291 // Build a record of all used, undefined objects that require definitions.
4292 RecordData UndefinedButUsed;
Nick Lewyckyf0f56162013-01-31 03:23:57 +00004293
4294 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004295 SemaRef.getUndefinedButUsed(Undefined);
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004296 for (const auto &I : Undefined) {
4297 AddDeclRef(I.first, UndefinedButUsed);
4298 AddSourceLocation(I.second, UndefinedButUsed);
Nick Lewycky8334af82013-01-26 00:35:08 +00004299 }
4300
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00004301 // Build a record containing all delete-expressions that we would like to
4302 // analyze later in AST.
4303 RecordData DeleteExprsToAnalyze;
4304
4305 for (const auto &DeleteExprsInfo :
4306 SemaRef.getMismatchingDeleteExpressions()) {
4307 AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
4308 DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
4309 for (const auto &DeleteLoc : DeleteExprsInfo.second) {
4310 AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
4311 DeleteExprsToAnalyze.push_back(DeleteLoc.second);
4312 }
4313 }
4314
Douglas Gregor112b9072012-10-18 05:31:06 +00004315 // Write the control block
Adrian Prantladbd2b12015-09-22 23:26:31 +00004316 uint64_t Signature = WriteControlBlock(PP, Context, isysroot, OutputFile);
Douglas Gregor112b9072012-10-18 05:31:06 +00004317
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00004318 // Write the remaining AST contents.
Sebastian Redl539c5062010-08-18 23:57:32 +00004319 Stream.EnterSubblock(AST_BLOCK_ID, 5);
Douglas Gregor851443c2011-08-12 01:39:19 +00004320
Argyrios Kyrtzidis39605402012-12-13 21:38:23 +00004321 // This is so that older clang versions, before the introduction
4322 // of the control block, can read and reject the newer PCH format.
Mehdi Amini57a41912015-09-10 01:46:39 +00004323 {
4324 RecordData Record = {VERSION_MAJOR};
4325 Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4326 }
Argyrios Kyrtzidis39605402012-12-13 21:38:23 +00004327
Douglas Gregor851443c2011-08-12 01:39:19 +00004328 // Create a lexical update block containing all of the declarations in the
4329 // translation unit that do not come from other AST files.
4330 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00004331 SmallVector<uint32_t, 128> NewGlobalKindDeclPairs;
4332 for (const auto *D : TU->noload_decls()) {
4333 if (!D->isFromASTFile()) {
4334 NewGlobalKindDeclPairs.push_back(D->getKind());
4335 NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
4336 }
Douglas Gregor851443c2011-08-12 01:39:19 +00004337 }
4338
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004339 auto *Abv = new llvm::BitCodeAbbrev();
Douglas Gregor851443c2011-08-12 01:39:19 +00004340 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4341 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4342 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv);
Mehdi Amini57a41912015-09-10 01:46:39 +00004343 {
4344 RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
4345 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4346 bytes(NewGlobalKindDeclPairs));
4347 }
4348
Douglas Gregor851443c2011-08-12 01:39:19 +00004349 // And a visible updates block for the translation unit.
4350 Abv = new llvm::BitCodeAbbrev();
4351 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4352 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
Douglas Gregor851443c2011-08-12 01:39:19 +00004353 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4354 UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv);
4355 WriteDeclContextVisibleUpdate(TU);
Richard Smithf19e1272015-03-07 00:04:49 +00004356
4357 // If we have any extern "C" names, write out a visible update for them.
4358 if (Context.ExternCContext)
4359 WriteDeclContextVisibleUpdate(Context.ExternCContext);
Douglas Gregor851443c2011-08-12 01:39:19 +00004360
4361 // If the translation unit has an anonymous namespace, and we don't already
4362 // have an update block for it, write it as an update block.
Richard Smith6ef42932014-03-20 21:02:00 +00004363 // FIXME: Why do we not do this if there's already an update block?
Douglas Gregor851443c2011-08-12 01:39:19 +00004364 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4365 ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
Richard Smith6ef42932014-03-20 21:02:00 +00004366 if (Record.empty())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004367 Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
Douglas Gregor851443c2011-08-12 01:39:19 +00004368 }
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004369
Richard Smith5652c0f2014-03-21 01:48:23 +00004370 // Add update records for all mangling numbers and static local numbers.
4371 // These aren't really update records, but this is a convenient way of
4372 // tagging this rare extra data onto the declarations.
4373 for (const auto &Number : Context.MangleNumbers)
4374 if (!Number.first->isFromASTFile())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004375 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4376 Number.second));
Richard Smith5652c0f2014-03-21 01:48:23 +00004377 for (const auto &Number : Context.StaticLocalNumbers)
4378 if (!Number.first->isFromASTFile())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004379 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4380 Number.second));
Richard Smith5652c0f2014-03-21 01:48:23 +00004381
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004382 // Make sure visible decls, added to DeclContexts previously loaded from
4383 // an AST file, are registered for serialization.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004384 for (const auto *I : UpdatingVisibleDecls) {
4385 GetDeclRef(I);
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004386 }
4387
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +00004388 // Make sure all decls associated with an identifier are registered for
Richard Smith79bf9202015-08-24 03:33:22 +00004389 // serialization, if we're storing decls with identifiers.
4390 if (!WritingModule || !getLangOpts().CPlusPlus) {
4391 llvm::SmallVector<const IdentifierInfo*, 256> IIs;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004392 for (const auto &ID : PP.getIdentifierTable()) {
4393 const IdentifierInfo *II = ID.second;
Richard Smith79bf9202015-08-24 03:33:22 +00004394 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
4395 IIs.push_back(II);
4396 }
4397 // Sort the identifiers to visit based on their name.
4398 std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
4399 for (const IdentifierInfo *II : IIs) {
4400 for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4401 DEnd = SemaRef.IdResolver.end();
4402 D != DEnd; ++D) {
4403 GetDeclRef(*D);
4404 }
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +00004405 }
4406 }
4407
Douglas Gregor5204bde2011-08-02 16:26:37 +00004408 // Form the record of special types.
4409 RecordData SpecialTypes;
Douglas Gregor5204bde2011-08-02 16:26:37 +00004410 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
Douglas Gregor5204bde2011-08-02 16:26:37 +00004411 AddTypeRef(Context.getFILEType(), SpecialTypes);
4412 AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4413 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4414 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4415 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
Douglas Gregor5204bde2011-08-02 16:26:37 +00004416 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00004417 AddTypeRef(Context.getucontext_tType(), SpecialTypes);
Douglas Gregora28bcdd2011-12-01 02:07:58 +00004418
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004419 if (Chain) {
4420 // Write the mapping information describing our module dependencies and how
4421 // each of those modules were mapped into our own offset/ID space, so that
4422 // the reader can build the appropriate mapping to its own offset/ID space.
4423 // The map consists solely of a blob with the following format:
4424 // *(module-name-len:i16 module-name:len*i8
4425 // source-location-offset:i32
4426 // identifier-id:i32
4427 // preprocessed-entity-id:i32
4428 // macro-definition-id:i32
Douglas Gregor253eefe2011-12-01 00:59:36 +00004429 // submodule-id:i32
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004430 // selector-id:i32
4431 // declaration-id:i32
4432 // c++-base-specifiers-id:i32
4433 // type-id:i32)
4434 //
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004435 auto *Abbrev = new BitCodeAbbrev();
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004436 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4437 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4438 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(Abbrev);
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004439 SmallString<2048> Buffer;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004440 {
4441 llvm::raw_svector_ostream Out(Buffer);
Ben Langmuir785180e2014-10-20 16:27:30 +00004442 for (ModuleFile *M : Chain->ModuleMgr) {
Justin Bognere1c147c2014-03-28 22:03:19 +00004443 using namespace llvm::support;
4444 endian::Writer<little> LE(Out);
Ben Langmuir785180e2014-10-20 16:27:30 +00004445 StringRef FileName = M->FileName;
Justin Bognere1c147c2014-03-28 22:03:19 +00004446 LE.write<uint16_t>(FileName.size());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004447 Out.write(FileName.data(), FileName.size());
Ben Langmuirfe971d92014-08-16 04:54:18 +00004448
Ben Langmuir785180e2014-10-20 16:27:30 +00004449 // Note: if a base ID was uint max, it would not be possible to load
4450 // another module after it or have more than one entity inside it.
4451 uint32_t None = std::numeric_limits<uint32_t>::max();
4452
4453 auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) {
4454 assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
4455 if (ShouldWrite)
4456 LE.write<uint32_t>(BaseID);
4457 else
4458 LE.write<uint32_t>(None);
4459 };
4460
Ben Langmuirfe971d92014-08-16 04:54:18 +00004461 // These values should be unique within a chain, since they will be read
4462 // as keys into ContinuousRangeMaps.
Ben Langmuir785180e2014-10-20 16:27:30 +00004463 writeBaseIDOrNone(M->SLocEntryBaseOffset, M->LocalNumSLocEntries);
4464 writeBaseIDOrNone(M->BaseIdentifierID, M->LocalNumIdentifiers);
4465 writeBaseIDOrNone(M->BaseMacroID, M->LocalNumMacros);
4466 writeBaseIDOrNone(M->BasePreprocessedEntityID,
4467 M->NumPreprocessedEntities);
4468 writeBaseIDOrNone(M->BaseSubmoduleID, M->LocalNumSubmodules);
4469 writeBaseIDOrNone(M->BaseSelectorID, M->LocalNumSelectors);
4470 writeBaseIDOrNone(M->BaseDeclID, M->LocalNumDecls);
4471 writeBaseIDOrNone(M->BaseTypeIndex, M->LocalNumTypes);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004472 }
4473 }
Mehdi Amini57a41912015-09-10 01:46:39 +00004474 RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004475 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4476 Buffer.data(), Buffer.size());
4477 }
Richard Smithb9eab6d2014-03-20 19:44:17 +00004478
Richard Smithb9eab6d2014-03-20 19:44:17 +00004479 RecordData DeclUpdatesOffsetsRecord;
4480
Richard Smith59442b42014-03-20 20:07:19 +00004481 // Keep writing types, declarations, and declaration update records
4482 // until we've emitted all of them.
Richard Smith01b2cb42014-07-26 06:37:51 +00004483 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
4484 WriteTypeAbbrevs();
4485 WriteDeclAbbrevs();
Richard Smith59442b42014-03-20 20:07:19 +00004486 do {
4487 WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
4488 while (!DeclTypesToEmit.empty()) {
4489 DeclOrType DOT = DeclTypesToEmit.front();
4490 DeclTypesToEmit.pop();
4491 if (DOT.isType())
4492 WriteType(DOT.getType());
4493 else
4494 WriteDecl(Context, DOT.getDecl());
4495 }
4496 } while (!DeclUpdates.empty());
Richard Smithb9eab6d2014-03-20 19:44:17 +00004497 Stream.ExitBlock();
4498
Richard Smithb9eab6d2014-03-20 19:44:17 +00004499 DoneWritingDeclsAndTypes = true;
4500
4501 // These things can only be done once we've written out decls and types.
4502 WriteTypeDeclOffsets();
Richard Smith5652c0f2014-03-21 01:48:23 +00004503 if (!DeclUpdatesOffsetsRecord.empty())
4504 Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
Richard Smithb9eab6d2014-03-20 19:44:17 +00004505 WriteCXXBaseSpecifiersOffsets();
Richard Smithc2bb8182015-03-24 06:36:48 +00004506 WriteCXXCtorInitializersOffsets();
Richard Smithb9eab6d2014-03-20 19:44:17 +00004507 WriteFileDeclIDsMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00004508 WriteSourceManagerBlock(Context.getSourceManager(), PP);
Richard Smithb9eab6d2014-03-20 19:44:17 +00004509 WriteComments();
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004510 WritePreprocessor(PP, isModule);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004511 WriteHeaderSearch(PP.getHeaderSearchInfo());
Sebastian Redla19a67f2010-08-03 21:58:15 +00004512 WriteSelectors(SemaRef);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00004513 WriteReferencedSelectorsPool(SemaRef);
Richard Smith9c254182015-07-19 21:41:12 +00004514 WriteLateParsedTemplates(SemaRef);
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004515 WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
Peter Collingbourne5df20e02011-02-15 19:46:30 +00004516 WriteFPPragmaOptions(SemaRef.getFPOptions());
4517 WriteOpenCLExtensions(SemaRef);
Argyrios Kyrtzidis0f06b982013-03-27 17:17:23 +00004518 WritePragmaDiagnosticMappings(Context.getDiagnostics(), isModule);
Douglas Gregor652d82a2009-04-18 05:55:16 +00004519
Douglas Gregora89c5ac2011-12-06 01:10:29 +00004520 // If we're emitting a module, write out the submodule information.
4521 if (WritingModule)
4522 WriteSubmodules(WritingModule);
4523
Douglas Gregor5204bde2011-08-02 16:26:37 +00004524 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
4525
Douglas Gregord4df8652009-04-22 22:02:47 +00004526 // Write the record containing external, unnamed definitions.
Ben Langmuir332aafe2014-01-31 01:06:56 +00004527 if (!EagerlyDeserializedDecls.empty())
4528 Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
Douglas Gregord4df8652009-04-22 22:02:47 +00004529
4530 // Write the record containing tentative definitions.
4531 if (!TentativeDefinitions.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004532 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregoracfc76c2009-04-22 22:18:58 +00004533
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00004534 // Write the record containing unused file scoped decls.
4535 if (!UnusedFileScopedDecls.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004536 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00004537
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004538 // Write the record containing weak undeclared identifiers.
4539 if (!WeakUndeclaredIdentifiers.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004540 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004541 WeakUndeclaredIdentifiers);
4542
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004543 // Write the record containing ext_vector type names.
4544 if (!ExtVectorDecls.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004545 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
Mike Stump11289f42009-09-09 15:08:12 +00004546
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004547 // Write the record containing VTable uses information.
4548 if (!VTableUses.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004549 Stream.EmitRecord(VTABLE_USES, VTableUses);
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004550
Nico Weber72889432014-09-06 01:25:55 +00004551 // Write the record containing potentially unused local typedefs.
4552 if (!UnusedLocalTypedefNameCandidates.empty())
4553 Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
4554 UnusedLocalTypedefNameCandidates);
4555
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004556 // Write the record containing pending implicit instantiations.
Chandler Carruth54080172010-08-25 08:44:16 +00004557 if (!PendingInstantiations.empty())
4558 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004559
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004560 // Write the record containing declaration references of Sema.
4561 if (!SemaDeclRefs.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004562 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004563
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004564 // Write the record containing CUDA-specific declaration references.
4565 if (!CUDASpecialDeclRefs.empty())
4566 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
Alexis Hunt27a761d2011-05-04 23:29:54 +00004567
4568 // Write the delegating constructors.
4569 if (!DelegatingCtorDecls.empty())
4570 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004571
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004572 // Write the known namespaces.
4573 if (!KnownNamespaces.empty())
4574 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
Nick Lewycky8334af82013-01-26 00:35:08 +00004575
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004576 // Write the undefined internal functions and variables, and inline functions.
4577 if (!UndefinedButUsed.empty())
4578 Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00004579
4580 if (!DeleteExprsToAnalyze.empty())
4581 Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
4582
Douglas Gregor851443c2011-08-12 01:39:19 +00004583 // Write the visible updates to DeclContexts.
Richard Smithcd45dbc2014-04-19 03:48:30 +00004584 for (auto *DC : UpdatedDeclContexts)
4585 WriteDeclContextVisibleUpdate(DC);
Douglas Gregor851443c2011-08-12 01:39:19 +00004586
Douglas Gregor959bb062011-12-03 01:15:29 +00004587 if (!WritingModule) {
4588 // Write the submodules that were imported, if any.
Aaron Ballman4f45b712014-03-21 15:22:56 +00004589 struct ModuleInfo {
4590 uint64_t ID;
4591 Module *M;
4592 ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
4593 };
Richard Smith56be7542014-03-21 00:33:59 +00004594 llvm::SmallVector<ModuleInfo, 64> Imports;
Aaron Ballmanbbc31212014-03-14 20:59:21 +00004595 for (const auto *I : Context.local_imports()) {
Douglas Gregor959bb062011-12-03 01:15:29 +00004596 assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
Aaron Ballman4f45b712014-03-21 15:22:56 +00004597 Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
4598 I->getImportedModule()));
Douglas Gregor959bb062011-12-03 01:15:29 +00004599 }
Richard Smith56be7542014-03-21 00:33:59 +00004600
4601 if (!Imports.empty()) {
4602 auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
4603 return A.ID < B.ID;
4604 };
Ben Langmuir5f95c8f2014-09-08 20:36:26 +00004605 auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
4606 return A.ID == B.ID;
4607 };
Richard Smith56be7542014-03-21 00:33:59 +00004608
4609 // Sort and deduplicate module IDs.
4610 std::sort(Imports.begin(), Imports.end(), Cmp);
Ben Langmuir5f95c8f2014-09-08 20:36:26 +00004611 Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
Richard Smith56be7542014-03-21 00:33:59 +00004612 Imports.end());
4613
4614 RecordData ImportedModules;
4615 for (const auto &Import : Imports) {
4616 ImportedModules.push_back(Import.ID);
4617 // FIXME: If the module has macros imported then later has declarations
4618 // imported, this location won't be the right one as a location for the
4619 // declaration imports.
Richard Smith10434f32015-05-02 02:08:26 +00004620 AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
Richard Smith56be7542014-03-21 00:33:59 +00004621 }
4622
Douglas Gregor959bb062011-12-03 01:15:29 +00004623 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
4624 }
Douglas Gregor0a839132011-12-03 00:59:55 +00004625 }
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004626
Douglas Gregor404cdde2012-01-27 01:47:08 +00004627 WriteObjCCategories();
Nico Weber779355f2016-03-02 23:22:00 +00004628 if(!WritingModule) {
Dario Domizioli13a0a382014-05-23 12:13:25 +00004629 WriteOptimizePragmaOptions(SemaRef);
Nico Weber779355f2016-03-02 23:22:00 +00004630 WriteMSStructPragmaOptions(SemaRef);
Nico Weber42932312016-03-03 00:17:35 +00004631 WriteMSPointersToMembersPragmaOptions(SemaRef);
Nico Weber779355f2016-03-02 23:22:00 +00004632 }
Richard Smithe40f2ba2013-08-07 21:41:30 +00004633
Douglas Gregor08f01292009-04-17 22:13:46 +00004634 // Some simple statistics
Mehdi Amini57a41912015-09-10 01:46:39 +00004635 RecordData::value_type Record[] = {
4636 NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts};
Sebastian Redl539c5062010-08-18 23:57:32 +00004637 Stream.EmitRecord(STATISTICS, Record);
Douglas Gregor8f45df52009-04-16 22:23:12 +00004638 Stream.ExitBlock();
Adrian Prantladbd2b12015-09-22 23:26:31 +00004639
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004640 // Write the module file extension blocks.
4641 for (const auto &ExtWriter : ModuleFileExtensionWriters)
Douglas Gregor8f64ca12015-12-08 22:43:32 +00004642 WriteModuleFileExtension(SemaRef, *ExtWriter);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004643
Adrian Prantladbd2b12015-09-22 23:26:31 +00004644 return Signature;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004645}
4646
Richard Smithb9eab6d2014-03-20 19:44:17 +00004647void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00004648 if (DeclUpdates.empty())
4649 return;
4650
Richard Smith59442b42014-03-20 20:07:19 +00004651 DeclUpdateMap LocalUpdates;
4652 LocalUpdates.swap(DeclUpdates);
4653
Richard Smith6ef42932014-03-20 21:02:00 +00004654 for (auto &DeclUpdate : LocalUpdates) {
4655 const Decl *D = DeclUpdate.first;
Argyrios Kyrtzidis3ba70b82010-10-24 17:26:46 +00004656
Richard Smithd28ac5b2014-03-22 23:33:22 +00004657 bool HasUpdatedBody = false;
Richard Smith69c82bf2016-04-01 22:52:03 +00004658 RecordData RecordData;
4659 ASTRecordWriter Record(*this, RecordData);
Richard Smith6ef42932014-03-20 21:02:00 +00004660 for (auto &Update : DeclUpdate.second) {
4661 DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
4662
Richard Smith69c82bf2016-04-01 22:52:03 +00004663 // An updated body is emitted last, so that the reader doesn't need
4664 // to skip over the lazy body to reach statements for other records.
4665 if (Kind == UPD_CXX_ADDED_FUNCTION_DEFINITION)
4666 HasUpdatedBody = true;
4667 else
4668 Record.push_back(Kind);
4669
Richard Smith6ef42932014-03-20 21:02:00 +00004670 switch (Kind) {
4671 case UPD_CXX_ADDED_IMPLICIT_MEMBER:
4672 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4673 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
Richard Smithcd45dbc2014-04-19 03:48:30 +00004674 assert(Update.getDecl() && "no decl to add?");
Richard Smith6ef42932014-03-20 21:02:00 +00004675 Record.push_back(GetDeclRef(Update.getDecl()));
4676 break;
4677
Richard Smith4d235792014-08-07 18:53:08 +00004678 case UPD_CXX_ADDED_FUNCTION_DEFINITION:
Richard Smithd28ac5b2014-03-22 23:33:22 +00004679 break;
4680
Richard Smith4d235792014-08-07 18:53:08 +00004681 case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
Richard Smith69c82bf2016-04-01 22:52:03 +00004682 Record.AddSourceLocation(Update.getLoc());
Richard Smith4d235792014-08-07 18:53:08 +00004683 break;
4684
John McCall32791cc2016-01-06 22:34:54 +00004685 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT:
4686 AddStmt(const_cast<Expr*>(
4687 cast<ParmVarDecl>(Update.getDecl())->getDefaultArg()));
4688 break;
4689
Richard Smithcd45dbc2014-04-19 03:48:30 +00004690 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
4691 auto *RD = cast<CXXRecordDecl>(D);
Chandler Carruth8a3d24d2015-03-26 04:27:10 +00004692 UpdatedDeclContexts.insert(RD->getPrimaryContext());
Richard Smith69c82bf2016-04-01 22:52:03 +00004693 Record.AddCXXDefinitionData(RD);
Richard Smithcd45dbc2014-04-19 03:48:30 +00004694 Record.push_back(WriteDeclContextLexicalBlock(
4695 *Context, const_cast<CXXRecordDecl *>(RD)));
4696
4697 // This state is sometimes updated by template instantiation, when we
4698 // switch from the specialization referring to the template declaration
4699 // to it referring to the template definition.
4700 if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
4701 Record.push_back(MSInfo->getTemplateSpecializationKind());
Richard Smith69c82bf2016-04-01 22:52:03 +00004702 Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
Richard Smithcd45dbc2014-04-19 03:48:30 +00004703 } else {
4704 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
4705 Record.push_back(Spec->getTemplateSpecializationKind());
Richard Smith69c82bf2016-04-01 22:52:03 +00004706 Record.AddSourceLocation(Spec->getPointOfInstantiation());
Richard Smithdf352052014-05-22 20:59:29 +00004707
4708 // The instantiation might have been resolved to a partial
4709 // specialization. If so, record which one.
4710 auto From = Spec->getInstantiatedFrom();
4711 if (auto PartialSpec =
4712 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
4713 Record.push_back(true);
Richard Smith69c82bf2016-04-01 22:52:03 +00004714 Record.AddDeclRef(PartialSpec);
4715 Record.AddTemplateArgumentList(
4716 &Spec->getTemplateInstantiationArgs());
Richard Smithdf352052014-05-22 20:59:29 +00004717 } else {
4718 Record.push_back(false);
4719 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00004720 }
4721 Record.push_back(RD->getTagKind());
Richard Smith69c82bf2016-04-01 22:52:03 +00004722 Record.AddSourceLocation(RD->getLocation());
4723 Record.AddSourceLocation(RD->getLocStart());
4724 Record.AddSourceLocation(RD->getRBraceLoc());
Richard Smithcd45dbc2014-04-19 03:48:30 +00004725
4726 // Instantiation may change attributes; write them all out afresh.
4727 Record.push_back(D->hasAttrs());
Richard Smith69c82bf2016-04-01 22:52:03 +00004728 if (D->hasAttrs())
4729 Record.AddAttributes(D->getAttrs());
Richard Smithcd45dbc2014-04-19 03:48:30 +00004730
4731 // FIXME: Ensure we don't get here for explicit instantiations.
4732 break;
4733 }
4734
Richard Smithf8134002015-03-10 01:41:22 +00004735 case UPD_CXX_RESOLVED_DTOR_DELETE:
Richard Smith69c82bf2016-04-01 22:52:03 +00004736 Record.AddDeclRef(Update.getDecl());
Richard Smithf8134002015-03-10 01:41:22 +00004737 break;
4738
Richard Smith564417a2014-03-20 21:47:22 +00004739 case UPD_CXX_RESOLVED_EXCEPTION_SPEC:
4740 addExceptionSpec(
4741 *this,
4742 cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>(),
4743 Record);
4744 break;
4745
Richard Smith6ef42932014-03-20 21:02:00 +00004746 case UPD_CXX_DEDUCED_RETURN_TYPE:
4747 Record.push_back(GetOrCreateTypeID(Update.getType()));
4748 break;
4749
4750 case UPD_DECL_MARKED_USED:
4751 break;
Richard Smith5652c0f2014-03-21 01:48:23 +00004752
4753 case UPD_MANGLING_NUMBER:
4754 case UPD_STATIC_LOCAL_NUMBER:
4755 Record.push_back(Update.getNumber());
4756 break;
Richard Smith65ebb4a2015-03-26 04:09:53 +00004757
Alexey Bataev97720002014-11-11 04:05:39 +00004758 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
Richard Smith69c82bf2016-04-01 22:52:03 +00004759 Record.AddSourceRange(
4760 D->getAttr<OMPThreadPrivateDeclAttr>()->getRange());
Alexey Bataev97720002014-11-11 04:05:39 +00004761 break;
Richard Smith65ebb4a2015-03-26 04:09:53 +00004762
4763 case UPD_DECL_EXPORTED:
Richard Smith4caa4492015-05-15 02:34:32 +00004764 Record.push_back(getSubmoduleID(Update.getModule()));
Richard Smith65ebb4a2015-03-26 04:09:53 +00004765 break;
Alex Denisovfde64952015-06-26 05:28:36 +00004766
4767 case UPD_ADDED_ATTR_TO_RECORD:
Richard Smith69c82bf2016-04-01 22:52:03 +00004768 Record.AddAttributes(llvm::makeArrayRef(Update.getAttr()));
Alex Denisovfde64952015-06-26 05:28:36 +00004769 break;
Richard Smith6ef42932014-03-20 21:02:00 +00004770 }
4771 }
4772
Richard Smithd28ac5b2014-03-22 23:33:22 +00004773 if (HasUpdatedBody) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004774 const auto *Def = cast<FunctionDecl>(D);
Richard Smith4d235792014-08-07 18:53:08 +00004775 Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
Richard Smithd28ac5b2014-03-22 23:33:22 +00004776 Record.push_back(Def->isInlined());
Richard Smith69c82bf2016-04-01 22:52:03 +00004777 Record.AddSourceLocation(Def->getInnerLocStart());
4778 AddFunctionDefinition(Def, Record.getRecordData());
Richard Smithd28ac5b2014-03-22 23:33:22 +00004779 }
4780
Richard Smithcd45dbc2014-04-19 03:48:30 +00004781 OffsetsRecord.push_back(GetDeclRef(D));
Richard Smith69c82bf2016-04-01 22:52:03 +00004782 OffsetsRecord.push_back(Record.Emit(DECL_UPDATES));
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00004783
Richard Smithc2bb8182015-03-24 06:36:48 +00004784 FlushPendingAfterDecl();
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00004785 }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00004786}
4787
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004788void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
Richard Smithb22a1d12016-03-27 20:13:24 +00004789 uint32_t Raw = Loc.getRawEncoding();
4790 Record.push_back((Raw << 1) | (Raw >> 31));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004791}
4792
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004793void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
Chris Lattnerca025db2010-05-07 21:43:38 +00004794 AddSourceLocation(Range.getBegin(), Record);
4795 AddSourceLocation(Range.getEnd(), Record);
4796}
4797
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004798void ASTWriter::AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004799 Record.push_back(Value.getBitWidth());
Benjamin Kramer25f9ea62010-09-06 23:43:28 +00004800 const uint64_t *Words = Value.getRawData();
4801 Record.append(Words, Words + Value.getNumWords());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004802}
4803
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004804void ASTWriter::AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record) {
Douglas Gregor1daeb692009-04-13 18:14:40 +00004805 Record.push_back(Value.isUnsigned());
4806 AddAPInt(Value, Record);
4807}
4808
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004809void ASTWriter::AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record) {
Douglas Gregore0a3a512009-04-14 21:55:33 +00004810 AddAPInt(Value.bitcastToAPInt(), Record);
4811}
4812
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004813void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
Douglas Gregor4621c6a2009-04-22 18:49:13 +00004814 Record.push_back(getIdentifierRef(II));
4815}
4816
Sebastian Redl539c5062010-08-18 23:57:32 +00004817IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
Craig Toppera13603a2014-05-22 05:54:18 +00004818 if (!II)
Douglas Gregor4621c6a2009-04-22 18:49:13 +00004819 return 0;
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00004820
Sebastian Redl539c5062010-08-18 23:57:32 +00004821 IdentID &ID = IdentifierIDs[II];
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00004822 if (ID == 0)
Sebastian Redlff4a2952010-07-23 23:49:55 +00004823 ID = NextIdentID++;
Douglas Gregor4621c6a2009-04-22 18:49:13 +00004824 return ID;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004825}
4826
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004827MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004828 // Don't emit builtin macros like __LINE__ to the AST file unless they
4829 // have been redefined by the header (in which case they are not
4830 // isBuiltinMacro).
Craig Toppera13603a2014-05-22 05:54:18 +00004831 if (!MI || MI->isBuiltinMacro())
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004832 return 0;
4833
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004834 MacroID &ID = MacroIDs[MI];
4835 if (ID == 0) {
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004836 ID = NextMacroID++;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004837 MacroInfoToEmitData Info = { Name, MI, ID };
4838 MacroInfosToEmit.push_back(Info);
4839 }
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004840 return ID;
4841}
4842
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004843MacroID ASTWriter::getMacroID(MacroInfo *MI) {
Craig Toppera13603a2014-05-22 05:54:18 +00004844 if (!MI || MI->isBuiltinMacro())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004845 return 0;
4846
4847 assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
4848 return MacroIDs[MI];
4849}
4850
4851uint64_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
Richard Smithd7329392015-04-21 21:46:32 +00004852 return IdentMacroDirectivesOffsetMap.lookup(Name);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00004853}
4854
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004855void ASTWriter::AddSelectorRef(const Selector SelRef, RecordDataImpl &Record) {
Sebastian Redl834bb972010-08-04 17:20:04 +00004856 Record.push_back(getSelectorRef(SelRef));
4857}
4858
Sebastian Redl539c5062010-08-18 23:57:32 +00004859SelectorID ASTWriter::getSelectorRef(Selector Sel) {
Craig Toppera13603a2014-05-22 05:54:18 +00004860 if (Sel.getAsOpaquePtr() == nullptr) {
Sebastian Redl834bb972010-08-04 17:20:04 +00004861 return 0;
Steve Naroff2ddea052009-04-23 10:39:46 +00004862 }
4863
Douglas Gregor8d7edce2013-02-08 21:30:59 +00004864 SelectorID SID = SelectorIDs[Sel];
Sebastian Redld95a56e2010-08-04 18:21:41 +00004865 if (SID == 0 && Chain) {
4866 // This might trigger a ReadSelector callback, which will set the ID for
4867 // this selector.
4868 Chain->LoadSelector(Sel);
Douglas Gregor8d7edce2013-02-08 21:30:59 +00004869 SID = SelectorIDs[Sel];
Sebastian Redld95a56e2010-08-04 18:21:41 +00004870 }
Steve Naroff2ddea052009-04-23 10:39:46 +00004871 if (SID == 0) {
Sebastian Redld95a56e2010-08-04 18:21:41 +00004872 SID = NextSelectorID++;
Douglas Gregor8d7edce2013-02-08 21:30:59 +00004873 SelectorIDs[Sel] = SID;
Steve Naroff2ddea052009-04-23 10:39:46 +00004874 }
Sebastian Redl834bb972010-08-04 17:20:04 +00004875 return SID;
Steve Naroff2ddea052009-04-23 10:39:46 +00004876}
4877
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004878void ASTWriter::AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record) {
Chris Lattnercba86142010-05-10 00:25:06 +00004879 AddDeclRef(Temp->getDestructor(), Record);
4880}
4881
Richard Smithc2bb8182015-03-24 06:36:48 +00004882void ASTWriter::AddCXXCtorInitializersRef(ArrayRef<CXXCtorInitializer *> Inits,
4883 RecordDataImpl &Record) {
4884 assert(!Inits.empty() && "Empty ctor initializer sets are not recorded");
4885 CXXCtorInitializersToWrite.push_back(
4886 QueuedCXXCtorInitializers(NextCXXCtorInitializersID, Inits));
4887 Record.push_back(NextCXXCtorInitializersID++);
4888}
4889
Douglas Gregord4c5ed02010-10-29 22:39:52 +00004890void ASTWriter::AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases,
Richard Smithc2bb8182015-03-24 06:36:48 +00004891 CXXBaseSpecifier const *BasesEnd,
Douglas Gregord4c5ed02010-10-29 22:39:52 +00004892 RecordDataImpl &Record) {
4893 assert(Bases != BasesEnd && "Empty base-specifier sets are not recorded");
4894 CXXBaseSpecifiersToWrite.push_back(
4895 QueuedCXXBaseSpecifiers(NextCXXBaseSpecifiersID,
4896 Bases, BasesEnd));
4897 Record.push_back(NextCXXBaseSpecifiersID++);
4898}
4899
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004900void ASTWriter::AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004901 const TemplateArgumentLocInfo &Arg,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004902 RecordDataImpl &Record) {
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004903 switch (Kind) {
John McCall0ad16662009-10-29 08:12:44 +00004904 case TemplateArgument::Expression:
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004905 AddStmt(Arg.getAsExpr());
John McCall0ad16662009-10-29 08:12:44 +00004906 break;
4907 case TemplateArgument::Type:
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004908 AddTypeSourceInfo(Arg.getAsTypeSourceInfo(), Record);
John McCall0ad16662009-10-29 08:12:44 +00004909 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004910 case TemplateArgument::Template:
Douglas Gregor9d802122011-03-02 17:09:35 +00004911 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00004912 AddSourceLocation(Arg.getTemplateNameLoc(), Record);
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004913 break;
4914 case TemplateArgument::TemplateExpansion:
Douglas Gregor9d802122011-03-02 17:09:35 +00004915 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004916 AddSourceLocation(Arg.getTemplateNameLoc(), Record);
Douglas Gregoreb29d182011-01-05 17:40:24 +00004917 AddSourceLocation(Arg.getTemplateEllipsisLoc(), Record);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004918 break;
John McCall0ad16662009-10-29 08:12:44 +00004919 case TemplateArgument::Null:
4920 case TemplateArgument::Integral:
4921 case TemplateArgument::Declaration:
Eli Friedmanb826a002012-09-26 02:36:12 +00004922 case TemplateArgument::NullPtr:
John McCall0ad16662009-10-29 08:12:44 +00004923 case TemplateArgument::Pack:
Eli Friedmanb826a002012-09-26 02:36:12 +00004924 // FIXME: Is this right?
John McCall0ad16662009-10-29 08:12:44 +00004925 break;
4926 }
4927}
4928
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004929void ASTWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004930 RecordDataImpl &Record) {
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004931 AddTemplateArgument(Arg.getArgument(), Record);
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00004932
4933 if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
4934 bool InfoHasSameExpr
4935 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
4936 Record.push_back(InfoHasSameExpr);
4937 if (InfoHasSameExpr)
4938 return; // Avoid storing the same expr twice.
4939 }
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00004940 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo(),
4941 Record);
4942}
4943
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004944void ASTWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo,
4945 RecordDataImpl &Record) {
Craig Toppera13603a2014-05-22 05:54:18 +00004946 if (!TInfo) {
John McCall8f115c62009-10-16 21:56:05 +00004947 AddTypeRef(QualType(), Record);
4948 return;
4949 }
4950
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004951 AddTypeLoc(TInfo->getTypeLoc(), Record);
4952}
4953
4954void ASTWriter::AddTypeLoc(TypeLoc TL, RecordDataImpl &Record) {
4955 AddTypeRef(TL.getType(), Record);
4956
John McCall8f115c62009-10-16 21:56:05 +00004957 TypeLocWriter TLW(*this, Record);
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004958 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00004959 TLW.Visit(TL);
John McCall8f115c62009-10-16 21:56:05 +00004960}
4961
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00004962void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
Argyrios Kyrtzidis9ab44ea2010-08-20 16:04:14 +00004963 Record.push_back(GetOrCreateTypeID(T));
4964}
4965
Richard Smith2095ffe2015-03-16 20:11:03 +00004966TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
Richard Smith1fa5d642013-05-11 05:45:24 +00004967 assert(Context);
Richard Smith2095ffe2015-03-16 20:11:03 +00004968 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
4969 if (T.isNull())
4970 return TypeIdx();
4971 assert(!T.getLocalFastQualifiers());
4972
4973 TypeIdx &Idx = TypeIdxs[T];
4974 if (Idx.getIndex() == 0) {
4975 if (DoneWritingDeclsAndTypes) {
4976 assert(0 && "New type seen after serializing all the types to emit!");
4977 return TypeIdx();
4978 }
4979
4980 // We haven't seen this type before. Assign it a new ID and put it
4981 // into the queue of types to emit.
4982 Idx = TypeIdx(NextTypeID++);
4983 DeclTypesToEmit.push(T);
4984 }
4985 return Idx;
4986 });
Argyrios Kyrtzidis082e4612010-08-20 16:04:20 +00004987}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004988
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00004989TypeID ASTWriter::getTypeID(QualType T) const {
Richard Smith1fa5d642013-05-11 05:45:24 +00004990 assert(Context);
Richard Smith2095ffe2015-03-16 20:11:03 +00004991 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
4992 if (T.isNull())
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004993 return TypeIdx();
Richard Smith2095ffe2015-03-16 20:11:03 +00004994 assert(!T.getLocalFastQualifiers());
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004995
Richard Smith2095ffe2015-03-16 20:11:03 +00004996 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
4997 assert(I != TypeIdxs.end() && "Type not emitted!");
4998 return I->second;
4999 });
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005000}
5001
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005002void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005003 Record.push_back(GetDeclRef(D));
5004}
5005
Sebastian Redl539c5062010-08-18 23:57:32 +00005006DeclID ASTWriter::GetDeclRef(const Decl *D) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005007 assert(WritingAST && "Cannot request a declaration ID before AST writing");
Craig Toppera13603a2014-05-22 05:54:18 +00005008
5009 if (!D) {
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005010 return 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005011 }
Douglas Gregorb3163e52012-01-05 22:33:30 +00005012
5013 // If D comes from an AST file, its declaration ID is already known and
5014 // fixed.
5015 if (D->isFromASTFile())
5016 return D->getGlobalID();
5017
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005018 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
Sebastian Redl539c5062010-08-18 23:57:32 +00005019 DeclID &ID = DeclIDs[D];
Mike Stump11289f42009-09-09 15:08:12 +00005020 if (ID == 0) {
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005021 if (DoneWritingDeclsAndTypes) {
5022 assert(0 && "New decl seen after serializing all the decls to emit!");
5023 return 0;
5024 }
5025
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005026 // We haven't seen this declaration before. Give it a new ID and
5027 // enqueue it in the list of declarations to emit.
Sebastian Redlff4a2952010-07-23 23:49:55 +00005028 ID = NextDeclID++;
Douglas Gregor12bfa382009-10-17 00:13:19 +00005029 DeclTypesToEmit.push(const_cast<Decl *>(D));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005030 }
5031
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005032 return ID;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005033}
5034
Sebastian Redl539c5062010-08-18 23:57:32 +00005035DeclID ASTWriter::getDeclID(const Decl *D) {
Craig Toppera13603a2014-05-22 05:54:18 +00005036 if (!D)
Douglas Gregore84a9da2009-04-20 20:36:09 +00005037 return 0;
5038
Douglas Gregorb3163e52012-01-05 22:33:30 +00005039 // If D comes from an AST file, its declaration ID is already known and
5040 // fixed.
5041 if (D->isFromASTFile())
5042 return D->getGlobalID();
5043
Douglas Gregore84a9da2009-04-20 20:36:09 +00005044 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
5045 return DeclIDs[D];
5046}
5047
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005048void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005049 assert(ID);
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005050 assert(D);
5051
5052 SourceLocation Loc = D->getLocation();
5053 if (Loc.isInvalid())
5054 return;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005055
5056 // We only keep track of the file-level declarations of each file.
5057 if (!D->getLexicalDeclContext()->isFileContext())
5058 return;
Argyrios Kyrtzidise1bc99e2012-02-24 19:45:46 +00005059 // FIXME: ParmVarDecls that are part of a function type of a parameter of
5060 // a function/objc method, should not have TU as lexical context.
Argyrios Kyrtzidisffe055a82012-02-24 01:12:38 +00005061 if (isa<ParmVarDecl>(D))
5062 return;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005063
5064 SourceManager &SM = Context->getSourceManager();
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005065 SourceLocation FileLoc = SM.getFileLoc(Loc);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005066 assert(SM.isLocalSourceLocation(FileLoc));
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005067 FileID FID;
5068 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00005069 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005070 if (FID.isInvalid())
5071 return;
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00005072 assert(SM.getSLocEntry(FID).isFile());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005073
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00005074 DeclIDInFileInfo *&Info = FileDeclIDs[FID];
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005075 if (!Info)
5076 Info = new DeclIDInFileInfo();
5077
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005078 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005079 LocDeclIDsTy &Decls = Info->DeclIDs;
5080
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005081 if (Decls.empty() || Decls.back().first <= Offset) {
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005082 Decls.push_back(LocDecl);
5083 return;
5084 }
5085
Benjamin Kramer45025c02013-08-24 13:22:59 +00005086 LocDeclIDsTy::iterator I =
5087 std::upper_bound(Decls.begin(), Decls.end(), LocDecl, llvm::less_first());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005088
5089 Decls.insert(I, LocDecl);
5090}
5091
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005092void ASTWriter::AddDeclarationName(DeclarationName Name, RecordDataImpl &Record) {
Chris Lattner258172e2009-04-27 07:35:58 +00005093 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005094 Record.push_back(Name.getNameKind());
5095 switch (Name.getNameKind()) {
5096 case DeclarationName::Identifier:
5097 AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
5098 break;
5099
5100 case DeclarationName::ObjCZeroArgSelector:
5101 case DeclarationName::ObjCOneArgSelector:
5102 case DeclarationName::ObjCMultiArgSelector:
Steve Naroff2ddea052009-04-23 10:39:46 +00005103 AddSelectorRef(Name.getObjCSelector(), Record);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005104 break;
5105
5106 case DeclarationName::CXXConstructorName:
5107 case DeclarationName::CXXDestructorName:
5108 case DeclarationName::CXXConversionFunctionName:
5109 AddTypeRef(Name.getCXXNameType(), Record);
5110 break;
5111
5112 case DeclarationName::CXXOperatorName:
5113 Record.push_back(Name.getCXXOverloadedOperator());
5114 break;
5115
Alexis Hunt3d221f22009-11-29 07:34:05 +00005116 case DeclarationName::CXXLiteralOperatorName:
5117 AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record);
5118 break;
5119
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005120 case DeclarationName::CXXUsingDirective:
5121 // No extra data to emit
5122 break;
5123 }
5124}
Chris Lattnerca025db2010-05-07 21:43:38 +00005125
Richard Smithd08aeb62014-08-28 01:33:39 +00005126unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
5127 assert(needsAnonymousDeclarationNumber(D) &&
5128 "expected an anonymous declaration");
5129
5130 // Number the anonymous declarations within this context, if we've not
5131 // already done so.
5132 auto It = AnonymousDeclarationNumbers.find(D);
5133 if (It == AnonymousDeclarationNumbers.end()) {
Richard Smith2b560572015-02-07 03:11:11 +00005134 auto *DC = D->getLexicalDeclContext();
5135 numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
5136 AnonymousDeclarationNumbers[ND] = Number;
5137 });
Richard Smithd08aeb62014-08-28 01:33:39 +00005138
5139 It = AnonymousDeclarationNumbers.find(D);
5140 assert(It != AnonymousDeclarationNumbers.end() &&
5141 "declaration not found within its lexical context");
5142 }
5143
5144 return It->second;
5145}
5146
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005147void ASTWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005148 DeclarationName Name, RecordDataImpl &Record) {
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005149 switch (Name.getNameKind()) {
5150 case DeclarationName::CXXConstructorName:
5151 case DeclarationName::CXXDestructorName:
5152 case DeclarationName::CXXConversionFunctionName:
5153 AddTypeSourceInfo(DNLoc.NamedType.TInfo, Record);
5154 break;
5155
5156 case DeclarationName::CXXOperatorName:
5157 AddSourceLocation(
5158 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.BeginOpNameLoc),
5159 Record);
5160 AddSourceLocation(
5161 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc),
5162 Record);
5163 break;
5164
5165 case DeclarationName::CXXLiteralOperatorName:
5166 AddSourceLocation(
5167 SourceLocation::getFromRawEncoding(DNLoc.CXXLiteralOperatorName.OpNameLoc),
5168 Record);
5169 break;
5170
5171 case DeclarationName::Identifier:
5172 case DeclarationName::ObjCZeroArgSelector:
5173 case DeclarationName::ObjCOneArgSelector:
5174 case DeclarationName::ObjCMultiArgSelector:
5175 case DeclarationName::CXXUsingDirective:
5176 break;
5177 }
5178}
5179
5180void ASTWriter::AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005181 RecordDataImpl &Record) {
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005182 AddDeclarationName(NameInfo.getName(), Record);
5183 AddSourceLocation(NameInfo.getLoc(), Record);
5184 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName(), Record);
5185}
5186
5187void ASTWriter::AddQualifierInfo(const QualifierInfo &Info,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005188 RecordDataImpl &Record) {
Douglas Gregor14454802011-02-25 02:25:35 +00005189 AddNestedNameSpecifierLoc(Info.QualifierLoc, Record);
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005190 Record.push_back(Info.NumTemplParamLists);
5191 for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i)
5192 AddTemplateParameterList(Info.TemplParamLists[i], Record);
5193}
5194
Sebastian Redl55c0ad52010-08-18 23:56:21 +00005195void ASTWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005196 RecordDataImpl &Record) {
Chris Lattnerca025db2010-05-07 21:43:38 +00005197 // Nested name specifiers usually aren't too long. I think that 8 would
Chris Lattner57540c52011-04-15 05:22:18 +00005198 // typically accommodate the vast majority.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005199 SmallVector<NestedNameSpecifier *, 8> NestedNames;
Chris Lattnerca025db2010-05-07 21:43:38 +00005200
5201 // Push each of the NNS's onto a stack for serialization in reverse order.
5202 while (NNS) {
5203 NestedNames.push_back(NNS);
5204 NNS = NNS->getPrefix();
5205 }
5206
5207 Record.push_back(NestedNames.size());
5208 while(!NestedNames.empty()) {
5209 NNS = NestedNames.pop_back_val();
5210 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
5211 Record.push_back(Kind);
5212 switch (Kind) {
5213 case NestedNameSpecifier::Identifier:
5214 AddIdentifierRef(NNS->getAsIdentifier(), Record);
5215 break;
5216
5217 case NestedNameSpecifier::Namespace:
5218 AddDeclRef(NNS->getAsNamespace(), Record);
5219 break;
5220
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005221 case NestedNameSpecifier::NamespaceAlias:
5222 AddDeclRef(NNS->getAsNamespaceAlias(), Record);
5223 break;
5224
Chris Lattnerca025db2010-05-07 21:43:38 +00005225 case NestedNameSpecifier::TypeSpec:
5226 case NestedNameSpecifier::TypeSpecWithTemplate:
5227 AddTypeRef(QualType(NNS->getAsType(), 0), Record);
5228 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5229 break;
5230
5231 case NestedNameSpecifier::Global:
5232 // Don't need to write an associated value.
5233 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00005234
5235 case NestedNameSpecifier::Super:
5236 AddDeclRef(NNS->getAsRecordDecl(), Record);
5237 break;
Chris Lattnerca025db2010-05-07 21:43:38 +00005238 }
5239 }
5240}
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005241
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005242void ASTWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
5243 RecordDataImpl &Record) {
5244 // Nested name specifiers usually aren't too long. I think that 8 would
Chris Lattner57540c52011-04-15 05:22:18 +00005245 // typically accommodate the vast majority.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005246 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005247
5248 // Push each of the nested-name-specifiers's onto a stack for
5249 // serialization in reverse order.
5250 while (NNS) {
5251 NestedNames.push_back(NNS);
5252 NNS = NNS.getPrefix();
5253 }
5254
5255 Record.push_back(NestedNames.size());
5256 while(!NestedNames.empty()) {
5257 NNS = NestedNames.pop_back_val();
5258 NestedNameSpecifier::SpecifierKind Kind
5259 = NNS.getNestedNameSpecifier()->getKind();
5260 Record.push_back(Kind);
5261 switch (Kind) {
5262 case NestedNameSpecifier::Identifier:
5263 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier(), Record);
5264 AddSourceRange(NNS.getLocalSourceRange(), Record);
5265 break;
5266
5267 case NestedNameSpecifier::Namespace:
5268 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace(), Record);
5269 AddSourceRange(NNS.getLocalSourceRange(), Record);
5270 break;
5271
5272 case NestedNameSpecifier::NamespaceAlias:
5273 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias(), Record);
5274 AddSourceRange(NNS.getLocalSourceRange(), Record);
5275 break;
5276
5277 case NestedNameSpecifier::TypeSpec:
5278 case NestedNameSpecifier::TypeSpecWithTemplate:
5279 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5280 AddTypeLoc(NNS.getTypeLoc(), Record);
5281 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
5282 break;
5283
5284 case NestedNameSpecifier::Global:
5285 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
5286 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00005287
5288 case NestedNameSpecifier::Super:
5289 AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl(), Record);
5290 AddSourceRange(NNS.getLocalSourceRange(), Record);
5291 break;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005292 }
5293 }
5294}
5295
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005296void ASTWriter::AddTemplateName(TemplateName Name, RecordDataImpl &Record) {
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005297 TemplateName::NameKind Kind = Name.getKind();
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005298 Record.push_back(Kind);
5299 switch (Kind) {
5300 case TemplateName::Template:
5301 AddDeclRef(Name.getAsTemplateDecl(), Record);
5302 break;
5303
5304 case TemplateName::OverloadedTemplate: {
5305 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
5306 Record.push_back(OvT->size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005307 for (const auto &I : *OvT)
5308 AddDeclRef(I, Record);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005309 break;
5310 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005311
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005312 case TemplateName::QualifiedTemplate: {
5313 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
5314 AddNestedNameSpecifier(QualT->getQualifier(), Record);
5315 Record.push_back(QualT->hasTemplateKeyword());
5316 AddDeclRef(QualT->getTemplateDecl(), Record);
5317 break;
5318 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005319
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005320 case TemplateName::DependentTemplate: {
5321 DependentTemplateName *DepT = Name.getAsDependentTemplateName();
5322 AddNestedNameSpecifier(DepT->getQualifier(), Record);
5323 Record.push_back(DepT->isIdentifier());
5324 if (DepT->isIdentifier())
5325 AddIdentifierRef(DepT->getIdentifier(), Record);
5326 else
5327 Record.push_back(DepT->getOperator());
5328 break;
5329 }
John McCalld9dfe3a2011-06-30 08:33:18 +00005330
5331 case TemplateName::SubstTemplateTemplateParm: {
5332 SubstTemplateTemplateParmStorage *subst
5333 = Name.getAsSubstTemplateTemplateParm();
5334 AddDeclRef(subst->getParameter(), Record);
5335 AddTemplateName(subst->getReplacement(), Record);
5336 break;
5337 }
Douglas Gregor5590be02011-01-15 06:45:20 +00005338
5339 case TemplateName::SubstTemplateTemplateParmPack: {
5340 SubstTemplateTemplateParmPackStorage *SubstPack
5341 = Name.getAsSubstTemplateTemplateParmPack();
5342 AddDeclRef(SubstPack->getParameterPack(), Record);
5343 AddTemplateArgument(SubstPack->getArgumentPack(), Record);
5344 break;
5345 }
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005346 }
5347}
5348
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005349void ASTWriter::AddTemplateArgument(const TemplateArgument &Arg,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005350 RecordDataImpl &Record) {
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005351 Record.push_back(Arg.getKind());
5352 switch (Arg.getKind()) {
5353 case TemplateArgument::Null:
5354 break;
5355 case TemplateArgument::Type:
5356 AddTypeRef(Arg.getAsType(), Record);
5357 break;
5358 case TemplateArgument::Declaration:
5359 AddDeclRef(Arg.getAsDecl(), Record);
David Blaikie952a9b12014-10-17 18:00:12 +00005360 AddTypeRef(Arg.getParamTypeForDecl(), Record);
Eli Friedmanb826a002012-09-26 02:36:12 +00005361 break;
5362 case TemplateArgument::NullPtr:
5363 AddTypeRef(Arg.getNullPtrType(), Record);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005364 break;
5365 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005366 AddAPSInt(Arg.getAsIntegral(), Record);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005367 AddTypeRef(Arg.getIntegralType(), Record);
5368 break;
5369 case TemplateArgument::Template:
Douglas Gregore1d60df2011-01-14 23:41:42 +00005370 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
5371 break;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005372 case TemplateArgument::TemplateExpansion:
5373 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
David Blaikie05785d12013-02-20 22:23:23 +00005374 if (Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
Douglas Gregore1d60df2011-01-14 23:41:42 +00005375 Record.push_back(*NumExpansions + 1);
5376 else
5377 Record.push_back(0);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005378 break;
5379 case TemplateArgument::Expression:
5380 AddStmt(Arg.getAsExpr());
5381 break;
5382 case TemplateArgument::Pack:
5383 Record.push_back(Arg.pack_size());
Aaron Ballman2a89e852014-07-15 21:32:31 +00005384 for (const auto &P : Arg.pack_elements())
5385 AddTemplateArgument(P, Record);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005386 break;
5387 }
5388}
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005389
5390void
Sebastian Redl55c0ad52010-08-18 23:56:21 +00005391ASTWriter::AddTemplateParameterList(const TemplateParameterList *TemplateParams,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005392 RecordDataImpl &Record) {
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005393 assert(TemplateParams && "No TemplateParams!");
5394 AddSourceLocation(TemplateParams->getTemplateLoc(), Record);
5395 AddSourceLocation(TemplateParams->getLAngleLoc(), Record);
5396 AddSourceLocation(TemplateParams->getRAngleLoc(), Record);
5397 Record.push_back(TemplateParams->size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005398 for (const auto &P : *TemplateParams)
5399 AddDeclRef(P, Record);
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005400}
5401
5402/// \brief Emit a template argument list.
5403void
Sebastian Redl55c0ad52010-08-18 23:56:21 +00005404ASTWriter::AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005405 RecordDataImpl &Record) {
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005406 assert(TemplateArgs && "No TemplateArgs!");
Douglas Gregor1ccc8412010-11-07 23:05:16 +00005407 Record.push_back(TemplateArgs->size());
5408 for (int i=0, e = TemplateArgs->size(); i != e; ++i)
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005409 AddTemplateArgument(TemplateArgs->get(i), Record);
5410}
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005411
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005412void
5413ASTWriter::AddASTTemplateArgumentListInfo
5414(const ASTTemplateArgumentListInfo *ASTTemplArgList, RecordDataImpl &Record) {
5415 assert(ASTTemplArgList && "No ASTTemplArgList!");
5416 AddSourceLocation(ASTTemplArgList->LAngleLoc, Record);
5417 AddSourceLocation(ASTTemplArgList->RAngleLoc, Record);
5418 Record.push_back(ASTTemplArgList->NumTemplateArgs);
5419 const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
5420 for (int i=0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
5421 AddTemplateArgumentLoc(TemplArgs[i], Record);
5422}
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005423
5424void
Argyrios Kyrtzidis0f05fb92012-11-28 03:56:16 +00005425ASTWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set, RecordDataImpl &Record) {
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005426 Record.push_back(Set.size());
Argyrios Kyrtzidis0f05fb92012-11-28 03:56:16 +00005427 for (ASTUnresolvedSet::const_iterator
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005428 I = Set.begin(), E = Set.end(); I != E; ++I) {
5429 AddDeclRef(I.getDecl(), Record);
5430 Record.push_back(I.getAccess());
5431 }
5432}
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005433
Sebastian Redl55c0ad52010-08-18 23:56:21 +00005434void ASTWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005435 RecordDataImpl &Record) {
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005436 Record.push_back(Base.isVirtual());
5437 Record.push_back(Base.isBaseOfClass());
5438 Record.push_back(Base.getAccessSpecifierAsWritten());
Sebastian Redl08905022011-02-05 19:23:19 +00005439 Record.push_back(Base.getInheritConstructors());
Nick Lewycky19b9f952010-07-26 16:56:01 +00005440 AddTypeSourceInfo(Base.getTypeSourceInfo(), Record);
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005441 AddSourceRange(Base.getSourceRange(), Record);
Douglas Gregor752a5952011-01-03 22:36:02 +00005442 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
5443 : SourceLocation(),
5444 Record);
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005445}
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00005446
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005447void ASTWriter::FlushCXXBaseSpecifiers() {
5448 RecordData Record;
Richard Smithc2bb8182015-03-24 06:36:48 +00005449 unsigned N = CXXBaseSpecifiersToWrite.size();
5450 for (unsigned I = 0; I != N; ++I) {
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005451 Record.clear();
5452
5453 // Record the offset of this base-specifier set.
Douglas Gregorc27b2872011-08-04 00:01:48 +00005454 unsigned Index = CXXBaseSpecifiersToWrite[I].ID - 1;
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005455 if (Index == CXXBaseSpecifiersOffsets.size())
5456 CXXBaseSpecifiersOffsets.push_back(Stream.GetCurrentBitNo());
5457 else {
5458 if (Index > CXXBaseSpecifiersOffsets.size())
5459 CXXBaseSpecifiersOffsets.resize(Index + 1);
5460 CXXBaseSpecifiersOffsets[Index] = Stream.GetCurrentBitNo();
5461 }
5462
5463 const CXXBaseSpecifier *B = CXXBaseSpecifiersToWrite[I].Bases,
5464 *BEnd = CXXBaseSpecifiersToWrite[I].BasesEnd;
5465 Record.push_back(BEnd - B);
5466 for (; B != BEnd; ++B)
5467 AddCXXBaseSpecifier(*B, Record);
5468 Stream.EmitRecord(serialization::DECL_CXX_BASE_SPECIFIERS, Record);
Douglas Gregord5853042010-10-30 04:28:16 +00005469
5470 // Flush any expressions that were written as part of the base specifiers.
5471 FlushStmts();
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005472 }
5473
Richard Smithc2bb8182015-03-24 06:36:48 +00005474 assert(N == CXXBaseSpecifiersToWrite.size() &&
5475 "added more base specifiers while writing base specifiers");
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005476 CXXBaseSpecifiersToWrite.clear();
5477}
5478
Alexis Hunt1d792652011-01-08 20:30:50 +00005479void ASTWriter::AddCXXCtorInitializers(
5480 const CXXCtorInitializer * const *CtorInitializers,
5481 unsigned NumCtorInitializers,
5482 RecordDataImpl &Record) {
5483 Record.push_back(NumCtorInitializers);
5484 for (unsigned i=0; i != NumCtorInitializers; ++i) {
5485 const CXXCtorInitializer *Init = CtorInitializers[i];
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005486
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005487 if (Init->isBaseInitializer()) {
Alexis Hunt37a477f2011-05-04 01:19:08 +00005488 Record.push_back(CTOR_INITIALIZER_BASE);
Douglas Gregord73f3dd2011-11-01 01:16:03 +00005489 AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005490 Record.push_back(Init->isBaseVirtual());
Alexis Hunt37a477f2011-05-04 01:19:08 +00005491 } else if (Init->isDelegatingInitializer()) {
5492 Record.push_back(CTOR_INITIALIZER_DELEGATING);
Douglas Gregord73f3dd2011-11-01 01:16:03 +00005493 AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
Alexis Hunt37a477f2011-05-04 01:19:08 +00005494 } else if (Init->isMemberInitializer()){
5495 Record.push_back(CTOR_INITIALIZER_MEMBER);
5496 AddDeclRef(Init->getMember(), Record);
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005497 } else {
Alexis Hunt37a477f2011-05-04 01:19:08 +00005498 Record.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
5499 AddDeclRef(Init->getIndirectMember(), Record);
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005500 }
Francois Pichetd583da02010-12-04 09:14:42 +00005501
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005502 AddSourceLocation(Init->getMemberLocation(), Record);
5503 AddStmt(Init->getInit());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005504 AddSourceLocation(Init->getLParenLoc(), Record);
5505 AddSourceLocation(Init->getRParenLoc(), Record);
5506 Record.push_back(Init->isWritten());
5507 if (Init->isWritten()) {
5508 Record.push_back(Init->getSourceOrder());
5509 } else {
5510 Record.push_back(Init->getNumArrayIndices());
5511 for (unsigned i=0, e=Init->getNumArrayIndices(); i != e; ++i)
5512 AddDeclRef(Init->getArrayIndex(i), Record);
5513 }
5514 }
5515}
5516
Richard Smithc2bb8182015-03-24 06:36:48 +00005517void ASTWriter::FlushCXXCtorInitializers() {
5518 RecordData Record;
5519
5520 unsigned N = CXXCtorInitializersToWrite.size();
Daniel Jasperc77b0a12015-03-24 08:06:38 +00005521 (void)N; // Silence unused warning in non-assert builds.
Richard Smithc2bb8182015-03-24 06:36:48 +00005522 for (auto &Init : CXXCtorInitializersToWrite) {
5523 Record.clear();
5524
5525 // Record the offset of this mem-initializer list.
5526 unsigned Index = Init.ID - 1;
5527 if (Index == CXXCtorInitializersOffsets.size())
5528 CXXCtorInitializersOffsets.push_back(Stream.GetCurrentBitNo());
5529 else {
5530 if (Index > CXXCtorInitializersOffsets.size())
5531 CXXCtorInitializersOffsets.resize(Index + 1);
5532 CXXCtorInitializersOffsets[Index] = Stream.GetCurrentBitNo();
5533 }
5534
5535 AddCXXCtorInitializers(Init.Inits.data(), Init.Inits.size(), Record);
5536 Stream.EmitRecord(serialization::DECL_CXX_CTOR_INITIALIZERS, Record);
5537
5538 // Flush any expressions that were written as part of the initializers.
5539 FlushStmts();
5540 }
5541
5542 assert(N == CXXCtorInitializersToWrite.size() &&
5543 "added more ctor initializers while writing ctor initializers");
5544 CXXCtorInitializersToWrite.clear();
5545}
5546
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005547void ASTWriter::AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record) {
Richard Smith053f6c62014-05-16 23:01:30 +00005548 auto &Data = D->data();
Douglas Gregor99ae8062012-02-14 17:54:36 +00005549 Record.push_back(Data.IsLambda);
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005550 Record.push_back(Data.UserDeclaredConstructor);
Richard Smith328aae52012-11-30 05:11:39 +00005551 Record.push_back(Data.UserDeclaredSpecialMembers);
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005552 Record.push_back(Data.Aggregate);
5553 Record.push_back(Data.PlainOldData);
5554 Record.push_back(Data.Empty);
5555 Record.push_back(Data.Polymorphic);
5556 Record.push_back(Data.Abstract);
Chandler Carruth583edf82011-04-30 10:07:30 +00005557 Record.push_back(Data.IsStandardLayout);
Chandler Carruthb1963742011-04-30 09:17:45 +00005558 Record.push_back(Data.HasNoNonEmptyBases);
5559 Record.push_back(Data.HasPrivateFields);
5560 Record.push_back(Data.HasProtectedFields);
5561 Record.push_back(Data.HasPublicFields);
Douglas Gregor61226d32011-05-13 01:05:07 +00005562 Record.push_back(Data.HasMutableFields);
Richard Smithab44d5b2013-12-10 08:25:00 +00005563 Record.push_back(Data.HasVariantMembers);
Richard Smith561fb152012-02-25 07:33:38 +00005564 Record.push_back(Data.HasOnlyCMembers);
Richard Smithe2648ba2012-05-07 01:07:30 +00005565 Record.push_back(Data.HasInClassInitializer);
Richard Smith593f9932012-12-08 02:01:17 +00005566 Record.push_back(Data.HasUninitializedReferenceMember);
Nico Weber6a6376b2016-02-19 01:52:46 +00005567 Record.push_back(Data.HasUninitializedFields);
Richard Smith6b02d462012-12-08 08:32:28 +00005568 Record.push_back(Data.NeedOverloadResolutionForMoveConstructor);
5569 Record.push_back(Data.NeedOverloadResolutionForMoveAssignment);
5570 Record.push_back(Data.NeedOverloadResolutionForDestructor);
5571 Record.push_back(Data.DefaultedMoveConstructorIsDeleted);
5572 Record.push_back(Data.DefaultedMoveAssignmentIsDeleted);
5573 Record.push_back(Data.DefaultedDestructorIsDeleted);
Richard Smith328aae52012-11-30 05:11:39 +00005574 Record.push_back(Data.HasTrivialSpecialMembers);
Richard Smithb45a6f72014-04-17 20:33:01 +00005575 Record.push_back(Data.DeclaredNonTrivialSpecialMembers);
Richard Smith328aae52012-11-30 05:11:39 +00005576 Record.push_back(Data.HasIrrelevantDestructor);
Richard Smith111af8d2011-08-10 18:11:37 +00005577 Record.push_back(Data.HasConstexprNonCopyMoveConstructor);
Nico Weber72c57f42016-02-24 20:58:14 +00005578 Record.push_back(Data.HasDefaultedDefaultConstructor);
Richard Smith561fb152012-02-25 07:33:38 +00005579 Record.push_back(Data.DefaultedDefaultConstructorIsConstexpr);
Richard Smith561fb152012-02-25 07:33:38 +00005580 Record.push_back(Data.HasConstexprDefaultConstructor);
Chandler Carruthe71d0622011-04-24 02:49:34 +00005581 Record.push_back(Data.HasNonLiteralTypeFieldsOrBases);
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005582 Record.push_back(Data.ComputedVisibleConversions);
Alexis Huntea6f0322011-05-11 22:34:38 +00005583 Record.push_back(Data.UserProvidedDefaultConstructor);
Richard Smith328aae52012-11-30 05:11:39 +00005584 Record.push_back(Data.DeclaredSpecialMembers);
Richard Smith1c33fe82012-11-28 06:23:12 +00005585 Record.push_back(Data.ImplicitCopyConstructorHasConstParam);
5586 Record.push_back(Data.ImplicitCopyAssignmentHasConstParam);
5587 Record.push_back(Data.HasDeclaredCopyConstructorWithConstParam);
5588 Record.push_back(Data.HasDeclaredCopyAssignmentWithConstParam);
Richard Smith561fb152012-02-25 07:33:38 +00005589 // IsLambda bit is already saved.
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005590
5591 Record.push_back(Data.NumBases);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005592 if (Data.NumBases > 0)
5593 AddCXXBaseSpecifiersRef(Data.getBases(), Data.getBases() + Data.NumBases,
5594 Record);
5595
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005596 // FIXME: Make VBases lazily computed when needed to avoid storing them.
5597 Record.push_back(Data.NumVBases);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005598 if (Data.NumVBases > 0)
5599 AddCXXBaseSpecifiersRef(Data.getVBases(), Data.getVBases() + Data.NumVBases,
5600 Record);
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005601
Richard Smitha4ba74c2013-08-30 04:46:40 +00005602 AddUnresolvedSet(Data.Conversions.get(*Context), Record);
5603 AddUnresolvedSet(Data.VisibleConversions.get(*Context), Record);
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005604 // Data.Definition is the owning decl, no need to write it.
Richard Smith68ad0e72013-06-26 02:41:25 +00005605 AddDeclRef(D->getFirstFriend(), Record);
Douglas Gregor99ae8062012-02-14 17:54:36 +00005606
5607 // Add lambda-specific data.
5608 if (Data.IsLambda) {
Richard Smith053f6c62014-05-16 23:01:30 +00005609 auto &Lambda = D->getLambdaData();
Douglas Gregor680e9e02012-02-21 19:11:17 +00005610 Record.push_back(Lambda.Dependent);
Faisal Valic1a6dc42013-10-23 16:10:50 +00005611 Record.push_back(Lambda.IsGenericLambda);
5612 Record.push_back(Lambda.CaptureDefault);
Douglas Gregor99ae8062012-02-14 17:54:36 +00005613 Record.push_back(Lambda.NumCaptures);
5614 Record.push_back(Lambda.NumExplicitCaptures);
Douglas Gregor63798542012-02-20 19:44:39 +00005615 Record.push_back(Lambda.ManglingNumber);
Douglas Gregor7fcbd902012-02-21 00:37:24 +00005616 AddDeclRef(Lambda.ContextDecl, Record);
Eli Friedmand564afb2012-09-19 01:18:11 +00005617 AddTypeSourceInfo(Lambda.MethodTyInfo, Record);
Douglas Gregor99ae8062012-02-14 17:54:36 +00005618 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00005619 const LambdaCapture &Capture = Lambda.Captures[I];
Douglas Gregor99ae8062012-02-14 17:54:36 +00005620 AddSourceLocation(Capture.getLocation(), Record);
5621 Record.push_back(Capture.isImplicit());
Richard Smithba71c082013-05-16 06:20:58 +00005622 Record.push_back(Capture.getCaptureKind());
5623 switch (Capture.getCaptureKind()) {
Faisal Validc6b5962016-03-21 09:25:37 +00005624 case LCK_StarThis:
Richard Smithba71c082013-05-16 06:20:58 +00005625 case LCK_This:
Alexey Bataev39c81e22014-08-28 04:28:19 +00005626 case LCK_VLAType:
Richard Smithba71c082013-05-16 06:20:58 +00005627 break;
5628 case LCK_ByCopy:
Richard Smithbb13c9a2013-09-28 04:02:39 +00005629 case LCK_ByRef:
Richard Smithba71c082013-05-16 06:20:58 +00005630 VarDecl *Var =
Craig Toppera13603a2014-05-22 05:54:18 +00005631 Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
Richard Smithba71c082013-05-16 06:20:58 +00005632 AddDeclRef(Var, Record);
5633 AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
5634 : SourceLocation(),
5635 Record);
5636 break;
5637 }
Douglas Gregor99ae8062012-02-14 17:54:36 +00005638 }
5639 }
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005640}
5641
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005642void ASTWriter::ReaderInitialized(ASTReader *Reader) {
Sebastian Redl07a89a82010-07-30 00:29:29 +00005643 assert(Reader && "Cannot remove chain");
Douglas Gregordf0c1512011-08-18 04:12:04 +00005644 assert((!Chain || Chain == Reader) && "Cannot replace chain");
Sebastian Redl07a89a82010-07-30 00:29:29 +00005645 assert(FirstDeclID == NextDeclID &&
5646 FirstTypeID == NextTypeID &&
5647 FirstIdentID == NextIdentID &&
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005648 FirstMacroID == NextMacroID &&
Douglas Gregor253eefe2011-12-01 00:59:36 +00005649 FirstSubmoduleID == NextSubmoduleID &&
Sebastian Redld95a56e2010-08-04 18:21:41 +00005650 FirstSelectorID == NextSelectorID &&
Sebastian Redl07a89a82010-07-30 00:29:29 +00005651 "Setting chain after writing has started.");
Douglas Gregor925296b2011-07-19 16:10:42 +00005652
Sebastian Redl07a89a82010-07-30 00:29:29 +00005653 Chain = Reader;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005654
Richard Smith7f330cd2015-03-18 01:42:29 +00005655 // Note, this will get called multiple times, once one the reader starts up
5656 // and again each time it's done reading a PCH or module.
Douglas Gregordf0c1512011-08-18 04:12:04 +00005657 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
5658 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
5659 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005660 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
Douglas Gregor253eefe2011-12-01 00:59:36 +00005661 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
Douglas Gregordf0c1512011-08-18 04:12:04 +00005662 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005663 NextDeclID = FirstDeclID;
5664 NextTypeID = FirstTypeID;
5665 NextIdentID = FirstIdentID;
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005666 NextMacroID = FirstMacroID;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005667 NextSelectorID = FirstSelectorID;
Douglas Gregor253eefe2011-12-01 00:59:36 +00005668 NextSubmoduleID = FirstSubmoduleID;
Sebastian Redl07a89a82010-07-30 00:29:29 +00005669}
5670
Sebastian Redl539c5062010-08-18 23:57:32 +00005671void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005672 // Always keep the highest ID. See \p TypeRead() for more information.
5673 IdentID &StoredID = IdentifierIDs[II];
5674 if (ID > StoredID)
5675 StoredID = ID;
Sebastian Redlff4a2952010-07-23 23:49:55 +00005676}
5677
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005678void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005679 // Always keep the highest ID. See \p TypeRead() for more information.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005680 MacroID &StoredID = MacroIDs[MI];
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005681 if (ID > StoredID)
5682 StoredID = ID;
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005683}
5684
Argyrios Kyrtzidisbb5c7eae2010-08-20 16:03:59 +00005685void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005686 // Always take the highest-numbered type index. This copes with an interesting
5687 // case for chained AST writing where we schedule writing the type and then,
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005688 // later, deserialize the type from another AST. In this case, we want to
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005689 // keep the higher-numbered entry so that we can properly write it out to
5690 // the AST file.
5691 TypeIdx &StoredIdx = TypeIdxs[T];
5692 if (Idx.getIndex() >= StoredIdx.getIndex())
5693 StoredIdx = Idx;
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00005694}
5695
Sebastian Redl539c5062010-08-18 23:57:32 +00005696void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005697 // Always keep the highest ID. See \p TypeRead() for more information.
5698 SelectorID &StoredID = SelectorIDs[S];
5699 if (ID > StoredID)
5700 StoredID = ID;
Sebastian Redl834bb972010-08-04 17:20:04 +00005701}
Douglas Gregor91096292010-10-02 19:29:26 +00005702
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00005703void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
Richard Smith66a81862015-05-04 02:25:31 +00005704 MacroDefinitionRecord *MD) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00005705 assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
Douglas Gregor91096292010-10-02 19:29:26 +00005706 MacroDefinitions[MD] = ID;
5707}
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005708
Douglas Gregore37a85a2011-12-02 17:30:13 +00005709void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
5710 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
5711 SubmoduleIDs[Mod] = ID;
5712}
5713
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005714void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
John McCallf937c022011-10-07 06:10:15 +00005715 assert(D->isCompleteDefinition());
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005716 assert(!WritingAST && "Already writing the AST!");
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005717 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005718 // We are interested when a PCH decl is modified.
Douglas Gregorb3722e22011-09-09 23:01:35 +00005719 if (RD->isFromASTFile()) {
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005720 // A forward reference was mutated into a definition. Rewrite it.
5721 // FIXME: This happens during template instantiation, should we
5722 // have created a new definition decl instead ?
Richard Smithcd45dbc2014-04-19 03:48:30 +00005723 assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
5724 "completed a tag from another module but not by instantiation?");
5725 DeclUpdates[RD].push_back(
5726 DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION));
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005727 }
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005728 }
5729}
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005730
Richard Smithf983f7f2015-10-13 00:23:25 +00005731static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) {
5732 if (D->isFromASTFile())
5733 return true;
5734
5735 // If we've not loaded any modules, this can't be imported.
5736 if (!Chain || !Chain->getModuleManager().size())
5737 return false;
5738
5739 // The predefined __va_list_tag struct is imported if we imported any decls.
5740 // FIXME: This is a gross hack.
5741 return D == D->getASTContext().getVaListTagDecl();
5742}
5743
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005744void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
Vassil Vassilev632eac32016-03-16 11:17:04 +00005745 // TU is handled elsewhere.
5746 if (isa<TranslationUnitDecl>(DC))
5747 return;
5748
5749 // Namespaces are handled elsewhere, except for template instantiations of
5750 // FunctionTemplateDecls in namespaces. We are interested in cases where the
5751 // local instantiations are added to an imported context. Only happens when
5752 // adding ADL lookup candidates, for example templated friends.
5753 if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None &&
5754 !isa<FunctionTemplateDecl>(D))
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005755 return;
5756
Richard Smithf983f7f2015-10-13 00:23:25 +00005757 // We're only interested in cases where a local declaration is added to an
5758 // imported context.
5759 if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC)))
5760 return;
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005761
Richard Smith0f4e2c42015-08-06 04:23:48 +00005762 assert(DC == DC->getPrimaryContext() && "added to non-primary context");
Douglas Gregor9f782892013-01-21 15:25:38 +00005763 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
Richard Smithe9a8bc32014-09-30 00:45:29 +00005764 assert(!WritingAST && "Already writing the AST!");
Richard Smithf983f7f2015-10-13 00:23:25 +00005765 if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) {
5766 // We're adding a visible declaration to a predefined decl context. Ensure
5767 // that we write out all of its lookup results so we don't get a nasty
5768 // surprise when we try to emit its lookup table.
5769 for (auto *Child : DC->decls())
5770 UpdatingVisibleDecls.push_back(Child);
5771 }
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005772 UpdatingVisibleDecls.push_back(D);
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005773}
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005774
5775void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
5776 assert(D->isImplicit());
Richard Smithf983f7f2015-10-13 00:23:25 +00005777
5778 // We're only interested in cases where a local declaration is added to an
5779 // imported context.
5780 if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD))
5781 return;
5782
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005783 if (!isa<CXXMethodDecl>(D))
Richard Smithf983f7f2015-10-13 00:23:25 +00005784 return;
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005785
5786 // A decl coming from PCH was modified.
John McCallf937c022011-10-07 06:10:15 +00005787 assert(RD->isCompleteDefinition());
Richard Smithe9a8bc32014-09-30 00:45:29 +00005788 assert(!WritingAST && "Already writing the AST!");
Aaron Ballman4f45b712014-03-21 15:22:56 +00005789 DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005790}
Argyrios Kyrtzidis402dbbb2010-10-28 07:38:42 +00005791
Richard Smith564417a2014-03-20 21:47:22 +00005792void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005793 assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
5794 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00005795 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005796 // If we don't already know the exception specification for this redecl
5797 // chain, add an update record for it.
5798 if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
5799 ->getType()
5800 ->castAs<FunctionProtoType>()
5801 ->getExceptionSpecType()))
5802 DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
5803 });
Richard Smith564417a2014-03-20 21:47:22 +00005804}
5805
Richard Smith1fa5d642013-05-11 05:45:24 +00005806void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
5807 assert(!WritingAST && "Already writing the AST!");
Richard Smith9e2341d2015-03-23 03:25:59 +00005808 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00005809 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005810 DeclUpdates[D].push_back(
5811 DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
5812 });
Richard Smith1fa5d642013-05-11 05:45:24 +00005813}
5814
Richard Smithf8134002015-03-10 01:41:22 +00005815void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
5816 const FunctionDecl *Delete) {
5817 assert(!WritingAST && "Already writing the AST!");
5818 assert(Delete && "Not given an operator delete");
Richard Smith9e2341d2015-03-23 03:25:59 +00005819 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00005820 Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005821 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete));
5822 });
Richard Smithf8134002015-03-10 01:41:22 +00005823}
5824
Sebastian Redlab238a72011-04-24 16:28:06 +00005825void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005826 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005827 if (!D->isFromASTFile())
Sebastian Redlab238a72011-04-24 16:28:06 +00005828 return; // Declaration not imported from PCH.
5829
Richard Smith4d235792014-08-07 18:53:08 +00005830 // Implicit function decl from a PCH was defined.
5831 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
Sebastian Redlab238a72011-04-24 16:28:06 +00005832}
5833
Richard Smithd28ac5b2014-03-22 23:33:22 +00005834void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
5835 assert(!WritingAST && "Already writing the AST!");
5836 if (!D->isFromASTFile())
5837 return;
5838
Richard Smith9e2341d2015-03-23 03:25:59 +00005839 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
Richard Smithd28ac5b2014-03-22 23:33:22 +00005840}
5841
Sebastian Redl2ac2c722011-04-29 08:19:30 +00005842void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005843 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005844 if (!D->isFromASTFile())
Sebastian Redl2ac2c722011-04-29 08:19:30 +00005845 return;
5846
5847 // Since the actual instantiation is delayed, this really means that we need
5848 // to update the instantiation location.
Richard Smith6ef42932014-03-20 21:02:00 +00005849 DeclUpdates[D].push_back(
Aaron Ballman4f45b712014-03-21 15:22:56 +00005850 DeclUpdate(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER,
5851 D->getMemberSpecializationInfo()->getPointOfInstantiation()));
Sebastian Redl2ac2c722011-04-29 08:19:30 +00005852}
5853
John McCall32791cc2016-01-06 22:34:54 +00005854void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) {
5855 assert(!WritingAST && "Already writing the AST!");
5856 if (!D->isFromASTFile())
5857 return;
5858
5859 DeclUpdates[D].push_back(
5860 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D));
5861}
5862
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00005863void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
5864 const ObjCInterfaceDecl *IFD) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005865 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005866 if (!IFD->isFromASTFile())
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00005867 return; // Declaration not imported from PCH.
Douglas Gregor404cdde2012-01-27 01:47:08 +00005868
5869 assert(IFD->getDefinition() && "Category on a class without a definition?");
5870 ObjCClassesWithCategories.insert(
5871 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00005872}
Argyrios Kyrtzidisb97a4022011-11-12 21:07:46 +00005873
Eli Friedman276dd182013-09-05 00:02:25 +00005874void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
5875 assert(!WritingAST && "Already writing the AST!");
5876 if (!D->isFromASTFile())
5877 return;
5878
Aaron Ballman4f45b712014-03-21 15:22:56 +00005879 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
Eli Friedman276dd182013-09-05 00:02:25 +00005880}
Alexey Bataev97720002014-11-11 04:05:39 +00005881
5882void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
5883 assert(!WritingAST && "Already writing the AST!");
5884 if (!D->isFromASTFile())
5885 return;
5886
5887 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE));
5888}
Richard Smith65ebb4a2015-03-26 04:09:53 +00005889
Richard Smith4caa4492015-05-15 02:34:32 +00005890void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
Richard Smith65ebb4a2015-03-26 04:09:53 +00005891 assert(!WritingAST && "Already writing the AST!");
5892 assert(D->isHidden() && "expected a hidden declaration");
Richard Smith4caa4492015-05-15 02:34:32 +00005893 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M));
Richard Smith65ebb4a2015-03-26 04:09:53 +00005894}
Alex Denisovfde64952015-06-26 05:28:36 +00005895
5896void ASTWriter::AddedAttributeToRecord(const Attr *Attr,
5897 const RecordDecl *Record) {
5898 assert(!WritingAST && "Already writing the AST!");
5899 if (!Record->isFromASTFile())
5900 return;
5901 DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr));
5902}