blob: 1e72ced2ee364bdee8e8f7c8d32e4ada1f590e68 [file] [log] [blame]
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001//===- ASTWriter.cpp - AST File Writer ------------------------------------===//
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Sebastian Redl55c0ad52010-08-18 23:56:21 +000010// This file defines the ASTWriter class, which writes AST files.
Douglas Gregoref84c4b2009-04-09 22:27:44 +000011//
12//===----------------------------------------------------------------------===//
13
Sebastian Redl1914c6f2010-08-18 23:56:37 +000014#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidis4bd97102010-08-20 16:03:52 +000015#include "ASTCommon.h"
Richard Smithd88a7f12015-09-01 20:35:42 +000016#include "ASTReaderInternals.h"
17#include "MultiOnDiskHashTable.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000018#include "clang/AST/ASTContext.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000019#include "clang/AST/ASTUnresolvedSet.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000020#include "clang/AST/Attr.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000021#include "clang/AST/Decl.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000022#include "clang/AST/DeclBase.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000023#include "clang/AST/DeclCXX.h"
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +000024#include "clang/AST/DeclContextInternals.h"
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +000025#include "clang/AST/DeclFriend.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000026#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "clang/AST/DeclTemplate.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000028#include "clang/AST/DeclarationName.h"
Douglas Gregorfeb84b02009-04-14 21:18:50 +000029#include "clang/AST/Expr.h"
John McCallbfd822c2010-08-24 07:32:53 +000030#include "clang/AST/ExprCXX.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000031#include "clang/AST/LambdaCapture.h"
32#include "clang/AST/NestedNameSpecifier.h"
33#include "clang/AST/RawCommentList.h"
34#include "clang/AST/TemplateName.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000035#include "clang/AST/Type.h"
John McCall8f115c62009-10-16 21:56:05 +000036#include "clang/AST/TypeLocVisitor.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000037#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000038#include "clang/Basic/DiagnosticOptions.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000039#include "clang/Basic/FileManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000040#include "clang/Basic/FileSystemOptions.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000041#include "clang/Basic/IdentifierTable.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000042#include "clang/Basic/LLVM.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000043#include "clang/Basic/Lambda.h"
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +000044#include "clang/Basic/LangOptions.h"
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +000045#include "clang/Basic/MemoryBufferCache.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000046#include "clang/Basic/Module.h"
47#include "clang/Basic/ObjCRuntime.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000048#include "clang/Basic/OpenCLOptions.h"
49#include "clang/Basic/SourceLocation.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000050#include "clang/Basic/SourceManager.h"
Douglas Gregor4c7626e2009-04-13 16:31:14 +000051#include "clang/Basic/SourceManagerInternals.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000052#include "clang/Basic/Specifiers.h"
Douglas Gregorbfbde532009-04-10 21:16:55 +000053#include "clang/Basic/TargetInfo.h"
Douglas Gregorcb177f12012-10-16 23:40:58 +000054#include "clang/Basic/TargetOptions.h"
Douglas Gregor7b71e632009-04-27 22:23:34 +000055#include "clang/Basic/Version.h"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000056#include "clang/Basic/VersionTuple.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000057#include "clang/Lex/HeaderSearch.h"
58#include "clang/Lex/HeaderSearchOptions.h"
59#include "clang/Lex/MacroInfo.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000060#include "clang/Lex/ModuleMap.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000061#include "clang/Lex/PreprocessingRecord.h"
62#include "clang/Lex/Preprocessor.h"
63#include "clang/Lex/PreprocessorOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000064#include "clang/Lex/Token.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000065#include "clang/Sema/IdentifierResolver.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000066#include "clang/Sema/ObjCMethodList.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000067#include "clang/Sema/Sema.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000068#include "clang/Sema/Weak.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000069#include "clang/Serialization/ASTReader.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000070#include "clang/Serialization/Module.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000071#include "clang/Serialization/ModuleFileExtension.h"
Richard Smithb5aaf5a2015-09-01 02:35:58 +000072#include "clang/Serialization/SerializationDiagnostic.h"
Douglas Gregore0a3a512009-04-14 21:55:33 +000073#include "llvm/ADT/APFloat.h"
74#include "llvm/ADT/APInt.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000075#include "llvm/ADT/APSInt.h"
76#include "llvm/ADT/ArrayRef.h"
77#include "llvm/ADT/DenseMap.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000078#include "llvm/ADT/Hashing.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000079#include "llvm/ADT/Optional.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000080#include "llvm/ADT/PointerIntPair.h"
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +000081#include "llvm/ADT/STLExtras.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000082#include "llvm/ADT/SmallSet.h"
83#include "llvm/ADT/SmallString.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000084#include "llvm/ADT/SmallVector.h"
Daniel Dunbarf8502d52009-10-17 23:52:28 +000085#include "llvm/ADT/StringExtras.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000086#include "llvm/ADT/StringMap.h"
87#include "llvm/ADT/StringRef.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000088#include "llvm/Bitcode/BitCodes.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000089#include "llvm/Bitcode/BitstreamWriter.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000090#include "llvm/Support/Casting.h"
Richard Smithaada85c2016-02-06 02:06:43 +000091#include "llvm/Support/Compression.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000092#include "llvm/Support/Endian.h"
Justin Bognere1c147c2014-03-28 22:03:19 +000093#include "llvm/Support/EndianStream.h"
George Rimarc39f5492017-01-17 15:45:31 +000094#include "llvm/Support/Error.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000095#include "llvm/Support/ErrorHandling.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000096#include "llvm/Support/MemoryBuffer.h"
Justin Bognerbb094f02014-04-18 19:57:06 +000097#include "llvm/Support/OnDiskHashTable.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000098#include "llvm/Support/Path.h"
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +000099#include "llvm/Support/SHA1.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000100#include "llvm/Support/raw_ostream.h"
Douglas Gregor925296b2011-07-19 16:10:42 +0000101#include <algorithm>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000102#include <cassert>
103#include <cstdint>
104#include <cstdlib>
105#include <cstring>
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000106#include <ctime>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000107#include <deque>
108#include <limits>
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000109#include <memory>
110#include <queue>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000111#include <tuple>
Douglas Gregor925296b2011-07-19 16:10:42 +0000112#include <utility>
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000113#include <vector>
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +0000114
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000115using namespace clang;
Sebastian Redl539c5062010-08-18 23:57:32 +0000116using namespace clang::serialization;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000117
Sebastian Redl3df5a082010-07-30 17:03:48 +0000118template <typename T, typename Allocator>
Reid Kleckner012665e2015-05-21 00:13:09 +0000119static StringRef bytes(const std::vector<T, Allocator> &v) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000120 if (v.empty()) return StringRef();
121 return StringRef(reinterpret_cast<const char*>(&v[0]),
Benjamin Kramerd47a12a2011-04-24 17:44:50 +0000122 sizeof(T) * v.size());
Sebastian Redl3df5a082010-07-30 17:03:48 +0000123}
Benjamin Kramerd47a12a2011-04-24 17:44:50 +0000124
125template <typename T>
Reid Kleckner012665e2015-05-21 00:13:09 +0000126static StringRef bytes(const SmallVectorImpl<T> &v) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000127 return StringRef(reinterpret_cast<const char*>(v.data()),
Benjamin Kramerd47a12a2011-04-24 17:44:50 +0000128 sizeof(T) * v.size());
Sebastian Redl3df5a082010-07-30 17:03:48 +0000129}
130
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000131//===----------------------------------------------------------------------===//
132// Type serialization
133//===----------------------------------------------------------------------===//
Chris Lattner7099dbc2009-04-27 06:16:06 +0000134
Richard Smith290d8012016-04-06 17:06:00 +0000135namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000136
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000137 class ASTTypeWriter {
Sebastian Redl55c0ad52010-08-18 23:56:21 +0000138 ASTWriter &Writer;
Richard Smith69c82bf2016-04-01 22:52:03 +0000139 ASTRecordWriter Record;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000140
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000141 /// \brief Type code that corresponds to the record generated.
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000142 TypeCode Code = static_cast<TypeCode>(0);
143
Richard Smith01b2cb42014-07-26 06:37:51 +0000144 /// \brief Abbreviation to use for the record, if any.
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000145 unsigned AbbrevToUse = 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000146
Richard Smith290d8012016-04-06 17:06:00 +0000147 public:
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000148 ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000149 : Writer(Writer), Record(Writer, Record) {}
Richard Smith290d8012016-04-06 17:06:00 +0000150
151 uint64_t Emit() {
152 return Record.Emit(Code, AbbrevToUse);
153 }
154
155 void Visit(QualType T) {
156 if (T.hasLocalNonFastQualifiers()) {
157 Qualifiers Qs = T.getLocalQualifiers();
158 Record.AddTypeRef(T.getLocalUnqualifiedType());
159 Record.push_back(Qs.getAsOpaqueValue());
160 Code = TYPE_EXT_QUAL;
161 AbbrevToUse = Writer.TypeExtQualAbbrev;
162 } else {
163 switch (T->getTypeClass()) {
164 // For all of the concrete, non-dependent types, call the
165 // appropriate visitor function.
166#define TYPE(Class, Base) \
167 case Type::Class: Visit##Class##Type(cast<Class##Type>(T)); break;
168#define ABSTRACT_TYPE(Class, Base)
169#include "clang/AST/TypeNodes.def"
170 }
171 }
172 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000173
174 void VisitArrayType(const ArrayType *T);
175 void VisitFunctionType(const FunctionType *T);
176 void VisitTagType(const TagType *T);
177
178#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
179#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000180#include "clang/AST/TypeNodes.def"
181 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000182
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000183} // namespace clang
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000184
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000185void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
David Blaikie83d382b2011-09-23 05:06:16 +0000186 llvm_unreachable("Built-in types are never serialized");
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000187}
188
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000189void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000190 Record.AddTypeRef(T->getElementType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000191 Code = TYPE_COMPLEX;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000192}
193
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000194void ASTTypeWriter::VisitPointerType(const PointerType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000195 Record.AddTypeRef(T->getPointeeType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000196 Code = TYPE_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000197}
198
Reid Kleckner8a365022013-06-24 17:51:48 +0000199void ASTTypeWriter::VisitDecayedType(const DecayedType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000200 Record.AddTypeRef(T->getOriginalType());
Reid Kleckner8a365022013-06-24 17:51:48 +0000201 Code = TYPE_DECAYED;
202}
203
Reid Kleckner0503a872013-12-05 01:23:43 +0000204void ASTTypeWriter::VisitAdjustedType(const AdjustedType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000205 Record.AddTypeRef(T->getOriginalType());
206 Record.AddTypeRef(T->getAdjustedType());
Reid Kleckner0503a872013-12-05 01:23:43 +0000207 Code = TYPE_ADJUSTED;
208}
209
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000210void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000211 Record.AddTypeRef(T->getPointeeType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000212 Code = TYPE_BLOCK_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000213}
214
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000215void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000216 Record.AddTypeRef(T->getPointeeTypeAsWritten());
Richard Smith0f538462011-04-12 10:38:03 +0000217 Record.push_back(T->isSpelledAsLValue());
Sebastian Redl539c5062010-08-18 23:57:32 +0000218 Code = TYPE_LVALUE_REFERENCE;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000219}
220
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000221void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000222 Record.AddTypeRef(T->getPointeeTypeAsWritten());
Sebastian Redl539c5062010-08-18 23:57:32 +0000223 Code = TYPE_RVALUE_REFERENCE;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000224}
225
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000226void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000227 Record.AddTypeRef(T->getPointeeType());
228 Record.AddTypeRef(QualType(T->getClass(), 0));
Sebastian Redl539c5062010-08-18 23:57:32 +0000229 Code = TYPE_MEMBER_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000230}
231
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000232void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000233 Record.AddTypeRef(T->getElementType());
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000234 Record.push_back(T->getSizeModifier()); // FIXME: stable values
John McCall8ccfcb52009-09-24 19:53:00 +0000235 Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000236}
237
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000238void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000239 VisitArrayType(T);
Richard Smith69c82bf2016-04-01 22:52:03 +0000240 Record.AddAPInt(T->getSize());
Sebastian Redl539c5062010-08-18 23:57:32 +0000241 Code = TYPE_CONSTANT_ARRAY;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000242}
243
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000244void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000245 VisitArrayType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000246 Code = TYPE_INCOMPLETE_ARRAY;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000247}
248
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000249void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000250 VisitArrayType(T);
Richard Smith69c82bf2016-04-01 22:52:03 +0000251 Record.AddSourceLocation(T->getLBracketLoc());
252 Record.AddSourceLocation(T->getRBracketLoc());
Richard Smith290d8012016-04-06 17:06:00 +0000253 Record.AddStmt(T->getSizeExpr());
Sebastian Redl539c5062010-08-18 23:57:32 +0000254 Code = TYPE_VARIABLE_ARRAY;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000255}
256
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000257void ASTTypeWriter::VisitVectorType(const VectorType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000258 Record.AddTypeRef(T->getElementType());
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000259 Record.push_back(T->getNumElements());
Bob Wilsonaeb56442010-11-10 21:56:12 +0000260 Record.push_back(T->getVectorKind());
Sebastian Redl539c5062010-08-18 23:57:32 +0000261 Code = TYPE_VECTOR;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000262}
263
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000264void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000265 VisitVectorType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000266 Code = TYPE_EXT_VECTOR;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000267}
268
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000269void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000270 Record.AddTypeRef(T->getReturnType());
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000271 FunctionType::ExtInfo C = T->getExtInfo();
272 Record.push_back(C.getNoReturn());
Eli Friedmanc5b20b52011-04-09 08:18:08 +0000273 Record.push_back(C.getHasRegParm());
Rafael Espindola49b85ab2010-03-30 22:15:11 +0000274 Record.push_back(C.getRegParm());
Douglas Gregor8c940862010-01-18 17:14:39 +0000275 // FIXME: need to stabilize encoding of calling convention...
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000276 Record.push_back(C.getCC());
John McCall31168b02011-06-15 23:02:42 +0000277 Record.push_back(C.getProducesResult());
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +0000278 Record.push_back(C.getNoCallerSavedRegs());
Richard Smith01b2cb42014-07-26 06:37:51 +0000279
280 if (C.getHasRegParm() || C.getRegParm() || C.getProducesResult())
281 AbbrevToUse = 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000282}
283
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000284void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000285 VisitFunctionType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000286 Code = TYPE_FUNCTION_NO_PROTO;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000287}
288
Richard Smith290d8012016-04-06 17:06:00 +0000289static void addExceptionSpec(const FunctionProtoType *T,
290 ASTRecordWriter &Record) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000291 Record.push_back(T->getExceptionSpecType());
292 if (T->getExceptionSpecType() == EST_Dynamic) {
293 Record.push_back(T->getNumExceptions());
294 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
Richard Smith69c82bf2016-04-01 22:52:03 +0000295 Record.AddTypeRef(T->getExceptionType(I));
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000296 } else if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
Richard Smith290d8012016-04-06 17:06:00 +0000297 Record.AddStmt(T->getNoexceptExpr());
Richard Smith8b987a92012-04-21 17:47:47 +0000298 } else if (T->getExceptionSpecType() == EST_Uninstantiated) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000299 Record.AddDeclRef(T->getExceptionSpecDecl());
300 Record.AddDeclRef(T->getExceptionSpecTemplate());
Richard Smithd3b5c9082012-07-27 04:22:15 +0000301 } else if (T->getExceptionSpecType() == EST_Unevaluated) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000302 Record.AddDeclRef(T->getExceptionSpecDecl());
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000303 }
Richard Smith564417a2014-03-20 21:47:22 +0000304}
305
306void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
307 VisitFunctionType(T);
Richard Smith01b2cb42014-07-26 06:37:51 +0000308
Richard Smith564417a2014-03-20 21:47:22 +0000309 Record.push_back(T->isVariadic());
310 Record.push_back(T->hasTrailingReturn());
311 Record.push_back(T->getTypeQuals());
312 Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
Richard Smith290d8012016-04-06 17:06:00 +0000313 addExceptionSpec(T, Record);
Richard Smith01b2cb42014-07-26 06:37:51 +0000314
315 Record.push_back(T->getNumParams());
316 for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
Richard Smith69c82bf2016-04-01 22:52:03 +0000317 Record.AddTypeRef(T->getParamType(I));
Richard Smith01b2cb42014-07-26 06:37:51 +0000318
John McCall18afab72016-03-01 00:49:02 +0000319 if (T->hasExtParameterInfos()) {
320 for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
321 Record.push_back(T->getExtParameterInfo(I).getOpaqueValue());
322 }
323
Richard Smith01b2cb42014-07-26 06:37:51 +0000324 if (T->isVariadic() || T->hasTrailingReturn() || T->getTypeQuals() ||
John McCall18afab72016-03-01 00:49:02 +0000325 T->getRefQualifier() || T->getExceptionSpecType() != EST_None ||
326 T->hasExtParameterInfos())
Richard Smith01b2cb42014-07-26 06:37:51 +0000327 AbbrevToUse = 0;
328
Sebastian Redl539c5062010-08-18 23:57:32 +0000329 Code = TYPE_FUNCTION_PROTO;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000330}
331
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000332void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000333 Record.AddDeclRef(T->getDecl());
Sebastian Redl539c5062010-08-18 23:57:32 +0000334 Code = TYPE_UNRESOLVED_USING;
John McCallb96ec562009-12-04 22:46:56 +0000335}
John McCallb96ec562009-12-04 22:46:56 +0000336
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000337void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000338 Record.AddDeclRef(T->getDecl());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +0000339 assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
Richard Smith69c82bf2016-04-01 22:52:03 +0000340 Record.AddTypeRef(T->getCanonicalTypeInternal());
Sebastian Redl539c5062010-08-18 23:57:32 +0000341 Code = TYPE_TYPEDEF;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000342}
343
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000344void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
Richard Smith290d8012016-04-06 17:06:00 +0000345 Record.AddStmt(T->getUnderlyingExpr());
Sebastian Redl539c5062010-08-18 23:57:32 +0000346 Code = TYPE_TYPEOF_EXPR;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000347}
348
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000349void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000350 Record.AddTypeRef(T->getUnderlyingType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000351 Code = TYPE_TYPEOF;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000352}
353
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000354void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000355 Record.AddTypeRef(T->getUnderlyingType());
Richard Smith290d8012016-04-06 17:06:00 +0000356 Record.AddStmt(T->getUnderlyingExpr());
Sebastian Redl539c5062010-08-18 23:57:32 +0000357 Code = TYPE_DECLTYPE;
Anders Carlsson81df7b82009-06-24 19:06:50 +0000358}
359
Alexis Hunte852b102011-05-24 22:41:36 +0000360void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000361 Record.AddTypeRef(T->getBaseType());
362 Record.AddTypeRef(T->getUnderlyingType());
Alexis Hunte852b102011-05-24 22:41:36 +0000363 Record.push_back(T->getUTTKind());
364 Code = TYPE_UNARY_TRANSFORM;
365}
366
Richard Smith30482bc2011-02-20 03:19:35 +0000367void ASTTypeWriter::VisitAutoType(const AutoType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000368 Record.AddTypeRef(T->getDeducedType());
Richard Smithe301ba22015-11-11 02:02:15 +0000369 Record.push_back((unsigned)T->getKeyword());
Richard Smith27d807c2013-04-30 13:56:41 +0000370 if (T->getDeducedType().isNull())
371 Record.push_back(T->isDependentType());
Richard Smith30482bc2011-02-20 03:19:35 +0000372 Code = TYPE_AUTO;
373}
374
Richard Smith600b5262017-01-26 20:40:47 +0000375void ASTTypeWriter::VisitDeducedTemplateSpecializationType(
376 const DeducedTemplateSpecializationType *T) {
377 Record.AddTemplateName(T->getTemplateName());
378 Record.AddTypeRef(T->getDeducedType());
379 if (T->getDeducedType().isNull())
380 Record.push_back(T->isDependentType());
381 Code = TYPE_DEDUCED_TEMPLATE_SPECIALIZATION;
382}
383
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000384void ASTTypeWriter::VisitTagType(const TagType *T) {
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +0000385 Record.push_back(T->isDependentType());
Richard Smith69c82bf2016-04-01 22:52:03 +0000386 Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +0000387 assert(!T->isBeingDefined() &&
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000388 "Cannot serialize in the middle of a type definition");
389}
390
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000391void ASTTypeWriter::VisitRecordType(const RecordType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000392 VisitTagType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000393 Code = TYPE_RECORD;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000394}
395
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000396void ASTTypeWriter::VisitEnumType(const EnumType *T) {
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000397 VisitTagType(T);
Sebastian Redl539c5062010-08-18 23:57:32 +0000398 Code = TYPE_ENUM;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000399}
400
John McCall81904512011-01-06 01:58:22 +0000401void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000402 Record.AddTypeRef(T->getModifiedType());
403 Record.AddTypeRef(T->getEquivalentType());
John McCall81904512011-01-06 01:58:22 +0000404 Record.push_back(T->getAttrKind());
405 Code = TYPE_ATTRIBUTED;
406}
407
Mike Stump11289f42009-09-09 15:08:12 +0000408void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000409ASTTypeWriter::VisitSubstTemplateTypeParmType(
John McCallcebee162009-10-18 09:09:24 +0000410 const SubstTemplateTypeParmType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000411 Record.AddTypeRef(QualType(T->getReplacedParameter(), 0));
412 Record.AddTypeRef(T->getReplacementType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000413 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
John McCallcebee162009-10-18 09:09:24 +0000414}
415
416void
Douglas Gregorada4b792011-01-14 02:55:32 +0000417ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
418 const SubstTemplateTypeParmPackType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000419 Record.AddTypeRef(QualType(T->getReplacedParameter(), 0));
420 Record.AddTemplateArgument(T->getArgumentPack());
Douglas Gregorada4b792011-01-14 02:55:32 +0000421 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK;
422}
423
424void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000425ASTTypeWriter::VisitTemplateSpecializationType(
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000426 const TemplateSpecializationType *T) {
Argyrios Kyrtzidisa4ed1812010-07-08 13:09:53 +0000427 Record.push_back(T->isDependentType());
Richard Smith69c82bf2016-04-01 22:52:03 +0000428 Record.AddTemplateName(T->getTemplateName());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000429 Record.push_back(T->getNumArgs());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +0000430 for (const auto &ArgI : *T)
Richard Smith69c82bf2016-04-01 22:52:03 +0000431 Record.AddTemplateArgument(ArgI);
432 Record.AddTypeRef(T->isTypeAlias() ? T->getAliasedType()
433 : T->isCanonicalUnqualified()
434 ? QualType()
435 : T->getCanonicalTypeInternal());
Sebastian Redl539c5062010-08-18 23:57:32 +0000436 Code = TYPE_TEMPLATE_SPECIALIZATION;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000437}
438
439void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000440ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
Argyrios Kyrtzidis4a57bd02010-06-30 08:49:25 +0000441 VisitArrayType(T);
Richard Smith290d8012016-04-06 17:06:00 +0000442 Record.AddStmt(T->getSizeExpr());
Richard Smith69c82bf2016-04-01 22:52:03 +0000443 Record.AddSourceRange(T->getBracketsRange());
Sebastian Redl539c5062010-08-18 23:57:32 +0000444 Code = TYPE_DEPENDENT_SIZED_ARRAY;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000445}
446
447void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000448ASTTypeWriter::VisitDependentSizedExtVectorType(
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000449 const DependentSizedExtVectorType *T) {
Alex Lorenz00aee432017-03-22 10:04:48 +0000450 Record.AddTypeRef(T->getElementType());
451 Record.AddStmt(T->getSizeExpr());
452 Record.AddSourceLocation(T->getAttributeLoc());
453 Code = TYPE_DEPENDENT_SIZED_EXT_VECTOR;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000454}
455
Andrew Gozillon572bbb02017-10-02 06:25:51 +0000456void
457ASTTypeWriter::VisitDependentAddressSpaceType(
458 const DependentAddressSpaceType *T) {
459 Record.AddTypeRef(T->getPointeeType());
460 Record.AddStmt(T->getAddrSpaceExpr());
461 Record.AddSourceLocation(T->getAttributeLoc());
462 Code = TYPE_DEPENDENT_ADDRESS_SPACE;
463}
464
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000465void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000466ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000467 Record.push_back(T->getDepth());
468 Record.push_back(T->getIndex());
469 Record.push_back(T->isParameterPack());
Richard Smith69c82bf2016-04-01 22:52:03 +0000470 Record.AddDeclRef(T->getDecl());
Sebastian Redl539c5062010-08-18 23:57:32 +0000471 Code = TYPE_TEMPLATE_TYPE_PARM;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000472}
473
474void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000475ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
Argyrios Kyrtzidisbfcacee2010-06-24 08:57:31 +0000476 Record.push_back(T->getKeyword());
Richard Smith69c82bf2016-04-01 22:52:03 +0000477 Record.AddNestedNameSpecifier(T->getQualifier());
478 Record.AddIdentifierRef(T->getIdentifier());
479 Record.AddTypeRef(
480 T->isCanonicalUnqualified() ? QualType() : T->getCanonicalTypeInternal());
Sebastian Redl539c5062010-08-18 23:57:32 +0000481 Code = TYPE_DEPENDENT_NAME;
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000482}
483
484void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000485ASTTypeWriter::VisitDependentTemplateSpecializationType(
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +0000486 const DependentTemplateSpecializationType *T) {
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +0000487 Record.push_back(T->getKeyword());
Richard Smith69c82bf2016-04-01 22:52:03 +0000488 Record.AddNestedNameSpecifier(T->getQualifier());
489 Record.AddIdentifierRef(T->getIdentifier());
Argyrios Kyrtzidisf0f7a792010-06-25 16:24:58 +0000490 Record.push_back(T->getNumArgs());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +0000491 for (const auto &I : *T)
Richard Smith69c82bf2016-04-01 22:52:03 +0000492 Record.AddTemplateArgument(I);
Sebastian Redl539c5062010-08-18 23:57:32 +0000493 Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000494}
495
Douglas Gregord2fa7662010-12-20 02:24:11 +0000496void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000497 Record.AddTypeRef(T->getPattern());
David Blaikie05785d12013-02-20 22:23:23 +0000498 if (Optional<unsigned> NumExpansions = T->getNumExpansions())
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000499 Record.push_back(*NumExpansions + 1);
500 else
501 Record.push_back(0);
Douglas Gregord2fa7662010-12-20 02:24:11 +0000502 Code = TYPE_PACK_EXPANSION;
503}
504
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000505void ASTTypeWriter::VisitParenType(const ParenType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000506 Record.AddTypeRef(T->getInnerType());
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000507 Code = TYPE_PAREN;
508}
509
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000510void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000511 Record.push_back(T->getKeyword());
Richard Smith69c82bf2016-04-01 22:52:03 +0000512 Record.AddNestedNameSpecifier(T->getQualifier());
513 Record.AddTypeRef(T->getNamedType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000514 Code = TYPE_ELABORATED;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000515}
516
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000517void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000518 Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
519 Record.AddTypeRef(T->getInjectedSpecializationType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000520 Code = TYPE_INJECTED_CLASS_NAME;
John McCalle78aac42010-03-10 03:28:59 +0000521}
522
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000523void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000524 Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
Sebastian Redl539c5062010-08-18 23:57:32 +0000525 Code = TYPE_OBJC_INTERFACE;
John McCall8b07ec22010-05-15 11:32:37 +0000526}
527
Manman Rene6be26c2016-09-13 17:25:08 +0000528void ASTTypeWriter::VisitObjCTypeParamType(const ObjCTypeParamType *T) {
529 Record.AddDeclRef(T->getDecl());
530 Record.push_back(T->getNumProtocols());
531 for (const auto *I : T->quals())
532 Record.AddDeclRef(I);
533 Code = TYPE_OBJC_TYPE_PARAM;
534}
535
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000536void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000537 Record.AddTypeRef(T->getBaseType());
Douglas Gregore83b9562015-07-07 03:57:53 +0000538 Record.push_back(T->getTypeArgsAsWritten().size());
539 for (auto TypeArg : T->getTypeArgsAsWritten())
Richard Smith69c82bf2016-04-01 22:52:03 +0000540 Record.AddTypeRef(TypeArg);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000541 Record.push_back(T->getNumProtocols());
Aaron Ballman1683f7b2014-03-17 15:55:30 +0000542 for (const auto *I : T->quals())
Richard Smith69c82bf2016-04-01 22:52:03 +0000543 Record.AddDeclRef(I);
Douglas Gregorab209d82015-07-07 03:58:42 +0000544 Record.push_back(T->isKindOfTypeAsWritten());
Sebastian Redl539c5062010-08-18 23:57:32 +0000545 Code = TYPE_OBJC_OBJECT;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000546}
547
Steve Narofffb4330f2009-06-17 22:40:22 +0000548void
Sebastian Redl42a0f6a2010-08-18 23:56:27 +0000549ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000550 Record.AddTypeRef(T->getPointeeType());
Sebastian Redl539c5062010-08-18 23:57:32 +0000551 Code = TYPE_OBJC_OBJECT_POINTER;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000552}
553
Eli Friedman0dfb8892011-10-06 23:00:33 +0000554void
555ASTTypeWriter::VisitAtomicType(const AtomicType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000556 Record.AddTypeRef(T->getValueType());
Eli Friedman0dfb8892011-10-06 23:00:33 +0000557 Code = TYPE_ATOMIC;
558}
559
Xiuli Pan9c14e282016-01-09 12:53:17 +0000560void
561ASTTypeWriter::VisitPipeType(const PipeType *T) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000562 Record.AddTypeRef(T->getElementType());
Joey Goulye3c85de2016-12-01 11:30:49 +0000563 Record.push_back(T->isReadOnly());
564 Code = TYPE_PIPE;
Xiuli Pan9c14e282016-01-09 12:53:17 +0000565}
566
John McCall8f115c62009-10-16 21:56:05 +0000567namespace {
568
569class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
Richard Smith290d8012016-04-06 17:06:00 +0000570 ASTRecordWriter &Record;
John McCall8f115c62009-10-16 21:56:05 +0000571
572public:
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000573 TypeLocWriter(ASTRecordWriter &Record) : Record(Record) {}
John McCall8f115c62009-10-16 21:56:05 +0000574
John McCall17001972009-10-18 01:05:36 +0000575#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCall8f115c62009-10-16 21:56:05 +0000576#define TYPELOC(CLASS, PARENT) \
John McCall17001972009-10-18 01:05:36 +0000577 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +0000578#include "clang/AST/TypeLocNodes.def"
579
John McCall17001972009-10-18 01:05:36 +0000580 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
581 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +0000582};
583
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000584} // namespace
John McCall8f115c62009-10-16 21:56:05 +0000585
John McCall17001972009-10-18 01:05:36 +0000586void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
587 // nothing to do
John McCall8f115c62009-10-16 21:56:05 +0000588}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000589
John McCall17001972009-10-18 01:05:36 +0000590void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000591 Record.AddSourceLocation(TL.getBuiltinLoc());
Douglas Gregorc9b7a592010-01-18 18:04:31 +0000592 if (TL.needsExtraLocalData()) {
Faisal Vali090da2d2018-01-01 18:23:28 +0000593 Record.push_back(TL.getWrittenTypeSpec());
594 Record.push_back(TL.getWrittenSignSpec());
595 Record.push_back(TL.getWrittenWidthSpec());
Douglas Gregorc9b7a592010-01-18 18:04:31 +0000596 Record.push_back(TL.hasModeAttr());
597 }
John McCall8f115c62009-10-16 21:56:05 +0000598}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000599
John McCall17001972009-10-18 01:05:36 +0000600void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000601 Record.AddSourceLocation(TL.getNameLoc());
John McCall8f115c62009-10-16 21:56:05 +0000602}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000603
John McCall17001972009-10-18 01:05:36 +0000604void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000605 Record.AddSourceLocation(TL.getStarLoc());
John McCall8f115c62009-10-16 21:56:05 +0000606}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000607
Reid Kleckner8a365022013-06-24 17:51:48 +0000608void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
609 // nothing to do
610}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000611
Reid Kleckner0503a872013-12-05 01:23:43 +0000612void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
613 // nothing to do
614}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000615
John McCall17001972009-10-18 01:05:36 +0000616void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000617 Record.AddSourceLocation(TL.getCaretLoc());
John McCall8f115c62009-10-16 21:56:05 +0000618}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000619
John McCall17001972009-10-18 01:05:36 +0000620void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000621 Record.AddSourceLocation(TL.getAmpLoc());
John McCall8f115c62009-10-16 21:56:05 +0000622}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000623
John McCall17001972009-10-18 01:05:36 +0000624void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000625 Record.AddSourceLocation(TL.getAmpAmpLoc());
John McCall8f115c62009-10-16 21:56:05 +0000626}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000627
John McCall17001972009-10-18 01:05:36 +0000628void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000629 Record.AddSourceLocation(TL.getStarLoc());
630 Record.AddTypeSourceInfo(TL.getClassTInfo());
John McCall8f115c62009-10-16 21:56:05 +0000631}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000632
John McCall17001972009-10-18 01:05:36 +0000633void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000634 Record.AddSourceLocation(TL.getLBracketLoc());
635 Record.AddSourceLocation(TL.getRBracketLoc());
John McCall17001972009-10-18 01:05:36 +0000636 Record.push_back(TL.getSizeExpr() ? 1 : 0);
637 if (TL.getSizeExpr())
Richard Smith290d8012016-04-06 17:06:00 +0000638 Record.AddStmt(TL.getSizeExpr());
John McCall8f115c62009-10-16 21:56:05 +0000639}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000640
John McCall17001972009-10-18 01:05:36 +0000641void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
642 VisitArrayTypeLoc(TL);
643}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000644
John McCall17001972009-10-18 01:05:36 +0000645void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
646 VisitArrayTypeLoc(TL);
647}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000648
John McCall17001972009-10-18 01:05:36 +0000649void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
650 VisitArrayTypeLoc(TL);
651}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000652
John McCall17001972009-10-18 01:05:36 +0000653void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
654 DependentSizedArrayTypeLoc TL) {
655 VisitArrayTypeLoc(TL);
656}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000657
Andrew Gozillon572bbb02017-10-02 06:25:51 +0000658void TypeLocWriter::VisitDependentAddressSpaceTypeLoc(
659 DependentAddressSpaceTypeLoc TL) {
660 Record.AddSourceLocation(TL.getAttrNameLoc());
661 SourceRange range = TL.getAttrOperandParensRange();
662 Record.AddSourceLocation(range.getBegin());
663 Record.AddSourceLocation(range.getEnd());
664 Record.AddStmt(TL.getAttrExprOperand());
665}
666
John McCall17001972009-10-18 01:05:36 +0000667void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
668 DependentSizedExtVectorTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000669 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000670}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000671
John McCall17001972009-10-18 01:05:36 +0000672void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000673 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000674}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000675
John McCall17001972009-10-18 01:05:36 +0000676void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000677 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000678}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000679
John McCall17001972009-10-18 01:05:36 +0000680void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000681 Record.AddSourceLocation(TL.getLocalRangeBegin());
682 Record.AddSourceLocation(TL.getLParenLoc());
683 Record.AddSourceLocation(TL.getRParenLoc());
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +0000684 Record.AddSourceRange(TL.getExceptionSpecRange());
Richard Smith69c82bf2016-04-01 22:52:03 +0000685 Record.AddSourceLocation(TL.getLocalRangeEnd());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +0000686 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000687 Record.AddDeclRef(TL.getParam(i));
John McCall17001972009-10-18 01:05:36 +0000688}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000689
John McCall17001972009-10-18 01:05:36 +0000690void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
691 VisitFunctionTypeLoc(TL);
692}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000693
John McCall17001972009-10-18 01:05:36 +0000694void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
695 VisitFunctionTypeLoc(TL);
696}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000697
John McCallb96ec562009-12-04 22:46:56 +0000698void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000699 Record.AddSourceLocation(TL.getNameLoc());
John McCallb96ec562009-12-04 22:46:56 +0000700}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000701
John McCall17001972009-10-18 01:05:36 +0000702void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000703 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000704}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000705
Manman Rene6be26c2016-09-13 17:25:08 +0000706void TypeLocWriter::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
707 if (TL.getNumProtocols()) {
708 Record.AddSourceLocation(TL.getProtocolLAngleLoc());
709 Record.AddSourceLocation(TL.getProtocolRAngleLoc());
710 }
711 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
712 Record.AddSourceLocation(TL.getProtocolLoc(i));
713}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000714
John McCall17001972009-10-18 01:05:36 +0000715void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000716 Record.AddSourceLocation(TL.getTypeofLoc());
717 Record.AddSourceLocation(TL.getLParenLoc());
718 Record.AddSourceLocation(TL.getRParenLoc());
John McCall17001972009-10-18 01:05:36 +0000719}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000720
John McCall17001972009-10-18 01:05:36 +0000721void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000722 Record.AddSourceLocation(TL.getTypeofLoc());
723 Record.AddSourceLocation(TL.getLParenLoc());
724 Record.AddSourceLocation(TL.getRParenLoc());
725 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
John McCall17001972009-10-18 01:05:36 +0000726}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000727
John McCall17001972009-10-18 01:05:36 +0000728void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000729 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000730}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000731
Alexis Hunte852b102011-05-24 22:41:36 +0000732void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000733 Record.AddSourceLocation(TL.getKWLoc());
734 Record.AddSourceLocation(TL.getLParenLoc());
735 Record.AddSourceLocation(TL.getRParenLoc());
736 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
Alexis Hunte852b102011-05-24 22:41:36 +0000737}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000738
Richard Smith30482bc2011-02-20 03:19:35 +0000739void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000740 Record.AddSourceLocation(TL.getNameLoc());
Richard Smith30482bc2011-02-20 03:19:35 +0000741}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000742
Richard Smith600b5262017-01-26 20:40:47 +0000743void TypeLocWriter::VisitDeducedTemplateSpecializationTypeLoc(
744 DeducedTemplateSpecializationTypeLoc TL) {
745 Record.AddSourceLocation(TL.getTemplateNameLoc());
746}
747
John McCall17001972009-10-18 01:05:36 +0000748void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000749 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000750}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000751
John McCall17001972009-10-18 01:05:36 +0000752void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000753 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000754}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000755
John McCall81904512011-01-06 01:58:22 +0000756void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000757 Record.AddSourceLocation(TL.getAttrNameLoc());
John McCall81904512011-01-06 01:58:22 +0000758 if (TL.hasAttrOperand()) {
759 SourceRange range = TL.getAttrOperandParensRange();
Richard Smith69c82bf2016-04-01 22:52:03 +0000760 Record.AddSourceLocation(range.getBegin());
761 Record.AddSourceLocation(range.getEnd());
John McCall81904512011-01-06 01:58:22 +0000762 }
763 if (TL.hasAttrExprOperand()) {
764 Expr *operand = TL.getAttrExprOperand();
765 Record.push_back(operand ? 1 : 0);
Richard Smith290d8012016-04-06 17:06:00 +0000766 if (operand) Record.AddStmt(operand);
John McCall81904512011-01-06 01:58:22 +0000767 } else if (TL.hasAttrEnumOperand()) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000768 Record.AddSourceLocation(TL.getAttrEnumOperandLoc());
John McCall81904512011-01-06 01:58:22 +0000769 }
770}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000771
John McCall17001972009-10-18 01:05:36 +0000772void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000773 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000774}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000775
John McCallcebee162009-10-18 09:09:24 +0000776void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
777 SubstTemplateTypeParmTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000778 Record.AddSourceLocation(TL.getNameLoc());
John McCallcebee162009-10-18 09:09:24 +0000779}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000780
Douglas Gregorada4b792011-01-14 02:55:32 +0000781void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
782 SubstTemplateTypeParmPackTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000783 Record.AddSourceLocation(TL.getNameLoc());
Douglas Gregorada4b792011-01-14 02:55:32 +0000784}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000785
John McCall17001972009-10-18 01:05:36 +0000786void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
787 TemplateSpecializationTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000788 Record.AddSourceLocation(TL.getTemplateKeywordLoc());
789 Record.AddSourceLocation(TL.getTemplateNameLoc());
790 Record.AddSourceLocation(TL.getLAngleLoc());
791 Record.AddSourceLocation(TL.getRAngleLoc());
John McCall0ad16662009-10-29 08:12:44 +0000792 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000793 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
794 TL.getArgLoc(i).getLocInfo());
John McCall17001972009-10-18 01:05:36 +0000795}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000796
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000797void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000798 Record.AddSourceLocation(TL.getLParenLoc());
799 Record.AddSourceLocation(TL.getRParenLoc());
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000800}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000801
Abramo Bagnara6150c882010-05-11 21:36:43 +0000802void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000803 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
804 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
John McCall17001972009-10-18 01:05:36 +0000805}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000806
John McCalle78aac42010-03-10 03:28:59 +0000807void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000808 Record.AddSourceLocation(TL.getNameLoc());
John McCalle78aac42010-03-10 03:28:59 +0000809}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000810
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +0000811void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000812 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
813 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
814 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000815}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000816
John McCallc392f372010-06-11 00:33:02 +0000817void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
818 DependentTemplateSpecializationTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000819 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
820 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
821 Record.AddSourceLocation(TL.getTemplateKeywordLoc());
822 Record.AddSourceLocation(TL.getTemplateNameLoc());
823 Record.AddSourceLocation(TL.getLAngleLoc());
824 Record.AddSourceLocation(TL.getRAngleLoc());
John McCallc392f372010-06-11 00:33:02 +0000825 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
Richard Smith69c82bf2016-04-01 22:52:03 +0000826 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
827 TL.getArgLoc(I).getLocInfo());
John McCallc392f372010-06-11 00:33:02 +0000828}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000829
Douglas Gregord2fa7662010-12-20 02:24:11 +0000830void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000831 Record.AddSourceLocation(TL.getEllipsisLoc());
Douglas Gregord2fa7662010-12-20 02:24:11 +0000832}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000833
John McCall17001972009-10-18 01:05:36 +0000834void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000835 Record.AddSourceLocation(TL.getNameLoc());
John McCall8b07ec22010-05-15 11:32:37 +0000836}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000837
John McCall8b07ec22010-05-15 11:32:37 +0000838void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
839 Record.push_back(TL.hasBaseTypeAsWritten());
Richard Smith69c82bf2016-04-01 22:52:03 +0000840 Record.AddSourceLocation(TL.getTypeArgsLAngleLoc());
841 Record.AddSourceLocation(TL.getTypeArgsRAngleLoc());
Douglas Gregore9d95f12015-07-07 03:57:35 +0000842 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000843 Record.AddTypeSourceInfo(TL.getTypeArgTInfo(i));
844 Record.AddSourceLocation(TL.getProtocolLAngleLoc());
845 Record.AddSourceLocation(TL.getProtocolRAngleLoc());
John McCall17001972009-10-18 01:05:36 +0000846 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000847 Record.AddSourceLocation(TL.getProtocolLoc(i));
John McCall8f115c62009-10-16 21:56:05 +0000848}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000849
John McCallfc93cf92009-10-22 22:37:11 +0000850void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000851 Record.AddSourceLocation(TL.getStarLoc());
John McCallfc93cf92009-10-22 22:37:11 +0000852}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000853
Eli Friedman0dfb8892011-10-06 23:00:33 +0000854void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000855 Record.AddSourceLocation(TL.getKWLoc());
856 Record.AddSourceLocation(TL.getLParenLoc());
857 Record.AddSourceLocation(TL.getRParenLoc());
Eli Friedman0dfb8892011-10-06 23:00:33 +0000858}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000859
Xiuli Pan9c14e282016-01-09 12:53:17 +0000860void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000861 Record.AddSourceLocation(TL.getKWLoc());
Xiuli Pan9c14e282016-01-09 12:53:17 +0000862}
John McCall8f115c62009-10-16 21:56:05 +0000863
Richard Smith01b2cb42014-07-26 06:37:51 +0000864void ASTWriter::WriteTypeAbbrevs() {
865 using namespace llvm;
866
David Blaikieb44f0bf2017-01-04 22:36:43 +0000867 std::shared_ptr<BitCodeAbbrev> Abv;
Richard Smith01b2cb42014-07-26 06:37:51 +0000868
869 // Abbreviation for TYPE_EXT_QUAL
David Blaikieb44f0bf2017-01-04 22:36:43 +0000870 Abv = std::make_shared<BitCodeAbbrev>();
Richard Smith01b2cb42014-07-26 06:37:51 +0000871 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
872 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
873 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals
David Blaikieb44f0bf2017-01-04 22:36:43 +0000874 TypeExtQualAbbrev = Stream.EmitAbbrev(std::move(Abv));
Richard Smith01b2cb42014-07-26 06:37:51 +0000875
876 // Abbreviation for TYPE_FUNCTION_PROTO
David Blaikieb44f0bf2017-01-04 22:36:43 +0000877 Abv = std::make_shared<BitCodeAbbrev>();
Richard Smith01b2cb42014-07-26 06:37:51 +0000878 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_FUNCTION_PROTO));
879 // FunctionType
880 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ReturnType
881 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NoReturn
882 Abv->Add(BitCodeAbbrevOp(0)); // HasRegParm
883 Abv->Add(BitCodeAbbrevOp(0)); // RegParm
884 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // CC
885 Abv->Add(BitCodeAbbrevOp(0)); // ProducesResult
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +0000886 Abv->Add(BitCodeAbbrevOp(0)); // NoCallerSavedRegs
Richard Smith01b2cb42014-07-26 06:37:51 +0000887 // FunctionProtoType
888 Abv->Add(BitCodeAbbrevOp(0)); // IsVariadic
889 Abv->Add(BitCodeAbbrevOp(0)); // HasTrailingReturn
890 Abv->Add(BitCodeAbbrevOp(0)); // TypeQuals
891 Abv->Add(BitCodeAbbrevOp(0)); // RefQualifier
892 Abv->Add(BitCodeAbbrevOp(EST_None)); // ExceptionSpec
893 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // NumParams
894 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
895 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Params
David Blaikieb44f0bf2017-01-04 22:36:43 +0000896 TypeFunctionProtoAbbrev = Stream.EmitAbbrev(std::move(Abv));
Richard Smith01b2cb42014-07-26 06:37:51 +0000897}
898
Chris Lattner19cea4e2009-04-22 05:57:30 +0000899//===----------------------------------------------------------------------===//
Sebastian Redl55c0ad52010-08-18 23:56:21 +0000900// ASTWriter Implementation
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000901//===----------------------------------------------------------------------===//
902
Chris Lattner28fa4e62009-04-26 22:26:21 +0000903static void EmitBlockID(unsigned ID, const char *Name,
904 llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000905 ASTWriter::RecordDataImpl &Record) {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000906 Record.clear();
907 Record.push_back(ID);
908 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
909
910 // Emit the block name if present.
Craig Toppera13603a2014-05-22 05:54:18 +0000911 if (!Name || Name[0] == 0)
912 return;
Chris Lattner28fa4e62009-04-26 22:26:21 +0000913 Record.clear();
914 while (*Name)
915 Record.push_back(*Name++);
916 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
917}
918
919static void EmitRecordID(unsigned ID, const char *Name,
920 llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000921 ASTWriter::RecordDataImpl &Record) {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000922 Record.clear();
923 Record.push_back(ID);
924 while (*Name)
925 Record.push_back(*Name++);
926 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000927}
928
929static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000930 ASTWriter::RecordDataImpl &Record) {
Sebastian Redl539c5062010-08-18 23:57:32 +0000931#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
Chris Lattnerccac3a62009-04-27 00:49:53 +0000932 RECORD(STMT_STOP);
933 RECORD(STMT_NULL_PTR);
Richard Smith01b2cb42014-07-26 06:37:51 +0000934 RECORD(STMT_REF_PTR);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000935 RECORD(STMT_NULL);
936 RECORD(STMT_COMPOUND);
937 RECORD(STMT_CASE);
938 RECORD(STMT_DEFAULT);
939 RECORD(STMT_LABEL);
Richard Smithc202b282012-04-14 00:33:13 +0000940 RECORD(STMT_ATTRIBUTED);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000941 RECORD(STMT_IF);
942 RECORD(STMT_SWITCH);
943 RECORD(STMT_WHILE);
944 RECORD(STMT_DO);
945 RECORD(STMT_FOR);
946 RECORD(STMT_GOTO);
947 RECORD(STMT_INDIRECT_GOTO);
948 RECORD(STMT_CONTINUE);
949 RECORD(STMT_BREAK);
950 RECORD(STMT_RETURN);
951 RECORD(STMT_DECL);
Chad Rosierde70e0e2012-08-25 00:11:56 +0000952 RECORD(STMT_GCCASM);
Chad Rosiere30d4992012-08-24 23:51:02 +0000953 RECORD(STMT_MSASM);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000954 RECORD(EXPR_PREDEFINED);
955 RECORD(EXPR_DECL_REF);
956 RECORD(EXPR_INTEGER_LITERAL);
957 RECORD(EXPR_FLOATING_LITERAL);
958 RECORD(EXPR_IMAGINARY_LITERAL);
959 RECORD(EXPR_STRING_LITERAL);
960 RECORD(EXPR_CHARACTER_LITERAL);
961 RECORD(EXPR_PAREN);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000962 RECORD(EXPR_PAREN_LIST);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000963 RECORD(EXPR_UNARY_OPERATOR);
964 RECORD(EXPR_SIZEOF_ALIGN_OF);
965 RECORD(EXPR_ARRAY_SUBSCRIPT);
966 RECORD(EXPR_CALL);
967 RECORD(EXPR_MEMBER);
968 RECORD(EXPR_BINARY_OPERATOR);
969 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
970 RECORD(EXPR_CONDITIONAL_OPERATOR);
971 RECORD(EXPR_IMPLICIT_CAST);
972 RECORD(EXPR_CSTYLE_CAST);
973 RECORD(EXPR_COMPOUND_LITERAL);
974 RECORD(EXPR_EXT_VECTOR_ELEMENT);
975 RECORD(EXPR_INIT_LIST);
976 RECORD(EXPR_DESIGNATED_INIT);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000977 RECORD(EXPR_DESIGNATED_INIT_UPDATE);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000978 RECORD(EXPR_IMPLICIT_VALUE_INIT);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000979 RECORD(EXPR_NO_INIT);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000980 RECORD(EXPR_VA_ARG);
981 RECORD(EXPR_ADDR_LABEL);
982 RECORD(EXPR_STMT);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000983 RECORD(EXPR_CHOOSE);
984 RECORD(EXPR_GNU_NULL);
985 RECORD(EXPR_SHUFFLE_VECTOR);
986 RECORD(EXPR_BLOCK);
Peter Collingbourne91147592011-04-15 00:35:48 +0000987 RECORD(EXPR_GENERIC_SELECTION);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000988 RECORD(EXPR_OBJC_STRING_LITERAL);
Patrick Beard0caa3942012-04-19 00:25:12 +0000989 RECORD(EXPR_OBJC_BOXED_EXPRESSION);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000990 RECORD(EXPR_OBJC_ARRAY_LITERAL);
991 RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000992 RECORD(EXPR_OBJC_ENCODE);
993 RECORD(EXPR_OBJC_SELECTOR_EXPR);
994 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
995 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
996 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
997 RECORD(EXPR_OBJC_KVC_REF_EXPR);
998 RECORD(EXPR_OBJC_MESSAGE_EXPR);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000999 RECORD(STMT_OBJC_FOR_COLLECTION);
1000 RECORD(STMT_OBJC_CATCH);
1001 RECORD(STMT_OBJC_FINALLY);
1002 RECORD(STMT_OBJC_AT_TRY);
1003 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
1004 RECORD(STMT_OBJC_AT_THROW);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001005 RECORD(EXPR_OBJC_BOOL_LITERAL);
Richard Smith01b2cb42014-07-26 06:37:51 +00001006 RECORD(STMT_CXX_CATCH);
1007 RECORD(STMT_CXX_TRY);
1008 RECORD(STMT_CXX_FOR_RANGE);
Sam Weinige83b3ac2010-02-07 06:32:43 +00001009 RECORD(EXPR_CXX_OPERATOR_CALL);
Richard Smithf1b4b8b2014-07-27 04:29:04 +00001010 RECORD(EXPR_CXX_MEMBER_CALL);
Sam Weinige83b3ac2010-02-07 06:32:43 +00001011 RECORD(EXPR_CXX_CONSTRUCT);
Richard Smithf1b4b8b2014-07-27 04:29:04 +00001012 RECORD(EXPR_CXX_TEMPORARY_OBJECT);
Sam Weinige83b3ac2010-02-07 06:32:43 +00001013 RECORD(EXPR_CXX_STATIC_CAST);
1014 RECORD(EXPR_CXX_DYNAMIC_CAST);
1015 RECORD(EXPR_CXX_REINTERPRET_CAST);
1016 RECORD(EXPR_CXX_CONST_CAST);
1017 RECORD(EXPR_CXX_FUNCTIONAL_CAST);
Richard Smithc67fdd42012-03-07 08:35:16 +00001018 RECORD(EXPR_USER_DEFINED_LITERAL);
Richard Smithcc1b96d2013-06-12 22:31:48 +00001019 RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
Sam Weinige83b3ac2010-02-07 06:32:43 +00001020 RECORD(EXPR_CXX_BOOL_LITERAL);
1021 RECORD(EXPR_CXX_NULL_PTR_LITERAL);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001022 RECORD(EXPR_CXX_TYPEID_EXPR);
1023 RECORD(EXPR_CXX_TYPEID_TYPE);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001024 RECORD(EXPR_CXX_THIS);
1025 RECORD(EXPR_CXX_THROW);
1026 RECORD(EXPR_CXX_DEFAULT_ARG);
Richard Smith01b2cb42014-07-26 06:37:51 +00001027 RECORD(EXPR_CXX_DEFAULT_INIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001028 RECORD(EXPR_CXX_BIND_TEMPORARY);
1029 RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
1030 RECORD(EXPR_CXX_NEW);
1031 RECORD(EXPR_CXX_DELETE);
1032 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
1033 RECORD(EXPR_EXPR_WITH_CLEANUPS);
1034 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
1035 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
1036 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
1037 RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
1038 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
Richard Smith01b2cb42014-07-26 06:37:51 +00001039 RECORD(EXPR_CXX_EXPRESSION_TRAIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001040 RECORD(EXPR_CXX_NOEXCEPT);
1041 RECORD(EXPR_OPAQUE_VALUE);
Richard Smith01b2cb42014-07-26 06:37:51 +00001042 RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR);
1043 RECORD(EXPR_TYPE_TRAIT);
1044 RECORD(EXPR_ARRAY_TYPE_TRAIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001045 RECORD(EXPR_PACK_EXPANSION);
1046 RECORD(EXPR_SIZEOF_PACK);
Richard Smith01b2cb42014-07-26 06:37:51 +00001047 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001048 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
Richard Smith01b2cb42014-07-26 06:37:51 +00001049 RECORD(EXPR_FUNCTION_PARM_PACK);
1050 RECORD(EXPR_MATERIALIZE_TEMPORARY);
Peter Collingbourne41f85462011-02-09 21:07:24 +00001051 RECORD(EXPR_CUDA_KERNEL_CALL);
Richard Smith01b2cb42014-07-26 06:37:51 +00001052 RECORD(EXPR_CXX_UUIDOF_EXPR);
1053 RECORD(EXPR_CXX_UUIDOF_TYPE);
1054 RECORD(EXPR_LAMBDA);
Chris Lattnerccac3a62009-04-27 00:49:53 +00001055#undef RECORD
Chris Lattner28fa4e62009-04-26 22:26:21 +00001056}
Mike Stump11289f42009-09-09 15:08:12 +00001057
Sebastian Redl55c0ad52010-08-18 23:56:21 +00001058void ASTWriter::WriteBlockInfoBlock() {
Chris Lattner28fa4e62009-04-26 22:26:21 +00001059 RecordData Record;
Peter Collingbourned3a6c702016-11-01 01:18:57 +00001060 Stream.EnterBlockInfoBlock();
Mike Stump11289f42009-09-09 15:08:12 +00001061
Sebastian Redl539c5062010-08-18 23:57:32 +00001062#define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
1063#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
Mike Stump11289f42009-09-09 15:08:12 +00001064
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001065 // Control Block.
1066 BLOCK(CONTROL_BLOCK);
1067 RECORD(METADATA);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001068 RECORD(MODULE_NAME);
Richard Smithfa715652015-08-31 22:43:10 +00001069 RECORD(MODULE_DIRECTORY);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001070 RECORD(MODULE_MAP_FILE);
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001071 RECORD(IMPORTS);
Douglas Gregorfad10d82012-10-18 18:36:53 +00001072 RECORD(ORIGINAL_FILE);
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001073 RECORD(ORIGINAL_PCH_DIR);
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +00001074 RECORD(ORIGINAL_FILE_ID);
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001075 RECORD(INPUT_FILE_OFFSETS);
Richard Smith0516b182015-09-08 19:40:14 +00001076
1077 BLOCK(OPTIONS_BLOCK);
1078 RECORD(LANGUAGE_OPTIONS);
1079 RECORD(TARGET_OPTIONS);
Douglas Gregorc6317db2012-10-24 15:49:58 +00001080 RECORD(FILE_SYSTEM_OPTIONS);
Douglas Gregor2d302362012-10-24 16:50:34 +00001081 RECORD(HEADER_SEARCH_OPTIONS);
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001082 RECORD(PREPROCESSOR_OPTIONS);
1083
Douglas Gregor108cb222012-10-19 00:45:00 +00001084 BLOCK(INPUT_FILES_BLOCK);
1085 RECORD(INPUT_FILE);
1086
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001087 // AST Top-Level Block.
1088 BLOCK(AST_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001089 RECORD(TYPE_OFFSET);
1090 RECORD(DECL_OFFSET);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001091 RECORD(IDENTIFIER_OFFSET);
1092 RECORD(IDENTIFIER_TABLE);
Ben Langmuir332aafe2014-01-31 01:06:56 +00001093 RECORD(EAGERLY_DESERIALIZED_DECLS);
David Blaikie9ffe5a32017-01-30 05:00:26 +00001094 RECORD(MODULAR_CODEGEN_DECLS);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001095 RECORD(SPECIAL_TYPES);
1096 RECORD(STATISTICS);
1097 RECORD(TENTATIVE_DEFINITIONS);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001098 RECORD(SELECTOR_OFFSETS);
1099 RECORD(METHOD_POOL);
1100 RECORD(PP_COUNTER_VALUE);
Douglas Gregor258ae542009-04-27 06:38:32 +00001101 RECORD(SOURCE_LOCATION_OFFSETS);
1102 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor61cac2b2009-04-27 20:06:05 +00001103 RECORD(EXT_VECTOR_DECLS);
Richard Smithfa715652015-08-31 22:43:10 +00001104 RECORD(UNUSED_FILESCOPED_DECLS);
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00001105 RECORD(PPD_ENTITIES_OFFSETS);
Richard Smithfa715652015-08-31 22:43:10 +00001106 RECORD(VTABLE_USES);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00001107 RECORD(REFERENCED_SELECTOR_POOL);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001108 RECORD(TU_UPDATE_LEXICAL);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001109 RECORD(SEMA_DECL_REFS);
1110 RECORD(WEAK_UNDECLARED_IDENTIFIERS);
1111 RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001112 RECORD(UPDATE_VISIBLE);
1113 RECORD(DECL_UPDATE_OFFSETS);
1114 RECORD(DECL_UPDATES);
Peter Collingbourne5df20e02011-02-15 19:46:30 +00001115 RECORD(CUDA_SPECIAL_DECL_REFS);
Douglas Gregor09b69892011-02-10 17:09:37 +00001116 RECORD(HEADER_SEARCH_TABLE);
Peter Collingbourne5df20e02011-02-15 19:46:30 +00001117 RECORD(FP_PRAGMA_OPTIONS);
1118 RECORD(OPENCL_EXTENSIONS);
Yaxun Liu5b746652016-12-18 05:18:55 +00001119 RECORD(OPENCL_EXTENSION_TYPES);
1120 RECORD(OPENCL_EXTENSION_DECLS);
Alexis Hunt27a761d2011-05-04 23:29:54 +00001121 RECORD(DELEGATING_CTORS);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001122 RECORD(KNOWN_NAMESPACES);
Douglas Gregor78d0b572011-08-04 16:39:39 +00001123 RECORD(MODULE_OFFSET_MAP);
1124 RECORD(SOURCE_MANAGER_LINE_TABLE);
Douglas Gregor404cdde2012-01-27 01:47:08 +00001125 RECORD(OBJC_CATEGORIES_MAP);
Douglas Gregor66e4add2011-12-19 21:09:25 +00001126 RECORD(FILE_SORTED_DECLS);
1127 RECORD(IMPORTED_MODULES);
Douglas Gregor404cdde2012-01-27 01:47:08 +00001128 RECORD(OBJC_CATEGORIES);
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00001129 RECORD(MACRO_OFFSET);
Richard Smithfa715652015-08-31 22:43:10 +00001130 RECORD(INTERESTING_IDENTIFIERS);
1131 RECORD(UNDEFINED_BUT_USED);
Richard Smithe40f2ba2013-08-07 21:41:30 +00001132 RECORD(LATE_PARSED_TEMPLATE);
Dario Domizioli13a0a382014-05-23 12:13:25 +00001133 RECORD(OPTIMIZE_PRAGMA_OPTIONS);
Nico Weber779355f2016-03-02 23:22:00 +00001134 RECORD(MSSTRUCT_PRAGMA_OPTIONS);
Nico Weber42932312016-03-03 00:17:35 +00001135 RECORD(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS);
Richard Smithfa715652015-08-31 22:43:10 +00001136 RECORD(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES);
Richard Smithfa715652015-08-31 22:43:10 +00001137 RECORD(DELETE_EXPRS_TO_ANALYZE);
Justin Lebar67a78a62016-10-08 22:15:58 +00001138 RECORD(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH);
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00001139 RECORD(PP_CONDITIONAL_STACK);
Douglas Gregor358cd442012-01-15 16:58:34 +00001140
Chris Lattner28fa4e62009-04-26 22:26:21 +00001141 // SourceManager Block.
Chris Lattner64031982009-04-27 00:40:25 +00001142 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001143 RECORD(SM_SLOC_FILE_ENTRY);
1144 RECORD(SM_SLOC_BUFFER_ENTRY);
1145 RECORD(SM_SLOC_BUFFER_BLOB);
Richard Smithaada85c2016-02-06 02:06:43 +00001146 RECORD(SM_SLOC_BUFFER_BLOB_COMPRESSED);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001147 RECORD(SM_SLOC_EXPANSION_ENTRY);
Mike Stump11289f42009-09-09 15:08:12 +00001148
Chris Lattner28fa4e62009-04-26 22:26:21 +00001149 // Preprocessor Block.
Chris Lattner64031982009-04-27 00:40:25 +00001150 BLOCK(PREPROCESSOR_BLOCK);
Richard Smithec216502015-02-13 19:48:37 +00001151 RECORD(PP_MACRO_DIRECTIVE_HISTORY);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001152 RECORD(PP_MACRO_FUNCTION_LIKE);
Richard Smithd7329392015-04-21 21:46:32 +00001153 RECORD(PP_MACRO_OBJECT_LIKE);
1154 RECORD(PP_MODULE_MACRO);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001155 RECORD(PP_TOKEN);
Richard Smithec216502015-02-13 19:48:37 +00001156
Richard Smithfa715652015-08-31 22:43:10 +00001157 // Submodule Block.
1158 BLOCK(SUBMODULE_BLOCK);
1159 RECORD(SUBMODULE_METADATA);
1160 RECORD(SUBMODULE_DEFINITION);
1161 RECORD(SUBMODULE_UMBRELLA_HEADER);
1162 RECORD(SUBMODULE_HEADER);
1163 RECORD(SUBMODULE_TOPHEADER);
1164 RECORD(SUBMODULE_UMBRELLA_DIR);
1165 RECORD(SUBMODULE_IMPORTS);
1166 RECORD(SUBMODULE_EXPORTS);
1167 RECORD(SUBMODULE_REQUIRES);
1168 RECORD(SUBMODULE_EXCLUDED_HEADER);
1169 RECORD(SUBMODULE_LINK_LIBRARY);
1170 RECORD(SUBMODULE_CONFIG_MACRO);
1171 RECORD(SUBMODULE_CONFLICT);
1172 RECORD(SUBMODULE_PRIVATE_HEADER);
1173 RECORD(SUBMODULE_TEXTUAL_HEADER);
1174 RECORD(SUBMODULE_PRIVATE_TEXTUAL_HEADER);
Richard Smithdc1f0422016-07-20 19:10:16 +00001175 RECORD(SUBMODULE_INITIALIZERS);
Douglas Gregorf0b11de2017-09-14 23:38:44 +00001176 RECORD(SUBMODULE_EXPORT_AS);
Richard Smithfa715652015-08-31 22:43:10 +00001177
1178 // Comments Block.
1179 BLOCK(COMMENTS_BLOCK);
1180 RECORD(COMMENTS_RAW_COMMENT);
1181
Douglas Gregor12bfa382009-10-17 00:13:19 +00001182 // Decls and Types block.
1183 BLOCK(DECLTYPES_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001184 RECORD(TYPE_EXT_QUAL);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001185 RECORD(TYPE_COMPLEX);
1186 RECORD(TYPE_POINTER);
1187 RECORD(TYPE_BLOCK_POINTER);
1188 RECORD(TYPE_LVALUE_REFERENCE);
1189 RECORD(TYPE_RVALUE_REFERENCE);
1190 RECORD(TYPE_MEMBER_POINTER);
1191 RECORD(TYPE_CONSTANT_ARRAY);
1192 RECORD(TYPE_INCOMPLETE_ARRAY);
1193 RECORD(TYPE_VARIABLE_ARRAY);
1194 RECORD(TYPE_VECTOR);
1195 RECORD(TYPE_EXT_VECTOR);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001196 RECORD(TYPE_FUNCTION_NO_PROTO);
Richard Smithf1b4b8b2014-07-27 04:29:04 +00001197 RECORD(TYPE_FUNCTION_PROTO);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001198 RECORD(TYPE_TYPEDEF);
1199 RECORD(TYPE_TYPEOF_EXPR);
1200 RECORD(TYPE_TYPEOF);
1201 RECORD(TYPE_RECORD);
1202 RECORD(TYPE_ENUM);
1203 RECORD(TYPE_OBJC_INTERFACE);
Steve Narofffb4330f2009-06-17 22:40:22 +00001204 RECORD(TYPE_OBJC_OBJECT_POINTER);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001205 RECORD(TYPE_DECLTYPE);
1206 RECORD(TYPE_ELABORATED);
1207 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
1208 RECORD(TYPE_UNRESOLVED_USING);
1209 RECORD(TYPE_INJECTED_CLASS_NAME);
1210 RECORD(TYPE_OBJC_OBJECT);
1211 RECORD(TYPE_TEMPLATE_TYPE_PARM);
1212 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
1213 RECORD(TYPE_DEPENDENT_NAME);
1214 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
1215 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
1216 RECORD(TYPE_PAREN);
1217 RECORD(TYPE_PACK_EXPANSION);
1218 RECORD(TYPE_ATTRIBUTED);
1219 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
Richard Smithf1b4b8b2014-07-27 04:29:04 +00001220 RECORD(TYPE_AUTO);
1221 RECORD(TYPE_UNARY_TRANSFORM);
Eli Friedman0dfb8892011-10-06 23:00:33 +00001222 RECORD(TYPE_ATOMIC);
Richard Smithf1b4b8b2014-07-27 04:29:04 +00001223 RECORD(TYPE_DECAYED);
1224 RECORD(TYPE_ADJUSTED);
Manman Rene6be26c2016-09-13 17:25:08 +00001225 RECORD(TYPE_OBJC_TYPE_PARAM);
Richard Smithd61d4ac2015-08-22 20:13:39 +00001226 RECORD(LOCAL_REDECLARATIONS);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001227 RECORD(DECL_TYPEDEF);
Richard Smith01b2cb42014-07-26 06:37:51 +00001228 RECORD(DECL_TYPEALIAS);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001229 RECORD(DECL_ENUM);
1230 RECORD(DECL_RECORD);
1231 RECORD(DECL_ENUM_CONSTANT);
1232 RECORD(DECL_FUNCTION);
1233 RECORD(DECL_OBJC_METHOD);
1234 RECORD(DECL_OBJC_INTERFACE);
1235 RECORD(DECL_OBJC_PROTOCOL);
1236 RECORD(DECL_OBJC_IVAR);
1237 RECORD(DECL_OBJC_AT_DEFS_FIELD);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001238 RECORD(DECL_OBJC_CATEGORY);
1239 RECORD(DECL_OBJC_CATEGORY_IMPL);
1240 RECORD(DECL_OBJC_IMPLEMENTATION);
1241 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
1242 RECORD(DECL_OBJC_PROPERTY);
1243 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001244 RECORD(DECL_FIELD);
John McCall5e77d762013-04-16 07:28:30 +00001245 RECORD(DECL_MS_PROPERTY);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001246 RECORD(DECL_VAR);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001247 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattner28fa4e62009-04-26 22:26:21 +00001248 RECORD(DECL_PARM_VAR);
Chris Lattnerdb397b62009-04-26 22:32:16 +00001249 RECORD(DECL_FILE_SCOPE_ASM);
1250 RECORD(DECL_BLOCK);
1251 RECORD(DECL_CONTEXT_LEXICAL);
1252 RECORD(DECL_CONTEXT_VISIBLE);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001253 RECORD(DECL_NAMESPACE);
1254 RECORD(DECL_NAMESPACE_ALIAS);
1255 RECORD(DECL_USING);
1256 RECORD(DECL_USING_SHADOW);
1257 RECORD(DECL_USING_DIRECTIVE);
1258 RECORD(DECL_UNRESOLVED_USING_VALUE);
1259 RECORD(DECL_UNRESOLVED_USING_TYPENAME);
1260 RECORD(DECL_LINKAGE_SPEC);
1261 RECORD(DECL_CXX_RECORD);
1262 RECORD(DECL_CXX_METHOD);
1263 RECORD(DECL_CXX_CONSTRUCTOR);
Richard Smith5179eb72016-06-28 19:03:57 +00001264 RECORD(DECL_CXX_INHERITED_CONSTRUCTOR);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001265 RECORD(DECL_CXX_DESTRUCTOR);
1266 RECORD(DECL_CXX_CONVERSION);
1267 RECORD(DECL_ACCESS_SPEC);
1268 RECORD(DECL_FRIEND);
1269 RECORD(DECL_FRIEND_TEMPLATE);
1270 RECORD(DECL_CLASS_TEMPLATE);
1271 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
1272 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001273 RECORD(DECL_VAR_TEMPLATE);
1274 RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
1275 RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001276 RECORD(DECL_FUNCTION_TEMPLATE);
1277 RECORD(DECL_TEMPLATE_TYPE_PARM);
1278 RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
1279 RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
Richard Smithefc884a2016-04-13 07:41:35 +00001280 RECORD(DECL_TYPE_ALIAS_TEMPLATE);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001281 RECORD(DECL_STATIC_ASSERT);
1282 RECORD(DECL_CXX_BASE_SPECIFIERS);
Richard Smithefc884a2016-04-13 07:41:35 +00001283 RECORD(DECL_CXX_CTOR_INITIALIZERS);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001284 RECORD(DECL_INDIRECTFIELD);
1285 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
Richard Smithefc884a2016-04-13 07:41:35 +00001286 RECORD(DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK);
1287 RECORD(DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION);
1288 RECORD(DECL_IMPORT);
1289 RECORD(DECL_OMP_THREADPRIVATE);
1290 RECORD(DECL_EMPTY);
1291 RECORD(DECL_OBJC_TYPE_PARAM);
1292 RECORD(DECL_OMP_CAPTUREDEXPR);
1293 RECORD(DECL_PRAGMA_COMMENT);
1294 RECORD(DECL_PRAGMA_DETECT_MISMATCH);
1295 RECORD(DECL_OMP_DECLARE_REDUCTION);
Douglas Gregor0beaec02011-02-08 16:34:17 +00001296
Douglas Gregor03412ba2011-06-03 02:27:19 +00001297 // Statements and Exprs can occur in the Decls and Types block.
1298 AddStmtsExprs(Stream, Record);
1299
Douglas Gregor92a96f52011-02-08 21:58:10 +00001300 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001301 RECORD(PPD_MACRO_EXPANSION);
Douglas Gregor92a96f52011-02-08 21:58:10 +00001302 RECORD(PPD_MACRO_DEFINITION);
1303 RECORD(PPD_INCLUSION_DIRECTIVE);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00001304
1305 // Decls and Types block.
1306 BLOCK(EXTENSION_BLOCK);
1307 RECORD(EXTENSION_METADATA);
1308
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001309 BLOCK(UNHASHED_CONTROL_BLOCK);
1310 RECORD(SIGNATURE);
1311 RECORD(DIAGNOSTIC_OPTIONS);
1312 RECORD(DIAG_PRAGMA_MAPPINGS);
1313
Chris Lattner28fa4e62009-04-26 22:26:21 +00001314#undef RECORD
1315#undef BLOCK
1316 Stream.ExitBlock();
1317}
1318
Richard Smith54cc3c22014-12-11 20:50:24 +00001319/// \brief Prepares a path for being written to an AST file by converting it
1320/// to an absolute path and removing nested './'s.
1321///
1322/// \return \c true if the path was changed.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +00001323static bool cleanPathForOutput(FileManager &FileMgr,
1324 SmallVectorImpl<char> &Path) {
Argyrios Kyrtzidis403cbcb2015-07-31 01:39:23 +00001325 bool Changed = FileMgr.makeAbsolutePath(Path);
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +00001326 return Changed | llvm::sys::path::remove_dots(Path);
Richard Smith54cc3c22014-12-11 20:50:24 +00001327}
1328
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001329/// \brief Adjusts the given filename to only write out the portion of the
1330/// filename that is not part of the system root directory.
Mike Stump11289f42009-09-09 15:08:12 +00001331///
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001332/// \param Filename the file name to adjust.
1333///
Richard Smith7ed1bc92014-12-05 22:42:13 +00001334/// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
1335/// the returned filename will be adjusted by this root directory.
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001336///
1337/// \returns either the original filename (if it needs no adjustment) or the
1338/// adjusted filename (which points into the @p Filename parameter).
Mike Stump11289f42009-09-09 15:08:12 +00001339static const char *
Richard Smith7ed1bc92014-12-05 22:42:13 +00001340adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001341 assert(Filename && "No file name to adjust?");
Mike Stump11289f42009-09-09 15:08:12 +00001342
Richard Smith7ed1bc92014-12-05 22:42:13 +00001343 if (BaseDir.empty())
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001344 return Filename;
Mike Stump11289f42009-09-09 15:08:12 +00001345
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001346 // Verify that the filename and the system root have the same prefix.
1347 unsigned Pos = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001348 for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
1349 if (Filename[Pos] != BaseDir[Pos])
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001350 return Filename; // Prefixes don't match.
Mike Stump11289f42009-09-09 15:08:12 +00001351
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001352 // We hit the end of the filename before we hit the end of the system root.
1353 if (!Filename[Pos])
1354 return Filename;
Mike Stump11289f42009-09-09 15:08:12 +00001355
Richard Smith7ed1bc92014-12-05 22:42:13 +00001356 // If there's not a path separator at the end of the base directory nor
1357 // immediately after it, then this isn't within the base directory.
1358 if (!llvm::sys::path::is_separator(Filename[Pos])) {
1359 if (!llvm::sys::path::is_separator(BaseDir.back()))
1360 return Filename;
1361 } else {
1362 // If the file name has a '/' at the current position, skip over the '/'.
1363 // We distinguish relative paths from absolute paths by the
1364 // absence of '/' at the beginning of relative paths.
1365 //
1366 // FIXME: This is wrong. We distinguish them by asking if the path is
1367 // absolute, which isn't the same thing. And there might be multiple '/'s
1368 // in a row. Use a better mechanism to indicate whether we have emitted an
1369 // absolute or relative path.
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001370 ++Pos;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001371 }
Mike Stump11289f42009-09-09 15:08:12 +00001372
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001373 return Filename + Pos;
1374}
Chris Lattner28fa4e62009-04-26 22:26:21 +00001375
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001376ASTFileSignature ASTWriter::createSignature(StringRef Bytes) {
1377 // Calculate the hash till start of UNHASHED_CONTROL_BLOCK.
1378 llvm::SHA1 Hasher;
1379 Hasher.update(ArrayRef<uint8_t>(Bytes.bytes_begin(), Bytes.size()));
1380 auto Hash = Hasher.result();
1381
1382 // Convert to an array [5*i32].
1383 ASTFileSignature Signature;
1384 auto LShift = [&](unsigned char Val, unsigned Shift) {
1385 return (uint32_t)Val << Shift;
1386 };
1387 for (int I = 0; I != 5; ++I)
1388 Signature[I] = LShift(Hash[I * 4 + 0], 24) | LShift(Hash[I * 4 + 1], 16) |
1389 LShift(Hash[I * 4 + 2], 8) | LShift(Hash[I * 4 + 3], 0);
1390
1391 return Signature;
1392}
1393
1394ASTFileSignature ASTWriter::writeUnhashedControlBlock(Preprocessor &PP,
1395 ASTContext &Context) {
1396 // Flush first to prepare the PCM hash (signature).
1397 Stream.FlushToWord();
1398 auto StartOfUnhashedControl = Stream.GetCurrentBitNo() >> 3;
1399
1400 // Enter the block and prepare to write records.
1401 RecordData Record;
1402 Stream.EnterSubblock(UNHASHED_CONTROL_BLOCK_ID, 5);
1403
1404 // For implicit modules, write the hash of the PCM as its signature.
1405 ASTFileSignature Signature;
1406 if (WritingModule &&
1407 PP.getHeaderSearchInfo().getHeaderSearchOpts().ModulesHashContent) {
1408 Signature = createSignature(StringRef(Buffer.begin(), StartOfUnhashedControl));
1409 Record.append(Signature.begin(), Signature.end());
1410 Stream.EmitRecord(SIGNATURE, Record);
1411 Record.clear();
Ben Langmuir487ea142014-10-23 18:05:36 +00001412 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001413
1414 // Diagnostic options.
1415 const auto &Diags = Context.getDiagnostics();
1416 const DiagnosticOptions &DiagOpts = Diags.getDiagnosticOptions();
1417#define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1418#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1419 Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1420#include "clang/Basic/DiagnosticOptions.def"
1421 Record.push_back(DiagOpts.Warnings.size());
1422 for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1423 AddString(DiagOpts.Warnings[I], Record);
1424 Record.push_back(DiagOpts.Remarks.size());
1425 for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1426 AddString(DiagOpts.Remarks[I], Record);
1427 // Note: we don't serialize the log or serialization file names, because they
1428 // are generally transient files and will almost always be overridden.
1429 Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1430
1431 // Write out the diagnostic/pragma mappings.
1432 WritePragmaDiagnosticMappings(Diags, /* IsModule = */ WritingModule);
1433
1434 // Leave the options block.
1435 Stream.ExitBlock();
1436 return Signature;
Ben Langmuir487ea142014-10-23 18:05:36 +00001437}
1438
Douglas Gregor112b9072012-10-18 05:31:06 +00001439/// \brief Write the control block.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001440void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context,
1441 StringRef isysroot,
1442 const std::string &OutputFile) {
Douglas Gregorbfbde532009-04-10 21:16:55 +00001443 using namespace llvm;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001444
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001445 Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001446 RecordData Record;
1447
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001448 // Metadata
David Blaikieb44f0bf2017-01-04 22:36:43 +00001449 auto MetadataAbbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001450 MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1451 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1452 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1453 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1454 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1455 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
Richard Smithe75ee0f2015-08-17 07:13:32 +00001456 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001457 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1458 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
David Blaikieb44f0bf2017-01-04 22:36:43 +00001459 unsigned MetadataAbbrevCode = Stream.EmitAbbrev(std::move(MetadataAbbrev));
Richard Smith7ed1bc92014-12-05 22:42:13 +00001460 assert((!WritingModule || isysroot.empty()) &&
1461 "writing module as a relocatable PCH?");
Mehdi Amini57a41912015-09-10 01:46:39 +00001462 {
1463 RecordData::value_type Record[] = {METADATA, VERSION_MAJOR, VERSION_MINOR,
1464 CLANG_VERSION_MAJOR, CLANG_VERSION_MINOR,
1465 !isysroot.empty(), IncludeTimestamps,
1466 ASTHasCompilerErrors};
1467 Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1468 getClangFullRepositoryVersion());
1469 }
Chandler Carruth885e78c2015-03-24 21:18:10 +00001470
Richard Smith8b706102017-05-31 20:56:55 +00001471 if (WritingModule) {
Richard Smith7ed1bc92014-12-05 22:42:13 +00001472 // Module name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001473 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001474 Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1475 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001476 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00001477 RecordData::value_type Record[] = {MODULE_NAME};
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001478 Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1479 }
1480
Richard Smith7ed1bc92014-12-05 22:42:13 +00001481 if (WritingModule && WritingModule->Directory) {
Richard Smith7ed1bc92014-12-05 22:42:13 +00001482 SmallString<128> BaseDir(WritingModule->Directory->getName());
Richard Smith54cc3c22014-12-11 20:50:24 +00001483 cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
Richard Smithf7b41372015-08-13 23:47:44 +00001484
1485 // If the home of the module is the current working directory, then we
1486 // want to pick up the cwd of the build process loading the module, not
1487 // our cwd, when we load this module.
1488 if (!PP.getHeaderSearchInfo()
1489 .getHeaderSearchOpts()
1490 .ModuleMapFileHomeIsCwd ||
1491 WritingModule->Directory->getName() != StringRef(".")) {
1492 // Module directory.
David Blaikieb44f0bf2017-01-04 22:36:43 +00001493 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Richard Smithf7b41372015-08-13 23:47:44 +00001494 Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1495 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
David Blaikieb44f0bf2017-01-04 22:36:43 +00001496 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
Richard Smithf7b41372015-08-13 23:47:44 +00001497
Mehdi Amini57a41912015-09-10 01:46:39 +00001498 RecordData::value_type Record[] = {MODULE_DIRECTORY};
Richard Smithf7b41372015-08-13 23:47:44 +00001499 Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
1500 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001501
1502 // Write out all other paths relative to the base directory if possible.
1503 BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1504 } else if (!isysroot.empty()) {
1505 // Write out paths relative to the sysroot if possible.
1506 BaseDirectory = isysroot;
1507 }
1508
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001509 // Module map file
Richard Smithd19389a2017-07-05 07:47:11 +00001510 if (WritingModule && WritingModule->Kind == Module::ModuleMapModule) {
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001511 Record.clear();
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001512
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001513 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
Richard Smith8b706102017-05-31 20:56:55 +00001514 AddPath(WritingModule->PresumedModuleMapFile.empty()
1515 ? Map.getModuleMapFileForUniquing(WritingModule)->getName()
1516 : StringRef(WritingModule->PresumedModuleMapFile),
1517 Record);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001518
1519 // Additional module map files.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001520 if (auto *AdditionalModMaps =
1521 Map.getAdditionalModuleMapFiles(WritingModule)) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001522 Record.push_back(AdditionalModMaps->size());
1523 for (const FileEntry *F : *AdditionalModMaps)
Richard Smith7ed1bc92014-12-05 22:42:13 +00001524 AddPath(F->getName(), Record);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001525 } else {
1526 Record.push_back(0);
1527 }
1528
1529 Stream.EmitRecord(MODULE_MAP_FILE, Record);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001530 }
1531
Douglas Gregor112b9072012-10-18 05:31:06 +00001532 // Imports
Douglas Gregor29cc6422011-08-17 21:07:30 +00001533 if (Chain) {
Douglas Gregor29cc6422011-08-17 21:07:30 +00001534 serialization::ModuleManager &Mgr = Chain->getModuleManager();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001535 Record.clear();
Douglas Gregordf0c1512011-08-18 04:12:04 +00001536
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001537 for (ModuleFile &M : Mgr) {
Douglas Gregordf0c1512011-08-18 04:12:04 +00001538 // Skip modules that weren't directly imported.
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001539 if (!M.isDirectlyImported())
Douglas Gregordf0c1512011-08-18 04:12:04 +00001540 continue;
1541
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001542 Record.push_back((unsigned)M.Kind); // FIXME: Stable encoding
1543 AddSourceLocation(M.ImportLoc, Record);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001544
1545 // If we have calculated signature, there is no need to store
1546 // the size or timestamp.
1547 Record.push_back(M.Signature ? 0 : M.File->getSize());
1548 Record.push_back(M.Signature ? 0 : getTimestampForOutput(M.File));
1549
1550 for (auto I : M.Signature)
1551 Record.push_back(I);
1552
Boris Kolpackovd30446f2017-08-31 06:26:43 +00001553 AddString(M.ModuleName, Record);
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001554 AddPath(M.FileName, Record);
Douglas Gregordf0c1512011-08-18 04:12:04 +00001555 }
Douglas Gregor29cc6422011-08-17 21:07:30 +00001556 Stream.EmitRecord(IMPORTS, Record);
1557 }
Mike Stump11289f42009-09-09 15:08:12 +00001558
Richard Smith0516b182015-09-08 19:40:14 +00001559 // Write the options block.
1560 Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
1561
Douglas Gregor112b9072012-10-18 05:31:06 +00001562 // Language options.
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001563 Record.clear();
Douglas Gregor112b9072012-10-18 05:31:06 +00001564 const LangOptions &LangOpts = Context.getLangOpts();
1565#define LANGOPT(Name, Bits, Default, Description) \
1566 Record.push_back(LangOpts.Name);
1567#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1568 Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001569#include "clang/Basic/LangOptions.def"
1570#define SANITIZER(NAME, ID) \
1571 Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
Will Dietzf54319c2013-01-18 11:30:38 +00001572#include "clang/Basic/Sanitizers.def"
Douglas Gregor112b9072012-10-18 05:31:06 +00001573
Ben Langmuircd98cb72015-06-23 18:20:18 +00001574 Record.push_back(LangOpts.ModuleFeatures.size());
1575 for (StringRef Feature : LangOpts.ModuleFeatures)
1576 AddString(Feature, Record);
1577
Douglas Gregor112b9072012-10-18 05:31:06 +00001578 Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1579 AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
Ben Langmuird4a667a2015-06-23 18:20:23 +00001580
1581 AddString(LangOpts.CurrentModule, Record);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001582
1583 // Comment options.
1584 Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001585 for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1586 AddString(I, Record);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001587 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00001588 Record.push_back(LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001589
Samuel Antaoee8fb302016-01-06 13:42:12 +00001590 // OpenMP offloading options.
1591 Record.push_back(LangOpts.OMPTargetTriples.size());
1592 for (auto &T : LangOpts.OMPTargetTriples)
1593 AddString(T.getTriple(), Record);
1594
1595 AddString(LangOpts.OMPHostIRFile, Record);
1596
Douglas Gregor112b9072012-10-18 05:31:06 +00001597 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1598
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001599 // Target options.
1600 Record.clear();
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001601 const TargetInfo &Target = Context.getTargetInfo();
1602 const TargetOptions &TargetOpts = Target.getTargetOpts();
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001603 AddString(TargetOpts.Triple, Record);
1604 AddString(TargetOpts.CPU, Record);
1605 AddString(TargetOpts.ABI, Record);
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001606 Record.push_back(TargetOpts.FeaturesAsWritten.size());
1607 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1608 AddString(TargetOpts.FeaturesAsWritten[I], Record);
1609 }
1610 Record.push_back(TargetOpts.Features.size());
1611 for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1612 AddString(TargetOpts.Features[I], Record);
1613 }
1614 Stream.EmitRecord(TARGET_OPTIONS, Record);
1615
Douglas Gregorc6317db2012-10-24 15:49:58 +00001616 // File system options.
1617 Record.clear();
Yaron Keren8dec46c2015-08-26 08:10:22 +00001618 const FileSystemOptions &FSOpts =
1619 Context.getSourceManager().getFileManager().getFileSystemOpts();
Douglas Gregorc6317db2012-10-24 15:49:58 +00001620 AddString(FSOpts.WorkingDir, Record);
1621 Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1622
Douglas Gregor2d302362012-10-24 16:50:34 +00001623 // Header search options.
1624 Record.clear();
1625 const HeaderSearchOptions &HSOpts
1626 = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1627 AddString(HSOpts.Sysroot, Record);
1628
1629 // Include entries.
1630 Record.push_back(HSOpts.UserEntries.size());
1631 for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1632 const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1633 AddString(Entry.Path, Record);
1634 Record.push_back(static_cast<unsigned>(Entry.Group));
Douglas Gregor2d302362012-10-24 16:50:34 +00001635 Record.push_back(Entry.IsFramework);
1636 Record.push_back(Entry.IgnoreSysRoot);
Douglas Gregor2d302362012-10-24 16:50:34 +00001637 }
1638
1639 // System header prefixes.
1640 Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1641 for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1642 AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1643 Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1644 }
1645
1646 AddString(HSOpts.ResourceDir, Record);
1647 AddString(HSOpts.ModuleCachePath, Record);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00001648 AddString(HSOpts.ModuleUserBuildPath, Record);
Douglas Gregor2d302362012-10-24 16:50:34 +00001649 Record.push_back(HSOpts.DisableModuleHash);
Richard Smith18934752017-06-06 00:32:01 +00001650 Record.push_back(HSOpts.ImplicitModuleMaps);
1651 Record.push_back(HSOpts.ModuleMapFileHomeIsCwd);
Douglas Gregor2d302362012-10-24 16:50:34 +00001652 Record.push_back(HSOpts.UseBuiltinIncludes);
1653 Record.push_back(HSOpts.UseStandardSystemIncludes);
1654 Record.push_back(HSOpts.UseStandardCXXIncludes);
1655 Record.push_back(HSOpts.UseLibcxx);
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00001656 // Write out the specific module cache path that contains the module files.
1657 AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
Douglas Gregor2d302362012-10-24 16:50:34 +00001658 Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1659
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001660 // Preprocessor options.
1661 Record.clear();
1662 const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1663
1664 // Macro definitions.
1665 Record.push_back(PPOpts.Macros.size());
1666 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1667 AddString(PPOpts.Macros[I].first, Record);
1668 Record.push_back(PPOpts.Macros[I].second);
1669 }
1670
1671 // Includes
1672 Record.push_back(PPOpts.Includes.size());
1673 for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1674 AddString(PPOpts.Includes[I], Record);
1675
1676 // Macro includes
1677 Record.push_back(PPOpts.MacroIncludes.size());
1678 for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1679 AddString(PPOpts.MacroIncludes[I], Record);
1680
Douglas Gregorb6368752012-10-24 23:41:50 +00001681 Record.push_back(PPOpts.UsePredefines);
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00001682 // Detailed record is important since it is used for the module cache hash.
1683 Record.push_back(PPOpts.DetailedRecord);
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001684 AddString(PPOpts.ImplicitPCHInclude, Record);
1685 AddString(PPOpts.ImplicitPTHInclude, Record);
1686 Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1687 Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1688
Richard Smith0516b182015-09-08 19:40:14 +00001689 // Leave the options block.
1690 Stream.ExitBlock();
1691
Douglas Gregora3b20262011-05-06 21:43:30 +00001692 // Original file name and file ID
Douglas Gregor45fe0362009-05-12 01:31:05 +00001693 SourceManager &SM = Context.getSourceManager();
1694 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
David Blaikieb44f0bf2017-01-04 22:36:43 +00001695 auto FileAbbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregorfad10d82012-10-18 18:36:53 +00001696 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1697 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
Douglas Gregor45fe0362009-05-12 01:31:05 +00001698 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001699 unsigned FileAbbrevCode = Stream.EmitAbbrev(std::move(FileAbbrev));
Douglas Gregor45fe0362009-05-12 01:31:05 +00001700
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001701 Record.clear();
Douglas Gregorfad10d82012-10-18 18:36:53 +00001702 Record.push_back(ORIGINAL_FILE);
Douglas Gregora3b20262011-05-06 21:43:30 +00001703 Record.push_back(SM.getMainFileID().getOpaqueValue());
Richard Smith7ed1bc92014-12-05 22:42:13 +00001704 EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
Douglas Gregor45fe0362009-05-12 01:31:05 +00001705 }
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00001706
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +00001707 Record.clear();
1708 Record.push_back(SM.getMainFileID().getOpaqueValue());
1709 Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1710
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001711 // Original PCH directory
1712 if (!OutputFile.empty() && OutputFile != "-") {
David Blaikieb44f0bf2017-01-04 22:36:43 +00001713 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001714 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1715 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001716 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001717
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001718 SmallString<128> OutputPath(OutputFile);
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001719
Argyrios Kyrtzidisc56419e2015-07-31 00:58:32 +00001720 SM.getFileManager().makeAbsolutePath(OutputPath);
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001721 StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1722
Mehdi Amini57a41912015-09-10 01:46:39 +00001723 RecordData::value_type Record[] = {ORIGINAL_PCH_DIR};
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001724 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1725 }
1726
Douglas Gregor49491f72013-03-15 22:15:07 +00001727 WriteInputFiles(Context.SourceMgr,
1728 PP.getHeaderSearchInfo().getHeaderSearchOpts(),
Douglas Gregora3dd9002013-07-22 20:48:33 +00001729 PP.getLangOpts().Modules);
Douglas Gregor72be3902012-10-19 00:38:02 +00001730 Stream.ExitBlock();
1731}
1732
Douglas Gregor49491f72013-03-15 22:15:07 +00001733namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001734
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001735/// \brief An input file.
1736struct InputFileEntry {
1737 const FileEntry *File;
1738 bool IsSystemFile;
1739 bool IsTransient;
1740 bool BufferOverridden;
1741 bool IsTopLevelModuleMap;
1742};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001743
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001744} // namespace
Douglas Gregor49491f72013-03-15 22:15:07 +00001745
1746void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1747 HeaderSearchOptions &HSOpts,
Douglas Gregora3dd9002013-07-22 20:48:33 +00001748 bool Modules) {
Douglas Gregor72be3902012-10-19 00:38:02 +00001749 using namespace llvm;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001750
Douglas Gregor72be3902012-10-19 00:38:02 +00001751 Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
Mehdi Amini57a41912015-09-10 01:46:39 +00001752
Douglas Gregor72be3902012-10-19 00:38:02 +00001753 // Create input-file abbreviation.
David Blaikieb44f0bf2017-01-04 22:36:43 +00001754 auto IFAbbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor72be3902012-10-19 00:38:02 +00001755 IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001756 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
Douglas Gregor72be3902012-10-19 00:38:02 +00001757 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1758 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001759 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
Richard Smitha8cfffa2015-11-26 02:04:16 +00001760 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
Richard Smithf3f84612017-06-29 02:19:42 +00001761 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Module map
Douglas Gregor72be3902012-10-19 00:38:02 +00001762 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001763 unsigned IFAbbrevCode = Stream.EmitAbbrev(std::move(IFAbbrev));
Douglas Gregor72be3902012-10-19 00:38:02 +00001764
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001765 // Get all ContentCache objects for files, sorted by whether the file is a
1766 // system one or not. System files go at the back, users files at the front.
Douglas Gregor49491f72013-03-15 22:15:07 +00001767 std::deque<InputFileEntry> SortedFiles;
Douglas Gregor72be3902012-10-19 00:38:02 +00001768 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1769 // Get this source location entry.
1770 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
NAKAMURA Takumideca50f2012-10-19 01:53:57 +00001771 assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
Douglas Gregor72be3902012-10-19 00:38:02 +00001772
1773 // We only care about file entries that were not overridden.
1774 if (!SLoc->isFile())
1775 continue;
Richard Smithf3f84612017-06-29 02:19:42 +00001776 const SrcMgr::FileInfo &File = SLoc->getFile();
1777 const SrcMgr::ContentCache *Cache = File.getContentCache();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001778 if (!Cache->OrigEntry)
Douglas Gregor72be3902012-10-19 00:38:02 +00001779 continue;
1780
Douglas Gregor49491f72013-03-15 22:15:07 +00001781 InputFileEntry Entry;
1782 Entry.File = Cache->OrigEntry;
1783 Entry.IsSystemFile = Cache->IsSystemFile;
Richard Smitha8cfffa2015-11-26 02:04:16 +00001784 Entry.IsTransient = Cache->IsTransient;
Douglas Gregor49491f72013-03-15 22:15:07 +00001785 Entry.BufferOverridden = Cache->BufferOverridden;
Richard Smithf3f84612017-06-29 02:19:42 +00001786 Entry.IsTopLevelModuleMap = isModuleMap(File.getFileCharacteristic()) &&
1787 File.getIncludeLoc().isInvalid();
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001788 if (Cache->IsSystemFile)
Douglas Gregor49491f72013-03-15 22:15:07 +00001789 SortedFiles.push_back(Entry);
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001790 else
Douglas Gregor49491f72013-03-15 22:15:07 +00001791 SortedFiles.push_front(Entry);
1792 }
1793
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001794 unsigned UserFilesNum = 0;
1795 // Write out all of the input files.
Richard Smithec216502015-02-13 19:48:37 +00001796 std::vector<uint64_t> InputFileOffsets;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001797 for (const auto &Entry : SortedFiles) {
Douglas Gregor49491f72013-03-15 22:15:07 +00001798 uint32_t &InputFileID = InputFileIDs[Entry.File];
Argyrios Kyrtzidise65856f2012-12-11 07:48:08 +00001799 if (InputFileID != 0)
1800 continue; // already recorded this file.
1801
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001802 // Record this entry's offset.
1803 InputFileOffsets.push_back(Stream.GetCurrentBitNo());
Argyrios Kyrtzidise65856f2012-12-11 07:48:08 +00001804
1805 InputFileID = InputFileOffsets.size();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001806
Douglas Gregor49491f72013-03-15 22:15:07 +00001807 if (!Entry.IsSystemFile)
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001808 ++UserFilesNum;
1809
Douglas Gregor72be3902012-10-19 00:38:02 +00001810 // Emit size/modification time for this file.
Mehdi Amini57a41912015-09-10 01:46:39 +00001811 // And whether this file was overridden.
1812 RecordData::value_type Record[] = {
Richard Smitha8cfffa2015-11-26 02:04:16 +00001813 INPUT_FILE,
1814 InputFileOffsets.size(),
1815 (uint64_t)Entry.File->getSize(),
1816 (uint64_t)getTimestampForOutput(Entry.File),
1817 Entry.BufferOverridden,
Richard Smithf3f84612017-06-29 02:19:42 +00001818 Entry.IsTransient,
1819 Entry.IsTopLevelModuleMap};
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001820
Richard Smith7ed1bc92014-12-05 22:42:13 +00001821 EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
1822 }
Douglas Gregor49491f72013-03-15 22:15:07 +00001823
Douglas Gregor112b9072012-10-18 05:31:06 +00001824 Stream.ExitBlock();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001825
1826 // Create input file offsets abbreviation.
David Blaikieb44f0bf2017-01-04 22:36:43 +00001827 auto OffsetsAbbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001828 OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1829 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001830 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1831 // input files
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001832 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
David Blaikieb44f0bf2017-01-04 22:36:43 +00001833 unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(std::move(OffsetsAbbrev));
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001834
1835 // Write input file offsets.
Mehdi Amini57a41912015-09-10 01:46:39 +00001836 RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
1837 InputFileOffsets.size(), UserFilesNum};
Reid Kleckner012665e2015-05-21 00:13:09 +00001838 Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
Douglas Gregor55abb232009-04-10 20:39:37 +00001839}
1840
Douglas Gregora7f71a92009-04-10 03:52:48 +00001841//===----------------------------------------------------------------------===//
1842// Source Manager Serialization
1843//===----------------------------------------------------------------------===//
1844
1845/// \brief Create an abbreviation for the SLocEntry that refers to a
1846/// file.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001847static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001848 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001849
David Blaikieb44f0bf2017-01-04 22:36:43 +00001850 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00001851 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001852 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1853 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
Richard Smithf3f84612017-06-29 02:19:42 +00001854 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
Douglas Gregora7f71a92009-04-10 03:52:48 +00001855 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregorb41ca8f2010-03-21 22:49:54 +00001856 // FileEntry fields.
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001857 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001858 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00001859 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1860 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
David Blaikieb44f0bf2017-01-04 22:36:43 +00001861 return Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001862}
1863
1864/// \brief Create an abbreviation for the SLocEntry that refers to a
1865/// buffer.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001866static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001867 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001868
David Blaikieb44f0bf2017-01-04 22:36:43 +00001869 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00001870 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001871 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1872 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
Richard Smithf3f84612017-06-29 02:19:42 +00001873 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
Douglas Gregora7f71a92009-04-10 03:52:48 +00001874 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1875 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
David Blaikieb44f0bf2017-01-04 22:36:43 +00001876 return Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001877}
1878
1879/// \brief Create an abbreviation for the SLocEntry that refers to a
1880/// buffer's blob.
Richard Smithaada85c2016-02-06 02:06:43 +00001881static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
1882 bool Compressed) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001883 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001884
David Blaikieb44f0bf2017-01-04 22:36:43 +00001885 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Richard Smithaada85c2016-02-06 02:06:43 +00001886 Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED
1887 : SM_SLOC_BUFFER_BLOB));
1888 if (Compressed)
1889 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
Douglas Gregora7f71a92009-04-10 03:52:48 +00001890 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
David Blaikieb44f0bf2017-01-04 22:36:43 +00001891 return Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001892}
1893
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001894/// \brief Create an abbreviation for the SLocEntry that refers to a macro
1895/// expansion.
1896static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001897 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001898
David Blaikieb44f0bf2017-01-04 22:36:43 +00001899 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001900 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001901 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1902 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1903 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1904 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Douglas Gregor83243272009-04-15 18:05:10 +00001905 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
David Blaikieb44f0bf2017-01-04 22:36:43 +00001906 return Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001907}
1908
Douglas Gregor09b69892011-02-10 17:09:37 +00001909namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001910
Douglas Gregor09b69892011-02-10 17:09:37 +00001911 // Trait used for the on-disk hash table of header search information.
1912 class HeaderFileInfoTrait {
1913 ASTWriter &Writer;
Douglas Gregor09b69892011-02-10 17:09:37 +00001914
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001915 // Keep track of the framework names we've used during serialization.
1916 SmallVector<char, 128> FrameworkStringData;
1917 llvm::StringMap<unsigned> FrameworkNameOffset;
1918
Douglas Gregor09b69892011-02-10 17:09:37 +00001919 public:
Richard Smith040e1262017-06-02 01:55:39 +00001920 HeaderFileInfoTrait(ASTWriter &Writer) : Writer(Writer) {}
1921
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001922 struct key_type {
Mehdi Amini004b9c72016-10-10 22:52:47 +00001923 StringRef Filename;
Richard Smith040e1262017-06-02 01:55:39 +00001924 off_t Size;
1925 time_t ModTime;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001926 };
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001927 using key_type_ref = const key_type &;
Richard Smith040e1262017-06-02 01:55:39 +00001928
1929 using UnresolvedModule =
1930 llvm::PointerIntPair<Module *, 2, ModuleMap::ModuleHeaderRole>;
Douglas Gregor09b69892011-02-10 17:09:37 +00001931
Richard Smith040e1262017-06-02 01:55:39 +00001932 struct data_type {
1933 const HeaderFileInfo &HFI;
1934 ArrayRef<ModuleMap::KnownHeader> KnownHeaders;
1935 UnresolvedModule Unresolved;
1936 };
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001937 using data_type_ref = const data_type &;
Richard Smith040e1262017-06-02 01:55:39 +00001938
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001939 using hash_value_type = unsigned;
1940 using offset_type = unsigned;
Douglas Gregor09b69892011-02-10 17:09:37 +00001941
Richard Smithe75ee0f2015-08-17 07:13:32 +00001942 hash_value_type ComputeHash(key_type_ref key) {
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001943 // The hash is based only on size/time of the file, so that the reader can
1944 // match even when symlinking or excess path elements ("foo/../", "../")
1945 // change the form of the name. However, complete path is still the key.
Richard Smith040e1262017-06-02 01:55:39 +00001946 return llvm::hash_combine(key.Size, key.ModTime);
Douglas Gregor09b69892011-02-10 17:09:37 +00001947 }
1948
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001949 std::pair<unsigned, unsigned>
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001950 EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001951 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001952
Richard Smith386bb072015-08-18 23:42:23 +00001953 endian::Writer<little> LE(Out);
Mehdi Amini004b9c72016-10-10 22:52:47 +00001954 unsigned KeyLen = key.Filename.size() + 1 + 8 + 8;
Richard Smith386bb072015-08-18 23:42:23 +00001955 LE.write<uint16_t>(KeyLen);
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001956 unsigned DataLen = 1 + 2 + 4 + 4;
Richard Smith040e1262017-06-02 01:55:39 +00001957 for (auto ModInfo : Data.KnownHeaders)
Richard Smith386bb072015-08-18 23:42:23 +00001958 if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
1959 DataLen += 4;
Richard Smith040e1262017-06-02 01:55:39 +00001960 if (Data.Unresolved.getPointer())
1961 DataLen += 4;
Richard Smith386bb072015-08-18 23:42:23 +00001962 LE.write<uint8_t>(DataLen);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001963 return std::make_pair(KeyLen, DataLen);
Douglas Gregor09b69892011-02-10 17:09:37 +00001964 }
Richard Smith040e1262017-06-02 01:55:39 +00001965
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001966 void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001967 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001968
Justin Bognere1c147c2014-03-28 22:03:19 +00001969 endian::Writer<little> LE(Out);
Richard Smith040e1262017-06-02 01:55:39 +00001970 LE.write<uint64_t>(key.Size);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001971 KeyLen -= 8;
Richard Smith040e1262017-06-02 01:55:39 +00001972 LE.write<uint64_t>(key.ModTime);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001973 KeyLen -= 8;
Mehdi Amini004b9c72016-10-10 22:52:47 +00001974 Out.write(key.Filename.data(), KeyLen);
Douglas Gregor09b69892011-02-10 17:09:37 +00001975 }
Richard Smith040e1262017-06-02 01:55:39 +00001976
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001977 void EmitData(raw_ostream &Out, key_type_ref key,
Douglas Gregor09b69892011-02-10 17:09:37 +00001978 data_type_ref Data, unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001979 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001980
Justin Bognere1c147c2014-03-28 22:03:19 +00001981 endian::Writer<little> LE(Out);
Douglas Gregor09b69892011-02-10 17:09:37 +00001982 uint64_t Start = Out.tell(); (void)Start;
1983
Richard Smithf3f84612017-06-29 02:19:42 +00001984 unsigned char Flags = (Data.HFI.isImport << 5)
1985 | (Data.HFI.isPragmaOnce << 4)
Richard Smith040e1262017-06-02 01:55:39 +00001986 | (Data.HFI.DirInfo << 1)
1987 | Data.HFI.IndexHeaderMapHeader;
Justin Bognere1c147c2014-03-28 22:03:19 +00001988 LE.write<uint8_t>(Flags);
Richard Smith040e1262017-06-02 01:55:39 +00001989 LE.write<uint16_t>(Data.HFI.NumIncludes);
Douglas Gregor09b69892011-02-10 17:09:37 +00001990
Richard Smith040e1262017-06-02 01:55:39 +00001991 if (!Data.HFI.ControllingMacro)
1992 LE.write<uint32_t>(Data.HFI.ControllingMacroID);
Douglas Gregor09b69892011-02-10 17:09:37 +00001993 else
Richard Smith040e1262017-06-02 01:55:39 +00001994 LE.write<uint32_t>(Writer.getIdentifierRef(Data.HFI.ControllingMacro));
1995
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001996 unsigned Offset = 0;
Richard Smith040e1262017-06-02 01:55:39 +00001997 if (!Data.HFI.Framework.empty()) {
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001998 // If this header refers into a framework, save the framework name.
1999 llvm::StringMap<unsigned>::iterator Pos
Richard Smith040e1262017-06-02 01:55:39 +00002000 = FrameworkNameOffset.find(Data.HFI.Framework);
Douglas Gregor4b123cb2011-07-28 04:50:02 +00002001 if (Pos == FrameworkNameOffset.end()) {
2002 Offset = FrameworkStringData.size() + 1;
Richard Smith040e1262017-06-02 01:55:39 +00002003 FrameworkStringData.append(Data.HFI.Framework.begin(),
2004 Data.HFI.Framework.end());
Douglas Gregor4b123cb2011-07-28 04:50:02 +00002005 FrameworkStringData.push_back(0);
2006
Richard Smith040e1262017-06-02 01:55:39 +00002007 FrameworkNameOffset[Data.HFI.Framework] = Offset;
Douglas Gregor4b123cb2011-07-28 04:50:02 +00002008 } else
2009 Offset = Pos->second;
2010 }
Justin Bognere1c147c2014-03-28 22:03:19 +00002011 LE.write<uint32_t>(Offset);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00002012
Richard Smith040e1262017-06-02 01:55:39 +00002013 auto EmitModule = [&](Module *M, ModuleMap::ModuleHeaderRole Role) {
2014 if (uint32_t ModID = Writer.getLocalOrImportedSubmoduleID(M)) {
2015 uint32_t Value = (ModID << 2) | (unsigned)Role;
Richard Smith386bb072015-08-18 23:42:23 +00002016 assert((Value >> 2) == ModID && "overflow in header module info");
2017 LE.write<uint32_t>(Value);
2018 }
Richard Smith040e1262017-06-02 01:55:39 +00002019 };
2020
2021 // FIXME: If the header is excluded, we should write out some
2022 // record of that fact.
2023 for (auto ModInfo : Data.KnownHeaders)
2024 EmitModule(ModInfo.getModule(), ModInfo.getRole());
2025 if (Data.Unresolved.getPointer())
2026 EmitModule(Data.Unresolved.getPointer(), Data.Unresolved.getInt());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00002027
Douglas Gregor09b69892011-02-10 17:09:37 +00002028 assert(Out.tell() - Start == DataLen && "Wrong data length");
2029 }
Douglas Gregor4b123cb2011-07-28 04:50:02 +00002030
2031 const char *strings_begin() const { return FrameworkStringData.begin(); }
2032 const char *strings_end() const { return FrameworkStringData.end(); }
Douglas Gregor09b69892011-02-10 17:09:37 +00002033 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002034
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002035} // namespace
Douglas Gregor09b69892011-02-10 17:09:37 +00002036
2037/// \brief Write the header search block for the list of files that
2038///
2039/// \param HS The header search structure to save.
Richard Smith7ed1bc92014-12-05 22:42:13 +00002040void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
Richard Smith040e1262017-06-02 01:55:39 +00002041 HeaderFileInfoTrait GeneratorTrait(*this);
2042 llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
2043 SmallVector<const char *, 4> SavedStrings;
2044 unsigned NumHeaderSearchEntries = 0;
2045
2046 // Find all unresolved headers for the current module. We generally will
2047 // have resolved them before we get here, but not necessarily: we might be
2048 // compiling a preprocessed module, where there is no requirement for the
2049 // original files to exist any more.
Benjamin Krameree021d52017-06-02 17:30:24 +00002050 const HeaderFileInfo Empty; // So we can take a reference.
Richard Smith040e1262017-06-02 01:55:39 +00002051 if (WritingModule) {
2052 llvm::SmallVector<Module *, 16> Worklist(1, WritingModule);
2053 while (!Worklist.empty()) {
2054 Module *M = Worklist.pop_back_val();
2055 if (!M->isAvailable())
2056 continue;
2057
2058 // Map to disk files where possible, to pick up any missing stat
2059 // information. This also means we don't need to check the unresolved
2060 // headers list when emitting resolved headers in the first loop below.
2061 // FIXME: It'd be preferable to avoid doing this if we were given
2062 // sufficient stat information in the module map.
2063 HS.getModuleMap().resolveHeaderDirectives(M);
2064
2065 // If the file didn't exist, we can still create a module if we were given
2066 // enough information in the module map.
2067 for (auto U : M->MissingHeaders) {
2068 // Check that we were given enough information to build a module
2069 // without this file existing on disk.
2070 if (!U.Size || (!U.ModTime && IncludeTimestamps)) {
2071 PP->Diag(U.FileNameLoc, diag::err_module_no_size_mtime_for_header)
2072 << WritingModule->getFullModuleName() << U.Size.hasValue()
2073 << U.FileName;
2074 continue;
2075 }
2076
2077 // Form the effective relative pathname for the file.
2078 SmallString<128> Filename(M->Directory->getName());
2079 llvm::sys::path::append(Filename, U.FileName);
2080 PreparePathForOutput(Filename);
2081
2082 StringRef FilenameDup = strdup(Filename.c_str());
2083 SavedStrings.push_back(FilenameDup.data());
2084
2085 HeaderFileInfoTrait::key_type Key = {
2086 FilenameDup, *U.Size, IncludeTimestamps ? *U.ModTime : 0
2087 };
2088 HeaderFileInfoTrait::data_type Data = {
Benjamin Krameree021d52017-06-02 17:30:24 +00002089 Empty, {}, {M, ModuleMap::headerKindToRole(U.Kind)}
Richard Smith040e1262017-06-02 01:55:39 +00002090 };
2091 // FIXME: Deal with cases where there are multiple unresolved header
2092 // directives in different submodules for the same header.
2093 Generator.insert(Key, Data, GeneratorTrait);
2094 ++NumHeaderSearchEntries;
2095 }
2096
2097 Worklist.append(M->submodule_begin(), M->submodule_end());
2098 }
2099 }
2100
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002101 SmallVector<const FileEntry *, 16> FilesByUID;
Douglas Gregor09b69892011-02-10 17:09:37 +00002102 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
2103
2104 if (FilesByUID.size() > HS.header_file_size())
2105 FilesByUID.resize(HS.header_file_size());
Richard Smith040e1262017-06-02 01:55:39 +00002106
Douglas Gregor09b69892011-02-10 17:09:37 +00002107 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
2108 const FileEntry *File = FilesByUID[UID];
2109 if (!File)
2110 continue;
2111
Richard Smith386bb072015-08-18 23:42:23 +00002112 // Get the file info. This will load info from the external source if
2113 // necessary. Skip emitting this file if we have no information on it
2114 // as a header file (in which case HFI will be null) or if it hasn't
2115 // changed since it was loaded. Also skip it if it's for a modular header
2116 // from a different module; in that case, we rely on the module(s)
2117 // containing the header to provide this information.
Richard Smithd8879c82015-08-24 21:59:32 +00002118 const HeaderFileInfo *HFI =
2119 HS.getExistingFileInfo(File, /*WantExternal*/!Chain);
2120 if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00002121 continue;
Douglas Gregor09b69892011-02-10 17:09:37 +00002122
Richard Smith7ed1bc92014-12-05 22:42:13 +00002123 // Massage the file path into an appropriate form.
Mehdi Amini004b9c72016-10-10 22:52:47 +00002124 StringRef Filename = File->getName();
Richard Smith7ed1bc92014-12-05 22:42:13 +00002125 SmallString<128> FilenameTmp(Filename);
2126 if (PreparePathForOutput(FilenameTmp)) {
2127 // If we performed any translation on the file name at all, we need to
2128 // save this string, since the generator will refer to it later.
Mehdi Amini004b9c72016-10-10 22:52:47 +00002129 Filename = StringRef(strdup(FilenameTmp.c_str()));
2130 SavedStrings.push_back(Filename.data());
Douglas Gregor09b69892011-02-10 17:09:37 +00002131 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002132
Richard Smith040e1262017-06-02 01:55:39 +00002133 HeaderFileInfoTrait::key_type Key = {
2134 Filename, File->getSize(), getTimestampForOutput(File)
2135 };
2136 HeaderFileInfoTrait::data_type Data = {
2137 *HFI, HS.getModuleMap().findAllModulesForHeader(File), {}
2138 };
2139 Generator.insert(Key, Data, GeneratorTrait);
Douglas Gregor09b69892011-02-10 17:09:37 +00002140 ++NumHeaderSearchEntries;
2141 }
Richard Smith040e1262017-06-02 01:55:39 +00002142
Douglas Gregor09b69892011-02-10 17:09:37 +00002143 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002144 SmallString<4096> TableData;
Douglas Gregor09b69892011-02-10 17:09:37 +00002145 uint32_t BucketOffset;
2146 {
Justin Bognere1c147c2014-03-28 22:03:19 +00002147 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002148
Douglas Gregor09b69892011-02-10 17:09:37 +00002149 llvm::raw_svector_ostream Out(TableData);
2150 // Make sure that no bucket is at offset 0
Justin Bognere1c147c2014-03-28 22:03:19 +00002151 endian::Writer<little>(Out).write<uint32_t>(0);
Douglas Gregor09b69892011-02-10 17:09:37 +00002152 BucketOffset = Generator.Emit(Out, GeneratorTrait);
2153 }
2154
2155 // Create a blob abbreviation
2156 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002157
David Blaikieb44f0bf2017-01-04 22:36:43 +00002158 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor09b69892011-02-10 17:09:37 +00002159 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
2160 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2161 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor4b123cb2011-07-28 04:50:02 +00002162 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor09b69892011-02-10 17:09:37 +00002163 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00002164 unsigned TableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor09b69892011-02-10 17:09:37 +00002165
Douglas Gregor4b123cb2011-07-28 04:50:02 +00002166 // Write the header search table
Mehdi Amini57a41912015-09-10 01:46:39 +00002167 RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
2168 NumHeaderSearchEntries, TableData.size()};
Douglas Gregor4b123cb2011-07-28 04:50:02 +00002169 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
Yaron Keren92e1b622015-03-18 10:17:07 +00002170 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
Douglas Gregor09b69892011-02-10 17:09:37 +00002171
2172 // Free all of the strings we had to duplicate.
2173 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
David Greenebae0e352013-01-15 22:09:43 +00002174 free(const_cast<char *>(SavedStrings[I]));
Douglas Gregor09b69892011-02-10 17:09:37 +00002175}
2176
George Rimarc39f5492017-01-17 15:45:31 +00002177static void emitBlob(llvm::BitstreamWriter &Stream, StringRef Blob,
2178 unsigned SLocBufferBlobCompressedAbbrv,
2179 unsigned SLocBufferBlobAbbrv) {
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002180 using RecordDataType = ASTWriter::RecordData::value_type;
George Rimarc39f5492017-01-17 15:45:31 +00002181
2182 // Compress the buffer if possible. We expect that almost all PCM
2183 // consumers will not want its contents.
2184 SmallString<0> CompressedBuffer;
2185 if (llvm::zlib::isAvailable()) {
2186 llvm::Error E = llvm::zlib::compress(Blob.drop_back(1), CompressedBuffer);
2187 if (!E) {
2188 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED,
2189 Blob.size() - 1};
2190 Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
2191 CompressedBuffer);
2192 return;
2193 }
2194 llvm::consumeError(std::move(E));
2195 }
2196
2197 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB};
2198 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob);
2199}
2200
Douglas Gregora7f71a92009-04-10 03:52:48 +00002201/// \brief Writes the block containing the serialized form of the
2202/// source manager.
2203///
2204/// TODO: We should probably use an on-disk hash table (stored in a
2205/// blob), indexed based on the file name, so that we only create
2206/// entries for files that we actually need. In the common case (no
2207/// errors), we probably won't have to create file entries for any of
2208/// the files in the AST.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002209void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
Richard Smith7ed1bc92014-12-05 22:42:13 +00002210 const Preprocessor &PP) {
Douglas Gregor258ae542009-04-27 06:38:32 +00002211 RecordData Record;
2212
Chris Lattner0910e3b2009-04-10 17:16:57 +00002213 // Enter the source manager block.
Richard Smithaada85c2016-02-06 02:06:43 +00002214 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
Douglas Gregora7f71a92009-04-10 03:52:48 +00002215
2216 // Abbreviations for the various kinds of source-location entries.
Chris Lattnerc4976c732009-04-27 19:03:22 +00002217 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
2218 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
Richard Smithaada85c2016-02-06 02:06:43 +00002219 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
2220 unsigned SLocBufferBlobCompressedAbbrv =
2221 CreateSLocBufferBlobAbbrev(Stream, true);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00002222 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
Douglas Gregora7f71a92009-04-10 03:52:48 +00002223
Douglas Gregor258ae542009-04-27 06:38:32 +00002224 // Write out the source location entry table. We skip the first
2225 // entry, which is always the same dummy entry.
Chris Lattner12d61d32009-04-27 19:01:47 +00002226 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor258ae542009-04-27 06:38:32 +00002227 RecordData PreloadSLocs;
Douglas Gregor925296b2011-07-19 16:10:42 +00002228 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
2229 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
Sebastian Redl5c415f32010-07-22 17:01:13 +00002230 I != N; ++I) {
Douglas Gregor8655e882009-10-16 22:46:09 +00002231 // Get this source location entry.
Douglas Gregor925296b2011-07-19 16:10:42 +00002232 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00002233 FileID FID = FileID::get(I);
2234 assert(&SourceMgr.getSLocEntry(FID) == SLoc);
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00002235
Douglas Gregor258ae542009-04-27 06:38:32 +00002236 // Record the offset of this source-location entry.
2237 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
2238
2239 // Figure out which record code to use.
2240 unsigned Code;
2241 if (SLoc->isFile()) {
Douglas Gregor9dc32122011-11-16 20:05:18 +00002242 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
2243 if (Cache->OrigEntry) {
Sebastian Redl539c5062010-08-18 23:57:32 +00002244 Code = SM_SLOC_FILE_ENTRY;
Argyrios Kyrtzidis92dd4662011-06-02 20:01:46 +00002245 } else
Sebastian Redl539c5062010-08-18 23:57:32 +00002246 Code = SM_SLOC_BUFFER_ENTRY;
Douglas Gregor258ae542009-04-27 06:38:32 +00002247 } else
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00002248 Code = SM_SLOC_EXPANSION_ENTRY;
Douglas Gregor258ae542009-04-27 06:38:32 +00002249 Record.clear();
2250 Record.push_back(Code);
2251
Douglas Gregor925296b2011-07-19 16:10:42 +00002252 // Starting offset of this entry within this module, so skip the dummy.
2253 Record.push_back(SLoc->getOffset() - 2);
Douglas Gregor258ae542009-04-27 06:38:32 +00002254 if (SLoc->isFile()) {
2255 const SrcMgr::FileInfo &File = SLoc->getFile();
Richard Smithb22a1d12016-03-27 20:13:24 +00002256 AddSourceLocation(File.getIncludeLoc(), Record);
Douglas Gregor258ae542009-04-27 06:38:32 +00002257 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
2258 Record.push_back(File.hasLineDirectives());
2259
2260 const SrcMgr::ContentCache *Content = File.getContentCache();
Richard Smithaada85c2016-02-06 02:06:43 +00002261 bool EmitBlob = false;
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002262 if (Content->OrigEntry) {
2263 assert(Content->OrigEntry == Content->ContentsEntry &&
Douglas Gregor9dc32122011-11-16 20:05:18 +00002264 "Writing to AST an overridden file is not supported");
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002265
Douglas Gregor3120d2c2012-10-22 18:42:04 +00002266 // The source location entry is a file. Emit input file ID.
2267 assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
2268 Record.push_back(InputFileIDs[Content->OrigEntry]);
Mike Stump11289f42009-09-09 15:08:12 +00002269
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00002270 Record.push_back(File.NumCreatedFIDs);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002271
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00002272 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002273 if (FDI != FileDeclIDs.end()) {
2274 Record.push_back(FDI->second->FirstDeclIndex);
2275 Record.push_back(FDI->second->DeclIDs.size());
2276 } else {
2277 Record.push_back(0);
2278 Record.push_back(0);
2279 }
Mehdi Amini5ae4a852015-09-09 20:35:37 +00002280
2281 Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
2282
Richard Smithaada85c2016-02-06 02:06:43 +00002283 if (Content->BufferOverridden || Content->IsTransient)
2284 EmitBlob = true;
Douglas Gregor258ae542009-04-27 06:38:32 +00002285 } else {
2286 // The source location entry is a buffer. The blob associated
2287 // with this entry contains the contents of the buffer.
2288
2289 // We add one to the size so that we capture the trailing NULL
2290 // that is required by llvm::MemoryBuffer::getMemBuffer (on
2291 // the reader side).
Douglas Gregor874cc622010-03-16 00:35:39 +00002292 const llvm::MemoryBuffer *Buffer
Chris Lattnerfb24a3a2010-04-20 20:35:58 +00002293 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
Mehdi Amini99d1b292016-10-01 16:38:28 +00002294 StringRef Name = Buffer->getBufferIdentifier();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00002295 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
Mehdi Amini99d1b292016-10-01 16:38:28 +00002296 StringRef(Name.data(), Name.size() + 1));
Richard Smithaada85c2016-02-06 02:06:43 +00002297 EmitBlob = true;
Douglas Gregor258ae542009-04-27 06:38:32 +00002298
Mehdi Amini99d1b292016-10-01 16:38:28 +00002299 if (Name == "<built-in>")
Douglas Gregor925296b2011-07-19 16:10:42 +00002300 PreloadSLocs.push_back(SLocEntryOffsets.size());
Douglas Gregor258ae542009-04-27 06:38:32 +00002301 }
Richard Smithaada85c2016-02-06 02:06:43 +00002302
2303 if (EmitBlob) {
2304 // Include the implicit terminating null character in the on-disk buffer
2305 // if we're writing it uncompressed.
2306 const llvm::MemoryBuffer *Buffer =
2307 Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
2308 StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
George Rimarc39f5492017-01-17 15:45:31 +00002309 emitBlob(Stream, Blob, SLocBufferBlobCompressedAbbrv,
2310 SLocBufferBlobAbbrv);
Richard Smithaada85c2016-02-06 02:06:43 +00002311 }
Douglas Gregor258ae542009-04-27 06:38:32 +00002312 } else {
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00002313 // The source location entry is a macro expansion.
Chandler Carruthee4c1d12011-07-26 04:56:51 +00002314 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
Richard Smithb22a1d12016-03-27 20:13:24 +00002315 AddSourceLocation(Expansion.getSpellingLoc(), Record);
2316 AddSourceLocation(Expansion.getExpansionLocStart(), Record);
2317 AddSourceLocation(Expansion.isMacroArgExpansion()
2318 ? SourceLocation()
2319 : Expansion.getExpansionLocEnd(),
2320 Record);
Douglas Gregor258ae542009-04-27 06:38:32 +00002321
2322 // Compute the token length for this macro expansion.
Douglas Gregor925296b2011-07-19 16:10:42 +00002323 unsigned NextOffset = SourceMgr.getNextLocalOffset();
Douglas Gregor8655e882009-10-16 22:46:09 +00002324 if (I + 1 != N)
Douglas Gregor925296b2011-07-19 16:10:42 +00002325 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
Douglas Gregor258ae542009-04-27 06:38:32 +00002326 Record.push_back(NextOffset - SLoc->getOffset() - 1);
Mehdi Amini5ae4a852015-09-09 20:35:37 +00002327 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
Douglas Gregor258ae542009-04-27 06:38:32 +00002328 }
2329 }
2330
Douglas Gregor8f45df52009-04-16 22:23:12 +00002331 Stream.ExitBlock();
Douglas Gregor258ae542009-04-27 06:38:32 +00002332
2333 if (SLocEntryOffsets.empty())
2334 return;
2335
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002336 // Write the source-location offsets table into the AST block. This
Douglas Gregor258ae542009-04-27 06:38:32 +00002337 // table is used for lazily loading source-location information.
2338 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002339
David Blaikieb44f0bf2017-01-04 22:36:43 +00002340 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00002341 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
Douglas Gregor258ae542009-04-27 06:38:32 +00002342 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
Douglas Gregor925296b2011-07-19 16:10:42 +00002343 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
Douglas Gregor258ae542009-04-27 06:38:32 +00002344 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
David Blaikieb44f0bf2017-01-04 22:36:43 +00002345 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00002346 {
2347 RecordData::value_type Record[] = {
2348 SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
2349 SourceMgr.getNextLocalOffset() - 1 /* skip dummy */};
2350 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
2351 bytes(SLocEntryOffsets));
2352 }
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002353 // Write the source location entry preloads array, telling the AST
Douglas Gregor258ae542009-04-27 06:38:32 +00002354 // reader which source locations entries it should load eagerly.
Sebastian Redl539c5062010-08-18 23:57:32 +00002355 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregor925296b2011-07-19 16:10:42 +00002356
2357 // Write the line table. It depends on remapping working, so it must come
2358 // after the source location offsets.
2359 if (SourceMgr.hasLineTable()) {
2360 LineTableInfo &LineTable = SourceMgr.getLineTable();
2361
2362 Record.clear();
Richard Smith63078492015-09-01 07:41:55 +00002363
2364 // Emit the needed file names.
2365 llvm::DenseMap<int, int> FilenameMap;
Hans Wennborg14487362017-12-04 22:28:45 +00002366 FilenameMap[-1] = -1; // For unspecified filenames.
Richard Smith63078492015-09-01 07:41:55 +00002367 for (const auto &L : LineTable) {
2368 if (L.first.ID < 0)
2369 continue;
2370 for (auto &LE : L.second) {
2371 if (FilenameMap.insert(std::make_pair(LE.FilenameID,
Hans Wennborg14487362017-12-04 22:28:45 +00002372 FilenameMap.size() - 1)).second)
Richard Smith63078492015-09-01 07:41:55 +00002373 AddPath(LineTable.getFilename(LE.FilenameID), Record);
2374 }
2375 }
2376 Record.push_back(0);
Douglas Gregor925296b2011-07-19 16:10:42 +00002377
2378 // Emit the line entries
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002379 for (const auto &L : LineTable) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002380 // Only emit entries for local files.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002381 if (L.first.ID < 0)
Douglas Gregor925296b2011-07-19 16:10:42 +00002382 continue;
2383
2384 // Emit the file ID
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002385 Record.push_back(L.first.ID);
Douglas Gregor925296b2011-07-19 16:10:42 +00002386
2387 // Emit the line entries
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002388 Record.push_back(L.second.size());
2389 for (const auto &LE : L.second) {
2390 Record.push_back(LE.FileOffset);
2391 Record.push_back(LE.LineNo);
2392 Record.push_back(FilenameMap[LE.FilenameID]);
2393 Record.push_back((unsigned)LE.FileKind);
2394 Record.push_back(LE.IncludeOffset);
Douglas Gregor925296b2011-07-19 16:10:42 +00002395 }
2396 }
Richard Smith63078492015-09-01 07:41:55 +00002397
Douglas Gregor925296b2011-07-19 16:10:42 +00002398 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
2399 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00002400}
2401
Douglas Gregorc5046832009-04-27 18:38:38 +00002402//===----------------------------------------------------------------------===//
2403// Preprocessor Serialization
2404//===----------------------------------------------------------------------===//
2405
Argyrios Kyrtzidis0aef0f02013-03-15 22:43:10 +00002406static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
2407 const Preprocessor &PP) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002408 if (MacroInfo *MI = MD->getMacroInfo())
2409 if (MI->isBuiltinMacro())
2410 return true;
Argyrios Kyrtzidis0aef0f02013-03-15 22:43:10 +00002411
2412 if (IsModule) {
2413 SourceLocation Loc = MD->getLocation();
2414 if (Loc.isInvalid())
2415 return true;
2416 if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
2417 return true;
2418 }
2419
2420 return false;
2421}
2422
Chris Lattnereeffaef2009-04-10 17:15:23 +00002423/// \brief Writes the block containing the serialized form of the
2424/// preprocessor.
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00002425void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002426 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
2427 if (PPRec)
2428 WritePreprocessorDetail(*PPRec);
2429
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002430 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00002431 RecordData ModuleMacroRecord;
Chris Lattner0910e3b2009-04-10 17:16:57 +00002432
Chris Lattner0af3ba12009-04-13 01:29:17 +00002433 // If the preprocessor __COUNTER__ value has been bumped, remember it.
2434 if (PP.getCounterValue() != 0) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002435 RecordData::value_type Record[] = {PP.getCounterValue()};
Sebastian Redl539c5062010-08-18 23:57:32 +00002436 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
Douglas Gregoreda6a892009-04-26 00:07:37 +00002437 }
2438
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00002439 if (PP.isRecordingPreamble() && PP.hasRecordedPreamble()) {
2440 assert(!IsModule);
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00002441 auto SkipInfo = PP.getPreambleSkipInfo();
2442 if (SkipInfo.hasValue()) {
2443 Record.push_back(true);
2444 AddSourceLocation(SkipInfo->HashTokenLoc, Record);
2445 AddSourceLocation(SkipInfo->IfTokenLoc, Record);
2446 Record.push_back(SkipInfo->FoundNonSkipPortion);
2447 Record.push_back(SkipInfo->FoundElse);
2448 AddSourceLocation(SkipInfo->ElseLoc, Record);
2449 } else {
2450 Record.push_back(false);
2451 }
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00002452 for (const auto &Cond : PP.getPreambleConditionalStack()) {
2453 AddSourceLocation(Cond.IfLoc, Record);
2454 Record.push_back(Cond.WasSkipping);
2455 Record.push_back(Cond.FoundNonSkip);
2456 Record.push_back(Cond.FoundElse);
2457 }
2458 Stream.EmitRecord(PP_CONDITIONAL_STACK, Record);
2459 Record.clear();
2460 }
2461
Douglas Gregoreda6a892009-04-26 00:07:37 +00002462 // Enter the preprocessor block.
Douglas Gregor796d76a2010-10-20 22:00:55 +00002463 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
Mike Stump11289f42009-09-09 15:08:12 +00002464
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002465 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
Richard Smithb5aaf5a2015-09-01 02:35:58 +00002466 // FIXME: Include a location for the use, and say which one was used.
Douglas Gregoreda6a892009-04-26 00:07:37 +00002467 if (PP.SawDateOrTime())
Richard Smithb5aaf5a2015-09-01 02:35:58 +00002468 PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
Douglas Gregor796d76a2010-10-20 22:00:55 +00002469
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002470 // Loop over all the macro directives that are live at the end of the file,
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002471 // emitting each to the PP section.
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002472
Richard Smithee977932015-05-01 21:22:17 +00002473 // Construct the list of identifiers with macro directives that need to be
2474 // serialized.
2475 SmallVector<const IdentifierInfo *, 128> MacroIdentifiers;
2476 for (auto &Id : PP.getIdentifierTable())
2477 if (Id.second->hadMacroDefinition() &&
2478 (!Id.second->isFromAST() ||
2479 Id.second->hasChangedSinceDeserialization()))
2480 MacroIdentifiers.push_back(Id.second);
Douglas Gregor2e5571d2011-02-10 18:20:09 +00002481 // Sort the set of macro definitions that need to be serialized by the
2482 // name of the macro, to provide a stable ordering.
Richard Smithee977932015-05-01 21:22:17 +00002483 std::sort(MacroIdentifiers.begin(), MacroIdentifiers.end(),
2484 llvm::less_ptr<IdentifierInfo>());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002485
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002486 // Emit the macro directives as a list and associate the offset with the
2487 // identifier they belong to.
Richard Smithee977932015-05-01 21:22:17 +00002488 for (const IdentifierInfo *Name : MacroIdentifiers) {
2489 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name);
Richard Smithd7329392015-04-21 21:46:32 +00002490 auto StartOffset = Stream.GetCurrentBitNo();
2491
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002492 // Emit the macro directives in reverse source order.
2493 for (; MD; MD = MD->getPrevious()) {
Richard Smithd7329392015-04-21 21:46:32 +00002494 // Once we hit an ignored macro, we're done: the rest of the chain
2495 // will all be ignored macros.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002496 if (shouldIgnoreMacro(MD, IsModule, PP))
Richard Smithd7329392015-04-21 21:46:32 +00002497 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002498
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002499 AddSourceLocation(MD->getLocation(), Record);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002500 Record.push_back(MD->getKind());
Richard Smithdaa69e02014-07-25 04:40:03 +00002501 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
Richard Smith3981b172015-04-30 02:16:23 +00002502 Record.push_back(getMacroRef(DefMD->getInfo(), Name));
Richard Smith713369b2015-04-23 20:40:50 +00002503 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002504 Record.push_back(VisMD->isPublic());
2505 }
Richard Smithb8b2ed62015-04-23 18:18:26 +00002506 }
Richard Smithd7329392015-04-21 21:46:32 +00002507
Richard Smithb8b2ed62015-04-23 18:18:26 +00002508 // Write out any exported module macros.
Richard Smithee977932015-05-01 21:22:17 +00002509 bool EmittedModuleMacros = false;
Manman Ren33d80292016-05-31 18:19:32 +00002510 // We write out exported module macros for PCH as well.
2511 auto Leafs = PP.getLeafModuleMacros(Name);
2512 SmallVector<ModuleMacro*, 8> Worklist(Leafs.begin(), Leafs.end());
2513 llvm::DenseMap<ModuleMacro*, unsigned> Visits;
2514 while (!Worklist.empty()) {
2515 auto *Macro = Worklist.pop_back_val();
Richard Smithd7329392015-04-21 21:46:32 +00002516
Manman Ren33d80292016-05-31 18:19:32 +00002517 // Emit a record indicating this submodule exports this macro.
2518 ModuleMacroRecord.push_back(
2519 getSubmoduleID(Macro->getOwningModule()));
2520 ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
2521 for (auto *M : Macro->overrides())
2522 ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
Richard Smithd7329392015-04-21 21:46:32 +00002523
Manman Ren33d80292016-05-31 18:19:32 +00002524 Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2525 ModuleMacroRecord.clear();
Richard Smithd7329392015-04-21 21:46:32 +00002526
Manman Ren33d80292016-05-31 18:19:32 +00002527 // Enqueue overridden macros once we've visited all their ancestors.
2528 for (auto *M : Macro->overrides())
2529 if (++Visits[M] == M->getNumOverridingMacros())
2530 Worklist.push_back(M);
Richard Smithee977932015-05-01 21:22:17 +00002531
Manman Ren33d80292016-05-31 18:19:32 +00002532 EmittedModuleMacros = true;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002533 }
Richard Smithd7329392015-04-21 21:46:32 +00002534
Richard Smithee977932015-05-01 21:22:17 +00002535 if (Record.empty() && !EmittedModuleMacros)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002536 continue;
2537
Richard Smithd7329392015-04-21 21:46:32 +00002538 IdentMacroDirectivesOffsetMap[Name] = StartOffset;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002539 Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2540 Record.clear();
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002541 }
Alexander Kornienko1d26c022012-09-25 17:18:14 +00002542
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002543 /// \brief Offsets of each of the macros into the bitstream, indexed by
2544 /// the local macro ID
2545 ///
2546 /// For each identifier that is associated with a macro, this map
2547 /// provides the offset into the bitstream where that macro is
2548 /// defined.
2549 std::vector<uint32_t> MacroOffsets;
2550
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002551 for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2552 const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2553 MacroInfo *MI = MacroInfosToEmit[I].MI;
2554 MacroID ID = MacroInfosToEmit[I].ID;
Douglas Gregoreb114da2010-10-01 01:03:07 +00002555
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002556 if (ID < FirstMacroID) {
2557 assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2558 continue;
Chris Lattner2199f5b2009-04-10 18:08:30 +00002559 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002560
2561 // Record the local offset of this macro.
2562 unsigned Index = ID - FirstMacroID;
2563 if (Index == MacroOffsets.size())
2564 MacroOffsets.push_back(Stream.GetCurrentBitNo());
2565 else {
2566 if (Index > MacroOffsets.size())
2567 MacroOffsets.resize(Index + 1);
2568
2569 MacroOffsets[Index] = Stream.GetCurrentBitNo();
2570 }
2571
2572 AddIdentifierRef(Name, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002573 AddSourceLocation(MI->getDefinitionLoc(), Record);
2574 AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2575 Record.push_back(MI->isUsed());
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00002576 Record.push_back(MI->isUsedForHeaderGuard());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002577 unsigned Code;
2578 if (MI->isObjectLike()) {
2579 Code = PP_MACRO_OBJECT_LIKE;
2580 } else {
2581 Code = PP_MACRO_FUNCTION_LIKE;
2582
2583 Record.push_back(MI->isC99Varargs());
2584 Record.push_back(MI->isGNUVarargs());
2585 Record.push_back(MI->hasCommaPasting());
Faisal Valiac506d72017-07-17 17:18:43 +00002586 Record.push_back(MI->getNumParams());
2587 for (const IdentifierInfo *Param : MI->params())
2588 AddIdentifierRef(Param, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002589 }
2590
2591 // If we have a detailed preprocessing record, record the macro definition
2592 // ID that corresponds to this macro.
2593 if (PPRec)
2594 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2595
2596 Stream.EmitRecord(Code, Record);
2597 Record.clear();
2598
2599 // Emit the tokens array.
2600 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2601 // Note that we know that the preprocessor does not have any annotation
2602 // tokens in it because they are created by the parser, and thus can't
2603 // be in a macro definition.
2604 const Token &Tok = MI->getReplacementToken(TokNo);
John McCallf413f5e2013-05-03 00:10:13 +00002605 AddToken(Tok, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002606 Stream.EmitRecord(PP_TOKEN, Record);
2607 Record.clear();
2608 }
2609 ++NumMacros;
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002610 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002611
Douglas Gregor92a96f52011-02-08 21:58:10 +00002612 Stream.ExitBlock();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002613
2614 // Write the offsets table for macro IDs.
2615 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002616
David Blaikieb44f0bf2017-01-04 22:36:43 +00002617 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002618 Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2619 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2620 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2621 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2622
David Blaikieb44f0bf2017-01-04 22:36:43 +00002623 unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00002624 {
2625 RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
2626 FirstMacroID - NUM_PREDEF_MACRO_IDS};
2627 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
2628 }
Douglas Gregor92a96f52011-02-08 21:58:10 +00002629}
2630
2631void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
Argyrios Kyrtzidis7f448362011-09-19 20:40:42 +00002632 if (PPRec.local_begin() == PPRec.local_end())
Douglas Gregor92a96f52011-02-08 21:58:10 +00002633 return;
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002634
Argyrios Kyrtzidis64f63812011-09-19 20:40:25 +00002635 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002636
Douglas Gregor92a96f52011-02-08 21:58:10 +00002637 // Enter the preprocessor block.
2638 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002639
Douglas Gregoraae92242010-03-19 21:51:54 +00002640 // If the preprocessor has a preprocessing record, emit it.
2641 unsigned NumPreprocessingRecords = 0;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002642 using namespace llvm;
2643
2644 // Set up the abbreviation for
2645 unsigned InclusionAbbrev = 0;
2646 {
David Blaikieb44f0bf2017-01-04 22:36:43 +00002647 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor92a96f52011-02-08 21:58:10 +00002648 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
Douglas Gregor92a96f52011-02-08 21:58:10 +00002649 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2650 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2651 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
Argyrios Kyrtzidisf590e092012-10-02 16:10:46 +00002652 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
Douglas Gregor92a96f52011-02-08 21:58:10 +00002653 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00002654 InclusionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor92a96f52011-02-08 21:58:10 +00002655 }
2656
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002657 unsigned FirstPreprocessorEntityID
2658 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
2659 + NUM_PREDEF_PP_ENTITY_IDS;
2660 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002661 RecordData Record;
Argyrios Kyrtzidis7f448362011-09-19 20:40:42 +00002662 for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2663 EEnd = PPRec.local_end();
Douglas Gregor0d4b4312011-08-04 17:06:18 +00002664 E != EEnd;
2665 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
Douglas Gregor92a96f52011-02-08 21:58:10 +00002666 Record.clear();
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002667
Richard Smith66a81862015-05-04 02:25:31 +00002668 PreprocessedEntityOffsets.push_back(
2669 PPEntityOffset((*E)->getSourceRange(), Stream.GetCurrentBitNo()));
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002670
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002671 if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002672 // Record this macro definition's ID.
2673 MacroDefinitions[MD] = NextPreprocessorEntityID;
Richard Smith66a81862015-05-04 02:25:31 +00002674
Douglas Gregor92a96f52011-02-08 21:58:10 +00002675 AddIdentifierRef(MD->getName(), Record);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002676 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2677 continue;
Douglas Gregoraae92242010-03-19 21:51:54 +00002678 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002679
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002680 if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
Argyrios Kyrtzidis80f78b92011-09-08 17:18:41 +00002681 Record.push_back(ME->isBuiltinMacro());
2682 if (ME->isBuiltinMacro())
2683 AddIdentifierRef(ME->getName(), Record);
2684 else
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002685 Record.push_back(MacroDefinitions[ME->getDefinition()]);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00002686 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002687 continue;
2688 }
2689
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002690 if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
Douglas Gregor92a96f52011-02-08 21:58:10 +00002691 Record.push_back(PPD_INCLUSION_DIRECTIVE);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002692 Record.push_back(ID->getFileName().size());
2693 Record.push_back(ID->wasInQuotes());
2694 Record.push_back(static_cast<unsigned>(ID->getKind()));
Argyrios Kyrtzidisf590e092012-10-02 16:10:46 +00002695 Record.push_back(ID->importedModule());
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002696 SmallString<64> Buffer;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002697 Buffer += ID->getFileName();
Argyrios Kyrtzidis8dbcfc32012-03-08 01:08:28 +00002698 // Check that the FileEntry is not null because it was not resolved and
2699 // we create a PCH even with compiler errors.
2700 if (ID->getFile())
2701 Buffer += ID->getFile()->getName();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00002702 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002703 continue;
2704 }
2705
2706 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2707 }
Douglas Gregor8f45df52009-04-16 22:23:12 +00002708 Stream.ExitBlock();
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002709
Douglas Gregoraae92242010-03-19 21:51:54 +00002710 // Write the offsets table for the preprocessing record.
2711 if (NumPreprocessingRecords > 0) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002712 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2713
Douglas Gregoraae92242010-03-19 21:51:54 +00002714 // Write the offsets table for identifier IDs.
2715 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002716
David Blaikieb44f0bf2017-01-04 22:36:43 +00002717 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002718 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002719 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
Douglas Gregoraae92242010-03-19 21:51:54 +00002720 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00002721 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002722
Mehdi Amini57a41912015-09-10 01:46:39 +00002723 RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
2724 FirstPreprocessorEntityID -
2725 NUM_PREDEF_PP_ENTITY_IDS};
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002726 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00002727 bytes(PreprocessedEntityOffsets));
Douglas Gregoraae92242010-03-19 21:51:54 +00002728 }
Chris Lattnereeffaef2009-04-10 17:15:23 +00002729}
2730
Richard Smith386bb072015-08-18 23:42:23 +00002731unsigned ASTWriter::getLocalOrImportedSubmoduleID(Module *Mod) {
Richard Smith080056b2015-08-18 21:53:42 +00002732 if (!Mod)
2733 return 0;
2734
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002735 llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
2736 if (Known != SubmoduleIDs.end())
2737 return Known->second;
Richard Smith386bb072015-08-18 23:42:23 +00002738
Richard Smithdc1f0422016-07-20 19:10:16 +00002739 auto *Top = Mod->getTopLevelModule();
2740 if (Top != WritingModule &&
Bruno Cardoso Lopes17da34d2017-02-07 21:54:57 +00002741 (getLangOpts().CompilingPCH ||
2742 !Top->fullModuleNameIs(StringRef(getLangOpts().CurrentModule))))
Richard Smith386bb072015-08-18 23:42:23 +00002743 return 0;
2744
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002745 return SubmoduleIDs[Mod] = NextSubmoduleID++;
2746}
2747
Richard Smith386bb072015-08-18 23:42:23 +00002748unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2749 // FIXME: This can easily happen, if we have a reference to a submodule that
2750 // did not result in us loading a module file for that submodule. For
2751 // instance, a cross-top-level-module 'conflict' declaration will hit this.
2752 unsigned ID = getLocalOrImportedSubmoduleID(Mod);
2753 assert((ID || !Mod) &&
2754 "asked for module ID for non-local, non-imported module");
2755 return ID;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00002756}
2757
Douglas Gregor253eefe2011-12-01 00:59:36 +00002758/// \brief Compute the number of modules within the given tree (including the
2759/// given module).
2760static unsigned getNumberOfModules(Module *Mod) {
2761 unsigned ChildModules = 0;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002762 for (auto Sub = Mod->submodule_begin(), SubEnd = Mod->submodule_end();
Douglas Gregor253eefe2011-12-01 00:59:36 +00002763 Sub != SubEnd; ++Sub)
Douglas Gregoreb90e832012-01-04 23:32:19 +00002764 ChildModules += getNumberOfModules(*Sub);
Douglas Gregor253eefe2011-12-01 00:59:36 +00002765
2766 return ChildModules + 1;
2767}
2768
Douglas Gregorde3ef502011-11-30 23:21:26 +00002769void ASTWriter::WriteSubmodules(Module *WritingModule) {
Douglas Gregor69021972011-11-30 17:33:56 +00002770 // Enter the submodule description block.
Richard Smith202210b2014-10-24 20:23:01 +00002771 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
Douglas Gregor69021972011-11-30 17:33:56 +00002772
2773 // Write the abbreviations needed for the submodules block.
2774 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002775
David Blaikieb44f0bf2017-01-04 22:36:43 +00002776 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor69021972011-11-30 17:33:56 +00002777 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002778 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
Douglas Gregor69021972011-11-30 17:33:56 +00002779 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
Richard Smithdd8b5332017-09-04 05:37:53 +00002780 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Kind
Douglas Gregor69021972011-11-30 17:33:56 +00002781 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2782 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
Richard Smith9bca2982014-03-08 00:03:56 +00002783 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2784 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
Douglas Gregora686e1b2012-01-27 19:52:33 +00002785 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
Douglas Gregor73441092011-12-05 22:27:44 +00002786 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
Douglas Gregor73441092011-12-05 22:27:44 +00002787 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002788 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
Douglas Gregor69021972011-11-30 17:33:56 +00002789 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002790 unsigned DefinitionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor69021972011-11-30 17:33:56 +00002791
David Blaikieb44f0bf2017-01-04 22:36:43 +00002792 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor524e33e2011-12-08 19:11:24 +00002793 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
Douglas Gregor69021972011-11-30 17:33:56 +00002794 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002795 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor69021972011-11-30 17:33:56 +00002796
David Blaikieb44f0bf2017-01-04 22:36:43 +00002797 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor69021972011-11-30 17:33:56 +00002798 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2799 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002800 unsigned HeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor524e33e2011-12-08 19:11:24 +00002801
David Blaikieb44f0bf2017-01-04 22:36:43 +00002802 Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +00002803 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2804 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002805 unsigned TopHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +00002806
David Blaikieb44f0bf2017-01-04 22:36:43 +00002807 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor524e33e2011-12-08 19:11:24 +00002808 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2809 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002810 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor524e33e2011-12-08 19:11:24 +00002811
David Blaikieb44f0bf2017-01-04 22:36:43 +00002812 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002813 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
Richard Smitha3feee22013-10-28 22:18:19 +00002814 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2815 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
David Blaikieb44f0bf2017-01-04 22:36:43 +00002816 unsigned RequiresAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002817
David Blaikieb44f0bf2017-01-04 22:36:43 +00002818 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor59527662012-10-15 06:28:11 +00002819 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2820 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002821 unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor59527662012-10-15 06:28:11 +00002822
David Blaikieb44f0bf2017-01-04 22:36:43 +00002823 Abbrev = std::make_shared<BitCodeAbbrev>();
Richard Smith306d8922014-10-22 23:50:56 +00002824 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
2825 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002826 unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Richard Smith306d8922014-10-22 23:50:56 +00002827
David Blaikieb44f0bf2017-01-04 22:36:43 +00002828 Abbrev = std::make_shared<BitCodeAbbrev>();
Lawrence Crowlb53e5482013-06-20 21:14:14 +00002829 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2830 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002831 unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Lawrence Crowlb53e5482013-06-20 21:14:14 +00002832
David Blaikieb44f0bf2017-01-04 22:36:43 +00002833 Abbrev = std::make_shared<BitCodeAbbrev>();
Richard Smith202210b2014-10-24 20:23:01 +00002834 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
2835 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002836 unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Richard Smith202210b2014-10-24 20:23:01 +00002837
David Blaikieb44f0bf2017-01-04 22:36:43 +00002838 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002839 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2840 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2841 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002842 unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002843
David Blaikieb44f0bf2017-01-04 22:36:43 +00002844 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002845 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2846 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002847 unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002848
David Blaikieb44f0bf2017-01-04 22:36:43 +00002849 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregorfb912652013-03-20 21:10:35 +00002850 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2851 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
2852 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
David Blaikieb44f0bf2017-01-04 22:36:43 +00002853 unsigned ConflictAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregorfb912652013-03-20 21:10:35 +00002854
Douglas Gregorf0b11de2017-09-14 23:38:44 +00002855 Abbrev = std::make_shared<BitCodeAbbrev>();
2856 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXPORT_AS));
2857 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2858 unsigned ExportAsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2859
Douglas Gregor253eefe2011-12-01 00:59:36 +00002860 // Write the submodule metadata block.
Richard Smith145e15a2017-04-24 23:12:30 +00002861 RecordData::value_type Record[] = {
2862 getNumberOfModules(WritingModule),
Richard Smithdd8b5332017-09-04 05:37:53 +00002863 FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS};
Douglas Gregor253eefe2011-12-01 00:59:36 +00002864 Stream.EmitRecord(SUBMODULE_METADATA, Record);
2865
Douglas Gregor69021972011-11-30 17:33:56 +00002866 // Write all of the submodules.
Douglas Gregorde3ef502011-11-30 23:21:26 +00002867 std::queue<Module *> Q;
Douglas Gregor69021972011-11-30 17:33:56 +00002868 Q.push(WritingModule);
Douglas Gregor69021972011-11-30 17:33:56 +00002869 while (!Q.empty()) {
Douglas Gregorde3ef502011-11-30 23:21:26 +00002870 Module *Mod = Q.front();
Douglas Gregor69021972011-11-30 17:33:56 +00002871 Q.pop();
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002872 unsigned ID = getSubmoduleID(Mod);
Mehdi Amini57a41912015-09-10 01:46:39 +00002873
2874 uint64_t ParentID = 0;
Douglas Gregor69021972011-11-30 17:33:56 +00002875 if (Mod->Parent) {
2876 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
Mehdi Amini57a41912015-09-10 01:46:39 +00002877 ParentID = SubmoduleIDs[Mod->Parent];
Douglas Gregor69021972011-11-30 17:33:56 +00002878 }
Mehdi Amini57a41912015-09-10 01:46:39 +00002879
2880 // Emit the definition of the block.
2881 {
David Blaikie9ffe5a32017-01-30 05:00:26 +00002882 RecordData::value_type Record[] = {SUBMODULE_DEFINITION,
2883 ID,
2884 ParentID,
Simon Pilgrimf331a662017-09-04 10:54:39 +00002885 (RecordData::value_type)Mod->Kind,
David Blaikie9ffe5a32017-01-30 05:00:26 +00002886 Mod->IsFramework,
2887 Mod->IsExplicit,
2888 Mod->IsSystem,
2889 Mod->IsExternC,
2890 Mod->InferSubmodules,
2891 Mod->InferExplicitSubmodules,
2892 Mod->InferExportWildcard,
David Blaikiee6b7c282017-04-11 20:46:34 +00002893 Mod->ConfigMacrosExhaustive};
Mehdi Amini57a41912015-09-10 01:46:39 +00002894 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2895 }
2896
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002897 // Emit the requirements.
Richard Smith080056b2015-08-18 21:53:42 +00002898 for (const auto &R : Mod->Requirements) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002899 RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.second};
Richard Smith080056b2015-08-18 21:53:42 +00002900 Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.first);
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002901 }
2902
Douglas Gregor69021972011-11-30 17:33:56 +00002903 // Emit the umbrella header, if there is one.
Richard Smith2b63d152015-05-16 02:28:53 +00002904 if (auto UmbrellaHeader = Mod->getUmbrellaHeader()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002905 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
Richard Smith2b63d152015-05-16 02:28:53 +00002906 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2907 UmbrellaHeader.NameAsWritten);
2908 } else if (auto UmbrellaDir = Mod->getUmbrellaDir()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002909 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
2910 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
Richard Smith2b63d152015-05-16 02:28:53 +00002911 UmbrellaDir.NameAsWritten);
Douglas Gregor69021972011-11-30 17:33:56 +00002912 }
Richard Smith306d8922014-10-22 23:50:56 +00002913
Douglas Gregor69021972011-11-30 17:33:56 +00002914 // Emit the headers.
Richard Smith202210b2014-10-24 20:23:01 +00002915 struct {
Richard Smith3c1a41a2014-12-02 00:08:08 +00002916 unsigned RecordKind;
Richard Smith202210b2014-10-24 20:23:01 +00002917 unsigned Abbrev;
Richard Smith3c1a41a2014-12-02 00:08:08 +00002918 Module::HeaderKind HeaderKind;
Richard Smith202210b2014-10-24 20:23:01 +00002919 } HeaderLists[] = {
Richard Smith3c1a41a2014-12-02 00:08:08 +00002920 {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
2921 {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
2922 {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
Richard Smith202210b2014-10-24 20:23:01 +00002923 {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
Richard Smith3c1a41a2014-12-02 00:08:08 +00002924 Module::HK_PrivateTextual},
2925 {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
Richard Smith202210b2014-10-24 20:23:01 +00002926 };
2927 for (auto &HL : HeaderLists) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002928 RecordData::value_type Record[] = {HL.RecordKind};
Richard Smith3c1a41a2014-12-02 00:08:08 +00002929 for (auto &H : Mod->Headers[HL.HeaderKind])
2930 Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
2931 }
2932
2933 // Emit the top headers.
2934 {
2935 auto TopHeaders = Mod->getTopHeaders(PP->getFileManager());
Mehdi Amini57a41912015-09-10 01:46:39 +00002936 RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
Richard Smith3c1a41a2014-12-02 00:08:08 +00002937 for (auto *H : TopHeaders)
2938 Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, H->getName());
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +00002939 }
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002940
2941 // Emit the imports.
2942 if (!Mod->Imports.empty()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002943 RecordData Record;
Richard Smith080056b2015-08-18 21:53:42 +00002944 for (auto *I : Mod->Imports)
2945 Record.push_back(getSubmoduleID(I));
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002946 Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2947 }
2948
Douglas Gregor24bb9232011-12-02 18:58:38 +00002949 // Emit the exports.
2950 if (!Mod->Exports.empty()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002951 RecordData Record;
Richard Smith080056b2015-08-18 21:53:42 +00002952 for (const auto &E : Mod->Exports) {
2953 // FIXME: This may fail; we don't require that all exported modules
2954 // are local or imported.
2955 Record.push_back(getSubmoduleID(E.getPointer()));
2956 Record.push_back(E.getInt());
Douglas Gregor24bb9232011-12-02 18:58:38 +00002957 }
2958 Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2959 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002960
Daniel Jasperba7f2f72013-09-24 09:14:14 +00002961 //FIXME: How do we emit the 'use'd modules? They may not be submodules.
2962 // Might be unnecessary as use declarations are only used to build the
2963 // module itself.
2964
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002965 // Emit the link libraries.
Richard Smith080056b2015-08-18 21:53:42 +00002966 for (const auto &LL : Mod->LinkLibraries) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002967 RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
2968 LL.IsFramework};
Richard Smith080056b2015-08-18 21:53:42 +00002969 Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002970 }
2971
Douglas Gregorfb912652013-03-20 21:10:35 +00002972 // Emit the conflicts.
Richard Smith080056b2015-08-18 21:53:42 +00002973 for (const auto &C : Mod->Conflicts) {
Richard Smith080056b2015-08-18 21:53:42 +00002974 // FIXME: This may fail; we don't require that all conflicting modules
2975 // are local or imported.
Mehdi Amini57a41912015-09-10 01:46:39 +00002976 RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
2977 getSubmoduleID(C.Other)};
Richard Smith080056b2015-08-18 21:53:42 +00002978 Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message);
Douglas Gregorfb912652013-03-20 21:10:35 +00002979 }
2980
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002981 // Emit the configuration macros.
Richard Smith080056b2015-08-18 21:53:42 +00002982 for (const auto &CM : Mod->ConfigMacros) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002983 RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
Richard Smith080056b2015-08-18 21:53:42 +00002984 Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM);
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002985 }
2986
Richard Smithdc1f0422016-07-20 19:10:16 +00002987 // Emit the initializers, if any.
2988 RecordData Inits;
2989 for (Decl *D : Context->getModuleInitializers(Mod))
2990 Inits.push_back(GetDeclRef(D));
2991 if (!Inits.empty())
2992 Stream.EmitRecord(SUBMODULE_INITIALIZERS, Inits);
2993
Douglas Gregorf0b11de2017-09-14 23:38:44 +00002994 // Emit the name of the re-exported module, if any.
2995 if (!Mod->ExportAsModule.empty()) {
2996 RecordData::value_type Record[] = {SUBMODULE_EXPORT_AS};
2997 Stream.EmitRecordWithBlob(ExportAsAbbrev, Record, Mod->ExportAsModule);
2998 }
2999
Douglas Gregor69021972011-11-30 17:33:56 +00003000 // Queue up the submodules of this module.
Richard Smith080056b2015-08-18 21:53:42 +00003001 for (auto *M : Mod->submodules())
3002 Q.push(M);
Douglas Gregor69021972011-11-30 17:33:56 +00003003 }
3004
3005 Stream.ExitBlock();
Richard Smith23d8d032015-05-14 00:45:20 +00003006
Richard Smith23d8d032015-05-14 00:45:20 +00003007 assert((NextSubmoduleID - FirstSubmoduleID ==
3008 getNumberOfModules(WritingModule)) &&
3009 "Wrong # of submodules; found a reference to a non-local, "
3010 "non-imported submodule?");
Douglas Gregor69021972011-11-30 17:33:56 +00003011}
3012
Argyrios Kyrtzidis0f06b982013-03-27 17:17:23 +00003013void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
3014 bool isModule) {
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00003015 llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
3016 DiagStateIDMap;
3017 unsigned CurrID = 0;
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00003018 RecordData Record;
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00003019
Richard Smithe37391c2017-05-03 00:28:49 +00003020 auto EncodeDiagStateFlags =
3021 [](const DiagnosticsEngine::DiagState *DS) -> unsigned {
3022 unsigned Result = (unsigned)DS->ExtBehavior;
3023 for (unsigned Val :
Daniel Jasperba9aefc2017-05-03 07:48:27 +00003024 {(unsigned)DS->IgnoreAllWarnings, (unsigned)DS->EnableAllWarnings,
3025 (unsigned)DS->WarningsAsErrors, (unsigned)DS->ErrorsAsFatal,
3026 (unsigned)DS->SuppressSystemWarnings})
Richard Smithe37391c2017-05-03 00:28:49 +00003027 Result = (Result << 1) | Val;
3028 return Result;
3029 };
3030
3031 unsigned Flags = EncodeDiagStateFlags(Diag.DiagStatesByLoc.FirstDiagState);
3032 Record.push_back(Flags);
3033
Richard Smithd230de22017-01-26 01:01:01 +00003034 auto AddDiagState = [&](const DiagnosticsEngine::DiagState *State,
3035 bool IncludeNonPragmaStates) {
Richard Smithe37391c2017-05-03 00:28:49 +00003036 // Ensure that the diagnostic state wasn't modified since it was created.
3037 // We will not correctly round-trip this information otherwise.
3038 assert(Flags == EncodeDiagStateFlags(State) &&
3039 "diag state flags vary in single AST file");
3040
Richard Smithd230de22017-01-26 01:01:01 +00003041 unsigned &DiagStateID = DiagStateIDMap[State];
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00003042 Record.push_back(DiagStateID);
Richard Smithd230de22017-01-26 01:01:01 +00003043
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00003044 if (DiagStateID == 0) {
3045 DiagStateID = ++CurrID;
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00003046
3047 // Add a placeholder for the number of mappings.
3048 auto SizeIdx = Record.size();
3049 Record.emplace_back();
Richard Smithd230de22017-01-26 01:01:01 +00003050 for (const auto &I : *State) {
3051 if (I.second.isPragma() || IncludeNonPragmaStates) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003052 Record.push_back(I.first);
Richard Smithe37391c2017-05-03 00:28:49 +00003053 Record.push_back(I.second.serialize());
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00003054 }
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00003055 }
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00003056 // Update the placeholder.
3057 Record[SizeIdx] = (Record.size() - SizeIdx) / 2;
Richard Smithd230de22017-01-26 01:01:01 +00003058 }
3059 };
3060
3061 AddDiagState(Diag.DiagStatesByLoc.FirstDiagState, isModule);
Richard Smithd230de22017-01-26 01:01:01 +00003062
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00003063 // Reserve a spot for the number of locations with state transitions.
3064 auto NumLocationsIdx = Record.size();
3065 Record.emplace_back();
3066
3067 // Emit the state transitions.
3068 unsigned NumLocations = 0;
Richard Smithd230de22017-01-26 01:01:01 +00003069 for (auto &FileIDAndFile : Diag.DiagStatesByLoc.Files) {
3070 if (!FileIDAndFile.first.isValid() ||
3071 !FileIDAndFile.second.HasLocalTransitions)
3072 continue;
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00003073 ++NumLocations;
Richard Smithd230de22017-01-26 01:01:01 +00003074 AddSourceLocation(Diag.SourceMgr->getLocForStartOfFile(FileIDAndFile.first),
3075 Record);
3076 Record.push_back(FileIDAndFile.second.StateTransitions.size());
3077 for (auto &StatePoint : FileIDAndFile.second.StateTransitions) {
3078 Record.push_back(StatePoint.Offset);
3079 AddDiagState(StatePoint.State, false);
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00003080 }
3081 }
3082
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00003083 // Backpatch the number of locations.
3084 Record[NumLocationsIdx] = NumLocations;
3085
3086 // Emit CurDiagStateLoc. Do it last in order to match source order.
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00003087 //
3088 // This also protects against a hypothetical corner case with simulating
3089 // -Werror settings for implicit modules in the ASTReader, where reading
3090 // CurDiagState out of context could change whether warning pragmas are
3091 // treated as errors.
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00003092 AddSourceLocation(Diag.DiagStatesByLoc.CurDiagStateLoc, Record);
3093 AddDiagState(Diag.DiagStatesByLoc.CurDiagState, false);
3094
Duncan P. N. Exon Smithf2435b92017-04-12 02:31:17 +00003095 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00003096}
3097
Douglas Gregorc5046832009-04-27 18:38:38 +00003098//===----------------------------------------------------------------------===//
3099// Type Serialization
3100//===----------------------------------------------------------------------===//
Chris Lattnereeffaef2009-04-10 17:15:23 +00003101
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003102/// \brief Write the representation of a type to the AST stream.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003103void ASTWriter::WriteType(QualType T) {
Richard Smith290d8012016-04-06 17:06:00 +00003104 TypeIdx &IdxRef = TypeIdxs[T];
3105 if (IdxRef.getIndex() == 0) // we haven't seen this type before.
3106 IdxRef = TypeIdx(NextTypeID++);
3107 TypeIdx Idx = IdxRef;
Mike Stump11289f42009-09-09 15:08:12 +00003108
Douglas Gregor9b3932c2010-10-05 18:37:06 +00003109 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
Douglas Gregordc72caa2010-10-04 18:21:45 +00003110
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003111 RecordData Record;
Mike Stump11289f42009-09-09 15:08:12 +00003112
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003113 // Emit the type's representation.
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003114 ASTTypeWriter W(*this, Record);
Richard Smith290d8012016-04-06 17:06:00 +00003115 W.Visit(T);
3116 uint64_t Offset = W.Emit();
John McCall8ccfcb52009-09-24 19:53:00 +00003117
Richard Smith290d8012016-04-06 17:06:00 +00003118 // Record the offset for this type.
3119 unsigned Index = Idx.getIndex() - FirstTypeID;
3120 if (TypeOffsets.size() == Index)
3121 TypeOffsets.push_back(Offset);
3122 else if (TypeOffsets.size() < Index) {
3123 TypeOffsets.resize(Index + 1);
3124 TypeOffsets[Index] = Offset;
John McCall8ccfcb52009-09-24 19:53:00 +00003125 } else {
Richard Smith290d8012016-04-06 17:06:00 +00003126 llvm_unreachable("Types emitted in wrong order");
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003127 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003128}
3129
Douglas Gregorc5046832009-04-27 18:38:38 +00003130//===----------------------------------------------------------------------===//
3131// Declaration Serialization
3132//===----------------------------------------------------------------------===//
3133
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003134/// \brief Write the block containing all of the declaration IDs
3135/// lexically declared within the given DeclContext.
3136///
3137/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
3138/// bistream, or 0 if no block was written.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003139uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003140 DeclContext *DC) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003141 if (DC->decls_empty())
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003142 return 0;
3143
Douglas Gregor8f45df52009-04-16 22:23:12 +00003144 uint64_t Offset = Stream.GetCurrentBitNo();
Richard Smith82f8fcd2015-08-06 22:07:25 +00003145 SmallVector<uint32_t, 128> KindDeclPairs;
3146 for (const auto *D : DC->decls()) {
3147 KindDeclPairs.push_back(D->getKind());
3148 KindDeclPairs.push_back(GetDeclRef(D));
3149 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003150
Douglas Gregora57c3ab2009-04-22 22:34:57 +00003151 ++NumLexicalDeclContexts;
Mehdi Amini57a41912015-09-10 01:46:39 +00003152 RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
Richard Smith82f8fcd2015-08-06 22:07:25 +00003153 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
3154 bytes(KindDeclPairs));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00003155 return Offset;
3156}
3157
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003158void ASTWriter::WriteTypeDeclOffsets() {
Sebastian Redl1ea025b2010-07-16 16:36:56 +00003159 using namespace llvm;
Sebastian Redl1ea025b2010-07-16 16:36:56 +00003160
3161 // Write the type offsets array
David Blaikieb44f0bf2017-01-04 22:36:43 +00003162 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00003163 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
Sebastian Redl1ea025b2010-07-16 16:36:56 +00003164 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
Douglas Gregor5204bde2011-08-02 16:26:37 +00003165 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
Sebastian Redl1ea025b2010-07-16 16:36:56 +00003166 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
David Blaikieb44f0bf2017-01-04 22:36:43 +00003167 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00003168 {
3169 RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(),
3170 FirstTypeID - NUM_PREDEF_TYPE_IDS};
3171 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
3172 }
Sebastian Redl1ea025b2010-07-16 16:36:56 +00003173
3174 // Write the declaration offsets array
David Blaikieb44f0bf2017-01-04 22:36:43 +00003175 Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00003176 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
Sebastian Redl1ea025b2010-07-16 16:36:56 +00003177 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
Douglas Gregorf7180622011-08-03 15:48:04 +00003178 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
Sebastian Redl1ea025b2010-07-16 16:36:56 +00003179 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
David Blaikieb44f0bf2017-01-04 22:36:43 +00003180 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00003181 {
3182 RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(),
3183 FirstDeclID - NUM_PREDEF_DECL_IDS};
3184 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
3185 }
Sebastian Redl1ea025b2010-07-16 16:36:56 +00003186}
3187
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00003188void ASTWriter::WriteFileDeclIDsMap() {
3189 using namespace llvm;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00003190
Chandler Carruthb306d732015-03-27 00:31:20 +00003191 SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs(
3192 FileDeclIDs.begin(), FileDeclIDs.end());
3193 std::sort(SortedFileDeclIDs.begin(), SortedFileDeclIDs.end(),
3194 llvm::less_first());
3195
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00003196 // Join the vectors of DeclIDs from all files.
Chandler Carruthb306d732015-03-27 00:31:20 +00003197 SmallVector<DeclID, 256> FileGroupedDeclIDs;
3198 for (auto &FileDeclEntry : SortedFileDeclIDs) {
3199 DeclIDInFileInfo &Info = *FileDeclEntry.second;
3200 Info.FirstDeclIndex = FileGroupedDeclIDs.size();
3201 for (auto &LocDeclEntry : Info.DeclIDs)
3202 FileGroupedDeclIDs.push_back(LocDeclEntry.second);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00003203 }
3204
David Blaikieb44f0bf2017-01-04 22:36:43 +00003205 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00003206 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00003207 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00003208 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00003209 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00003210 RecordData::value_type Record[] = {FILE_SORTED_DECLS,
3211 FileGroupedDeclIDs.size()};
Reid Kleckner012665e2015-05-21 00:13:09 +00003212 Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00003213}
3214
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00003215void ASTWriter::WriteComments() {
3216 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +00003217 ArrayRef<RawComment *> RawComments = Context->Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00003218 RecordData Record;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003219 for (const auto *I : RawComments) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00003220 Record.clear();
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003221 AddSourceRange(I->getSourceRange(), Record);
3222 Record.push_back(I->getKind());
3223 Record.push_back(I->isTrailingComment());
3224 Record.push_back(I->isAlmostTrailingComment());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00003225 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
3226 }
3227 Stream.ExitBlock();
3228}
3229
Douglas Gregorc5046832009-04-27 18:38:38 +00003230//===----------------------------------------------------------------------===//
3231// Global Method Pool and Selector Serialization
3232//===----------------------------------------------------------------------===//
3233
Douglas Gregore84a9da2009-04-20 20:36:09 +00003234namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003235
Douglas Gregorc78d3462009-04-24 21:10:55 +00003236// Trait used for the on-disk hash table used in the method pool.
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003237class ASTMethodPoolTrait {
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003238 ASTWriter &Writer;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003239
3240public:
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003241 using key_type = Selector;
3242 using key_type_ref = key_type;
Mike Stump11289f42009-09-09 15:08:12 +00003243
Sebastian Redl834bb972010-08-04 17:20:04 +00003244 struct data_type {
Sebastian Redl539c5062010-08-18 23:57:32 +00003245 SelectorID ID;
Sebastian Redl834bb972010-08-04 17:20:04 +00003246 ObjCMethodList Instance, Factory;
3247 };
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003248 using data_type_ref = const data_type &;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003249
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003250 using hash_value_type = unsigned;
3251 using offset_type = unsigned;
Justin Bogner25463f12014-04-18 20:27:24 +00003252
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003253 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) {}
Mike Stump11289f42009-09-09 15:08:12 +00003254
Justin Bogner25463f12014-04-18 20:27:24 +00003255 static hash_value_type ComputeHash(Selector Sel) {
Argyrios Kyrtzidis4bd97102010-08-20 16:03:52 +00003256 return serialization::ComputeHash(Sel);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003257 }
Mike Stump11289f42009-09-09 15:08:12 +00003258
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003259 std::pair<unsigned, unsigned>
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003260 EmitKeyDataLength(raw_ostream& Out, Selector Sel,
Douglas Gregorc78d3462009-04-24 21:10:55 +00003261 data_type_ref Methods) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003262 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003263
Justin Bognere1c147c2014-03-28 22:03:19 +00003264 endian::Writer<little> LE(Out);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003265 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
Justin Bognere1c147c2014-03-28 22:03:19 +00003266 LE.write<uint16_t>(KeyLen);
Sebastian Redl834bb972010-08-04 17:20:04 +00003267 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
3268 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003269 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003270 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00003271 DataLen += 4;
Sebastian Redl834bb972010-08-04 17:20:04 +00003272 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003273 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003274 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00003275 DataLen += 4;
Justin Bognere1c147c2014-03-28 22:03:19 +00003276 LE.write<uint16_t>(DataLen);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003277 return std::make_pair(KeyLen, DataLen);
3278 }
Mike Stump11289f42009-09-09 15:08:12 +00003279
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003280 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003281 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003282
Justin Bognere1c147c2014-03-28 22:03:19 +00003283 endian::Writer<little> LE(Out);
Mike Stump11289f42009-09-09 15:08:12 +00003284 uint64_t Start = Out.tell();
Douglas Gregor95c13f52009-04-25 17:48:32 +00003285 assert((Start >> 32) == 0 && "Selector key offset too large");
3286 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003287 unsigned N = Sel.getNumArgs();
Justin Bognere1c147c2014-03-28 22:03:19 +00003288 LE.write<uint16_t>(N);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003289 if (N == 0)
3290 N = 1;
3291 for (unsigned I = 0; I != N; ++I)
Justin Bognere1c147c2014-03-28 22:03:19 +00003292 LE.write<uint32_t>(
3293 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003294 }
Mike Stump11289f42009-09-09 15:08:12 +00003295
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003296 void EmitData(raw_ostream& Out, key_type_ref,
Douglas Gregor4647cfa2009-04-24 21:49:02 +00003297 data_type_ref Methods, unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003298 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003299
Justin Bognere1c147c2014-03-28 22:03:19 +00003300 endian::Writer<little> LE(Out);
Douglas Gregor4647cfa2009-04-24 21:49:02 +00003301 uint64_t Start = Out.tell(); (void)Start;
Justin Bognere1c147c2014-03-28 22:03:19 +00003302 LE.write<uint32_t>(Methods.ID);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003303 unsigned NumInstanceMethods = 0;
Sebastian Redl834bb972010-08-04 17:20:04 +00003304 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003305 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003306 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00003307 ++NumInstanceMethods;
3308
3309 unsigned NumFactoryMethods = 0;
Sebastian Redl834bb972010-08-04 17:20:04 +00003310 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003311 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003312 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00003313 ++NumFactoryMethods;
3314
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003315 unsigned InstanceBits = Methods.Instance.getBits();
3316 assert(InstanceBits < 4);
Nico Weberff4b35e2014-12-27 22:14:15 +00003317 unsigned InstanceHasMoreThanOneDeclBit =
3318 Methods.Instance.hasMoreThanOneDecl();
3319 unsigned FullInstanceBits = (NumInstanceMethods << 3) |
3320 (InstanceHasMoreThanOneDeclBit << 2) |
3321 InstanceBits;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003322 unsigned FactoryBits = Methods.Factory.getBits();
3323 assert(FactoryBits < 4);
Nico Weberff4b35e2014-12-27 22:14:15 +00003324 unsigned FactoryHasMoreThanOneDeclBit =
3325 Methods.Factory.hasMoreThanOneDecl();
3326 unsigned FullFactoryBits = (NumFactoryMethods << 3) |
3327 (FactoryHasMoreThanOneDeclBit << 2) |
3328 FactoryBits;
3329 LE.write<uint16_t>(FullInstanceBits);
3330 LE.write<uint16_t>(FullFactoryBits);
Sebastian Redl834bb972010-08-04 17:20:04 +00003331 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003332 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003333 if (Method->getMethod())
3334 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
Sebastian Redl834bb972010-08-04 17:20:04 +00003335 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003336 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003337 if (Method->getMethod())
3338 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
Douglas Gregor4647cfa2009-04-24 21:49:02 +00003339
3340 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorc78d3462009-04-24 21:10:55 +00003341 }
3342};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003343
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003344} // namespace
Douglas Gregorc78d3462009-04-24 21:10:55 +00003345
Sebastian Redla19a67f2010-08-03 21:58:15 +00003346/// \brief Write ObjC data: selectors and the method pool.
Douglas Gregorc78d3462009-04-24 21:10:55 +00003347///
3348/// The method pool contains both instance and factory methods, stored
Sebastian Redla19a67f2010-08-03 21:58:15 +00003349/// in an on-disk hash table indexed by the selector. The hash table also
3350/// contains an empty entry for every other selector known to Sema.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003351void ASTWriter::WriteSelectors(Sema &SemaRef) {
Douglas Gregorc78d3462009-04-24 21:10:55 +00003352 using namespace llvm;
3353
Sebastian Redla19a67f2010-08-03 21:58:15 +00003354 // Do we have to do anything at all?
Sebastian Redl834bb972010-08-04 17:20:04 +00003355 if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
Sebastian Redla19a67f2010-08-03 21:58:15 +00003356 return;
Sebastian Redld95a56e2010-08-04 18:21:41 +00003357 unsigned NumTableEntries = 0;
Sebastian Redla19a67f2010-08-03 21:58:15 +00003358 // Create and write out the blob that contains selectors and the method pool.
Douglas Gregorc78d3462009-04-24 21:10:55 +00003359 {
Justin Bognerbb094f02014-04-18 19:57:06 +00003360 llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003361 ASTMethodPoolTrait Trait(*this);
Mike Stump11289f42009-09-09 15:08:12 +00003362
Sebastian Redla19a67f2010-08-03 21:58:15 +00003363 // Create the on-disk hash table representation. We walk through every
3364 // selector we've seen and look it up in the method pool.
Sebastian Redld95a56e2010-08-04 18:21:41 +00003365 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003366 for (auto &SelectorAndID : SelectorIDs) {
3367 Selector S = SelectorAndID.first;
3368 SelectorID ID = SelectorAndID.second;
Sebastian Redla19a67f2010-08-03 21:58:15 +00003369 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003370 ASTMethodPoolTrait::data_type Data = {
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003371 ID,
Sebastian Redl834bb972010-08-04 17:20:04 +00003372 ObjCMethodList(),
3373 ObjCMethodList()
3374 };
3375 if (F != SemaRef.MethodPool.end()) {
3376 Data.Instance = F->second.first;
3377 Data.Factory = F->second.second;
3378 }
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003379 // Only write this selector if it's not in an existing AST or something
Sebastian Redld95a56e2010-08-04 18:21:41 +00003380 // changed.
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003381 if (Chain && ID < FirstSelectorID) {
Sebastian Redld95a56e2010-08-04 18:21:41 +00003382 // Selector already exists. Did it change?
3383 bool changed = false;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003384 for (ObjCMethodList *M = &Data.Instance;
3385 !changed && M && M->getMethod(); M = M->getNext()) {
3386 if (!M->getMethod()->isFromASTFile())
Sebastian Redld95a56e2010-08-04 18:21:41 +00003387 changed = true;
3388 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003389 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003390 M = M->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003391 if (!M->getMethod()->isFromASTFile())
Sebastian Redld95a56e2010-08-04 18:21:41 +00003392 changed = true;
3393 }
3394 if (!changed)
3395 continue;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003396 } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
Sebastian Redl6e1a2a02010-08-04 21:22:45 +00003397 // A new method pool entry.
3398 ++NumTableEntries;
Sebastian Redld95a56e2010-08-04 18:21:41 +00003399 }
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003400 Generator.insert(S, Data, Trait);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003401 }
3402
Douglas Gregorc78d3462009-04-24 21:10:55 +00003403 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003404 SmallString<4096> MethodPool;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003405 uint32_t BucketOffset;
3406 {
Justin Bognere1c147c2014-03-28 22:03:19 +00003407 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003408
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003409 ASTMethodPoolTrait Trait(*this);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003410 llvm::raw_svector_ostream Out(MethodPool);
3411 // Make sure that no bucket is at offset 0
Justin Bognere1c147c2014-03-28 22:03:19 +00003412 endian::Writer<little>(Out).write<uint32_t>(0);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003413 BucketOffset = Generator.Emit(Out, Trait);
3414 }
3415
3416 // Create a blob abbreviation
David Blaikieb44f0bf2017-01-04 22:36:43 +00003417 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00003418 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003419 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor95c13f52009-04-25 17:48:32 +00003420 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003421 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00003422 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003423
Douglas Gregor95c13f52009-04-25 17:48:32 +00003424 // Write the method pool
Mehdi Amini57a41912015-09-10 01:46:39 +00003425 {
3426 RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3427 NumTableEntries};
3428 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3429 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00003430
3431 // Create a blob abbreviation for the selector table offsets.
David Blaikieb44f0bf2017-01-04 22:36:43 +00003432 Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00003433 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
Douglas Gregord4c5ed02010-10-29 22:39:52 +00003434 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
Douglas Gregor8f364fb2011-08-03 23:28:44 +00003435 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
Douglas Gregor95c13f52009-04-25 17:48:32 +00003436 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00003437 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor95c13f52009-04-25 17:48:32 +00003438
3439 // Write the selector offsets table.
Mehdi Amini57a41912015-09-10 01:46:39 +00003440 {
3441 RecordData::value_type Record[] = {
3442 SELECTOR_OFFSETS, SelectorOffsets.size(),
3443 FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3444 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3445 bytes(SelectorOffsets));
3446 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00003447 }
3448}
3449
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003450/// \brief Write the selectors referenced in @selector expression into AST file.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003451void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003452 using namespace llvm;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003453
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003454 if (SemaRef.ReferencedSelectors.empty())
3455 return;
Sebastian Redlada023c2010-08-04 20:40:17 +00003456
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003457 RecordData Record;
Richard Smithe64e7452016-04-18 21:54:58 +00003458 ASTRecordWriter Writer(*this, Record);
Sebastian Redlada023c2010-08-04 20:40:17 +00003459
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003460 // Note: this writes out all references even for a dependent AST. But it is
Sebastian Redl51c79d82010-08-04 22:21:29 +00003461 // very tricky to fix, and given that @selector shouldn't really appear in
3462 // headers, probably not worth it. It's not a correctness issue.
Chandler Carruth12c8f652015-03-27 00:55:05 +00003463 for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
3464 Selector Sel = SelectorAndLocation.first;
3465 SourceLocation Loc = SelectorAndLocation.second;
Richard Smithe64e7452016-04-18 21:54:58 +00003466 Writer.AddSelectorRef(Sel);
3467 Writer.AddSourceLocation(Loc);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003468 }
Richard Smithe64e7452016-04-18 21:54:58 +00003469 Writer.Emit(REFERENCED_SELECTOR_POOL);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003470}
3471
Douglas Gregorc5046832009-04-27 18:38:38 +00003472//===----------------------------------------------------------------------===//
3473// Identifier Table Serialization
3474//===----------------------------------------------------------------------===//
3475
Richard Smithb3761912015-02-05 23:08:52 +00003476/// Determine the declaration that should be put into the name lookup table to
3477/// represent the given declaration in this module. This is usually D itself,
3478/// but if D was imported and merged into a local declaration, we want the most
3479/// recent local declaration instead. The chosen declaration will be the most
3480/// recent declaration in any module that imports this one.
3481static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
3482 NamedDecl *D) {
3483 if (!LangOpts.Modules || !D->isFromASTFile())
3484 return D;
3485
3486 if (Decl *Redecl = D->getPreviousDecl()) {
3487 // For Redeclarable decls, a prior declaration might be local.
3488 for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
Richard Smithd49941b2016-04-26 23:40:43 +00003489 // If we find a local decl, we're done.
3490 if (!Redecl->isFromASTFile()) {
3491 // Exception: in very rare cases (for injected-class-names), not all
3492 // redeclarations are in the same semantic context. Skip ones in a
3493 // different context. They don't go in this lookup table at all.
3494 if (!Redecl->getDeclContext()->getRedeclContext()->Equals(
3495 D->getDeclContext()->getRedeclContext()))
3496 continue;
Richard Smithb3761912015-02-05 23:08:52 +00003497 return cast<NamedDecl>(Redecl);
Richard Smithd49941b2016-04-26 23:40:43 +00003498 }
3499
Richard Smithfe620d22015-03-05 23:24:12 +00003500 // If we find a decl from a (chained-)PCH stop since we won't find a
Richard Smithb3761912015-02-05 23:08:52 +00003501 // local one.
Richard Smithd49941b2016-04-26 23:40:43 +00003502 if (Redecl->getOwningModuleID() == 0)
Richard Smithb3761912015-02-05 23:08:52 +00003503 break;
3504 }
3505 } else if (Decl *First = D->getCanonicalDecl()) {
3506 // For Mergeable decls, the first decl might be local.
3507 if (!First->isFromASTFile())
3508 return cast<NamedDecl>(First);
3509 }
3510
3511 // All declarations are imported. Our most recent declaration will also be
3512 // the most recent one in anyone who imports us.
3513 return D;
3514}
3515
Douglas Gregorc78d3462009-04-24 21:10:55 +00003516namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003517
Richard Smithcf97cf62015-04-19 01:34:23 +00003518class ASTIdentifierTableTrait {
3519 ASTWriter &Writer;
3520 Preprocessor &PP;
3521 IdentifierResolver &IdResolver;
Richard Smith9c254182015-07-19 21:41:12 +00003522 bool IsModule;
Richard Smitha534a312015-07-21 23:54:07 +00003523 bool NeedDecls;
Richard Smith33e0f7e2015-07-22 02:08:40 +00003524 ASTWriter::RecordData *InterestingIdentifierOffsets;
Richard Smithcf97cf62015-04-19 01:34:23 +00003525
3526 /// \brief Determines whether this is an "interesting" identifier that needs a
3527 /// full IdentifierInfo structure written into the hash table. Notably, this
3528 /// doesn't check whether the name has macros defined; use PublicMacroIterator
3529 /// to check that.
Richard Smith9c254182015-07-19 21:41:12 +00003530 bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
Richard Smithd7329392015-04-21 21:46:32 +00003531 if (MacroOffset ||
3532 II->isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +00003533 (IsModule ? II->hasRevertedBuiltin() : II->getObjCOrBuiltinID()) ||
Richard Smithcf97cf62015-04-19 01:34:23 +00003534 II->hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +00003535 (NeedDecls && II->getFETokenInfo<void>()))
Richard Smithcf97cf62015-04-19 01:34:23 +00003536 return true;
3537
3538 return false;
3539 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003540
Douglas Gregore84a9da2009-04-20 20:36:09 +00003541public:
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003542 using key_type = IdentifierInfo *;
3543 using key_type_ref = key_type;
Mike Stump11289f42009-09-09 15:08:12 +00003544
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003545 using data_type = IdentID;
3546 using data_type_ref = data_type;
Mike Stump11289f42009-09-09 15:08:12 +00003547
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003548 using hash_value_type = unsigned;
3549 using offset_type = unsigned;
Justin Bogner25463f12014-04-18 20:27:24 +00003550
Richard Smithd7329392015-04-21 21:46:32 +00003551 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
Richard Smith33e0f7e2015-07-22 02:08:40 +00003552 IdentifierResolver &IdResolver, bool IsModule,
3553 ASTWriter::RecordData *InterestingIdentifierOffsets)
Richard Smitha534a312015-07-21 23:54:07 +00003554 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
Richard Smith33e0f7e2015-07-22 02:08:40 +00003555 NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3556 InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
Douglas Gregore84a9da2009-04-20 20:36:09 +00003557
Richard Smithd79514e2016-02-05 19:03:40 +00003558 bool needDecls() const { return NeedDecls; }
3559
Justin Bogner25463f12014-04-18 20:27:24 +00003560 static hash_value_type ComputeHash(const IdentifierInfo* II) {
Daniel Dunbarf8502d52009-10-17 23:52:28 +00003561 return llvm::HashString(II->getName());
Douglas Gregore84a9da2009-04-20 20:36:09 +00003562 }
Mike Stump11289f42009-09-09 15:08:12 +00003563
Richard Smith33e0f7e2015-07-22 02:08:40 +00003564 bool isInterestingIdentifier(const IdentifierInfo *II) {
3565 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3566 return isInterestingIdentifier(II, MacroOffset);
3567 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003568
Richard Smith9c254182015-07-19 21:41:12 +00003569 bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) {
3570 return isInterestingIdentifier(II, 0);
3571 }
3572
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003573 std::pair<unsigned, unsigned>
Douglas Gregor935bc7a22011-10-27 09:33:13 +00003574 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003575 unsigned KeyLen = II->getLength() + 1;
Douglas Gregor1d583f22009-04-28 21:18:29 +00003576 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
Richard Smithd7329392015-04-21 21:46:32 +00003577 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3578 if (isInterestingIdentifier(II, MacroOffset)) {
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003579 DataLen += 2; // 2 bytes for builtin ID
3580 DataLen += 2; // 2 bytes for flags
Richard Smithd7329392015-04-21 21:46:32 +00003581 if (MacroOffset)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003582 DataLen += 4; // MacroDirectives offset.
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003583
Richard Smitha534a312015-07-21 23:54:07 +00003584 if (NeedDecls) {
3585 for (IdentifierResolver::iterator D = IdResolver.begin(II),
3586 DEnd = IdResolver.end();
3587 D != DEnd; ++D)
3588 DataLen += 4;
3589 }
Douglas Gregor1d583f22009-04-28 21:18:29 +00003590 }
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003591
Justin Bognere1c147c2014-03-28 22:03:19 +00003592 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003593
Justin Bognere1c147c2014-03-28 22:03:19 +00003594 endian::Writer<little> LE(Out);
3595
Richard Smithdf8a8312015-03-13 04:05:01 +00003596 assert((uint16_t)DataLen == DataLen && (uint16_t)KeyLen == KeyLen);
Justin Bognere1c147c2014-03-28 22:03:19 +00003597 LE.write<uint16_t>(DataLen);
Douglas Gregorab4df582009-04-28 20:01:51 +00003598 // We emit the key length after the data length so that every
3599 // string is preceded by a 16-bit length. This matches the PTH
3600 // format for storing identifiers.
Justin Bognere1c147c2014-03-28 22:03:19 +00003601 LE.write<uint16_t>(KeyLen);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003602 return std::make_pair(KeyLen, DataLen);
3603 }
Mike Stump11289f42009-09-09 15:08:12 +00003604
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003605 void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
Douglas Gregore84a9da2009-04-20 20:36:09 +00003606 unsigned KeyLen) {
3607 // Record the location of the key data. This is used when generating
3608 // the mapping from persistent IDs to strings.
3609 Writer.SetIdentifierOffset(II, Out.tell());
Richard Smith33e0f7e2015-07-22 02:08:40 +00003610
3611 // Emit the offset of the key/data length information to the interesting
3612 // identifiers table if necessary.
3613 if (InterestingIdentifierOffsets && isInterestingIdentifier(II))
3614 InterestingIdentifierOffsets->push_back(Out.tell() - 4);
3615
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003616 Out.write(II->getNameStart(), KeyLen);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003617 }
Mike Stump11289f42009-09-09 15:08:12 +00003618
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00003619 void EmitData(raw_ostream& Out, IdentifierInfo* II,
Sebastian Redl539c5062010-08-18 23:57:32 +00003620 IdentID ID, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003621 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003622
Justin Bognere1c147c2014-03-28 22:03:19 +00003623 endian::Writer<little> LE(Out);
Richard Smithcf97cf62015-04-19 01:34:23 +00003624
Richard Smithd7329392015-04-21 21:46:32 +00003625 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3626 if (!isInterestingIdentifier(II, MacroOffset)) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003627 LE.write<uint32_t>(ID << 1);
Douglas Gregor1d583f22009-04-28 21:18:29 +00003628 return;
3629 }
Douglas Gregorb9256522009-04-28 21:32:13 +00003630
Justin Bognere1c147c2014-03-28 22:03:19 +00003631 LE.write<uint32_t>((ID << 1) | 0x01);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003632 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3633 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
Justin Bognere1c147c2014-03-28 22:03:19 +00003634 LE.write<uint16_t>(Bits);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003635 Bits = 0;
Richard Smithd7329392015-04-21 21:46:32 +00003636 bool HadMacroDefinition = MacroOffset != 0;
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003637 Bits = (Bits << 1) | unsigned(HadMacroDefinition);
Daniel Dunbar91b640a2009-12-18 20:58:47 +00003638 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3639 Bits = (Bits << 1) | unsigned(II->isPoisoned());
Richard Smith9c254182015-07-19 21:41:12 +00003640 Bits = (Bits << 1) | unsigned(II->hasRevertedBuiltin());
Argyrios Kyrtzidis3084a612010-08-11 22:55:12 +00003641 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
Daniel Dunbar91b640a2009-12-18 20:58:47 +00003642 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
Justin Bognere1c147c2014-03-28 22:03:19 +00003643 LE.write<uint16_t>(Bits);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003644
Richard Smithd7329392015-04-21 21:46:32 +00003645 if (HadMacroDefinition)
3646 LE.write<uint32_t>(MacroOffset);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003647
Richard Smitha534a312015-07-21 23:54:07 +00003648 if (NeedDecls) {
3649 // Emit the declaration IDs in reverse order, because the
3650 // IdentifierResolver provides the declarations as they would be
3651 // visible (e.g., the function "stat" would come before the struct
3652 // "stat"), but the ASTReader adds declarations to the end of the list
3653 // (so we need to see the struct "stat" before the function "stat").
3654 // Only emit declarations that aren't from a chained PCH, though.
3655 SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II),
3656 IdResolver.end());
3657 for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(),
3658 DEnd = Decls.rend();
3659 D != DEnd; ++D)
3660 LE.write<uint32_t>(
3661 Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D)));
3662 }
Douglas Gregore84a9da2009-04-20 20:36:09 +00003663 }
3664};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003665
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003666} // namespace
Douglas Gregore84a9da2009-04-20 20:36:09 +00003667
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003668/// \brief Write the identifier table into the AST file.
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003669///
3670/// The identifier table consists of a blob containing string data
3671/// (the actual identifiers themselves) and a separate "offsets" index
3672/// that maps identifier IDs to locations within the blob.
Douglas Gregor935bc7a22011-10-27 09:33:13 +00003673void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3674 IdentifierResolver &IdResolver,
3675 bool IsModule) {
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003676 using namespace llvm;
3677
Richard Smith33e0f7e2015-07-22 02:08:40 +00003678 RecordData InterestingIdents;
3679
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003680 // Create and write out the blob that contains the identifier
3681 // strings.
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003682 {
Justin Bognerbb094f02014-04-18 19:57:06 +00003683 llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
Richard Smith33e0f7e2015-07-22 02:08:40 +00003684 ASTIdentifierTableTrait Trait(
3685 *this, PP, IdResolver, IsModule,
3686 (getLangOpts().CPlusPlus && IsModule) ? &InterestingIdents : nullptr);
Mike Stump11289f42009-09-09 15:08:12 +00003687
Douglas Gregore6648fb2009-04-28 20:33:11 +00003688 // Look for any identifiers that were named while processing the
3689 // headers, but are otherwise not needed. We add these to the hash
3690 // table to enable checking of the predefines buffer in the case
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003691 // where the user adds new macro definitions when building the AST
Douglas Gregore6648fb2009-04-28 20:33:11 +00003692 // file.
Chandler Carruth8440c982015-03-26 23:54:15 +00003693 SmallVector<const IdentifierInfo *, 128> IIs;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003694 for (const auto &ID : PP.getIdentifierTable())
3695 IIs.push_back(ID.second);
Chandler Carruth8440c982015-03-26 23:54:15 +00003696 // Sort the identifiers lexicographically before getting them references so
3697 // that their order is stable.
3698 std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
3699 for (const IdentifierInfo *II : IIs)
Richard Smith9c254182015-07-19 21:41:12 +00003700 if (Trait.isInterestingNonMacroIdentifier(II))
3701 getIdentifierRef(II);
Douglas Gregore6648fb2009-04-28 20:33:11 +00003702
Sebastian Redlff4a2952010-07-23 23:49:55 +00003703 // Create the on-disk hash table representation. We only store offsets
3704 // for identifiers that appear here for the first time.
3705 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
Chandler Carruth885e78c2015-03-24 21:18:10 +00003706 for (auto IdentIDPair : IdentifierIDs) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003707 auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
Chandler Carruth885e78c2015-03-24 21:18:10 +00003708 IdentID ID = IdentIDPair.second;
3709 assert(II && "NULL identifier in identifier table");
Vassil Vassilev262f41e2016-03-30 20:16:03 +00003710 // Write out identifiers if either the ID is local or the identifier has
3711 // changed since it was loaded.
3712 if (ID >= FirstIdentID || !Chain || !II->isFromAST()
3713 || II->hasChangedSinceDeserialization() ||
Richard Smithd79514e2016-02-05 19:03:40 +00003714 (Trait.needDecls() &&
3715 II->hasFETokenInfoChangedSinceDeserialization()))
Chandler Carruth885e78c2015-03-24 21:18:10 +00003716 Generator.insert(II, ID, Trait);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003717 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003718
Douglas Gregore84a9da2009-04-20 20:36:09 +00003719 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003720 SmallString<4096> IdentifierTable;
Douglas Gregora868bbd2009-04-21 22:25:48 +00003721 uint32_t BucketOffset;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003722 {
Justin Bognere1c147c2014-03-28 22:03:19 +00003723 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003724
Douglas Gregore84a9da2009-04-20 20:36:09 +00003725 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003726 // Make sure that no bucket is at offset 0
Justin Bognere1c147c2014-03-28 22:03:19 +00003727 endian::Writer<little>(Out).write<uint32_t>(0);
Douglas Gregora868bbd2009-04-21 22:25:48 +00003728 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003729 }
3730
3731 // Create a blob abbreviation
David Blaikieb44f0bf2017-01-04 22:36:43 +00003732 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00003733 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
Douglas Gregora868bbd2009-04-21 22:25:48 +00003734 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregore84a9da2009-04-20 20:36:09 +00003735 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00003736 unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003737
3738 // Write the identifier table
Mehdi Amini57a41912015-09-10 01:46:39 +00003739 RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
Yaron Keren92e1b622015-03-18 10:17:07 +00003740 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003741 }
3742
3743 // Write the offsets table for identifier IDs.
David Blaikieb44f0bf2017-01-04 22:36:43 +00003744 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00003745 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
Douglas Gregor0e149972009-04-25 19:10:14 +00003746 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
Douglas Gregor1ab036c2011-08-03 21:49:18 +00003747 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
Douglas Gregor0e149972009-04-25 19:10:14 +00003748 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00003749 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor0e149972009-04-25 19:10:14 +00003750
Douglas Gregor8d7edce2013-02-08 21:30:59 +00003751#ifndef NDEBUG
3752 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3753 assert(IdentifierOffsets[I] && "Missing identifier offset?");
3754#endif
Mehdi Amini57a41912015-09-10 01:46:39 +00003755
3756 RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
3757 IdentifierOffsets.size(),
3758 FirstIdentID - NUM_PREDEF_IDENT_IDS};
Douglas Gregor0e149972009-04-25 19:10:14 +00003759 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00003760 bytes(IdentifierOffsets));
Richard Smith33e0f7e2015-07-22 02:08:40 +00003761
3762 // In C++, write the list of interesting identifiers (those that are
3763 // defined as macros, poisoned, or similar unusual things).
3764 if (!InterestingIdents.empty())
3765 Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003766}
3767
Douglas Gregorc5046832009-04-27 18:38:38 +00003768//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003769// DeclContext's Name Lookup Table Serialization
3770//===----------------------------------------------------------------------===//
3771
3772namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003773
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003774// Trait used for the on-disk hash table used in the method pool.
3775class ASTDeclContextNameLookupTrait {
3776 ASTWriter &Writer;
Richard Smithd88a7f12015-09-01 20:35:42 +00003777 llvm::SmallVector<DeclID, 64> DeclIDs;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003778
3779public:
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003780 using key_type = DeclarationNameKey;
3781 using key_type_ref = key_type;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003782
Richard Smithd88a7f12015-09-01 20:35:42 +00003783 /// A start and end index into DeclIDs, representing a sequence of decls.
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003784 using data_type = std::pair<unsigned, unsigned>;
3785 using data_type_ref = const data_type &;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003786
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003787 using hash_value_type = unsigned;
3788 using offset_type = unsigned;
Justin Bogner25463f12014-04-18 20:27:24 +00003789
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003790 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) {}
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003791
Richard Smithd88a7f12015-09-01 20:35:42 +00003792 template<typename Coll>
3793 data_type getData(const Coll &Decls) {
3794 unsigned Start = DeclIDs.size();
3795 for (NamedDecl *D : Decls) {
3796 DeclIDs.push_back(
3797 Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3798 }
3799 return std::make_pair(Start, DeclIDs.size());
3800 }
3801
3802 data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
3803 unsigned Start = DeclIDs.size();
3804 for (auto ID : FromReader)
3805 DeclIDs.push_back(ID);
3806 return std::make_pair(Start, DeclIDs.size());
3807 }
3808
3809 static bool EqualKey(key_type_ref a, key_type_ref b) {
3810 return a == b;
3811 }
3812
Richard Smitha06c7e62015-08-26 23:55:49 +00003813 hash_value_type ComputeHash(DeclarationNameKey Name) {
3814 return Name.getHash();
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003815 }
3816
Richard Smithd88a7f12015-09-01 20:35:42 +00003817 void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
3818 assert(Writer.hasChain() &&
3819 "have reference to loaded module file but no chain?");
3820
3821 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003822
Richard Smithd88a7f12015-09-01 20:35:42 +00003823 endian::Writer<little>(Out)
3824 .write<uint32_t>(Writer.getChain()->getModuleFileID(F));
3825 }
3826
Richard Smitha06c7e62015-08-26 23:55:49 +00003827 std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
3828 DeclarationNameKey Name,
3829 data_type_ref Lookup) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003830 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003831
Justin Bognere1c147c2014-03-28 22:03:19 +00003832 endian::Writer<little> LE(Out);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003833 unsigned KeyLen = 1;
Richard Smitha06c7e62015-08-26 23:55:49 +00003834 switch (Name.getKind()) {
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003835 case DeclarationName::Identifier:
3836 case DeclarationName::ObjCZeroArgSelector:
3837 case DeclarationName::ObjCOneArgSelector:
3838 case DeclarationName::ObjCMultiArgSelector:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003839 case DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00003840 case DeclarationName::CXXDeductionGuideName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003841 KeyLen += 4;
3842 break;
3843 case DeclarationName::CXXOperatorName:
3844 KeyLen += 1;
3845 break;
Douglas Gregor3b65ed02011-08-02 18:32:54 +00003846 case DeclarationName::CXXConstructorName:
3847 case DeclarationName::CXXDestructorName:
3848 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003849 case DeclarationName::CXXUsingDirective:
3850 break;
3851 }
Justin Bognere1c147c2014-03-28 22:03:19 +00003852 LE.write<uint16_t>(KeyLen);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003853
Richard Smithf02662d2015-07-30 03:17:16 +00003854 // 4 bytes for each DeclID.
Richard Smithd88a7f12015-09-01 20:35:42 +00003855 unsigned DataLen = 4 * (Lookup.second - Lookup.first);
3856 assert(uint16_t(DataLen) == DataLen &&
3857 "too many decls for serialized lookup result");
Justin Bognere1c147c2014-03-28 22:03:19 +00003858 LE.write<uint16_t>(DataLen);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003859
3860 return std::make_pair(KeyLen, DataLen);
3861 }
3862
Richard Smitha06c7e62015-08-26 23:55:49 +00003863 void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003864 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003865
Justin Bognere1c147c2014-03-28 22:03:19 +00003866 endian::Writer<little> LE(Out);
Richard Smitha06c7e62015-08-26 23:55:49 +00003867 LE.write<uint8_t>(Name.getKind());
3868 switch (Name.getKind()) {
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003869 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +00003870 case DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00003871 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00003872 LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier()));
Benjamin Kramer53750b12012-09-19 13:40:40 +00003873 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003874 case DeclarationName::ObjCZeroArgSelector:
3875 case DeclarationName::ObjCOneArgSelector:
3876 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00003877 LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
Benjamin Kramer53750b12012-09-19 13:40:40 +00003878 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003879 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00003880 assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
Benjamin Kramer53750b12012-09-19 13:40:40 +00003881 "Invalid operator?");
Richard Smitha06c7e62015-08-26 23:55:49 +00003882 LE.write<uint8_t>(Name.getOperatorKind());
Benjamin Kramer53750b12012-09-19 13:40:40 +00003883 return;
Douglas Gregor3b65ed02011-08-02 18:32:54 +00003884 case DeclarationName::CXXConstructorName:
3885 case DeclarationName::CXXDestructorName:
3886 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003887 case DeclarationName::CXXUsingDirective:
Benjamin Kramer53750b12012-09-19 13:40:40 +00003888 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003889 }
Benjamin Kramer53750b12012-09-19 13:40:40 +00003890
3891 llvm_unreachable("Invalid name kind?");
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003892 }
3893
Richard Smitha06c7e62015-08-26 23:55:49 +00003894 void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
3895 unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003896 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003897
Justin Bognere1c147c2014-03-28 22:03:19 +00003898 endian::Writer<little> LE(Out);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003899 uint64_t Start = Out.tell(); (void)Start;
Richard Smithd88a7f12015-09-01 20:35:42 +00003900 for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
3901 LE.write<uint32_t>(DeclIDs[I]);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003902 assert(Out.tell() - Start == DataLen && "Data length is wrong");
3903 }
3904};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003905
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003906} // namespace
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003907
Chandler Carruthe972c362015-03-26 03:11:40 +00003908bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
3909 DeclContext *DC) {
3910 return Result.hasExternalDecls() && DC->NeedToReconcileExternalVisibleStorage;
3911}
3912
3913bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
3914 DeclContext *DC) {
3915 for (auto *D : Result.getLookupResult())
3916 if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
3917 return false;
3918
3919 return true;
3920}
3921
Richard Smithd88a7f12015-09-01 20:35:42 +00003922void
Chandler Carruthe972c362015-03-26 03:11:40 +00003923ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
Richard Smithcd45dbc2014-04-19 03:48:30 +00003924 llvm::SmallVectorImpl<char> &LookupTable) {
Chandler Carruthe972c362015-03-26 03:11:40 +00003925 assert(!ConstDC->HasLazyLocalLexicalLookups &&
3926 !ConstDC->HasLazyExternalLexicalLookups &&
Richard Smith9e2341d2015-03-23 03:25:59 +00003927 "must call buildLookups first");
Richard Smithcd45dbc2014-04-19 03:48:30 +00003928
Chandler Carruthe972c362015-03-26 03:11:40 +00003929 // FIXME: We need to build the lookups table, which is logically const.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003930 auto *DC = const_cast<DeclContext*>(ConstDC);
Chandler Carruthe972c362015-03-26 03:11:40 +00003931 assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
3932
3933 // Create the on-disk hash table representation.
Richard Smithd88a7f12015-09-01 20:35:42 +00003934 MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait,
3935 ASTDeclContextNameLookupTrait> Generator;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003936 ASTDeclContextNameLookupTrait Trait(*this);
3937
Chandler Carruthe972c362015-03-26 03:11:40 +00003938 // The first step is to collect the declaration names which we need to
3939 // serialize into the name lookup table, and to collect them in a stable
3940 // order.
3941 SmallVector<DeclarationName, 16> Names;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003942
Chandler Carruthe972c362015-03-26 03:11:40 +00003943 // We also build up small sets of the constructor and conversion function
3944 // names which are visible.
3945 llvm::SmallSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003946
Chandler Carruthe972c362015-03-26 03:11:40 +00003947 for (auto &Lookup : *DC->buildLookup()) {
3948 auto &Name = Lookup.first;
3949 auto &Result = Lookup.second;
3950
Douglas Gregor7dd37e52015-11-03 01:20:54 +00003951 // If there are no local declarations in our lookup result, we
3952 // don't need to write an entry for the name at all. If we can't
3953 // write out a lookup set without performing more deserialization,
3954 // just skip this entry.
3955 if (isLookupResultExternal(Result, DC) &&
Chandler Carruthe972c362015-03-26 03:11:40 +00003956 isLookupResultEntirelyExternal(Result, DC))
3957 continue;
3958
3959 // We also skip empty results. If any of the results could be external and
3960 // the currently available results are empty, then all of the results are
3961 // external and we skip it above. So the only way we get here with an empty
3962 // results is when no results could have been external *and* we have
3963 // external results.
3964 //
3965 // FIXME: While we might want to start emitting on-disk entries for negative
3966 // lookups into a decl context as an optimization, today we *have* to skip
3967 // them because there are names with empty lookup results in decl contexts
3968 // which we can't emit in any stable ordering: we lookup constructors and
3969 // conversion functions in the enclosing namespace scope creating empty
3970 // results for them. This in almost certainly a bug in Clang's name lookup,
3971 // but that is likely to be hard or impossible to fix and so we tolerate it
3972 // here by omitting lookups with empty results.
3973 if (Lookup.second.getLookupResult().empty())
3974 continue;
3975
3976 switch (Lookup.first.getNameKind()) {
3977 default:
3978 Names.push_back(Lookup.first);
3979 break;
3980
Richard Smithcd45dbc2014-04-19 03:48:30 +00003981 case DeclarationName::CXXConstructorName:
Chandler Carruthe972c362015-03-26 03:11:40 +00003982 assert(isa<CXXRecordDecl>(DC) &&
3983 "Cannot have a constructor name outside of a class!");
3984 ConstructorNameSet.insert(Name);
3985 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003986
3987 case DeclarationName::CXXConversionFunctionName:
Chandler Carruthe972c362015-03-26 03:11:40 +00003988 assert(isa<CXXRecordDecl>(DC) &&
3989 "Cannot have a conversion function name outside of a class!");
3990 ConversionNameSet.insert(Name);
Rafael Espindolac606b3e2015-03-25 04:43:15 +00003991 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003992 }
Chandler Carruth75c9f132015-03-25 00:34:51 +00003993 }
Chandler Carruth75c9f132015-03-25 00:34:51 +00003994
Chandler Carruthe972c362015-03-26 03:11:40 +00003995 // Sort the names into a stable order.
3996 std::sort(Names.begin(), Names.end());
3997
Chandler Carruthffbf7052015-03-26 22:27:09 +00003998 if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
Chandler Carruthe972c362015-03-26 03:11:40 +00003999 // We need to establish an ordering of constructor and conversion function
Chandler Carruthffbf7052015-03-26 22:27:09 +00004000 // names, and they don't have an intrinsic ordering.
Chandler Carruthe972c362015-03-26 03:11:40 +00004001
Chandler Carruthffbf7052015-03-26 22:27:09 +00004002 // First we try the easy case by forming the current context's constructor
4003 // name and adding that name first. This is a very useful optimization to
4004 // avoid walking the lexical declarations in many cases, and it also
4005 // handles the only case where a constructor name can come from some other
4006 // lexical context -- when that name is an implicit constructor merged from
4007 // another declaration in the redecl chain. Any non-implicit constructor or
4008 // conversion function which doesn't occur in all the lexical contexts
4009 // would be an ODR violation.
4010 auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
4011 Context->getCanonicalType(Context->getRecordType(D)));
4012 if (ConstructorNameSet.erase(ImplicitCtorName))
4013 Names.push_back(ImplicitCtorName);
Chandler Carruthe972c362015-03-26 03:11:40 +00004014
Chandler Carruthffbf7052015-03-26 22:27:09 +00004015 // If we still have constructors or conversion functions, we walk all the
4016 // names in the decl and add the constructors and conversion functions
4017 // which are visible in the order they lexically occur within the context.
4018 if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
4019 for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
4020 if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
4021 auto Name = ChildND->getDeclName();
4022 switch (Name.getNameKind()) {
4023 default:
4024 continue;
4025
4026 case DeclarationName::CXXConstructorName:
4027 if (ConstructorNameSet.erase(Name))
4028 Names.push_back(Name);
4029 break;
4030
4031 case DeclarationName::CXXConversionFunctionName:
4032 if (ConversionNameSet.erase(Name))
4033 Names.push_back(Name);
4034 break;
4035 }
4036
4037 if (ConstructorNameSet.empty() && ConversionNameSet.empty())
4038 break;
Chandler Carruthe972c362015-03-26 03:11:40 +00004039 }
4040
Chandler Carruthe972c362015-03-26 03:11:40 +00004041 assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
4042 "constructors by walking all the "
4043 "lexical members of the context.");
4044 assert(ConversionNameSet.empty() && "Failed to find all of the visible "
4045 "conversion functions by walking all "
4046 "the lexical members of the context.");
Richard Smith961eae52014-03-25 01:14:22 +00004047 }
4048
Chandler Carruthe972c362015-03-26 03:11:40 +00004049 // Next we need to do a lookup with each name into this decl context to fully
4050 // populate any results from external sources. We don't actually use the
4051 // results of these lookups because we only want to use the results after all
4052 // results have been loaded and the pointers into them will be stable.
4053 for (auto &Name : Names)
4054 DC->lookup(Name);
4055
4056 // Now we need to insert the results for each name into the hash table. For
4057 // constructor names and conversion function names, we actually need to merge
4058 // all of the results for them into one list of results each and insert
4059 // those.
4060 SmallVector<NamedDecl *, 8> ConstructorDecls;
4061 SmallVector<NamedDecl *, 8> ConversionDecls;
4062
4063 // Now loop over the names, either inserting them or appending for the two
4064 // special cases.
4065 for (auto &Name : Names) {
4066 DeclContext::lookup_result Result = DC->noload_lookup(Name);
4067
4068 switch (Name.getNameKind()) {
4069 default:
Richard Smithd88a7f12015-09-01 20:35:42 +00004070 Generator.insert(Name, Trait.getData(Result), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00004071 break;
4072
4073 case DeclarationName::CXXConstructorName:
4074 ConstructorDecls.append(Result.begin(), Result.end());
4075 break;
4076
4077 case DeclarationName::CXXConversionFunctionName:
4078 ConversionDecls.append(Result.begin(), Result.end());
4079 break;
4080 }
4081 }
4082
4083 // Handle our two special cases if we ended up having any. We arbitrarily use
4084 // the first declaration's name here because the name itself isn't part of
4085 // the key, only the kind of name is used.
4086 if (!ConstructorDecls.empty())
4087 Generator.insert(ConstructorDecls.front()->getDeclName(),
Richard Smithd88a7f12015-09-01 20:35:42 +00004088 Trait.getData(ConstructorDecls), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00004089 if (!ConversionDecls.empty())
4090 Generator.insert(ConversionDecls.front()->getDeclName(),
Richard Smithd88a7f12015-09-01 20:35:42 +00004091 Trait.getData(ConversionDecls), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00004092
Richard Smithd88a7f12015-09-01 20:35:42 +00004093 // Create the on-disk hash table. Also emit the existing imported and
4094 // merged table if there is one.
4095 auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr;
4096 Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr);
Richard Smith961eae52014-03-25 01:14:22 +00004097}
4098
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00004099/// \brief Write the block containing all of the declaration IDs
4100/// visible from the given DeclContext.
4101///
4102/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
Sebastian Redla4071b42010-08-24 00:50:09 +00004103/// bitstream, or 0 if no block was written.
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00004104uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
4105 DeclContext *DC) {
Richard Smith5fc18a92015-07-12 23:43:21 +00004106 // If we imported a key declaration of this namespace, write the visible
4107 // lookup results as an update record for it rather than including them
4108 // on this declaration. We will only look at key declarations on reload.
4109 if (isa<NamespaceDecl>(DC) && Chain &&
4110 Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) {
4111 // Only do this once, for the first local declaration of the namespace.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004112 for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
Richard Smith5fc18a92015-07-12 23:43:21 +00004113 Prev = Prev->getPreviousDecl())
4114 if (!Prev->isFromASTFile())
4115 return 0;
4116
4117 // Note that we need to emit an update record for the primary context.
4118 UpdatedDeclContexts.insert(DC->getPrimaryContext());
4119
4120 // Make sure all visible decls are written. They will be recorded later. We
4121 // do this using a side data structure so we can sort the names into
4122 // a deterministic order.
4123 StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup();
4124 SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16>
4125 LookupResults;
4126 if (Map) {
4127 LookupResults.reserve(Map->size());
4128 for (auto &Entry : *Map)
4129 LookupResults.push_back(
4130 std::make_pair(Entry.first, Entry.second.getLookupResult()));
4131 }
4132
4133 std::sort(LookupResults.begin(), LookupResults.end(), llvm::less_first());
4134 for (auto &NameAndResult : LookupResults) {
4135 DeclarationName Name = NameAndResult.first;
4136 DeclContext::lookup_result Result = NameAndResult.second;
4137 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
4138 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
4139 // We have to work around a name lookup bug here where negative lookup
4140 // results for these names get cached in namespace lookup tables (these
4141 // names should never be looked up in a namespace).
4142 assert(Result.empty() && "Cannot have a constructor or conversion "
4143 "function name in a namespace!");
4144 continue;
4145 }
4146
4147 for (NamedDecl *ND : Result)
4148 if (!ND->isFromASTFile())
4149 GetDeclRef(ND);
4150 }
4151
4152 return 0;
4153 }
4154
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00004155 if (DC->getPrimaryContext() != DC)
4156 return 0;
4157
Chandler Carruthe972c362015-03-26 03:11:40 +00004158 // Skip contexts which don't support name lookup.
4159 if (!DC->isLookupContext())
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00004160 return 0;
4161
4162 // If not in C++, we perform name lookup for the translation unit via the
4163 // IdentifierInfo chains, don't bother to build a visible-declarations table.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004164 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00004165 return 0;
4166
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00004167 // Serialize the contents of the mapping used for lookup. Note that,
4168 // although we have two very different code paths, the serialized
4169 // representation is the same for both cases: a declaration name,
4170 // followed by a size, followed by references to the visible
4171 // declarations that have that name.
4172 uint64_t Offset = Stream.GetCurrentBitNo();
Richard Smithf634c902012-03-16 06:12:59 +00004173 StoredDeclsMap *Map = DC->buildLookup();
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00004174 if (!Map || Map->empty())
4175 return 0;
4176
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00004177 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004178 SmallString<4096> LookupTable;
Richard Smithd88a7f12015-09-01 20:35:42 +00004179 GenerateNameLookupTable(DC, LookupTable);
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00004180
4181 // Write the lookup table
Mehdi Amini57a41912015-09-10 01:46:39 +00004182 RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00004183 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
Yaron Keren92e1b622015-03-18 10:17:07 +00004184 LookupTable);
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00004185 ++NumVisibleDeclContexts;
4186 return Offset;
4187}
4188
Sebastian Redla4071b42010-08-24 00:50:09 +00004189/// \brief Write an UPDATE_VISIBLE block for the given context.
4190///
4191/// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
4192/// DeclContext in a dependent AST file. As such, they only exist for the TU
Richard Smithf634c902012-03-16 06:12:59 +00004193/// (in C++), for namespaces, and for classes with forward-declared unscoped
4194/// enumeration members (in C++11).
Sebastian Redla4071b42010-08-24 00:50:09 +00004195void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
Richard Smith961eae52014-03-25 01:14:22 +00004196 StoredDeclsMap *Map = DC->getLookupPtr();
Sebastian Redla4071b42010-08-24 00:50:09 +00004197 if (!Map || Map->empty())
4198 return;
4199
Sebastian Redla4071b42010-08-24 00:50:09 +00004200 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004201 SmallString<4096> LookupTable;
Richard Smithd88a7f12015-09-01 20:35:42 +00004202 GenerateNameLookupTable(DC, LookupTable);
Sebastian Redla4071b42010-08-24 00:50:09 +00004203
Richard Smith5fc18a92015-07-12 23:43:21 +00004204 // If we're updating a namespace, select a key declaration as the key for the
4205 // update record; those are the only ones that will be checked on reload.
4206 if (isa<NamespaceDecl>(DC))
4207 DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
4208
Sebastian Redla4071b42010-08-24 00:50:09 +00004209 // Write the lookup table
Mehdi Amini57a41912015-09-10 01:46:39 +00004210 RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))};
Yaron Keren92e1b622015-03-18 10:17:07 +00004211 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
Sebastian Redla4071b42010-08-24 00:50:09 +00004212}
4213
Peter Collingbourne5df20e02011-02-15 19:46:30 +00004214/// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
4215void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
Adam Nemet484aa452017-03-27 19:17:25 +00004216 RecordData::value_type Record[] = {Opts.getInt()};
Peter Collingbourne5df20e02011-02-15 19:46:30 +00004217 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
4218}
4219
4220/// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
4221void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004222 if (!SemaRef.Context.getLangOpts().OpenCL)
Peter Collingbourne5df20e02011-02-15 19:46:30 +00004223 return;
4224
4225 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
4226 RecordData Record;
Yaxun Liu5b746652016-12-18 05:18:55 +00004227 for (const auto &I:Opts.OptMap) {
4228 AddString(I.getKey(), Record);
4229 auto V = I.getValue();
Yaxun Liucc2741c2016-12-18 06:35:06 +00004230 Record.push_back(V.Supported ? 1 : 0);
4231 Record.push_back(V.Enabled ? 1 : 0);
Yaxun Liu5b746652016-12-18 05:18:55 +00004232 Record.push_back(V.Avail);
4233 Record.push_back(V.Core);
4234 }
Peter Collingbourne5df20e02011-02-15 19:46:30 +00004235 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
4236}
4237
Yaxun Liu5b746652016-12-18 05:18:55 +00004238void ASTWriter::WriteOpenCLExtensionTypes(Sema &SemaRef) {
4239 if (!SemaRef.Context.getLangOpts().OpenCL)
4240 return;
4241
4242 RecordData Record;
4243 for (const auto &I : SemaRef.OpenCLTypeExtMap) {
4244 Record.push_back(
4245 static_cast<unsigned>(getTypeID(I.first->getCanonicalTypeInternal())));
4246 Record.push_back(I.second.size());
4247 for (auto Ext : I.second)
4248 AddString(Ext, Record);
4249 }
4250 Stream.EmitRecord(OPENCL_EXTENSION_TYPES, Record);
4251}
4252
4253void ASTWriter::WriteOpenCLExtensionDecls(Sema &SemaRef) {
4254 if (!SemaRef.Context.getLangOpts().OpenCL)
4255 return;
4256
4257 RecordData Record;
4258 for (const auto &I : SemaRef.OpenCLDeclExtMap) {
4259 Record.push_back(getDeclID(I.first));
4260 Record.push_back(static_cast<unsigned>(I.second.size()));
4261 for (auto Ext : I.second)
4262 AddString(Ext, Record);
4263 }
4264 Stream.EmitRecord(OPENCL_EXTENSION_DECLS, Record);
4265}
4266
Justin Lebar67a78a62016-10-08 22:15:58 +00004267void ASTWriter::WriteCUDAPragmas(Sema &SemaRef) {
4268 if (SemaRef.ForceCUDAHostDeviceDepth > 0) {
4269 RecordData::value_type Record[] = {SemaRef.ForceCUDAHostDeviceDepth};
4270 Stream.EmitRecord(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH, Record);
4271 }
4272}
4273
Douglas Gregor404cdde2012-01-27 01:47:08 +00004274void ASTWriter::WriteObjCCategories() {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004275 SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
Douglas Gregor404cdde2012-01-27 01:47:08 +00004276 RecordData Categories;
4277
4278 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
4279 unsigned Size = 0;
4280 unsigned StartIndex = Categories.size();
4281
4282 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
4283
4284 // Allocate space for the size.
4285 Categories.push_back(0);
4286
4287 // Add the categories.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00004288 for (ObjCInterfaceDecl::known_categories_iterator
4289 Cat = Class->known_categories_begin(),
4290 CatEnd = Class->known_categories_end();
4291 Cat != CatEnd; ++Cat, ++Size) {
4292 assert(getDeclID(*Cat) != 0 && "Bogus category");
4293 AddDeclRef(*Cat, Categories);
Douglas Gregor404cdde2012-01-27 01:47:08 +00004294 }
4295
4296 // Update the size.
4297 Categories[StartIndex] = Size;
4298
4299 // Record this interface -> category map.
4300 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
4301 CategoriesMap.push_back(CatInfo);
4302 }
4303
4304 // Sort the categories map by the definition ID, since the reader will be
4305 // performing binary searches on this information.
4306 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
4307
4308 // Emit the categories map.
4309 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004310
David Blaikieb44f0bf2017-01-04 22:36:43 +00004311 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor404cdde2012-01-27 01:47:08 +00004312 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
4313 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
4314 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004315 unsigned AbbrevID = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00004316
4317 RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
4318 Stream.EmitRecordWithBlob(AbbrevID, Record,
4319 reinterpret_cast<char *>(CategoriesMap.data()),
Douglas Gregor404cdde2012-01-27 01:47:08 +00004320 CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
Mehdi Amini57a41912015-09-10 01:46:39 +00004321
Douglas Gregor404cdde2012-01-27 01:47:08 +00004322 // Emit the category lists.
4323 Stream.EmitRecord(OBJC_CATEGORIES, Categories);
4324}
4325
Richard Smithe40f2ba2013-08-07 21:41:30 +00004326void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
4327 Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
4328
4329 if (LPTMap.empty())
4330 return;
4331
4332 RecordData Record;
Justin Lebar28f09c52016-10-10 16:26:08 +00004333 for (auto &LPTMapEntry : LPTMap) {
Chandler Carruth52cee4d2015-03-26 09:08:15 +00004334 const FunctionDecl *FD = LPTMapEntry.first;
Justin Lebar28f09c52016-10-10 16:26:08 +00004335 LateParsedTemplate &LPT = *LPTMapEntry.second;
Chandler Carruth52cee4d2015-03-26 09:08:15 +00004336 AddDeclRef(FD, Record);
Justin Lebar28f09c52016-10-10 16:26:08 +00004337 AddDeclRef(LPT.D, Record);
4338 Record.push_back(LPT.Toks.size());
Richard Smithe40f2ba2013-08-07 21:41:30 +00004339
Justin Lebar28f09c52016-10-10 16:26:08 +00004340 for (const auto &Tok : LPT.Toks) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004341 AddToken(Tok, Record);
Richard Smithe40f2ba2013-08-07 21:41:30 +00004342 }
4343 }
4344 Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
4345}
4346
Dario Domizioli13a0a382014-05-23 12:13:25 +00004347/// \brief Write the state of 'pragma clang optimize' at the end of the module.
4348void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
4349 RecordData Record;
4350 SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
4351 AddSourceLocation(PragmaLoc, Record);
4352 Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
4353}
4354
Nico Weber779355f2016-03-02 23:22:00 +00004355/// \brief Write the state of 'pragma ms_struct' at the end of the module.
4356void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
4357 RecordData Record;
4358 Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF);
4359 Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
4360}
4361
Nico Weber42932312016-03-03 00:17:35 +00004362/// \brief Write the state of 'pragma pointers_to_members' at the end of the
4363//module.
4364void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
4365 RecordData Record;
4366 Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod);
4367 AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record);
4368 Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
4369}
4370
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00004371/// \brief Write the state of 'pragma pack' at the end of the module.
4372void ASTWriter::WritePackPragmaOptions(Sema &SemaRef) {
Duncan P. N. Exon Smith03df14c2017-04-15 00:07:57 +00004373 // Don't serialize pragma pack state for modules, since it should only take
4374 // effect on a per-submodule basis.
4375 if (WritingModule)
4376 return;
4377
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00004378 RecordData Record;
4379 Record.push_back(SemaRef.PackStack.CurrentValue);
4380 AddSourceLocation(SemaRef.PackStack.CurrentPragmaLocation, Record);
4381 Record.push_back(SemaRef.PackStack.Stack.size());
4382 for (const auto &StackEntry : SemaRef.PackStack.Stack) {
4383 Record.push_back(StackEntry.Value);
4384 AddSourceLocation(StackEntry.PragmaLocation, Record);
Alex Lorenz45b40142017-07-28 14:41:21 +00004385 AddSourceLocation(StackEntry.PragmaPushLocation, Record);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00004386 AddString(StackEntry.StackSlotLabel, Record);
4387 }
4388 Stream.EmitRecord(PACK_PRAGMA_OPTIONS, Record);
4389}
4390
Douglas Gregor8f64ca12015-12-08 22:43:32 +00004391void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
4392 ModuleFileExtensionWriter &Writer) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004393 // Enter the extension block.
4394 Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
4395
4396 // Emit the metadata record abbreviation.
David Blaikieb44f0bf2017-01-04 22:36:43 +00004397 auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004398 Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
4399 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4400 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4401 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4402 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4403 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004404 unsigned Abbrev = Stream.EmitAbbrev(std::move(Abv));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004405
4406 // Emit the metadata record.
4407 RecordData Record;
4408 auto Metadata = Writer.getExtension()->getExtensionMetadata();
4409 Record.push_back(EXTENSION_METADATA);
4410 Record.push_back(Metadata.MajorVersion);
4411 Record.push_back(Metadata.MinorVersion);
4412 Record.push_back(Metadata.BlockName.size());
4413 Record.push_back(Metadata.UserInfo.size());
4414 SmallString<64> Buffer;
4415 Buffer += Metadata.BlockName;
4416 Buffer += Metadata.UserInfo;
4417 Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
4418
4419 // Emit the contents of the extension block.
Douglas Gregor8f64ca12015-12-08 22:43:32 +00004420 Writer.writeExtensionContents(SemaRef, Stream);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004421
4422 // Exit the extension block.
4423 Stream.ExitBlock();
4424}
4425
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00004426//===----------------------------------------------------------------------===//
Douglas Gregorc5046832009-04-27 18:38:38 +00004427// General Serialization Routines
4428//===----------------------------------------------------------------------===//
4429
Richard Smith69c82bf2016-04-01 22:52:03 +00004430/// \brief Emit the list of attributes to the specified record.
Richard Smith290d8012016-04-06 17:06:00 +00004431void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) {
4432 auto &Record = *this;
Argyrios Kyrtzidis9beef8e2010-10-18 19:20:11 +00004433 Record.push_back(Attrs.size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004434 for (const auto *A : Attrs) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00004435 Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
Richard Smith290d8012016-04-06 17:06:00 +00004436 Record.AddSourceRange(A->getRange());
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00004437
Alexis Huntdcfba7b2010-08-18 23:23:40 +00004438#include "clang/Serialization/AttrPCHWrite.inc"
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00004439 }
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00004440}
4441
John McCallf413f5e2013-05-03 00:10:13 +00004442void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
4443 AddSourceLocation(Tok.getLocation(), Record);
4444 Record.push_back(Tok.getLength());
4445
4446 // FIXME: When reading literal tokens, reconstruct the literal pointer
4447 // if it is needed.
4448 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
4449 // FIXME: Should translate token kind to a stable encoding.
4450 Record.push_back(Tok.getKind());
4451 // FIXME: Should translate token flags to a stable encoding.
4452 Record.push_back(Tok.getFlags());
4453}
4454
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004455void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00004456 Record.push_back(Str.size());
4457 Record.insert(Record.end(), Str.begin(), Str.end());
4458}
4459
Richard Smith7ed1bc92014-12-05 22:42:13 +00004460bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
Richard Smith54cc3c22014-12-11 20:50:24 +00004461 assert(Context && "should have context when outputting path");
Richard Smith7ed1bc92014-12-05 22:42:13 +00004462
Richard Smith54cc3c22014-12-11 20:50:24 +00004463 bool Changed =
4464 cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004465
4466 // Remove a prefix to make the path relative, if relevant.
4467 const char *PathBegin = Path.data();
4468 const char *PathPtr =
4469 adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
4470 if (PathPtr != PathBegin) {
4471 Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
4472 Changed = true;
4473 }
4474
4475 return Changed;
4476}
4477
4478void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
4479 SmallString<128> FilePath(Path);
4480 PreparePathForOutput(FilePath);
4481 AddString(FilePath, Record);
4482}
4483
Mehdi Amini57a41912015-09-10 01:46:39 +00004484void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
Richard Smith7ed1bc92014-12-05 22:42:13 +00004485 StringRef Path) {
4486 SmallString<128> FilePath(Path);
4487 PreparePathForOutput(FilePath);
4488 Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
4489}
4490
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004491void ASTWriter::AddVersionTuple(const VersionTuple &Version,
4492 RecordDataImpl &Record) {
4493 Record.push_back(Version.getMajor());
David Blaikie05785d12013-02-20 22:23:23 +00004494 if (Optional<unsigned> Minor = Version.getMinor())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004495 Record.push_back(*Minor + 1);
4496 else
4497 Record.push_back(0);
David Blaikie05785d12013-02-20 22:23:23 +00004498 if (Optional<unsigned> Subminor = Version.getSubminor())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004499 Record.push_back(*Subminor + 1);
4500 else
4501 Record.push_back(0);
4502}
4503
Douglas Gregore84a9da2009-04-20 20:36:09 +00004504/// \brief Note that the identifier II occurs at the given offset
4505/// within the identifier table.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004506void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Sebastian Redl539c5062010-08-18 23:57:32 +00004507 IdentID ID = IdentifierIDs[II];
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00004508 // Only store offsets new to this AST file. Other identifier names are looked
Sebastian Redlff4a2952010-07-23 23:49:55 +00004509 // up earlier in the chain and thus don't need an offset.
4510 if (ID >= FirstIdentID)
4511 IdentifierOffsets[ID - FirstIdentID] = Offset;
Douglas Gregore84a9da2009-04-20 20:36:09 +00004512}
4513
Douglas Gregor95c13f52009-04-25 17:48:32 +00004514/// \brief Note that the selector Sel occurs at the given offset
4515/// within the method pool/selector table.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004516void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
Douglas Gregor95c13f52009-04-25 17:48:32 +00004517 unsigned ID = SelectorIDs[Sel];
4518 assert(ID && "Unknown selector");
Sebastian Redld95a56e2010-08-04 18:21:41 +00004519 // Don't record offsets for selectors that are also available in a different
4520 // file.
4521 if (ID < FirstSelectorID)
4522 return;
4523 SelectorOffsets[ID - FirstSelectorID] = Offset;
Douglas Gregor95c13f52009-04-25 17:48:32 +00004524}
4525
David Blaikie61137e12017-01-05 18:23:18 +00004526ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream,
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004527 SmallVectorImpl<char> &Buffer, MemoryBufferCache &PCMCache,
David Blaikie61137e12017-01-05 18:23:18 +00004528 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
4529 bool IncludeTimestamps)
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004530 : Stream(Stream), Buffer(Buffer), PCMCache(PCMCache),
4531 IncludeTimestamps(IncludeTimestamps) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004532 for (const auto &Ext : Extensions) {
4533 if (auto Writer = Ext->createExtensionWriter(*this))
4534 ModuleFileExtensionWriters.push_back(std::move(Writer));
4535 }
4536}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004537
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004538ASTWriter::~ASTWriter() {
Reid Kleckner588c9372014-02-19 23:44:52 +00004539 llvm::DeleteContainerSeconds(FileDeclIDs);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004540}
4541
Richard Smithb3761912015-02-05 23:08:52 +00004542const LangOptions &ASTWriter::getLangOpts() const {
4543 assert(WritingAST && "can't determine lang opts when not writing AST");
4544 return Context->getLangOpts();
4545}
4546
Richard Smithe75ee0f2015-08-17 07:13:32 +00004547time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const {
4548 return IncludeTimestamps ? E->getModificationTime() : 0;
4549}
4550
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004551ASTFileSignature ASTWriter::WriteAST(Sema &SemaRef,
4552 const std::string &OutputFile,
4553 Module *WritingModule, StringRef isysroot,
4554 bool hasErrors) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00004555 WritingAST = true;
Adrian Prantladbd2b12015-09-22 23:26:31 +00004556
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00004557 ASTHasCompilerErrors = hasErrors;
4558
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004559 // Emit the file header.
Douglas Gregor8f45df52009-04-16 22:23:12 +00004560 Stream.Emit((unsigned)'C', 8);
4561 Stream.Emit((unsigned)'P', 8);
4562 Stream.Emit((unsigned)'C', 8);
4563 Stream.Emit((unsigned)'H', 8);
Mike Stump11289f42009-09-09 15:08:12 +00004564
Chris Lattner28fa4e62009-04-26 22:26:21 +00004565 WriteBlockInfoBlock();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004566
Douglas Gregoreda8e122011-08-09 15:13:55 +00004567 Context = &SemaRef.Context;
Douglas Gregora28bcdd2011-12-01 02:07:58 +00004568 PP = &SemaRef.PP;
Douglas Gregora89c5ac2011-12-06 01:10:29 +00004569 this->WritingModule = WritingModule;
Adrian Prantladbd2b12015-09-22 23:26:31 +00004570 ASTFileSignature Signature =
4571 WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
Craig Toppera13603a2014-05-22 05:54:18 +00004572 Context = nullptr;
4573 PP = nullptr;
4574 this->WritingModule = nullptr;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004575 this->BaseDirectory.clear();
Craig Toppera13603a2014-05-22 05:54:18 +00004576
Douglas Gregor2fd3d402011-09-17 00:05:03 +00004577 WritingAST = false;
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004578 if (SemaRef.Context.getLangOpts().ImplicitModules && WritingModule) {
4579 // Construct MemoryBuffer and update buffer manager.
4580 PCMCache.addBuffer(OutputFile,
4581 llvm::MemoryBuffer::getMemBufferCopy(
4582 StringRef(Buffer.begin(), Buffer.size())));
4583 }
Adrian Prantladbd2b12015-09-22 23:26:31 +00004584 return Signature;
Sebastian Redl143413f2010-07-12 22:02:52 +00004585}
4586
Douglas Gregora94a1542011-07-27 21:45:57 +00004587template<typename Vector>
4588static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4589 ASTWriter::RecordData &Record) {
Craig Toppera13603a2014-05-22 05:54:18 +00004590 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4591 I != E; ++I) {
Douglas Gregora94a1542011-07-27 21:45:57 +00004592 Writer.AddDeclRef(*I, Record);
4593 }
4594}
4595
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004596ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
4597 const std::string &OutputFile,
4598 Module *WritingModule) {
Sebastian Redl143413f2010-07-12 22:02:52 +00004599 using namespace llvm;
4600
Craig Toppera13603a2014-05-22 05:54:18 +00004601 bool isModule = WritingModule != nullptr;
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004602
Douglas Gregorcf68c582011-12-01 22:20:10 +00004603 // Make sure that the AST reader knows to finalize itself.
4604 if (Chain)
4605 Chain->finalizeForWriting();
4606
Sebastian Redl143413f2010-07-12 22:02:52 +00004607 ASTContext &Context = SemaRef.Context;
4608 Preprocessor &PP = SemaRef.PP;
4609
Douglas Gregordab42432011-08-12 00:15:20 +00004610 // Set up predefined declaration IDs.
Richard Smith5fc18a92015-07-12 23:43:21 +00004611 auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
4612 if (D) {
4613 assert(D->isCanonicalDecl() && "predefined decl is not canonical");
4614 DeclIDs[D] = ID;
Richard Smith5fc18a92015-07-12 23:43:21 +00004615 }
4616 };
4617 RegisterPredefDecl(Context.getTranslationUnitDecl(),
4618 PREDEF_DECL_TRANSLATION_UNIT_ID);
4619 RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
4620 RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
4621 RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
4622 RegisterPredefDecl(Context.ObjCProtocolClassDecl,
4623 PREDEF_DECL_OBJC_PROTOCOL_ID);
4624 RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
4625 RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
4626 RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
4627 PREDEF_DECL_OBJC_INSTANCETYPE_ID);
4628 RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
Richard Smith9b88a4c2015-07-27 05:40:23 +00004629 RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
Charles Davisc7d5c942015-09-17 20:55:33 +00004630 RegisterPredefDecl(Context.BuiltinMSVaListDecl,
4631 PREDEF_DECL_BUILTIN_MS_VA_LIST_ID);
Richard Smith5fc18a92015-07-12 23:43:21 +00004632 RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
David Majnemerd9b1a4f2015-11-04 03:40:30 +00004633 RegisterPredefDecl(Context.MakeIntegerSeqDecl,
4634 PREDEF_DECL_MAKE_INTEGER_SEQ_ID);
Quentin Colombet043406b2016-02-03 22:41:00 +00004635 RegisterPredefDecl(Context.CFConstantStringTypeDecl,
4636 PREDEF_DECL_CF_CONSTANT_STRING_ID);
Ben Langmuirf5416742016-02-04 00:55:24 +00004637 RegisterPredefDecl(Context.CFConstantStringTagDecl,
4638 PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID);
Eric Fiselier6ad68552016-07-01 01:24:09 +00004639 RegisterPredefDecl(Context.TypePackElementDecl,
4640 PREDEF_DECL_TYPE_PACK_ELEMENT_ID);
Meador Inge5d3fb222012-06-16 03:34:49 +00004641
Chris Lattner0c797362009-09-08 18:19:27 +00004642 // Build a record containing all of the tentative definitions in this file, in
Sebastian Redl35351a92010-01-31 22:27:38 +00004643 // TentativeDefinitions order. Generally, this record will be empty for
Chris Lattner0c797362009-09-08 18:19:27 +00004644 // headers.
Douglas Gregord4df8652009-04-22 22:02:47 +00004645 RecordData TentativeDefinitions;
Douglas Gregora94a1542011-07-27 21:45:57 +00004646 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
Douglas Gregoreb08bd42011-07-27 20:58:46 +00004647
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00004648 // Build a record containing all of the file scoped decls in this file.
4649 RecordData UnusedFileScopedDecls;
Argyrios Kyrtzidis59852362013-03-14 04:45:00 +00004650 if (!isModule)
4651 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
4652 UnusedFileScopedDecls);
Sebastian Redl08aca90252010-08-05 18:21:25 +00004653
Douglas Gregor851443c2011-08-12 01:39:19 +00004654 // Build a record containing all of the delegating constructors we still need
4655 // to resolve.
Alexis Hunt27a761d2011-05-04 23:29:54 +00004656 RecordData DelegatingCtorDecls;
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004657 if (!isModule)
4658 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
Alexis Hunt27a761d2011-05-04 23:29:54 +00004659
Douglas Gregor851443c2011-08-12 01:39:19 +00004660 // Write the set of weak, undeclared identifiers. We always write the
4661 // entire table, since later PCH files in a PCH chain are only interested in
4662 // the results at the end of the chain.
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004663 RecordData WeakUndeclaredIdentifiers;
Chandler Carruthf85d9822015-03-26 08:32:49 +00004664 for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) {
4665 IdentifierInfo *II = WeakUndeclaredIdentifier.first;
4666 WeakInfo &WI = WeakUndeclaredIdentifier.second;
4667 AddIdentifierRef(II, WeakUndeclaredIdentifiers);
4668 AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
4669 AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
4670 WeakUndeclaredIdentifiers.push_back(WI.getUsed());
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004671 }
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00004672
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004673 // Build a record containing all of the ext_vector declarations.
4674 RecordData ExtVectorDecls;
Douglas Gregorb7098a32011-07-28 00:39:29 +00004675 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004676
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004677 // Build a record containing all of the VTable uses information.
4678 RecordData VTableUses;
Argyrios Kyrtzidisedee67f2010-08-03 17:29:52 +00004679 if (!SemaRef.VTableUses.empty()) {
Argyrios Kyrtzidisedee67f2010-08-03 17:29:52 +00004680 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4681 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4682 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4683 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4684 }
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004685 }
4686
Nico Weber72889432014-09-06 01:25:55 +00004687 // Build a record containing all of the UnusedLocalTypedefNameCandidates.
4688 RecordData UnusedLocalTypedefNameCandidates;
4689 for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4690 AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
4691
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004692 // Build a record containing all of pending implicit instantiations.
Chandler Carruth54080172010-08-25 08:44:16 +00004693 RecordData PendingInstantiations;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004694 for (const auto &I : SemaRef.PendingInstantiations) {
4695 AddDeclRef(I.first, PendingInstantiations);
4696 AddSourceLocation(I.second, PendingInstantiations);
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004697 }
4698 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4699 "There are local ones at end of translation unit!");
4700
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004701 // Build a record containing some declaration references.
4702 RecordData SemaDeclRefs;
Richard Smith96269c52016-09-29 22:49:46 +00004703 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) {
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004704 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4705 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
Richard Smith96269c52016-09-29 22:49:46 +00004706 AddDeclRef(SemaRef.getStdAlignValT(), SemaDeclRefs);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004707 }
4708
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004709 RecordData CUDASpecialDeclRefs;
4710 if (Context.getcudaConfigureCallDecl()) {
4711 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4712 }
4713
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004714 // Build a record containing all of the known namespaces.
4715 RecordData KnownNamespaces;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004716 for (const auto &I : SemaRef.KnownNamespaces) {
4717 if (!I.second)
4718 AddDeclRef(I.first, KnownNamespaces);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004719 }
Douglas Gregor112b9072012-10-18 05:31:06 +00004720
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004721 // Build a record of all used, undefined objects that require definitions.
4722 RecordData UndefinedButUsed;
Nick Lewyckyf0f56162013-01-31 03:23:57 +00004723
4724 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004725 SemaRef.getUndefinedButUsed(Undefined);
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004726 for (const auto &I : Undefined) {
4727 AddDeclRef(I.first, UndefinedButUsed);
4728 AddSourceLocation(I.second, UndefinedButUsed);
Nick Lewycky8334af82013-01-26 00:35:08 +00004729 }
4730
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00004731 // Build a record containing all delete-expressions that we would like to
4732 // analyze later in AST.
4733 RecordData DeleteExprsToAnalyze;
4734
4735 for (const auto &DeleteExprsInfo :
4736 SemaRef.getMismatchingDeleteExpressions()) {
4737 AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
4738 DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
4739 for (const auto &DeleteLoc : DeleteExprsInfo.second) {
4740 AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
4741 DeleteExprsToAnalyze.push_back(DeleteLoc.second);
4742 }
4743 }
4744
Douglas Gregor112b9072012-10-18 05:31:06 +00004745 // Write the control block
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004746 WriteControlBlock(PP, Context, isysroot, OutputFile);
Douglas Gregor112b9072012-10-18 05:31:06 +00004747
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00004748 // Write the remaining AST contents.
Sebastian Redl539c5062010-08-18 23:57:32 +00004749 Stream.EnterSubblock(AST_BLOCK_ID, 5);
Douglas Gregor851443c2011-08-12 01:39:19 +00004750
Argyrios Kyrtzidis39605402012-12-13 21:38:23 +00004751 // This is so that older clang versions, before the introduction
4752 // of the control block, can read and reject the newer PCH format.
Mehdi Amini57a41912015-09-10 01:46:39 +00004753 {
4754 RecordData Record = {VERSION_MAJOR};
4755 Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4756 }
Argyrios Kyrtzidis39605402012-12-13 21:38:23 +00004757
Douglas Gregor851443c2011-08-12 01:39:19 +00004758 // Create a lexical update block containing all of the declarations in the
4759 // translation unit that do not come from other AST files.
4760 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00004761 SmallVector<uint32_t, 128> NewGlobalKindDeclPairs;
4762 for (const auto *D : TU->noload_decls()) {
4763 if (!D->isFromASTFile()) {
4764 NewGlobalKindDeclPairs.push_back(D->getKind());
4765 NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
4766 }
Douglas Gregor851443c2011-08-12 01:39:19 +00004767 }
4768
David Blaikieb44f0bf2017-01-04 22:36:43 +00004769 auto Abv = std::make_shared<BitCodeAbbrev>();
Douglas Gregor851443c2011-08-12 01:39:19 +00004770 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4771 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004772 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv));
Mehdi Amini57a41912015-09-10 01:46:39 +00004773 {
4774 RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
4775 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4776 bytes(NewGlobalKindDeclPairs));
4777 }
4778
Douglas Gregor851443c2011-08-12 01:39:19 +00004779 // And a visible updates block for the translation unit.
David Blaikieb44f0bf2017-01-04 22:36:43 +00004780 Abv = std::make_shared<BitCodeAbbrev>();
Douglas Gregor851443c2011-08-12 01:39:19 +00004781 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4782 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
Douglas Gregor851443c2011-08-12 01:39:19 +00004783 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004784 UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv));
Douglas Gregor851443c2011-08-12 01:39:19 +00004785 WriteDeclContextVisibleUpdate(TU);
Richard Smithf19e1272015-03-07 00:04:49 +00004786
4787 // If we have any extern "C" names, write out a visible update for them.
4788 if (Context.ExternCContext)
4789 WriteDeclContextVisibleUpdate(Context.ExternCContext);
Douglas Gregor851443c2011-08-12 01:39:19 +00004790
4791 // If the translation unit has an anonymous namespace, and we don't already
4792 // have an update block for it, write it as an update block.
Richard Smith6ef42932014-03-20 21:02:00 +00004793 // FIXME: Why do we not do this if there's already an update block?
Douglas Gregor851443c2011-08-12 01:39:19 +00004794 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4795 ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
Richard Smith6ef42932014-03-20 21:02:00 +00004796 if (Record.empty())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004797 Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
Douglas Gregor851443c2011-08-12 01:39:19 +00004798 }
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004799
Richard Smith5652c0f2014-03-21 01:48:23 +00004800 // Add update records for all mangling numbers and static local numbers.
4801 // These aren't really update records, but this is a convenient way of
4802 // tagging this rare extra data onto the declarations.
4803 for (const auto &Number : Context.MangleNumbers)
4804 if (!Number.first->isFromASTFile())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004805 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4806 Number.second));
Richard Smith5652c0f2014-03-21 01:48:23 +00004807 for (const auto &Number : Context.StaticLocalNumbers)
4808 if (!Number.first->isFromASTFile())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004809 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4810 Number.second));
Richard Smith5652c0f2014-03-21 01:48:23 +00004811
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004812 // Make sure visible decls, added to DeclContexts previously loaded from
Richard Smithc26d9742016-10-06 20:30:51 +00004813 // an AST file, are registered for serialization. Likewise for template
4814 // specializations added to imported templates.
4815 for (const auto *I : DeclsToEmitEvenIfUnreferenced) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004816 GetDeclRef(I);
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004817 }
4818
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +00004819 // Make sure all decls associated with an identifier are registered for
Richard Smith79bf9202015-08-24 03:33:22 +00004820 // serialization, if we're storing decls with identifiers.
4821 if (!WritingModule || !getLangOpts().CPlusPlus) {
4822 llvm::SmallVector<const IdentifierInfo*, 256> IIs;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004823 for (const auto &ID : PP.getIdentifierTable()) {
4824 const IdentifierInfo *II = ID.second;
Richard Smith79bf9202015-08-24 03:33:22 +00004825 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
4826 IIs.push_back(II);
4827 }
4828 // Sort the identifiers to visit based on their name.
4829 std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
4830 for (const IdentifierInfo *II : IIs) {
4831 for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4832 DEnd = SemaRef.IdResolver.end();
4833 D != DEnd; ++D) {
4834 GetDeclRef(*D);
4835 }
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +00004836 }
4837 }
4838
Manman Rena0f31a02016-04-29 19:04:05 +00004839 // For method pool in the module, if it contains an entry for a selector,
4840 // the entry should be complete, containing everything introduced by that
4841 // module and all modules it imports. It's possible that the entry is out of
4842 // date, so we need to pull in the new content here.
4843
4844 // It's possible that updateOutOfDateSelector can update SelectorIDs. To be
4845 // safe, we copy all selectors out.
4846 llvm::SmallVector<Selector, 256> AllSelectors;
4847 for (auto &SelectorAndID : SelectorIDs)
4848 AllSelectors.push_back(SelectorAndID.first);
4849 for (auto &Selector : AllSelectors)
4850 SemaRef.updateOutOfDateSelector(Selector);
4851
Douglas Gregor5204bde2011-08-02 16:26:37 +00004852 // Form the record of special types.
4853 RecordData SpecialTypes;
Douglas Gregor5204bde2011-08-02 16:26:37 +00004854 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
Douglas Gregor5204bde2011-08-02 16:26:37 +00004855 AddTypeRef(Context.getFILEType(), SpecialTypes);
4856 AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4857 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4858 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4859 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
Douglas Gregor5204bde2011-08-02 16:26:37 +00004860 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00004861 AddTypeRef(Context.getucontext_tType(), SpecialTypes);
Douglas Gregora28bcdd2011-12-01 02:07:58 +00004862
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004863 if (Chain) {
4864 // Write the mapping information describing our module dependencies and how
4865 // each of those modules were mapped into our own offset/ID space, so that
4866 // the reader can build the appropriate mapping to its own offset/ID space.
4867 // The map consists solely of a blob with the following format:
Boris Kolpackovd30446f2017-08-31 06:26:43 +00004868 // *(module-kind:i8
4869 // module-name-len:i16 module-name:len*i8
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004870 // source-location-offset:i32
4871 // identifier-id:i32
4872 // preprocessed-entity-id:i32
4873 // macro-definition-id:i32
Douglas Gregor253eefe2011-12-01 00:59:36 +00004874 // submodule-id:i32
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004875 // selector-id:i32
4876 // declaration-id:i32
4877 // c++-base-specifiers-id:i32
4878 // type-id:i32)
4879 //
Boris Kolpackovd30446f2017-08-31 06:26:43 +00004880 // module-kind is the ModuleKind enum value. If it is MK_PrebuiltModule or
4881 // MK_ExplicitModule, then the module-name is the module name. Otherwise,
4882 // it is the module file name.
David Blaikieb44f0bf2017-01-04 22:36:43 +00004883 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004884 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4885 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004886 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004887 SmallString<2048> Buffer;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004888 {
4889 llvm::raw_svector_ostream Out(Buffer);
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00004890 for (ModuleFile &M : Chain->ModuleMgr) {
Justin Bognere1c147c2014-03-28 22:03:19 +00004891 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00004892
Justin Bognere1c147c2014-03-28 22:03:19 +00004893 endian::Writer<little> LE(Out);
Boris Kolpackovd30446f2017-08-31 06:26:43 +00004894 LE.write<uint8_t>(static_cast<uint8_t>(M.Kind));
4895 StringRef Name =
4896 M.Kind == MK_PrebuiltModule || M.Kind == MK_ExplicitModule
4897 ? M.ModuleName
4898 : M.FileName;
4899 LE.write<uint16_t>(Name.size());
4900 Out.write(Name.data(), Name.size());
Ben Langmuirfe971d92014-08-16 04:54:18 +00004901
Ben Langmuir785180e2014-10-20 16:27:30 +00004902 // Note: if a base ID was uint max, it would not be possible to load
4903 // another module after it or have more than one entity inside it.
4904 uint32_t None = std::numeric_limits<uint32_t>::max();
4905
4906 auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) {
4907 assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
4908 if (ShouldWrite)
4909 LE.write<uint32_t>(BaseID);
4910 else
4911 LE.write<uint32_t>(None);
4912 };
4913
Ben Langmuirfe971d92014-08-16 04:54:18 +00004914 // These values should be unique within a chain, since they will be read
4915 // as keys into ContinuousRangeMaps.
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00004916 writeBaseIDOrNone(M.SLocEntryBaseOffset, M.LocalNumSLocEntries);
4917 writeBaseIDOrNone(M.BaseIdentifierID, M.LocalNumIdentifiers);
4918 writeBaseIDOrNone(M.BaseMacroID, M.LocalNumMacros);
4919 writeBaseIDOrNone(M.BasePreprocessedEntityID,
4920 M.NumPreprocessedEntities);
4921 writeBaseIDOrNone(M.BaseSubmoduleID, M.LocalNumSubmodules);
4922 writeBaseIDOrNone(M.BaseSelectorID, M.LocalNumSelectors);
4923 writeBaseIDOrNone(M.BaseDeclID, M.LocalNumDecls);
4924 writeBaseIDOrNone(M.BaseTypeIndex, M.LocalNumTypes);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004925 }
4926 }
Mehdi Amini57a41912015-09-10 01:46:39 +00004927 RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004928 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4929 Buffer.data(), Buffer.size());
4930 }
Richard Smithb9eab6d2014-03-20 19:44:17 +00004931
Richard Smithb9eab6d2014-03-20 19:44:17 +00004932 RecordData DeclUpdatesOffsetsRecord;
4933
Richard Smith59442b42014-03-20 20:07:19 +00004934 // Keep writing types, declarations, and declaration update records
4935 // until we've emitted all of them.
Richard Smith01b2cb42014-07-26 06:37:51 +00004936 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
4937 WriteTypeAbbrevs();
4938 WriteDeclAbbrevs();
Richard Smith59442b42014-03-20 20:07:19 +00004939 do {
4940 WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
4941 while (!DeclTypesToEmit.empty()) {
4942 DeclOrType DOT = DeclTypesToEmit.front();
4943 DeclTypesToEmit.pop();
4944 if (DOT.isType())
4945 WriteType(DOT.getType());
4946 else
4947 WriteDecl(Context, DOT.getDecl());
4948 }
4949 } while (!DeclUpdates.empty());
Richard Smithb9eab6d2014-03-20 19:44:17 +00004950 Stream.ExitBlock();
4951
Richard Smithb9eab6d2014-03-20 19:44:17 +00004952 DoneWritingDeclsAndTypes = true;
4953
4954 // These things can only be done once we've written out decls and types.
4955 WriteTypeDeclOffsets();
Richard Smith5652c0f2014-03-21 01:48:23 +00004956 if (!DeclUpdatesOffsetsRecord.empty())
4957 Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
Richard Smithb9eab6d2014-03-20 19:44:17 +00004958 WriteFileDeclIDsMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00004959 WriteSourceManagerBlock(Context.getSourceManager(), PP);
Richard Smithb9eab6d2014-03-20 19:44:17 +00004960 WriteComments();
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004961 WritePreprocessor(PP, isModule);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004962 WriteHeaderSearch(PP.getHeaderSearchInfo());
Sebastian Redla19a67f2010-08-03 21:58:15 +00004963 WriteSelectors(SemaRef);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00004964 WriteReferencedSelectorsPool(SemaRef);
Richard Smith9c254182015-07-19 21:41:12 +00004965 WriteLateParsedTemplates(SemaRef);
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004966 WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
Peter Collingbourne5df20e02011-02-15 19:46:30 +00004967 WriteFPPragmaOptions(SemaRef.getFPOptions());
4968 WriteOpenCLExtensions(SemaRef);
Yaxun Liu5b746652016-12-18 05:18:55 +00004969 WriteOpenCLExtensionTypes(SemaRef);
4970 WriteOpenCLExtensionDecls(SemaRef);
Justin Lebar67a78a62016-10-08 22:15:58 +00004971 WriteCUDAPragmas(SemaRef);
Douglas Gregor652d82a2009-04-18 05:55:16 +00004972
Douglas Gregora89c5ac2011-12-06 01:10:29 +00004973 // If we're emitting a module, write out the submodule information.
4974 if (WritingModule)
4975 WriteSubmodules(WritingModule);
4976
Douglas Gregor5204bde2011-08-02 16:26:37 +00004977 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
4978
Douglas Gregord4df8652009-04-22 22:02:47 +00004979 // Write the record containing external, unnamed definitions.
Ben Langmuir332aafe2014-01-31 01:06:56 +00004980 if (!EagerlyDeserializedDecls.empty())
4981 Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
Douglas Gregord4df8652009-04-22 22:02:47 +00004982
David Blaikief63556d2017-04-12 20:58:33 +00004983 if (!ModularCodegenDecls.empty())
David Blaikie9ffe5a32017-01-30 05:00:26 +00004984 Stream.EmitRecord(MODULAR_CODEGEN_DECLS, ModularCodegenDecls);
4985
Douglas Gregord4df8652009-04-22 22:02:47 +00004986 // Write the record containing tentative definitions.
4987 if (!TentativeDefinitions.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004988 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregoracfc76c2009-04-22 22:18:58 +00004989
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00004990 // Write the record containing unused file scoped decls.
4991 if (!UnusedFileScopedDecls.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004992 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00004993
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004994 // Write the record containing weak undeclared identifiers.
4995 if (!WeakUndeclaredIdentifiers.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004996 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004997 WeakUndeclaredIdentifiers);
4998
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004999 // Write the record containing ext_vector type names.
5000 if (!ExtVectorDecls.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00005001 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
Mike Stump11289f42009-09-09 15:08:12 +00005002
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00005003 // Write the record containing VTable uses information.
5004 if (!VTableUses.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00005005 Stream.EmitRecord(VTABLE_USES, VTableUses);
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00005006
Nico Weber72889432014-09-06 01:25:55 +00005007 // Write the record containing potentially unused local typedefs.
5008 if (!UnusedLocalTypedefNameCandidates.empty())
5009 Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
5010 UnusedLocalTypedefNameCandidates);
5011
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00005012 // Write the record containing pending implicit instantiations.
Chandler Carruth54080172010-08-25 08:44:16 +00005013 if (!PendingInstantiations.empty())
5014 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00005015
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00005016 // Write the record containing declaration references of Sema.
5017 if (!SemaDeclRefs.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00005018 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00005019
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00005020 // Write the record containing CUDA-specific declaration references.
5021 if (!CUDASpecialDeclRefs.empty())
5022 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
Alexis Hunt27a761d2011-05-04 23:29:54 +00005023
5024 // Write the delegating constructors.
5025 if (!DelegatingCtorDecls.empty())
5026 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00005027
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005028 // Write the known namespaces.
5029 if (!KnownNamespaces.empty())
5030 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
Nick Lewycky8334af82013-01-26 00:35:08 +00005031
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00005032 // Write the undefined internal functions and variables, and inline functions.
5033 if (!UndefinedButUsed.empty())
5034 Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00005035
5036 if (!DeleteExprsToAnalyze.empty())
5037 Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
5038
Douglas Gregor851443c2011-08-12 01:39:19 +00005039 // Write the visible updates to DeclContexts.
Richard Smithcd45dbc2014-04-19 03:48:30 +00005040 for (auto *DC : UpdatedDeclContexts)
5041 WriteDeclContextVisibleUpdate(DC);
Douglas Gregor851443c2011-08-12 01:39:19 +00005042
Douglas Gregor959bb062011-12-03 01:15:29 +00005043 if (!WritingModule) {
5044 // Write the submodules that were imported, if any.
Aaron Ballman4f45b712014-03-21 15:22:56 +00005045 struct ModuleInfo {
5046 uint64_t ID;
5047 Module *M;
5048 ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
5049 };
Richard Smith56be7542014-03-21 00:33:59 +00005050 llvm::SmallVector<ModuleInfo, 64> Imports;
Aaron Ballmanbbc31212014-03-14 20:59:21 +00005051 for (const auto *I : Context.local_imports()) {
Douglas Gregor959bb062011-12-03 01:15:29 +00005052 assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
Aaron Ballman4f45b712014-03-21 15:22:56 +00005053 Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
5054 I->getImportedModule()));
Douglas Gregor959bb062011-12-03 01:15:29 +00005055 }
Richard Smith56be7542014-03-21 00:33:59 +00005056
5057 if (!Imports.empty()) {
5058 auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
5059 return A.ID < B.ID;
5060 };
Ben Langmuir5f95c8f2014-09-08 20:36:26 +00005061 auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
5062 return A.ID == B.ID;
5063 };
Richard Smith56be7542014-03-21 00:33:59 +00005064
5065 // Sort and deduplicate module IDs.
5066 std::sort(Imports.begin(), Imports.end(), Cmp);
Ben Langmuir5f95c8f2014-09-08 20:36:26 +00005067 Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
Richard Smith56be7542014-03-21 00:33:59 +00005068 Imports.end());
5069
5070 RecordData ImportedModules;
5071 for (const auto &Import : Imports) {
5072 ImportedModules.push_back(Import.ID);
5073 // FIXME: If the module has macros imported then later has declarations
5074 // imported, this location won't be the right one as a location for the
5075 // declaration imports.
Richard Smith10434f32015-05-02 02:08:26 +00005076 AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
Richard Smith56be7542014-03-21 00:33:59 +00005077 }
5078
Douglas Gregor959bb062011-12-03 01:15:29 +00005079 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
5080 }
Douglas Gregor0a839132011-12-03 00:59:55 +00005081 }
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005082
Douglas Gregor404cdde2012-01-27 01:47:08 +00005083 WriteObjCCategories();
Nico Weber779355f2016-03-02 23:22:00 +00005084 if(!WritingModule) {
Dario Domizioli13a0a382014-05-23 12:13:25 +00005085 WriteOptimizePragmaOptions(SemaRef);
Nico Weber779355f2016-03-02 23:22:00 +00005086 WriteMSStructPragmaOptions(SemaRef);
Nico Weber42932312016-03-03 00:17:35 +00005087 WriteMSPointersToMembersPragmaOptions(SemaRef);
Nico Weber779355f2016-03-02 23:22:00 +00005088 }
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00005089 WritePackPragmaOptions(SemaRef);
Richard Smithe40f2ba2013-08-07 21:41:30 +00005090
Douglas Gregor08f01292009-04-17 22:13:46 +00005091 // Some simple statistics
Mehdi Amini57a41912015-09-10 01:46:39 +00005092 RecordData::value_type Record[] = {
5093 NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts};
Sebastian Redl539c5062010-08-18 23:57:32 +00005094 Stream.EmitRecord(STATISTICS, Record);
Douglas Gregor8f45df52009-04-16 22:23:12 +00005095 Stream.ExitBlock();
Adrian Prantladbd2b12015-09-22 23:26:31 +00005096
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005097 // Write the module file extension blocks.
5098 for (const auto &ExtWriter : ModuleFileExtensionWriters)
Douglas Gregor8f64ca12015-12-08 22:43:32 +00005099 WriteModuleFileExtension(SemaRef, *ExtWriter);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005100
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005101 return writeUnhashedControlBlock(PP, Context);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005102}
5103
Richard Smithb9eab6d2014-03-20 19:44:17 +00005104void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005105 if (DeclUpdates.empty())
5106 return;
5107
Richard Smith59442b42014-03-20 20:07:19 +00005108 DeclUpdateMap LocalUpdates;
5109 LocalUpdates.swap(DeclUpdates);
5110
Richard Smith6ef42932014-03-20 21:02:00 +00005111 for (auto &DeclUpdate : LocalUpdates) {
5112 const Decl *D = DeclUpdate.first;
Argyrios Kyrtzidis3ba70b82010-10-24 17:26:46 +00005113
Richard Smithd28ac5b2014-03-22 23:33:22 +00005114 bool HasUpdatedBody = false;
Richard Smith69c82bf2016-04-01 22:52:03 +00005115 RecordData RecordData;
5116 ASTRecordWriter Record(*this, RecordData);
Richard Smith6ef42932014-03-20 21:02:00 +00005117 for (auto &Update : DeclUpdate.second) {
5118 DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
5119
Richard Smith69c82bf2016-04-01 22:52:03 +00005120 // An updated body is emitted last, so that the reader doesn't need
5121 // to skip over the lazy body to reach statements for other records.
5122 if (Kind == UPD_CXX_ADDED_FUNCTION_DEFINITION)
5123 HasUpdatedBody = true;
5124 else
5125 Record.push_back(Kind);
5126
Richard Smith6ef42932014-03-20 21:02:00 +00005127 switch (Kind) {
5128 case UPD_CXX_ADDED_IMPLICIT_MEMBER:
5129 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
5130 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
Richard Smithcd45dbc2014-04-19 03:48:30 +00005131 assert(Update.getDecl() && "no decl to add?");
Richard Smith6ef42932014-03-20 21:02:00 +00005132 Record.push_back(GetDeclRef(Update.getDecl()));
5133 break;
5134
Richard Smith4d235792014-08-07 18:53:08 +00005135 case UPD_CXX_ADDED_FUNCTION_DEFINITION:
Richard Smithd28ac5b2014-03-22 23:33:22 +00005136 break;
5137
Richard Smith891fc7f2017-12-05 01:31:47 +00005138 case UPD_CXX_POINT_OF_INSTANTIATION:
5139 // FIXME: Do we need to also save the template specialization kind here?
Richard Smith69c82bf2016-04-01 22:52:03 +00005140 Record.AddSourceLocation(Update.getLoc());
Richard Smith891fc7f2017-12-05 01:31:47 +00005141 break;
5142
5143 case UPD_CXX_ADDED_VAR_DEFINITION: {
5144 const VarDecl *VD = cast<VarDecl>(D);
Richard Smithf5017592017-11-02 01:06:00 +00005145 Record.push_back(VD->isInline());
5146 Record.push_back(VD->isInlineSpecified());
Richard Smith05a21352017-06-22 22:18:46 +00005147 if (VD->getInit()) {
5148 Record.push_back(!VD->isInitKnownICE() ? 1
5149 : (VD->isInitICE() ? 3 : 2));
5150 Record.AddStmt(const_cast<Expr*>(VD->getInit()));
5151 } else {
5152 Record.push_back(0);
5153 }
Richard Smith4d235792014-08-07 18:53:08 +00005154 break;
Richard Smith05a21352017-06-22 22:18:46 +00005155 }
Richard Smith4d235792014-08-07 18:53:08 +00005156
John McCall32791cc2016-01-06 22:34:54 +00005157 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT:
Richard Smith290d8012016-04-06 17:06:00 +00005158 Record.AddStmt(const_cast<Expr *>(
5159 cast<ParmVarDecl>(Update.getDecl())->getDefaultArg()));
John McCall32791cc2016-01-06 22:34:54 +00005160 break;
5161
Richard Smith4b054b22016-08-24 21:25:37 +00005162 case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER:
5163 Record.AddStmt(
5164 cast<FieldDecl>(Update.getDecl())->getInClassInitializer());
5165 break;
5166
Richard Smithcd45dbc2014-04-19 03:48:30 +00005167 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
5168 auto *RD = cast<CXXRecordDecl>(D);
Chandler Carruth8a3d24d2015-03-26 04:27:10 +00005169 UpdatedDeclContexts.insert(RD->getPrimaryContext());
Richard Smith69c82bf2016-04-01 22:52:03 +00005170 Record.AddCXXDefinitionData(RD);
Richard Smith72e50fe2016-04-14 00:50:18 +00005171 Record.AddOffset(WriteDeclContextLexicalBlock(
Richard Smithcd45dbc2014-04-19 03:48:30 +00005172 *Context, const_cast<CXXRecordDecl *>(RD)));
5173
5174 // This state is sometimes updated by template instantiation, when we
5175 // switch from the specialization referring to the template declaration
5176 // to it referring to the template definition.
5177 if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
5178 Record.push_back(MSInfo->getTemplateSpecializationKind());
Richard Smith69c82bf2016-04-01 22:52:03 +00005179 Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
Richard Smithcd45dbc2014-04-19 03:48:30 +00005180 } else {
5181 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
5182 Record.push_back(Spec->getTemplateSpecializationKind());
Richard Smith69c82bf2016-04-01 22:52:03 +00005183 Record.AddSourceLocation(Spec->getPointOfInstantiation());
Richard Smithdf352052014-05-22 20:59:29 +00005184
5185 // The instantiation might have been resolved to a partial
5186 // specialization. If so, record which one.
5187 auto From = Spec->getInstantiatedFrom();
5188 if (auto PartialSpec =
5189 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
5190 Record.push_back(true);
Richard Smith69c82bf2016-04-01 22:52:03 +00005191 Record.AddDeclRef(PartialSpec);
5192 Record.AddTemplateArgumentList(
5193 &Spec->getTemplateInstantiationArgs());
Richard Smithdf352052014-05-22 20:59:29 +00005194 } else {
5195 Record.push_back(false);
5196 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00005197 }
5198 Record.push_back(RD->getTagKind());
Richard Smith69c82bf2016-04-01 22:52:03 +00005199 Record.AddSourceLocation(RD->getLocation());
5200 Record.AddSourceLocation(RD->getLocStart());
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00005201 Record.AddSourceRange(RD->getBraceRange());
Richard Smithcd45dbc2014-04-19 03:48:30 +00005202
5203 // Instantiation may change attributes; write them all out afresh.
5204 Record.push_back(D->hasAttrs());
Richard Smith69c82bf2016-04-01 22:52:03 +00005205 if (D->hasAttrs())
5206 Record.AddAttributes(D->getAttrs());
Richard Smithcd45dbc2014-04-19 03:48:30 +00005207
5208 // FIXME: Ensure we don't get here for explicit instantiations.
5209 break;
5210 }
5211
Richard Smithf8134002015-03-10 01:41:22 +00005212 case UPD_CXX_RESOLVED_DTOR_DELETE:
Richard Smith69c82bf2016-04-01 22:52:03 +00005213 Record.AddDeclRef(Update.getDecl());
Richard Smith5b349582017-10-13 01:55:36 +00005214 Record.AddStmt(cast<CXXDestructorDecl>(D)->getOperatorDeleteThisArg());
Richard Smithf8134002015-03-10 01:41:22 +00005215 break;
5216
Richard Smith564417a2014-03-20 21:47:22 +00005217 case UPD_CXX_RESOLVED_EXCEPTION_SPEC:
5218 addExceptionSpec(
Richard Smith564417a2014-03-20 21:47:22 +00005219 cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>(),
5220 Record);
5221 break;
5222
Richard Smith6ef42932014-03-20 21:02:00 +00005223 case UPD_CXX_DEDUCED_RETURN_TYPE:
5224 Record.push_back(GetOrCreateTypeID(Update.getType()));
5225 break;
5226
5227 case UPD_DECL_MARKED_USED:
5228 break;
Richard Smith5652c0f2014-03-21 01:48:23 +00005229
5230 case UPD_MANGLING_NUMBER:
5231 case UPD_STATIC_LOCAL_NUMBER:
5232 Record.push_back(Update.getNumber());
5233 break;
Richard Smith65ebb4a2015-03-26 04:09:53 +00005234
Alexey Bataev97720002014-11-11 04:05:39 +00005235 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
Richard Smith69c82bf2016-04-01 22:52:03 +00005236 Record.AddSourceRange(
5237 D->getAttr<OMPThreadPrivateDeclAttr>()->getRange());
Alexey Bataev97720002014-11-11 04:05:39 +00005238 break;
Richard Smith65ebb4a2015-03-26 04:09:53 +00005239
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00005240 case UPD_DECL_MARKED_OPENMP_DECLARETARGET:
5241 Record.AddSourceRange(
5242 D->getAttr<OMPDeclareTargetDeclAttr>()->getRange());
5243 break;
5244
Richard Smith65ebb4a2015-03-26 04:09:53 +00005245 case UPD_DECL_EXPORTED:
Richard Smith4caa4492015-05-15 02:34:32 +00005246 Record.push_back(getSubmoduleID(Update.getModule()));
Richard Smith65ebb4a2015-03-26 04:09:53 +00005247 break;
Alex Denisovfde64952015-06-26 05:28:36 +00005248
5249 case UPD_ADDED_ATTR_TO_RECORD:
Richard Smith69c82bf2016-04-01 22:52:03 +00005250 Record.AddAttributes(llvm::makeArrayRef(Update.getAttr()));
Alex Denisovfde64952015-06-26 05:28:36 +00005251 break;
Richard Smith6ef42932014-03-20 21:02:00 +00005252 }
5253 }
5254
Richard Smithd28ac5b2014-03-22 23:33:22 +00005255 if (HasUpdatedBody) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005256 const auto *Def = cast<FunctionDecl>(D);
Richard Smith4d235792014-08-07 18:53:08 +00005257 Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
Richard Smithd28ac5b2014-03-22 23:33:22 +00005258 Record.push_back(Def->isInlined());
Richard Smith69c82bf2016-04-01 22:52:03 +00005259 Record.AddSourceLocation(Def->getInnerLocStart());
Richard Smith290d8012016-04-06 17:06:00 +00005260 Record.AddFunctionDefinition(Def);
Richard Smithd28ac5b2014-03-22 23:33:22 +00005261 }
5262
Richard Smithcd45dbc2014-04-19 03:48:30 +00005263 OffsetsRecord.push_back(GetDeclRef(D));
Richard Smith69c82bf2016-04-01 22:52:03 +00005264 OffsetsRecord.push_back(Record.Emit(DECL_UPDATES));
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005265 }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005266}
5267
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005268void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
Richard Smithb22a1d12016-03-27 20:13:24 +00005269 uint32_t Raw = Loc.getRawEncoding();
5270 Record.push_back((Raw << 1) | (Raw >> 31));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005271}
5272
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005273void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
Chris Lattnerca025db2010-05-07 21:43:38 +00005274 AddSourceLocation(Range.getBegin(), Record);
5275 AddSourceLocation(Range.getEnd(), Record);
5276}
5277
Richard Smithf144b542016-04-08 21:54:32 +00005278void ASTRecordWriter::AddAPInt(const llvm::APInt &Value) {
5279 Record->push_back(Value.getBitWidth());
Benjamin Kramer25f9ea62010-09-06 23:43:28 +00005280 const uint64_t *Words = Value.getRawData();
Richard Smithf144b542016-04-08 21:54:32 +00005281 Record->append(Words, Words + Value.getNumWords());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005282}
5283
Richard Smithf144b542016-04-08 21:54:32 +00005284void ASTRecordWriter::AddAPSInt(const llvm::APSInt &Value) {
5285 Record->push_back(Value.isUnsigned());
5286 AddAPInt(Value);
Douglas Gregor1daeb692009-04-13 18:14:40 +00005287}
5288
Richard Smithf144b542016-04-08 21:54:32 +00005289void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) {
5290 AddAPInt(Value.bitcastToAPInt());
Douglas Gregore0a3a512009-04-14 21:55:33 +00005291}
5292
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005293void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
Douglas Gregor4621c6a2009-04-22 18:49:13 +00005294 Record.push_back(getIdentifierRef(II));
5295}
5296
Sebastian Redl539c5062010-08-18 23:57:32 +00005297IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
Craig Toppera13603a2014-05-22 05:54:18 +00005298 if (!II)
Douglas Gregor4621c6a2009-04-22 18:49:13 +00005299 return 0;
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00005300
Sebastian Redl539c5062010-08-18 23:57:32 +00005301 IdentID &ID = IdentifierIDs[II];
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00005302 if (ID == 0)
Sebastian Redlff4a2952010-07-23 23:49:55 +00005303 ID = NextIdentID++;
Douglas Gregor4621c6a2009-04-22 18:49:13 +00005304 return ID;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005305}
5306
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005307MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005308 // Don't emit builtin macros like __LINE__ to the AST file unless they
5309 // have been redefined by the header (in which case they are not
5310 // isBuiltinMacro).
Craig Toppera13603a2014-05-22 05:54:18 +00005311 if (!MI || MI->isBuiltinMacro())
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005312 return 0;
5313
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005314 MacroID &ID = MacroIDs[MI];
5315 if (ID == 0) {
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005316 ID = NextMacroID++;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005317 MacroInfoToEmitData Info = { Name, MI, ID };
5318 MacroInfosToEmit.push_back(Info);
5319 }
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005320 return ID;
5321}
5322
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005323MacroID ASTWriter::getMacroID(MacroInfo *MI) {
Craig Toppera13603a2014-05-22 05:54:18 +00005324 if (!MI || MI->isBuiltinMacro())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005325 return 0;
5326
5327 assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
5328 return MacroIDs[MI];
5329}
5330
5331uint64_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
Richard Smithd7329392015-04-21 21:46:32 +00005332 return IdentMacroDirectivesOffsetMap.lookup(Name);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005333}
5334
Richard Smithe64e7452016-04-18 21:54:58 +00005335void ASTRecordWriter::AddSelectorRef(const Selector SelRef) {
5336 Record->push_back(Writer->getSelectorRef(SelRef));
Sebastian Redl834bb972010-08-04 17:20:04 +00005337}
5338
Sebastian Redl539c5062010-08-18 23:57:32 +00005339SelectorID ASTWriter::getSelectorRef(Selector Sel) {
Craig Toppera13603a2014-05-22 05:54:18 +00005340 if (Sel.getAsOpaquePtr() == nullptr) {
Sebastian Redl834bb972010-08-04 17:20:04 +00005341 return 0;
Steve Naroff2ddea052009-04-23 10:39:46 +00005342 }
5343
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005344 SelectorID SID = SelectorIDs[Sel];
Sebastian Redld95a56e2010-08-04 18:21:41 +00005345 if (SID == 0 && Chain) {
5346 // This might trigger a ReadSelector callback, which will set the ID for
5347 // this selector.
5348 Chain->LoadSelector(Sel);
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005349 SID = SelectorIDs[Sel];
Sebastian Redld95a56e2010-08-04 18:21:41 +00005350 }
Steve Naroff2ddea052009-04-23 10:39:46 +00005351 if (SID == 0) {
Sebastian Redld95a56e2010-08-04 18:21:41 +00005352 SID = NextSelectorID++;
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005353 SelectorIDs[Sel] = SID;
Steve Naroff2ddea052009-04-23 10:39:46 +00005354 }
Sebastian Redl834bb972010-08-04 17:20:04 +00005355 return SID;
Steve Naroff2ddea052009-04-23 10:39:46 +00005356}
5357
Richard Smithe64e7452016-04-18 21:54:58 +00005358void ASTRecordWriter::AddCXXTemporary(const CXXTemporary *Temp) {
5359 AddDeclRef(Temp->getDestructor());
Chris Lattnercba86142010-05-10 00:25:06 +00005360}
5361
Richard Smith290d8012016-04-06 17:06:00 +00005362void ASTRecordWriter::AddTemplateArgumentLocInfo(
5363 TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg) {
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00005364 switch (Kind) {
John McCall0ad16662009-10-29 08:12:44 +00005365 case TemplateArgument::Expression:
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00005366 AddStmt(Arg.getAsExpr());
John McCall0ad16662009-10-29 08:12:44 +00005367 break;
5368 case TemplateArgument::Type:
Richard Smith290d8012016-04-06 17:06:00 +00005369 AddTypeSourceInfo(Arg.getAsTypeSourceInfo());
John McCall0ad16662009-10-29 08:12:44 +00005370 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005371 case TemplateArgument::Template:
Richard Smith290d8012016-04-06 17:06:00 +00005372 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5373 AddSourceLocation(Arg.getTemplateNameLoc());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005374 break;
5375 case TemplateArgument::TemplateExpansion:
Richard Smith290d8012016-04-06 17:06:00 +00005376 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5377 AddSourceLocation(Arg.getTemplateNameLoc());
5378 AddSourceLocation(Arg.getTemplateEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005379 break;
John McCall0ad16662009-10-29 08:12:44 +00005380 case TemplateArgument::Null:
5381 case TemplateArgument::Integral:
5382 case TemplateArgument::Declaration:
Eli Friedmanb826a002012-09-26 02:36:12 +00005383 case TemplateArgument::NullPtr:
John McCall0ad16662009-10-29 08:12:44 +00005384 case TemplateArgument::Pack:
Eli Friedmanb826a002012-09-26 02:36:12 +00005385 // FIXME: Is this right?
John McCall0ad16662009-10-29 08:12:44 +00005386 break;
5387 }
5388}
5389
Richard Smith290d8012016-04-06 17:06:00 +00005390void ASTRecordWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg) {
5391 AddTemplateArgument(Arg.getArgument());
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00005392
5393 if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
5394 bool InfoHasSameExpr
5395 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
Richard Smith290d8012016-04-06 17:06:00 +00005396 Record->push_back(InfoHasSameExpr);
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00005397 if (InfoHasSameExpr)
5398 return; // Avoid storing the same expr twice.
5399 }
Richard Smith290d8012016-04-06 17:06:00 +00005400 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo());
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00005401}
5402
Richard Smith290d8012016-04-06 17:06:00 +00005403void ASTRecordWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo) {
Craig Toppera13603a2014-05-22 05:54:18 +00005404 if (!TInfo) {
Richard Smith290d8012016-04-06 17:06:00 +00005405 AddTypeRef(QualType());
John McCall8f115c62009-10-16 21:56:05 +00005406 return;
5407 }
5408
Richard Smith290d8012016-04-06 17:06:00 +00005409 AddTypeLoc(TInfo->getTypeLoc());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005410}
5411
Richard Smith290d8012016-04-06 17:06:00 +00005412void ASTRecordWriter::AddTypeLoc(TypeLoc TL) {
5413 AddTypeRef(TL.getType());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005414
Richard Smith290d8012016-04-06 17:06:00 +00005415 TypeLocWriter TLW(*this);
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005416 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00005417 TLW.Visit(TL);
John McCall8f115c62009-10-16 21:56:05 +00005418}
5419
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005420void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
Argyrios Kyrtzidis9ab44ea2010-08-20 16:04:14 +00005421 Record.push_back(GetOrCreateTypeID(T));
5422}
5423
Richard Smith2095ffe2015-03-16 20:11:03 +00005424TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
Richard Smith1fa5d642013-05-11 05:45:24 +00005425 assert(Context);
Richard Smith2095ffe2015-03-16 20:11:03 +00005426 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5427 if (T.isNull())
5428 return TypeIdx();
5429 assert(!T.getLocalFastQualifiers());
5430
5431 TypeIdx &Idx = TypeIdxs[T];
5432 if (Idx.getIndex() == 0) {
5433 if (DoneWritingDeclsAndTypes) {
5434 assert(0 && "New type seen after serializing all the types to emit!");
5435 return TypeIdx();
5436 }
5437
5438 // We haven't seen this type before. Assign it a new ID and put it
5439 // into the queue of types to emit.
5440 Idx = TypeIdx(NextTypeID++);
5441 DeclTypesToEmit.push(T);
5442 }
5443 return Idx;
5444 });
Argyrios Kyrtzidis082e4612010-08-20 16:04:20 +00005445}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005446
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00005447TypeID ASTWriter::getTypeID(QualType T) const {
Richard Smith1fa5d642013-05-11 05:45:24 +00005448 assert(Context);
Richard Smith2095ffe2015-03-16 20:11:03 +00005449 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5450 if (T.isNull())
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005451 return TypeIdx();
Richard Smith2095ffe2015-03-16 20:11:03 +00005452 assert(!T.getLocalFastQualifiers());
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005453
Richard Smith2095ffe2015-03-16 20:11:03 +00005454 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
5455 assert(I != TypeIdxs.end() && "Type not emitted!");
5456 return I->second;
5457 });
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005458}
5459
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005460void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005461 Record.push_back(GetDeclRef(D));
5462}
5463
Sebastian Redl539c5062010-08-18 23:57:32 +00005464DeclID ASTWriter::GetDeclRef(const Decl *D) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005465 assert(WritingAST && "Cannot request a declaration ID before AST writing");
Craig Toppera13603a2014-05-22 05:54:18 +00005466
5467 if (!D) {
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005468 return 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005469 }
Douglas Gregorb3163e52012-01-05 22:33:30 +00005470
5471 // If D comes from an AST file, its declaration ID is already known and
5472 // fixed.
5473 if (D->isFromASTFile())
5474 return D->getGlobalID();
5475
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005476 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
Sebastian Redl539c5062010-08-18 23:57:32 +00005477 DeclID &ID = DeclIDs[D];
Mike Stump11289f42009-09-09 15:08:12 +00005478 if (ID == 0) {
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005479 if (DoneWritingDeclsAndTypes) {
5480 assert(0 && "New decl seen after serializing all the decls to emit!");
5481 return 0;
5482 }
5483
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005484 // We haven't seen this declaration before. Give it a new ID and
5485 // enqueue it in the list of declarations to emit.
Sebastian Redlff4a2952010-07-23 23:49:55 +00005486 ID = NextDeclID++;
Douglas Gregor12bfa382009-10-17 00:13:19 +00005487 DeclTypesToEmit.push(const_cast<Decl *>(D));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005488 }
5489
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005490 return ID;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005491}
5492
Sebastian Redl539c5062010-08-18 23:57:32 +00005493DeclID ASTWriter::getDeclID(const Decl *D) {
Craig Toppera13603a2014-05-22 05:54:18 +00005494 if (!D)
Douglas Gregore84a9da2009-04-20 20:36:09 +00005495 return 0;
5496
Douglas Gregorb3163e52012-01-05 22:33:30 +00005497 // If D comes from an AST file, its declaration ID is already known and
5498 // fixed.
5499 if (D->isFromASTFile())
5500 return D->getGlobalID();
5501
Douglas Gregore84a9da2009-04-20 20:36:09 +00005502 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
5503 return DeclIDs[D];
5504}
5505
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005506void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005507 assert(ID);
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005508 assert(D);
5509
5510 SourceLocation Loc = D->getLocation();
5511 if (Loc.isInvalid())
5512 return;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005513
5514 // We only keep track of the file-level declarations of each file.
5515 if (!D->getLexicalDeclContext()->isFileContext())
5516 return;
Argyrios Kyrtzidise1bc99e2012-02-24 19:45:46 +00005517 // FIXME: ParmVarDecls that are part of a function type of a parameter of
5518 // a function/objc method, should not have TU as lexical context.
Argyrios Kyrtzidisffe055a82012-02-24 01:12:38 +00005519 if (isa<ParmVarDecl>(D))
5520 return;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005521
5522 SourceManager &SM = Context->getSourceManager();
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005523 SourceLocation FileLoc = SM.getFileLoc(Loc);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005524 assert(SM.isLocalSourceLocation(FileLoc));
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005525 FileID FID;
5526 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00005527 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005528 if (FID.isInvalid())
5529 return;
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00005530 assert(SM.getSLocEntry(FID).isFile());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005531
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00005532 DeclIDInFileInfo *&Info = FileDeclIDs[FID];
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005533 if (!Info)
5534 Info = new DeclIDInFileInfo();
5535
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005536 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005537 LocDeclIDsTy &Decls = Info->DeclIDs;
5538
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005539 if (Decls.empty() || Decls.back().first <= Offset) {
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005540 Decls.push_back(LocDecl);
5541 return;
5542 }
5543
Benjamin Kramer45025c02013-08-24 13:22:59 +00005544 LocDeclIDsTy::iterator I =
5545 std::upper_bound(Decls.begin(), Decls.end(), LocDecl, llvm::less_first());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005546
5547 Decls.insert(I, LocDecl);
5548}
5549
Richard Smithe64e7452016-04-18 21:54:58 +00005550void ASTRecordWriter::AddDeclarationName(DeclarationName Name) {
Chris Lattner258172e2009-04-27 07:35:58 +00005551 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
Richard Smithe64e7452016-04-18 21:54:58 +00005552 Record->push_back(Name.getNameKind());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005553 switch (Name.getNameKind()) {
5554 case DeclarationName::Identifier:
Richard Smithe64e7452016-04-18 21:54:58 +00005555 AddIdentifierRef(Name.getAsIdentifierInfo());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005556 break;
5557
5558 case DeclarationName::ObjCZeroArgSelector:
5559 case DeclarationName::ObjCOneArgSelector:
5560 case DeclarationName::ObjCMultiArgSelector:
Richard Smithe64e7452016-04-18 21:54:58 +00005561 AddSelectorRef(Name.getObjCSelector());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005562 break;
5563
5564 case DeclarationName::CXXConstructorName:
5565 case DeclarationName::CXXDestructorName:
5566 case DeclarationName::CXXConversionFunctionName:
Richard Smithe64e7452016-04-18 21:54:58 +00005567 AddTypeRef(Name.getCXXNameType());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005568 break;
5569
Richard Smith35845152017-02-07 01:37:30 +00005570 case DeclarationName::CXXDeductionGuideName:
5571 AddDeclRef(Name.getCXXDeductionGuideTemplate());
5572 break;
5573
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005574 case DeclarationName::CXXOperatorName:
Richard Smithe64e7452016-04-18 21:54:58 +00005575 Record->push_back(Name.getCXXOverloadedOperator());
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005576 break;
5577
Alexis Hunt3d221f22009-11-29 07:34:05 +00005578 case DeclarationName::CXXLiteralOperatorName:
Richard Smithe64e7452016-04-18 21:54:58 +00005579 AddIdentifierRef(Name.getCXXLiteralIdentifier());
Alexis Hunt3d221f22009-11-29 07:34:05 +00005580 break;
5581
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005582 case DeclarationName::CXXUsingDirective:
5583 // No extra data to emit
5584 break;
5585 }
5586}
Chris Lattnerca025db2010-05-07 21:43:38 +00005587
Richard Smithd08aeb62014-08-28 01:33:39 +00005588unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
5589 assert(needsAnonymousDeclarationNumber(D) &&
5590 "expected an anonymous declaration");
5591
5592 // Number the anonymous declarations within this context, if we've not
5593 // already done so.
5594 auto It = AnonymousDeclarationNumbers.find(D);
5595 if (It == AnonymousDeclarationNumbers.end()) {
Richard Smith2b560572015-02-07 03:11:11 +00005596 auto *DC = D->getLexicalDeclContext();
5597 numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
5598 AnonymousDeclarationNumbers[ND] = Number;
5599 });
Richard Smithd08aeb62014-08-28 01:33:39 +00005600
5601 It = AnonymousDeclarationNumbers.find(D);
5602 assert(It != AnonymousDeclarationNumbers.end() &&
5603 "declaration not found within its lexical context");
5604 }
5605
5606 return It->second;
5607}
5608
Richard Smith290d8012016-04-06 17:06:00 +00005609void ASTRecordWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
5610 DeclarationName Name) {
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005611 switch (Name.getNameKind()) {
5612 case DeclarationName::CXXConstructorName:
5613 case DeclarationName::CXXDestructorName:
5614 case DeclarationName::CXXConversionFunctionName:
Richard Smith290d8012016-04-06 17:06:00 +00005615 AddTypeSourceInfo(DNLoc.NamedType.TInfo);
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005616 break;
5617
5618 case DeclarationName::CXXOperatorName:
Richard Smith290d8012016-04-06 17:06:00 +00005619 AddSourceLocation(SourceLocation::getFromRawEncoding(
5620 DNLoc.CXXOperatorName.BeginOpNameLoc));
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005621 AddSourceLocation(
Richard Smith290d8012016-04-06 17:06:00 +00005622 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc));
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005623 break;
5624
5625 case DeclarationName::CXXLiteralOperatorName:
Richard Smith290d8012016-04-06 17:06:00 +00005626 AddSourceLocation(SourceLocation::getFromRawEncoding(
5627 DNLoc.CXXLiteralOperatorName.OpNameLoc));
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005628 break;
5629
5630 case DeclarationName::Identifier:
5631 case DeclarationName::ObjCZeroArgSelector:
5632 case DeclarationName::ObjCOneArgSelector:
5633 case DeclarationName::ObjCMultiArgSelector:
5634 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00005635 case DeclarationName::CXXDeductionGuideName:
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005636 break;
5637 }
5638}
5639
Richard Smith290d8012016-04-06 17:06:00 +00005640void ASTRecordWriter::AddDeclarationNameInfo(
5641 const DeclarationNameInfo &NameInfo) {
5642 AddDeclarationName(NameInfo.getName());
5643 AddSourceLocation(NameInfo.getLoc());
5644 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName());
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005645}
5646
Richard Smith290d8012016-04-06 17:06:00 +00005647void ASTRecordWriter::AddQualifierInfo(const QualifierInfo &Info) {
5648 AddNestedNameSpecifierLoc(Info.QualifierLoc);
5649 Record->push_back(Info.NumTemplParamLists);
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005650 for (unsigned i = 0, e = Info.NumTemplParamLists; i != e; ++i)
Richard Smith290d8012016-04-06 17:06:00 +00005651 AddTemplateParameterList(Info.TemplParamLists[i]);
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005652}
5653
Richard Smithe64e7452016-04-18 21:54:58 +00005654void ASTRecordWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS) {
Chris Lattnerca025db2010-05-07 21:43:38 +00005655 // Nested name specifiers usually aren't too long. I think that 8 would
Chris Lattner57540c52011-04-15 05:22:18 +00005656 // typically accommodate the vast majority.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005657 SmallVector<NestedNameSpecifier *, 8> NestedNames;
Chris Lattnerca025db2010-05-07 21:43:38 +00005658
5659 // Push each of the NNS's onto a stack for serialization in reverse order.
5660 while (NNS) {
5661 NestedNames.push_back(NNS);
5662 NNS = NNS->getPrefix();
5663 }
5664
Richard Smithe64e7452016-04-18 21:54:58 +00005665 Record->push_back(NestedNames.size());
Chris Lattnerca025db2010-05-07 21:43:38 +00005666 while(!NestedNames.empty()) {
5667 NNS = NestedNames.pop_back_val();
5668 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
Richard Smithe64e7452016-04-18 21:54:58 +00005669 Record->push_back(Kind);
Chris Lattnerca025db2010-05-07 21:43:38 +00005670 switch (Kind) {
5671 case NestedNameSpecifier::Identifier:
Richard Smithe64e7452016-04-18 21:54:58 +00005672 AddIdentifierRef(NNS->getAsIdentifier());
Chris Lattnerca025db2010-05-07 21:43:38 +00005673 break;
5674
5675 case NestedNameSpecifier::Namespace:
Richard Smithe64e7452016-04-18 21:54:58 +00005676 AddDeclRef(NNS->getAsNamespace());
Chris Lattnerca025db2010-05-07 21:43:38 +00005677 break;
5678
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005679 case NestedNameSpecifier::NamespaceAlias:
Richard Smithe64e7452016-04-18 21:54:58 +00005680 AddDeclRef(NNS->getAsNamespaceAlias());
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005681 break;
5682
Chris Lattnerca025db2010-05-07 21:43:38 +00005683 case NestedNameSpecifier::TypeSpec:
5684 case NestedNameSpecifier::TypeSpecWithTemplate:
Richard Smithe64e7452016-04-18 21:54:58 +00005685 AddTypeRef(QualType(NNS->getAsType(), 0));
5686 Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
Chris Lattnerca025db2010-05-07 21:43:38 +00005687 break;
5688
5689 case NestedNameSpecifier::Global:
5690 // Don't need to write an associated value.
5691 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00005692
5693 case NestedNameSpecifier::Super:
Richard Smithe64e7452016-04-18 21:54:58 +00005694 AddDeclRef(NNS->getAsRecordDecl());
Nikola Smiljanic67860242014-09-26 00:28:20 +00005695 break;
Chris Lattnerca025db2010-05-07 21:43:38 +00005696 }
5697 }
5698}
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005699
Richard Smith290d8012016-04-06 17:06:00 +00005700void ASTRecordWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005701 // Nested name specifiers usually aren't too long. I think that 8 would
Chris Lattner57540c52011-04-15 05:22:18 +00005702 // typically accommodate the vast majority.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005703 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005704
5705 // Push each of the nested-name-specifiers's onto a stack for
5706 // serialization in reverse order.
5707 while (NNS) {
5708 NestedNames.push_back(NNS);
5709 NNS = NNS.getPrefix();
5710 }
5711
Richard Smith290d8012016-04-06 17:06:00 +00005712 Record->push_back(NestedNames.size());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005713 while(!NestedNames.empty()) {
5714 NNS = NestedNames.pop_back_val();
5715 NestedNameSpecifier::SpecifierKind Kind
5716 = NNS.getNestedNameSpecifier()->getKind();
Richard Smith290d8012016-04-06 17:06:00 +00005717 Record->push_back(Kind);
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005718 switch (Kind) {
5719 case NestedNameSpecifier::Identifier:
Richard Smith290d8012016-04-06 17:06:00 +00005720 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier());
5721 AddSourceRange(NNS.getLocalSourceRange());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005722 break;
5723
5724 case NestedNameSpecifier::Namespace:
Richard Smith290d8012016-04-06 17:06:00 +00005725 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace());
5726 AddSourceRange(NNS.getLocalSourceRange());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005727 break;
5728
5729 case NestedNameSpecifier::NamespaceAlias:
Richard Smith290d8012016-04-06 17:06:00 +00005730 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias());
5731 AddSourceRange(NNS.getLocalSourceRange());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005732 break;
5733
5734 case NestedNameSpecifier::TypeSpec:
5735 case NestedNameSpecifier::TypeSpecWithTemplate:
Richard Smith290d8012016-04-06 17:06:00 +00005736 Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5737 AddTypeLoc(NNS.getTypeLoc());
5738 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005739 break;
5740
5741 case NestedNameSpecifier::Global:
Richard Smith290d8012016-04-06 17:06:00 +00005742 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005743 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00005744
5745 case NestedNameSpecifier::Super:
Richard Smith290d8012016-04-06 17:06:00 +00005746 AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl());
5747 AddSourceRange(NNS.getLocalSourceRange());
Nikola Smiljanic67860242014-09-26 00:28:20 +00005748 break;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005749 }
5750 }
5751}
5752
Richard Smith290d8012016-04-06 17:06:00 +00005753void ASTRecordWriter::AddTemplateName(TemplateName Name) {
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005754 TemplateName::NameKind Kind = Name.getKind();
Richard Smith290d8012016-04-06 17:06:00 +00005755 Record->push_back(Kind);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005756 switch (Kind) {
5757 case TemplateName::Template:
Richard Smith290d8012016-04-06 17:06:00 +00005758 AddDeclRef(Name.getAsTemplateDecl());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005759 break;
5760
5761 case TemplateName::OverloadedTemplate: {
5762 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
Richard Smith290d8012016-04-06 17:06:00 +00005763 Record->push_back(OvT->size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005764 for (const auto &I : *OvT)
Richard Smith290d8012016-04-06 17:06:00 +00005765 AddDeclRef(I);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005766 break;
5767 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005768
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005769 case TemplateName::QualifiedTemplate: {
5770 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
Richard Smith290d8012016-04-06 17:06:00 +00005771 AddNestedNameSpecifier(QualT->getQualifier());
5772 Record->push_back(QualT->hasTemplateKeyword());
5773 AddDeclRef(QualT->getTemplateDecl());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005774 break;
5775 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005776
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005777 case TemplateName::DependentTemplate: {
5778 DependentTemplateName *DepT = Name.getAsDependentTemplateName();
Richard Smith290d8012016-04-06 17:06:00 +00005779 AddNestedNameSpecifier(DepT->getQualifier());
5780 Record->push_back(DepT->isIdentifier());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005781 if (DepT->isIdentifier())
Richard Smith290d8012016-04-06 17:06:00 +00005782 AddIdentifierRef(DepT->getIdentifier());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005783 else
Richard Smith290d8012016-04-06 17:06:00 +00005784 Record->push_back(DepT->getOperator());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005785 break;
5786 }
John McCalld9dfe3a2011-06-30 08:33:18 +00005787
5788 case TemplateName::SubstTemplateTemplateParm: {
5789 SubstTemplateTemplateParmStorage *subst
5790 = Name.getAsSubstTemplateTemplateParm();
Richard Smith290d8012016-04-06 17:06:00 +00005791 AddDeclRef(subst->getParameter());
5792 AddTemplateName(subst->getReplacement());
John McCalld9dfe3a2011-06-30 08:33:18 +00005793 break;
5794 }
Douglas Gregor5590be02011-01-15 06:45:20 +00005795
5796 case TemplateName::SubstTemplateTemplateParmPack: {
5797 SubstTemplateTemplateParmPackStorage *SubstPack
5798 = Name.getAsSubstTemplateTemplateParmPack();
Richard Smith290d8012016-04-06 17:06:00 +00005799 AddDeclRef(SubstPack->getParameterPack());
5800 AddTemplateArgument(SubstPack->getArgumentPack());
Douglas Gregor5590be02011-01-15 06:45:20 +00005801 break;
5802 }
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005803 }
5804}
5805
Richard Smith290d8012016-04-06 17:06:00 +00005806void ASTRecordWriter::AddTemplateArgument(const TemplateArgument &Arg) {
5807 Record->push_back(Arg.getKind());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005808 switch (Arg.getKind()) {
5809 case TemplateArgument::Null:
5810 break;
5811 case TemplateArgument::Type:
Richard Smith290d8012016-04-06 17:06:00 +00005812 AddTypeRef(Arg.getAsType());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005813 break;
5814 case TemplateArgument::Declaration:
Richard Smith290d8012016-04-06 17:06:00 +00005815 AddDeclRef(Arg.getAsDecl());
5816 AddTypeRef(Arg.getParamTypeForDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00005817 break;
5818 case TemplateArgument::NullPtr:
Richard Smith290d8012016-04-06 17:06:00 +00005819 AddTypeRef(Arg.getNullPtrType());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005820 break;
5821 case TemplateArgument::Integral:
Richard Smith290d8012016-04-06 17:06:00 +00005822 AddAPSInt(Arg.getAsIntegral());
5823 AddTypeRef(Arg.getIntegralType());
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005824 break;
5825 case TemplateArgument::Template:
Richard Smith290d8012016-04-06 17:06:00 +00005826 AddTemplateName(Arg.getAsTemplateOrTemplatePattern());
Douglas Gregore1d60df2011-01-14 23:41:42 +00005827 break;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005828 case TemplateArgument::TemplateExpansion:
Richard Smith290d8012016-04-06 17:06:00 +00005829 AddTemplateName(Arg.getAsTemplateOrTemplatePattern());
David Blaikie05785d12013-02-20 22:23:23 +00005830 if (Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
Richard Smith290d8012016-04-06 17:06:00 +00005831 Record->push_back(*NumExpansions + 1);
Douglas Gregore1d60df2011-01-14 23:41:42 +00005832 else
Richard Smith290d8012016-04-06 17:06:00 +00005833 Record->push_back(0);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005834 break;
5835 case TemplateArgument::Expression:
5836 AddStmt(Arg.getAsExpr());
5837 break;
5838 case TemplateArgument::Pack:
Richard Smith290d8012016-04-06 17:06:00 +00005839 Record->push_back(Arg.pack_size());
Aaron Ballman2a89e852014-07-15 21:32:31 +00005840 for (const auto &P : Arg.pack_elements())
Richard Smith290d8012016-04-06 17:06:00 +00005841 AddTemplateArgument(P);
Argyrios Kyrtzidis106caf922010-06-19 19:28:53 +00005842 break;
5843 }
5844}
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005845
Richard Smithe64e7452016-04-18 21:54:58 +00005846void ASTRecordWriter::AddTemplateParameterList(
5847 const TemplateParameterList *TemplateParams) {
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005848 assert(TemplateParams && "No TemplateParams!");
Richard Smithe64e7452016-04-18 21:54:58 +00005849 AddSourceLocation(TemplateParams->getTemplateLoc());
5850 AddSourceLocation(TemplateParams->getLAngleLoc());
5851 AddSourceLocation(TemplateParams->getRAngleLoc());
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00005852 // TODO: Concepts
Richard Smithe64e7452016-04-18 21:54:58 +00005853 Record->push_back(TemplateParams->size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005854 for (const auto &P : *TemplateParams)
Richard Smithe64e7452016-04-18 21:54:58 +00005855 AddDeclRef(P);
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005856}
5857
5858/// \brief Emit a template argument list.
Richard Smith290d8012016-04-06 17:06:00 +00005859void ASTRecordWriter::AddTemplateArgumentList(
5860 const TemplateArgumentList *TemplateArgs) {
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005861 assert(TemplateArgs && "No TemplateArgs!");
Richard Smith290d8012016-04-06 17:06:00 +00005862 Record->push_back(TemplateArgs->size());
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005863 for (int i = 0, e = TemplateArgs->size(); i != e; ++i)
Richard Smith290d8012016-04-06 17:06:00 +00005864 AddTemplateArgument(TemplateArgs->get(i));
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005865}
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005866
Richard Smith290d8012016-04-06 17:06:00 +00005867void ASTRecordWriter::AddASTTemplateArgumentListInfo(
5868 const ASTTemplateArgumentListInfo *ASTTemplArgList) {
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005869 assert(ASTTemplArgList && "No ASTTemplArgList!");
Richard Smith290d8012016-04-06 17:06:00 +00005870 AddSourceLocation(ASTTemplArgList->LAngleLoc);
5871 AddSourceLocation(ASTTemplArgList->RAngleLoc);
5872 Record->push_back(ASTTemplArgList->NumTemplateArgs);
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005873 const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005874 for (int i = 0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
Richard Smith290d8012016-04-06 17:06:00 +00005875 AddTemplateArgumentLoc(TemplArgs[i]);
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005876}
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005877
Richard Smithe64e7452016-04-18 21:54:58 +00005878void ASTRecordWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set) {
5879 Record->push_back(Set.size());
Argyrios Kyrtzidis0f05fb92012-11-28 03:56:16 +00005880 for (ASTUnresolvedSet::const_iterator
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005881 I = Set.begin(), E = Set.end(); I != E; ++I) {
Richard Smithe64e7452016-04-18 21:54:58 +00005882 AddDeclRef(I.getDecl());
5883 Record->push_back(I.getAccess());
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005884 }
5885}
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005886
Richard Smith290d8012016-04-06 17:06:00 +00005887// FIXME: Move this out of the main ASTRecordWriter interface.
5888void ASTRecordWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
5889 Record->push_back(Base.isVirtual());
5890 Record->push_back(Base.isBaseOfClass());
5891 Record->push_back(Base.getAccessSpecifierAsWritten());
5892 Record->push_back(Base.getInheritConstructors());
5893 AddTypeSourceInfo(Base.getTypeSourceInfo());
5894 AddSourceRange(Base.getSourceRange());
Douglas Gregor752a5952011-01-03 22:36:02 +00005895 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
Richard Smith290d8012016-04-06 17:06:00 +00005896 : SourceLocation());
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005897}
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00005898
Richard Smith645d2cf2016-04-14 00:29:55 +00005899static uint64_t EmitCXXBaseSpecifiers(ASTWriter &W,
5900 ArrayRef<CXXBaseSpecifier> Bases) {
5901 ASTWriter::RecordData Record;
5902 ASTRecordWriter Writer(W, Record);
5903 Writer.push_back(Bases.size());
Dmitry Polukhin790b5402016-04-06 10:01:46 +00005904
Richard Smith645d2cf2016-04-14 00:29:55 +00005905 for (auto &Base : Bases)
5906 Writer.AddCXXBaseSpecifier(Base);
Richard Smith290d8012016-04-06 17:06:00 +00005907
Richard Smith645d2cf2016-04-14 00:29:55 +00005908 return Writer.Emit(serialization::DECL_CXX_BASE_SPECIFIERS);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005909}
5910
Richard Smith290d8012016-04-06 17:06:00 +00005911// FIXME: Move this out of the main ASTRecordWriter interface.
Richard Smith645d2cf2016-04-14 00:29:55 +00005912void ASTRecordWriter::AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases) {
5913 AddOffset(EmitCXXBaseSpecifiers(*Writer, Bases));
5914}
5915
Richard Smithaa165cf2016-04-13 21:57:08 +00005916static uint64_t
5917EmitCXXCtorInitializers(ASTWriter &W,
5918 ArrayRef<CXXCtorInitializer *> CtorInits) {
5919 ASTWriter::RecordData Record;
5920 ASTRecordWriter Writer(W, Record);
5921 Writer.push_back(CtorInits.size());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005922
Richard Smithaa165cf2016-04-13 21:57:08 +00005923 for (auto *Init : CtorInits) {
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005924 if (Init->isBaseInitializer()) {
Richard Smithaa165cf2016-04-13 21:57:08 +00005925 Writer.push_back(CTOR_INITIALIZER_BASE);
5926 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
5927 Writer.push_back(Init->isBaseVirtual());
Alexis Hunt37a477f2011-05-04 01:19:08 +00005928 } else if (Init->isDelegatingInitializer()) {
Richard Smithaa165cf2016-04-13 21:57:08 +00005929 Writer.push_back(CTOR_INITIALIZER_DELEGATING);
5930 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
Alexis Hunt37a477f2011-05-04 01:19:08 +00005931 } else if (Init->isMemberInitializer()){
Richard Smithaa165cf2016-04-13 21:57:08 +00005932 Writer.push_back(CTOR_INITIALIZER_MEMBER);
5933 Writer.AddDeclRef(Init->getMember());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005934 } else {
Richard Smithaa165cf2016-04-13 21:57:08 +00005935 Writer.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
5936 Writer.AddDeclRef(Init->getIndirectMember());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005937 }
Francois Pichetd583da02010-12-04 09:14:42 +00005938
Richard Smithaa165cf2016-04-13 21:57:08 +00005939 Writer.AddSourceLocation(Init->getMemberLocation());
5940 Writer.AddStmt(Init->getInit());
5941 Writer.AddSourceLocation(Init->getLParenLoc());
5942 Writer.AddSourceLocation(Init->getRParenLoc());
5943 Writer.push_back(Init->isWritten());
Richard Smith30e304e2016-12-14 00:03:17 +00005944 if (Init->isWritten())
Richard Smithaa165cf2016-04-13 21:57:08 +00005945 Writer.push_back(Init->getSourceOrder());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005946 }
Richard Smithaa165cf2016-04-13 21:57:08 +00005947
5948 return Writer.Emit(serialization::DECL_CXX_CTOR_INITIALIZERS);
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005949}
5950
Richard Smithaa165cf2016-04-13 21:57:08 +00005951// FIXME: Move this out of the main ASTRecordWriter interface.
5952void ASTRecordWriter::AddCXXCtorInitializers(
5953 ArrayRef<CXXCtorInitializer *> CtorInits) {
5954 AddOffset(EmitCXXCtorInitializers(*Writer, CtorInits));
Richard Smithc2bb8182015-03-24 06:36:48 +00005955}
5956
Richard Smith290d8012016-04-06 17:06:00 +00005957void ASTRecordWriter::AddCXXDefinitionData(const CXXRecordDecl *D) {
Richard Smith053f6c62014-05-16 23:01:30 +00005958 auto &Data = D->data();
Richard Smith290d8012016-04-06 17:06:00 +00005959 Record->push_back(Data.IsLambda);
5960 Record->push_back(Data.UserDeclaredConstructor);
5961 Record->push_back(Data.UserDeclaredSpecialMembers);
5962 Record->push_back(Data.Aggregate);
5963 Record->push_back(Data.PlainOldData);
5964 Record->push_back(Data.Empty);
5965 Record->push_back(Data.Polymorphic);
5966 Record->push_back(Data.Abstract);
5967 Record->push_back(Data.IsStandardLayout);
5968 Record->push_back(Data.HasNoNonEmptyBases);
5969 Record->push_back(Data.HasPrivateFields);
5970 Record->push_back(Data.HasProtectedFields);
5971 Record->push_back(Data.HasPublicFields);
5972 Record->push_back(Data.HasMutableFields);
5973 Record->push_back(Data.HasVariantMembers);
5974 Record->push_back(Data.HasOnlyCMembers);
5975 Record->push_back(Data.HasInClassInitializer);
5976 Record->push_back(Data.HasUninitializedReferenceMember);
5977 Record->push_back(Data.HasUninitializedFields);
Richard Smith12e79312016-05-13 06:47:56 +00005978 Record->push_back(Data.HasInheritedConstructor);
5979 Record->push_back(Data.HasInheritedAssignment);
Richard Smith96cd6712017-08-16 01:49:53 +00005980 Record->push_back(Data.NeedOverloadResolutionForCopyConstructor);
Richard Smith290d8012016-04-06 17:06:00 +00005981 Record->push_back(Data.NeedOverloadResolutionForMoveConstructor);
5982 Record->push_back(Data.NeedOverloadResolutionForMoveAssignment);
5983 Record->push_back(Data.NeedOverloadResolutionForDestructor);
Richard Smith96cd6712017-08-16 01:49:53 +00005984 Record->push_back(Data.DefaultedCopyConstructorIsDeleted);
Richard Smith290d8012016-04-06 17:06:00 +00005985 Record->push_back(Data.DefaultedMoveConstructorIsDeleted);
5986 Record->push_back(Data.DefaultedMoveAssignmentIsDeleted);
5987 Record->push_back(Data.DefaultedDestructorIsDeleted);
5988 Record->push_back(Data.HasTrivialSpecialMembers);
5989 Record->push_back(Data.DeclaredNonTrivialSpecialMembers);
5990 Record->push_back(Data.HasIrrelevantDestructor);
5991 Record->push_back(Data.HasConstexprNonCopyMoveConstructor);
5992 Record->push_back(Data.HasDefaultedDefaultConstructor);
Richard Smith96cd6712017-08-16 01:49:53 +00005993 Record->push_back(Data.CanPassInRegisters);
Richard Smith290d8012016-04-06 17:06:00 +00005994 Record->push_back(Data.DefaultedDefaultConstructorIsConstexpr);
5995 Record->push_back(Data.HasConstexprDefaultConstructor);
5996 Record->push_back(Data.HasNonLiteralTypeFieldsOrBases);
5997 Record->push_back(Data.ComputedVisibleConversions);
5998 Record->push_back(Data.UserProvidedDefaultConstructor);
5999 Record->push_back(Data.DeclaredSpecialMembers);
Richard Smithdf054d32017-02-25 23:53:05 +00006000 Record->push_back(Data.ImplicitCopyConstructorCanHaveConstParamForVBase);
6001 Record->push_back(Data.ImplicitCopyConstructorCanHaveConstParamForNonVBase);
Richard Smith290d8012016-04-06 17:06:00 +00006002 Record->push_back(Data.ImplicitCopyAssignmentHasConstParam);
6003 Record->push_back(Data.HasDeclaredCopyConstructorWithConstParam);
6004 Record->push_back(Data.HasDeclaredCopyAssignmentWithConstParam);
Richard Trieufd1acbb2017-04-11 21:31:00 +00006005
6006 // getODRHash will compute the ODRHash if it has not been previously computed.
6007 Record->push_back(D->getODRHash());
David Blaikief63556d2017-04-12 20:58:33 +00006008 bool ModulesDebugInfo = Writer->Context->getLangOpts().ModulesDebugInfo &&
6009 Writer->WritingModule && !D->isDependentType();
6010 Record->push_back(ModulesDebugInfo);
6011 if (ModulesDebugInfo)
David Blaikie1ac9c982017-04-11 21:13:37 +00006012 Writer->ModularCodegenDecls.push_back(Writer->GetDeclRef(D));
6013
Richard Smith561fb152012-02-25 07:33:38 +00006014 // IsLambda bit is already saved.
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00006015
Richard Smith290d8012016-04-06 17:06:00 +00006016 Record->push_back(Data.NumBases);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00006017 if (Data.NumBases > 0)
Richard Smith645d2cf2016-04-14 00:29:55 +00006018 AddCXXBaseSpecifiers(Data.bases());
6019
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00006020 // FIXME: Make VBases lazily computed when needed to avoid storing them.
Richard Smith290d8012016-04-06 17:06:00 +00006021 Record->push_back(Data.NumVBases);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00006022 if (Data.NumVBases > 0)
Richard Smith645d2cf2016-04-14 00:29:55 +00006023 AddCXXBaseSpecifiers(Data.vbases());
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00006024
Richard Smith290d8012016-04-06 17:06:00 +00006025 AddUnresolvedSet(Data.Conversions.get(*Writer->Context));
6026 AddUnresolvedSet(Data.VisibleConversions.get(*Writer->Context));
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00006027 // Data.Definition is the owning decl, no need to write it.
Richard Smith290d8012016-04-06 17:06:00 +00006028 AddDeclRef(D->getFirstFriend());
Douglas Gregor99ae8062012-02-14 17:54:36 +00006029
6030 // Add lambda-specific data.
6031 if (Data.IsLambda) {
Richard Smith053f6c62014-05-16 23:01:30 +00006032 auto &Lambda = D->getLambdaData();
Richard Smith290d8012016-04-06 17:06:00 +00006033 Record->push_back(Lambda.Dependent);
6034 Record->push_back(Lambda.IsGenericLambda);
6035 Record->push_back(Lambda.CaptureDefault);
6036 Record->push_back(Lambda.NumCaptures);
6037 Record->push_back(Lambda.NumExplicitCaptures);
6038 Record->push_back(Lambda.ManglingNumber);
Richard Smith0bae6242016-08-25 00:34:00 +00006039 AddDeclRef(D->getLambdaContextDecl());
Richard Smith290d8012016-04-06 17:06:00 +00006040 AddTypeSourceInfo(Lambda.MethodTyInfo);
Douglas Gregor99ae8062012-02-14 17:54:36 +00006041 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00006042 const LambdaCapture &Capture = Lambda.Captures[I];
Richard Smith290d8012016-04-06 17:06:00 +00006043 AddSourceLocation(Capture.getLocation());
6044 Record->push_back(Capture.isImplicit());
6045 Record->push_back(Capture.getCaptureKind());
Richard Smithba71c082013-05-16 06:20:58 +00006046 switch (Capture.getCaptureKind()) {
Faisal Validc6b5962016-03-21 09:25:37 +00006047 case LCK_StarThis:
Richard Smithba71c082013-05-16 06:20:58 +00006048 case LCK_This:
Alexey Bataev39c81e22014-08-28 04:28:19 +00006049 case LCK_VLAType:
Richard Smithba71c082013-05-16 06:20:58 +00006050 break;
6051 case LCK_ByCopy:
Richard Smithbb13c9a2013-09-28 04:02:39 +00006052 case LCK_ByRef:
Richard Smithba71c082013-05-16 06:20:58 +00006053 VarDecl *Var =
Craig Toppera13603a2014-05-22 05:54:18 +00006054 Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
Richard Smith290d8012016-04-06 17:06:00 +00006055 AddDeclRef(Var);
Richard Smithba71c082013-05-16 06:20:58 +00006056 AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
Richard Smith290d8012016-04-06 17:06:00 +00006057 : SourceLocation());
Richard Smithba71c082013-05-16 06:20:58 +00006058 break;
6059 }
Douglas Gregor99ae8062012-02-14 17:54:36 +00006060 }
6061 }
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00006062}
6063
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006064void ASTWriter::ReaderInitialized(ASTReader *Reader) {
Sebastian Redl07a89a82010-07-30 00:29:29 +00006065 assert(Reader && "Cannot remove chain");
Douglas Gregordf0c1512011-08-18 04:12:04 +00006066 assert((!Chain || Chain == Reader) && "Cannot replace chain");
Sebastian Redl07a89a82010-07-30 00:29:29 +00006067 assert(FirstDeclID == NextDeclID &&
6068 FirstTypeID == NextTypeID &&
6069 FirstIdentID == NextIdentID &&
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00006070 FirstMacroID == NextMacroID &&
Douglas Gregor253eefe2011-12-01 00:59:36 +00006071 FirstSubmoduleID == NextSubmoduleID &&
Sebastian Redld95a56e2010-08-04 18:21:41 +00006072 FirstSelectorID == NextSelectorID &&
Sebastian Redl07a89a82010-07-30 00:29:29 +00006073 "Setting chain after writing has started.");
Douglas Gregor925296b2011-07-19 16:10:42 +00006074
Sebastian Redl07a89a82010-07-30 00:29:29 +00006075 Chain = Reader;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006076
Richard Smith7f330cd2015-03-18 01:42:29 +00006077 // Note, this will get called multiple times, once one the reader starts up
6078 // and again each time it's done reading a PCH or module.
Douglas Gregordf0c1512011-08-18 04:12:04 +00006079 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
6080 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
6081 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00006082 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
Douglas Gregor253eefe2011-12-01 00:59:36 +00006083 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
Douglas Gregordf0c1512011-08-18 04:12:04 +00006084 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006085 NextDeclID = FirstDeclID;
6086 NextTypeID = FirstTypeID;
6087 NextIdentID = FirstIdentID;
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00006088 NextMacroID = FirstMacroID;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00006089 NextSelectorID = FirstSelectorID;
Douglas Gregor253eefe2011-12-01 00:59:36 +00006090 NextSubmoduleID = FirstSubmoduleID;
Sebastian Redl07a89a82010-07-30 00:29:29 +00006091}
6092
Sebastian Redl539c5062010-08-18 23:57:32 +00006093void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00006094 // Always keep the highest ID. See \p TypeRead() for more information.
6095 IdentID &StoredID = IdentifierIDs[II];
6096 if (ID > StoredID)
6097 StoredID = ID;
Sebastian Redlff4a2952010-07-23 23:49:55 +00006098}
6099
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00006100void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00006101 // Always keep the highest ID. See \p TypeRead() for more information.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00006102 MacroID &StoredID = MacroIDs[MI];
Douglas Gregor8d7edce2013-02-08 21:30:59 +00006103 if (ID > StoredID)
6104 StoredID = ID;
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00006105}
6106
Argyrios Kyrtzidisbb5c7eae2010-08-20 16:03:59 +00006107void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
Douglas Gregor9b3932c2010-10-05 18:37:06 +00006108 // Always take the highest-numbered type index. This copes with an interesting
6109 // case for chained AST writing where we schedule writing the type and then,
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00006110 // later, deserialize the type from another AST. In this case, we want to
Douglas Gregor9b3932c2010-10-05 18:37:06 +00006111 // keep the higher-numbered entry so that we can properly write it out to
6112 // the AST file.
6113 TypeIdx &StoredIdx = TypeIdxs[T];
6114 if (Idx.getIndex() >= StoredIdx.getIndex())
6115 StoredIdx = Idx;
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00006116}
6117
Sebastian Redl539c5062010-08-18 23:57:32 +00006118void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00006119 // Always keep the highest ID. See \p TypeRead() for more information.
6120 SelectorID &StoredID = SelectorIDs[S];
6121 if (ID > StoredID)
6122 StoredID = ID;
Sebastian Redl834bb972010-08-04 17:20:04 +00006123}
Douglas Gregor91096292010-10-02 19:29:26 +00006124
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00006125void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
Richard Smith66a81862015-05-04 02:25:31 +00006126 MacroDefinitionRecord *MD) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00006127 assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
Douglas Gregor91096292010-10-02 19:29:26 +00006128 MacroDefinitions[MD] = ID;
6129}
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00006130
Douglas Gregore37a85a2011-12-02 17:30:13 +00006131void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
6132 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
6133 SubmoduleIDs[Mod] = ID;
6134}
6135
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00006136void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006137 if (Chain && Chain->isProcessingUpdateRecords()) return;
John McCallf937c022011-10-07 06:10:15 +00006138 assert(D->isCompleteDefinition());
Douglas Gregor2fd3d402011-09-17 00:05:03 +00006139 assert(!WritingAST && "Already writing the AST!");
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00006140 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00006141 // We are interested when a PCH decl is modified.
Douglas Gregorb3722e22011-09-09 23:01:35 +00006142 if (RD->isFromASTFile()) {
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00006143 // A forward reference was mutated into a definition. Rewrite it.
6144 // FIXME: This happens during template instantiation, should we
6145 // have created a new definition decl instead ?
Richard Smithcd45dbc2014-04-19 03:48:30 +00006146 assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
6147 "completed a tag from another module but not by instantiation?");
6148 DeclUpdates[RD].push_back(
6149 DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION));
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00006150 }
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00006151 }
6152}
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00006153
Richard Smithf983f7f2015-10-13 00:23:25 +00006154static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) {
6155 if (D->isFromASTFile())
6156 return true;
6157
Richard Smithf983f7f2015-10-13 00:23:25 +00006158 // The predefined __va_list_tag struct is imported if we imported any decls.
6159 // FIXME: This is a gross hack.
6160 return D == D->getASTContext().getVaListTagDecl();
6161}
6162
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00006163void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006164 if (Chain && Chain->isProcessingUpdateRecords()) return;
6165 assert(DC->isLookupContext() &&
Vassil Vassilev71eafde2016-04-06 20:56:03 +00006166 "Should not add lookup results to non-lookup contexts!");
6167
Vassil Vassilev632eac32016-03-16 11:17:04 +00006168 // TU is handled elsewhere.
6169 if (isa<TranslationUnitDecl>(DC))
6170 return;
6171
6172 // Namespaces are handled elsewhere, except for template instantiations of
6173 // FunctionTemplateDecls in namespaces. We are interested in cases where the
6174 // local instantiations are added to an imported context. Only happens when
6175 // adding ADL lookup candidates, for example templated friends.
6176 if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None &&
6177 !isa<FunctionTemplateDecl>(D))
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00006178 return;
6179
Richard Smithf983f7f2015-10-13 00:23:25 +00006180 // We're only interested in cases where a local declaration is added to an
6181 // imported context.
6182 if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC)))
6183 return;
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00006184
Richard Smith0f4e2c42015-08-06 04:23:48 +00006185 assert(DC == DC->getPrimaryContext() && "added to non-primary context");
Douglas Gregor9f782892013-01-21 15:25:38 +00006186 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
Richard Smithe9a8bc32014-09-30 00:45:29 +00006187 assert(!WritingAST && "Already writing the AST!");
Richard Smithf983f7f2015-10-13 00:23:25 +00006188 if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) {
6189 // We're adding a visible declaration to a predefined decl context. Ensure
6190 // that we write out all of its lookup results so we don't get a nasty
6191 // surprise when we try to emit its lookup table.
6192 for (auto *Child : DC->decls())
Richard Smithc26d9742016-10-06 20:30:51 +00006193 DeclsToEmitEvenIfUnreferenced.push_back(Child);
Richard Smithf983f7f2015-10-13 00:23:25 +00006194 }
Richard Smithc26d9742016-10-06 20:30:51 +00006195 DeclsToEmitEvenIfUnreferenced.push_back(D);
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00006196}
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00006197
6198void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006199 if (Chain && Chain->isProcessingUpdateRecords()) return;
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00006200 assert(D->isImplicit());
Richard Smithf983f7f2015-10-13 00:23:25 +00006201
6202 // We're only interested in cases where a local declaration is added to an
6203 // imported context.
6204 if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD))
6205 return;
6206
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00006207 if (!isa<CXXMethodDecl>(D))
Richard Smithf983f7f2015-10-13 00:23:25 +00006208 return;
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00006209
6210 // A decl coming from PCH was modified.
John McCallf937c022011-10-07 06:10:15 +00006211 assert(RD->isCompleteDefinition());
Richard Smithe9a8bc32014-09-30 00:45:29 +00006212 assert(!WritingAST && "Already writing the AST!");
Aaron Ballman4f45b712014-03-21 15:22:56 +00006213 DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00006214}
Argyrios Kyrtzidis402dbbb2010-10-28 07:38:42 +00006215
Richard Smith564417a2014-03-20 21:47:22 +00006216void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006217 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smith9e2341d2015-03-23 03:25:59 +00006218 assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
6219 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00006220 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00006221 // If we don't already know the exception specification for this redecl
6222 // chain, add an update record for it.
6223 if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
6224 ->getType()
6225 ->castAs<FunctionProtoType>()
6226 ->getExceptionSpecType()))
6227 DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
6228 });
Richard Smith564417a2014-03-20 21:47:22 +00006229}
6230
Richard Smith1fa5d642013-05-11 05:45:24 +00006231void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006232 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smith1fa5d642013-05-11 05:45:24 +00006233 assert(!WritingAST && "Already writing the AST!");
Richard Smith9e2341d2015-03-23 03:25:59 +00006234 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00006235 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00006236 DeclUpdates[D].push_back(
6237 DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
6238 });
Richard Smith1fa5d642013-05-11 05:45:24 +00006239}
6240
Richard Smithf8134002015-03-10 01:41:22 +00006241void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
Richard Smith5b349582017-10-13 01:55:36 +00006242 const FunctionDecl *Delete,
6243 Expr *ThisArg) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006244 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smithf8134002015-03-10 01:41:22 +00006245 assert(!WritingAST && "Already writing the AST!");
6246 assert(Delete && "Not given an operator delete");
Richard Smith9e2341d2015-03-23 03:25:59 +00006247 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00006248 Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00006249 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete));
6250 });
Richard Smithf8134002015-03-10 01:41:22 +00006251}
6252
Sebastian Redlab238a72011-04-24 16:28:06 +00006253void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006254 if (Chain && Chain->isProcessingUpdateRecords()) return;
Douglas Gregor2fd3d402011-09-17 00:05:03 +00006255 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00006256 if (!D->isFromASTFile())
Sebastian Redlab238a72011-04-24 16:28:06 +00006257 return; // Declaration not imported from PCH.
6258
Richard Smith4d235792014-08-07 18:53:08 +00006259 // Implicit function decl from a PCH was defined.
6260 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
Sebastian Redlab238a72011-04-24 16:28:06 +00006261}
6262
Richard Smith891fc7f2017-12-05 01:31:47 +00006263void ASTWriter::VariableDefinitionInstantiated(const VarDecl *D) {
6264 if (Chain && Chain->isProcessingUpdateRecords()) return;
6265 assert(!WritingAST && "Already writing the AST!");
6266 if (!D->isFromASTFile())
6267 return;
6268
6269 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_VAR_DEFINITION));
6270}
6271
Richard Smithd28ac5b2014-03-22 23:33:22 +00006272void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006273 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smithd28ac5b2014-03-22 23:33:22 +00006274 assert(!WritingAST && "Already writing the AST!");
6275 if (!D->isFromASTFile())
6276 return;
6277
Richard Smith9e2341d2015-03-23 03:25:59 +00006278 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
Richard Smithd28ac5b2014-03-22 23:33:22 +00006279}
6280
Richard Smith891fc7f2017-12-05 01:31:47 +00006281void ASTWriter::InstantiationRequested(const ValueDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006282 if (Chain && Chain->isProcessingUpdateRecords()) return;
Douglas Gregor2fd3d402011-09-17 00:05:03 +00006283 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00006284 if (!D->isFromASTFile())
Sebastian Redl2ac2c722011-04-29 08:19:30 +00006285 return;
6286
6287 // Since the actual instantiation is delayed, this really means that we need
6288 // to update the instantiation location.
Richard Smith891fc7f2017-12-05 01:31:47 +00006289 SourceLocation POI;
6290 if (auto *VD = dyn_cast<VarDecl>(D))
6291 POI = VD->getPointOfInstantiation();
6292 else
6293 POI = cast<FunctionDecl>(D)->getPointOfInstantiation();
6294 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_POINT_OF_INSTANTIATION, POI));
Sebastian Redl2ac2c722011-04-29 08:19:30 +00006295}
6296
John McCall32791cc2016-01-06 22:34:54 +00006297void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006298 if (Chain && Chain->isProcessingUpdateRecords()) return;
John McCall32791cc2016-01-06 22:34:54 +00006299 assert(!WritingAST && "Already writing the AST!");
6300 if (!D->isFromASTFile())
6301 return;
6302
6303 DeclUpdates[D].push_back(
6304 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D));
6305}
6306
Richard Smith4b054b22016-08-24 21:25:37 +00006307void ASTWriter::DefaultMemberInitializerInstantiated(const FieldDecl *D) {
6308 assert(!WritingAST && "Already writing the AST!");
6309 if (!D->isFromASTFile())
6310 return;
6311
6312 DeclUpdates[D].push_back(
6313 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER, D));
6314}
6315
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00006316void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
6317 const ObjCInterfaceDecl *IFD) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006318 if (Chain && Chain->isProcessingUpdateRecords()) return;
Douglas Gregor2fd3d402011-09-17 00:05:03 +00006319 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00006320 if (!IFD->isFromASTFile())
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00006321 return; // Declaration not imported from PCH.
Douglas Gregor404cdde2012-01-27 01:47:08 +00006322
6323 assert(IFD->getDefinition() && "Category on a class without a definition?");
6324 ObjCClassesWithCategories.insert(
6325 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00006326}
Argyrios Kyrtzidisb97a4022011-11-12 21:07:46 +00006327
Eli Friedman276dd182013-09-05 00:02:25 +00006328void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006329 if (Chain && Chain->isProcessingUpdateRecords()) return;
Eli Friedman276dd182013-09-05 00:02:25 +00006330 assert(!WritingAST && "Already writing the AST!");
Vassil Vassilev928c8252016-04-28 14:13:28 +00006331
6332 // If there is *any* declaration of the entity that's not from an AST file,
6333 // we can skip writing the update record. We make sure that isUsed() triggers
6334 // completion of the redeclaration chain of the entity.
6335 for (auto Prev = D->getMostRecentDecl(); Prev; Prev = Prev->getPreviousDecl())
6336 if (IsLocalDecl(Prev))
6337 return;
Eli Friedman276dd182013-09-05 00:02:25 +00006338
Aaron Ballman4f45b712014-03-21 15:22:56 +00006339 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
Eli Friedman276dd182013-09-05 00:02:25 +00006340}
Alexey Bataev97720002014-11-11 04:05:39 +00006341
6342void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006343 if (Chain && Chain->isProcessingUpdateRecords()) return;
Alexey Bataev97720002014-11-11 04:05:39 +00006344 assert(!WritingAST && "Already writing the AST!");
6345 if (!D->isFromASTFile())
6346 return;
6347
6348 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE));
6349}
Richard Smith65ebb4a2015-03-26 04:09:53 +00006350
Dmitry Polukhind69b5052016-05-09 14:59:13 +00006351void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
6352 const Attr *Attr) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006353 if (Chain && Chain->isProcessingUpdateRecords()) return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00006354 assert(!WritingAST && "Already writing the AST!");
6355 if (!D->isFromASTFile())
6356 return;
6357
Dmitry Polukhind69b5052016-05-09 14:59:13 +00006358 DeclUpdates[D].push_back(
6359 DeclUpdate(UPD_DECL_MARKED_OPENMP_DECLARETARGET, Attr));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00006360}
6361
Richard Smith4caa4492015-05-15 02:34:32 +00006362void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006363 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smith65ebb4a2015-03-26 04:09:53 +00006364 assert(!WritingAST && "Already writing the AST!");
6365 assert(D->isHidden() && "expected a hidden declaration");
Richard Smith4caa4492015-05-15 02:34:32 +00006366 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M));
Richard Smith65ebb4a2015-03-26 04:09:53 +00006367}
Alex Denisovfde64952015-06-26 05:28:36 +00006368
6369void ASTWriter::AddedAttributeToRecord(const Attr *Attr,
6370 const RecordDecl *Record) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006371 if (Chain && Chain->isProcessingUpdateRecords()) return;
Alex Denisovfde64952015-06-26 05:28:36 +00006372 assert(!WritingAST && "Already writing the AST!");
6373 if (!Record->isFromASTFile())
6374 return;
6375 DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr));
6376}
Richard Smithc26d9742016-10-06 20:30:51 +00006377
6378void ASTWriter::AddedCXXTemplateSpecialization(
6379 const ClassTemplateDecl *TD, const ClassTemplateSpecializationDecl *D) {
6380 assert(!WritingAST && "Already writing the AST!");
6381
6382 if (!TD->getFirstDecl()->isFromASTFile())
6383 return;
6384 if (Chain && Chain->isProcessingUpdateRecords())
6385 return;
6386
6387 DeclsToEmitEvenIfUnreferenced.push_back(D);
6388}
6389
6390void ASTWriter::AddedCXXTemplateSpecialization(
6391 const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) {
6392 assert(!WritingAST && "Already writing the AST!");
6393
6394 if (!TD->getFirstDecl()->isFromASTFile())
6395 return;
6396 if (Chain && Chain->isProcessingUpdateRecords())
6397 return;
6398
6399 DeclsToEmitEvenIfUnreferenced.push_back(D);
6400}
6401
6402void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
6403 const FunctionDecl *D) {
6404 assert(!WritingAST && "Already writing the AST!");
6405
6406 if (!TD->getFirstDecl()->isFromASTFile())
6407 return;
6408 if (Chain && Chain->isProcessingUpdateRecords())
6409 return;
6410
6411 DeclsToEmitEvenIfUnreferenced.push_back(D);
6412}