blob: 8247f5a84ecaabc122d5c87c6e9b6c2e91d19c93 [file] [log] [blame]
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001//===- ASTWriter.cpp - AST File Writer ------------------------------------===//
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Douglas Gregoref84c4b2009-04-09 22:27:44 +00006//
7//===----------------------------------------------------------------------===//
8//
Sebastian Redl55c0ad52010-08-18 23:56:21 +00009// This file defines the ASTWriter class, which writes AST files.
Douglas Gregoref84c4b2009-04-09 22:27:44 +000010//
11//===----------------------------------------------------------------------===//
12
Alexey Bataevb6e70842019-12-16 15:54:17 -050013#include "clang/AST/OpenMPClause.h"
John McCall2ac702a2019-12-14 03:17:03 -050014#include "clang/Serialization/ASTRecordWriter.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"
John McCalld505e572019-12-13 21:54:44 -050018#include "clang/AST/AbstractTypeWriter.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000019#include "clang/AST/ASTContext.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000020#include "clang/AST/ASTUnresolvedSet.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000021#include "clang/AST/Attr.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000022#include "clang/AST/Decl.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000023#include "clang/AST/DeclBase.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000024#include "clang/AST/DeclCXX.h"
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +000025#include "clang/AST/DeclContextInternals.h"
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +000026#include "clang/AST/DeclFriend.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000027#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "clang/AST/DeclTemplate.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000029#include "clang/AST/DeclarationName.h"
Douglas Gregorfeb84b02009-04-14 21:18:50 +000030#include "clang/AST/Expr.h"
John McCallbfd822c2010-08-24 07:32:53 +000031#include "clang/AST/ExprCXX.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000032#include "clang/AST/LambdaCapture.h"
33#include "clang/AST/NestedNameSpecifier.h"
34#include "clang/AST/RawCommentList.h"
35#include "clang/AST/TemplateName.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000036#include "clang/AST/Type.h"
John McCall8f115c62009-10-16 21:56:05 +000037#include "clang/AST/TypeLocVisitor.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000038#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000039#include "clang/Basic/DiagnosticOptions.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000040#include "clang/Basic/FileManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000041#include "clang/Basic/FileSystemOptions.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000042#include "clang/Basic/IdentifierTable.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000043#include "clang/Basic/LLVM.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000044#include "clang/Basic/Lambda.h"
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +000045#include "clang/Basic/LangOptions.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"
Chandler Carruth3a022472012-12-04 09:13:33 +000056#include "clang/Lex/HeaderSearch.h"
57#include "clang/Lex/HeaderSearchOptions.h"
58#include "clang/Lex/MacroInfo.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000059#include "clang/Lex/ModuleMap.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000060#include "clang/Lex/PreprocessingRecord.h"
61#include "clang/Lex/Preprocessor.h"
62#include "clang/Lex/PreprocessorOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000063#include "clang/Lex/Token.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000064#include "clang/Sema/IdentifierResolver.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000065#include "clang/Sema/ObjCMethodList.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000066#include "clang/Sema/Sema.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000067#include "clang/Sema/Weak.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000068#include "clang/Serialization/ASTReader.h"
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000069#include "clang/Serialization/InMemoryModuleCache.h"
Duncan P. N. Exon Smithf7170d12019-11-21 18:49:05 -080070#include "clang/Serialization/ModuleFile.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"
Ilya Biryukov45643102018-07-09 11:33:23 +000082#include "llvm/ADT/ScopeExit.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000083#include "llvm/ADT/SmallSet.h"
84#include "llvm/ADT/SmallString.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000085#include "llvm/ADT/SmallVector.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000086#include "llvm/ADT/StringMap.h"
87#include "llvm/ADT/StringRef.h"
Francis Visoiu Mistrihe0308272019-07-03 22:40:07 +000088#include "llvm/Bitstream/BitCodes.h"
89#include "llvm/Bitstream/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"
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +000092#include "llvm/Support/DJB.h"
Eugene Zelenkob7d89102017-11-11 00:08:50 +000093#include "llvm/Support/Endian.h"
Justin Bognere1c147c2014-03-28 22:03:19 +000094#include "llvm/Support/EndianStream.h"
George Rimarc39f5492017-01-17 15:45:31 +000095#include "llvm/Support/Error.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000096#include "llvm/Support/ErrorHandling.h"
Douglas Gregora7f71a92009-04-10 03:52:48 +000097#include "llvm/Support/MemoryBuffer.h"
Justin Bognerbb094f02014-04-18 19:57:06 +000098#include "llvm/Support/OnDiskHashTable.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000099#include "llvm/Support/Path.h"
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +0000100#include "llvm/Support/SHA1.h"
Pavel Labathd8c62902018-06-11 10:28:04 +0000101#include "llvm/Support/VersionTuple.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000102#include "llvm/Support/raw_ostream.h"
Douglas Gregor925296b2011-07-19 16:10:42 +0000103#include <algorithm>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000104#include <cassert>
105#include <cstdint>
106#include <cstdlib>
107#include <cstring>
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000108#include <ctime>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000109#include <deque>
110#include <limits>
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000111#include <memory>
112#include <queue>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000113#include <tuple>
Douglas Gregor925296b2011-07-19 16:10:42 +0000114#include <utility>
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000115#include <vector>
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +0000116
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000117using namespace clang;
Sebastian Redl539c5062010-08-18 23:57:32 +0000118using namespace clang::serialization;
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000119
Sebastian Redl3df5a082010-07-30 17:03:48 +0000120template <typename T, typename Allocator>
Reid Kleckner012665e2015-05-21 00:13:09 +0000121static StringRef bytes(const std::vector<T, Allocator> &v) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000122 if (v.empty()) return StringRef();
123 return StringRef(reinterpret_cast<const char*>(&v[0]),
Benjamin Kramerd47a12a2011-04-24 17:44:50 +0000124 sizeof(T) * v.size());
Sebastian Redl3df5a082010-07-30 17:03:48 +0000125}
Benjamin Kramerd47a12a2011-04-24 17:44:50 +0000126
127template <typename T>
Reid Kleckner012665e2015-05-21 00:13:09 +0000128static StringRef bytes(const SmallVectorImpl<T> &v) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000129 return StringRef(reinterpret_cast<const char*>(v.data()),
Benjamin Kramerd47a12a2011-04-24 17:44:50 +0000130 sizeof(T) * v.size());
Sebastian Redl3df5a082010-07-30 17:03:48 +0000131}
132
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000133//===----------------------------------------------------------------------===//
134// Type serialization
135//===----------------------------------------------------------------------===//
Chris Lattner7099dbc2009-04-27 06:16:06 +0000136
John McCalld505e572019-12-13 21:54:44 -0500137static TypeCode getTypeCodeForTypeClass(Type::TypeClass id) {
138 switch (id) {
139#define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
140 case Type::CLASS_ID: return TYPE_##CODE_ID;
141#include "clang/Serialization/TypeBitCodes.def"
142 case Type::Builtin:
143 llvm_unreachable("shouldn't be serializing a builtin type this way");
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000144 }
John McCalld505e572019-12-13 21:54:44 -0500145 llvm_unreachable("bad type kind");
Xiuli Pan9c14e282016-01-09 12:53:17 +0000146}
147
John McCall8f115c62009-10-16 21:56:05 +0000148namespace {
149
John McCalld505e572019-12-13 21:54:44 -0500150class ASTTypeWriter {
151 ASTWriter &Writer;
152 ASTWriter::RecordData Record;
153 ASTRecordWriter BasicWriter;
154
155public:
156 ASTTypeWriter(ASTWriter &Writer)
157 : Writer(Writer), BasicWriter(Writer, Record) {}
158
159 uint64_t write(QualType T) {
160 if (T.hasLocalNonFastQualifiers()) {
161 Qualifiers Qs = T.getLocalQualifiers();
162 BasicWriter.writeQualType(T.getLocalUnqualifiedType());
163 BasicWriter.writeQualifiers(Qs);
164 return BasicWriter.Emit(TYPE_EXT_QUAL, Writer.getTypeExtQualAbbrev());
165 }
166
167 const Type *typePtr = T.getTypePtr();
168 serialization::AbstractTypeWriter<ASTRecordWriter> atw(BasicWriter);
169 atw.write(typePtr);
170 return BasicWriter.Emit(getTypeCodeForTypeClass(typePtr->getTypeClass()),
171 /*abbrev*/ 0);
172 }
173};
174
John McCall8f115c62009-10-16 21:56:05 +0000175class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
Richard Smith290d8012016-04-06 17:06:00 +0000176 ASTRecordWriter &Record;
John McCall8f115c62009-10-16 21:56:05 +0000177
178public:
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000179 TypeLocWriter(ASTRecordWriter &Record) : Record(Record) {}
John McCall8f115c62009-10-16 21:56:05 +0000180
John McCall17001972009-10-18 01:05:36 +0000181#define ABSTRACT_TYPELOC(CLASS, PARENT)
John McCall8f115c62009-10-16 21:56:05 +0000182#define TYPELOC(CLASS, PARENT) \
John McCall17001972009-10-18 01:05:36 +0000183 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +0000184#include "clang/AST/TypeLocNodes.def"
185
John McCall17001972009-10-18 01:05:36 +0000186 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
187 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
John McCall8f115c62009-10-16 21:56:05 +0000188};
189
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000190} // namespace
John McCall8f115c62009-10-16 21:56:05 +0000191
John McCall17001972009-10-18 01:05:36 +0000192void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
193 // nothing to do
John McCall8f115c62009-10-16 21:56:05 +0000194}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000195
John McCall17001972009-10-18 01:05:36 +0000196void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000197 Record.AddSourceLocation(TL.getBuiltinLoc());
Douglas Gregorc9b7a592010-01-18 18:04:31 +0000198 if (TL.needsExtraLocalData()) {
Faisal Vali090da2d2018-01-01 18:23:28 +0000199 Record.push_back(TL.getWrittenTypeSpec());
200 Record.push_back(TL.getWrittenSignSpec());
201 Record.push_back(TL.getWrittenWidthSpec());
Douglas Gregorc9b7a592010-01-18 18:04:31 +0000202 Record.push_back(TL.hasModeAttr());
203 }
John McCall8f115c62009-10-16 21:56:05 +0000204}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000205
John McCall17001972009-10-18 01:05:36 +0000206void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000207 Record.AddSourceLocation(TL.getNameLoc());
John McCall8f115c62009-10-16 21:56:05 +0000208}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000209
John McCall17001972009-10-18 01:05:36 +0000210void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000211 Record.AddSourceLocation(TL.getStarLoc());
John McCall8f115c62009-10-16 21:56:05 +0000212}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000213
Reid Kleckner8a365022013-06-24 17:51:48 +0000214void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
215 // nothing to do
216}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000217
Reid Kleckner0503a872013-12-05 01:23:43 +0000218void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
219 // nothing to do
220}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000221
John McCall17001972009-10-18 01:05:36 +0000222void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000223 Record.AddSourceLocation(TL.getCaretLoc());
John McCall8f115c62009-10-16 21:56:05 +0000224}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000225
John McCall17001972009-10-18 01:05:36 +0000226void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000227 Record.AddSourceLocation(TL.getAmpLoc());
John McCall8f115c62009-10-16 21:56:05 +0000228}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000229
John McCall17001972009-10-18 01:05:36 +0000230void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000231 Record.AddSourceLocation(TL.getAmpAmpLoc());
John McCall8f115c62009-10-16 21:56:05 +0000232}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000233
John McCall17001972009-10-18 01:05:36 +0000234void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000235 Record.AddSourceLocation(TL.getStarLoc());
236 Record.AddTypeSourceInfo(TL.getClassTInfo());
John McCall8f115c62009-10-16 21:56:05 +0000237}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000238
John McCall17001972009-10-18 01:05:36 +0000239void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000240 Record.AddSourceLocation(TL.getLBracketLoc());
241 Record.AddSourceLocation(TL.getRBracketLoc());
John McCall17001972009-10-18 01:05:36 +0000242 Record.push_back(TL.getSizeExpr() ? 1 : 0);
243 if (TL.getSizeExpr())
Richard Smith290d8012016-04-06 17:06:00 +0000244 Record.AddStmt(TL.getSizeExpr());
John McCall8f115c62009-10-16 21:56:05 +0000245}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000246
John McCall17001972009-10-18 01:05:36 +0000247void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
248 VisitArrayTypeLoc(TL);
249}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000250
John McCall17001972009-10-18 01:05:36 +0000251void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
252 VisitArrayTypeLoc(TL);
253}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000254
John McCall17001972009-10-18 01:05:36 +0000255void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
256 VisitArrayTypeLoc(TL);
257}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000258
John McCall17001972009-10-18 01:05:36 +0000259void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
260 DependentSizedArrayTypeLoc TL) {
261 VisitArrayTypeLoc(TL);
262}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000263
Andrew Gozillon572bbb02017-10-02 06:25:51 +0000264void TypeLocWriter::VisitDependentAddressSpaceTypeLoc(
265 DependentAddressSpaceTypeLoc TL) {
266 Record.AddSourceLocation(TL.getAttrNameLoc());
267 SourceRange range = TL.getAttrOperandParensRange();
268 Record.AddSourceLocation(range.getBegin());
269 Record.AddSourceLocation(range.getEnd());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000270 Record.AddStmt(TL.getAttrExprOperand());
Andrew Gozillon572bbb02017-10-02 06:25:51 +0000271}
272
John McCall17001972009-10-18 01:05:36 +0000273void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
274 DependentSizedExtVectorTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000275 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000276}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000277
John McCall17001972009-10-18 01:05:36 +0000278void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000279 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000280}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000281
Erich Keanef702b022018-07-13 19:46:04 +0000282void TypeLocWriter::VisitDependentVectorTypeLoc(
283 DependentVectorTypeLoc TL) {
284 Record.AddSourceLocation(TL.getNameLoc());
285}
286
John McCall17001972009-10-18 01:05:36 +0000287void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000288 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000289}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000290
John McCall17001972009-10-18 01:05:36 +0000291void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000292 Record.AddSourceLocation(TL.getLocalRangeBegin());
293 Record.AddSourceLocation(TL.getLParenLoc());
294 Record.AddSourceLocation(TL.getRParenLoc());
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +0000295 Record.AddSourceRange(TL.getExceptionSpecRange());
Richard Smith69c82bf2016-04-01 22:52:03 +0000296 Record.AddSourceLocation(TL.getLocalRangeEnd());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +0000297 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000298 Record.AddDeclRef(TL.getParam(i));
John McCall17001972009-10-18 01:05:36 +0000299}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000300
John McCall17001972009-10-18 01:05:36 +0000301void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
302 VisitFunctionTypeLoc(TL);
303}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000304
John McCall17001972009-10-18 01:05:36 +0000305void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
306 VisitFunctionTypeLoc(TL);
307}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000308
John McCallb96ec562009-12-04 22:46:56 +0000309void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000310 Record.AddSourceLocation(TL.getNameLoc());
John McCallb96ec562009-12-04 22:46:56 +0000311}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000312
John McCall17001972009-10-18 01:05:36 +0000313void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000314 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000315}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000316
Manman Rene6be26c2016-09-13 17:25:08 +0000317void TypeLocWriter::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
318 if (TL.getNumProtocols()) {
319 Record.AddSourceLocation(TL.getProtocolLAngleLoc());
320 Record.AddSourceLocation(TL.getProtocolRAngleLoc());
321 }
322 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
323 Record.AddSourceLocation(TL.getProtocolLoc(i));
324}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000325
John McCall17001972009-10-18 01:05:36 +0000326void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000327 Record.AddSourceLocation(TL.getTypeofLoc());
328 Record.AddSourceLocation(TL.getLParenLoc());
329 Record.AddSourceLocation(TL.getRParenLoc());
John McCall17001972009-10-18 01:05:36 +0000330}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000331
John McCall17001972009-10-18 01:05:36 +0000332void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000333 Record.AddSourceLocation(TL.getTypeofLoc());
334 Record.AddSourceLocation(TL.getLParenLoc());
335 Record.AddSourceLocation(TL.getRParenLoc());
336 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
John McCall17001972009-10-18 01:05:36 +0000337}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000338
John McCall17001972009-10-18 01:05:36 +0000339void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000340 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000341}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000342
Alexis Hunte852b102011-05-24 22:41:36 +0000343void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000344 Record.AddSourceLocation(TL.getKWLoc());
345 Record.AddSourceLocation(TL.getLParenLoc());
346 Record.AddSourceLocation(TL.getRParenLoc());
347 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
Alexis Hunte852b102011-05-24 22:41:36 +0000348}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000349
Richard Smith30482bc2011-02-20 03:19:35 +0000350void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000351 Record.AddSourceLocation(TL.getNameLoc());
Richard Smith30482bc2011-02-20 03:19:35 +0000352}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000353
Richard Smith600b5262017-01-26 20:40:47 +0000354void TypeLocWriter::VisitDeducedTemplateSpecializationTypeLoc(
355 DeducedTemplateSpecializationTypeLoc TL) {
356 Record.AddSourceLocation(TL.getTemplateNameLoc());
357}
358
John McCall17001972009-10-18 01:05:36 +0000359void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000360 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000361}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000362
John McCall17001972009-10-18 01:05:36 +0000363void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000364 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000365}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000366
John McCall81904512011-01-06 01:58:22 +0000367void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
Richard Smithe43e2b32018-08-20 21:47:29 +0000368 Record.AddAttr(TL.getAttr());
John McCall81904512011-01-06 01:58:22 +0000369}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000370
John McCall17001972009-10-18 01:05:36 +0000371void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000372 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000373}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000374
John McCallcebee162009-10-18 09:09:24 +0000375void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
376 SubstTemplateTypeParmTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000377 Record.AddSourceLocation(TL.getNameLoc());
John McCallcebee162009-10-18 09:09:24 +0000378}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000379
Douglas Gregorada4b792011-01-14 02:55:32 +0000380void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
381 SubstTemplateTypeParmPackTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000382 Record.AddSourceLocation(TL.getNameLoc());
Douglas Gregorada4b792011-01-14 02:55:32 +0000383}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000384
John McCall17001972009-10-18 01:05:36 +0000385void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
386 TemplateSpecializationTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000387 Record.AddSourceLocation(TL.getTemplateKeywordLoc());
388 Record.AddSourceLocation(TL.getTemplateNameLoc());
389 Record.AddSourceLocation(TL.getLAngleLoc());
390 Record.AddSourceLocation(TL.getRAngleLoc());
John McCall0ad16662009-10-29 08:12:44 +0000391 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000392 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
393 TL.getArgLoc(i).getLocInfo());
John McCall17001972009-10-18 01:05:36 +0000394}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000395
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000396void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000397 Record.AddSourceLocation(TL.getLParenLoc());
398 Record.AddSourceLocation(TL.getRParenLoc());
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000399}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000400
Leonard Chanc72aaf62019-05-07 03:20:17 +0000401void TypeLocWriter::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
402 Record.AddSourceLocation(TL.getExpansionLoc());
403}
404
Abramo Bagnara6150c882010-05-11 21:36:43 +0000405void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000406 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
407 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
John McCall17001972009-10-18 01:05:36 +0000408}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000409
John McCalle78aac42010-03-10 03:28:59 +0000410void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000411 Record.AddSourceLocation(TL.getNameLoc());
John McCalle78aac42010-03-10 03:28:59 +0000412}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000413
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +0000414void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000415 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
416 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
417 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000418}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000419
John McCallc392f372010-06-11 00:33:02 +0000420void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
421 DependentTemplateSpecializationTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000422 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
423 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
424 Record.AddSourceLocation(TL.getTemplateKeywordLoc());
425 Record.AddSourceLocation(TL.getTemplateNameLoc());
426 Record.AddSourceLocation(TL.getLAngleLoc());
427 Record.AddSourceLocation(TL.getRAngleLoc());
John McCallc392f372010-06-11 00:33:02 +0000428 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
Richard Smith69c82bf2016-04-01 22:52:03 +0000429 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
430 TL.getArgLoc(I).getLocInfo());
John McCallc392f372010-06-11 00:33:02 +0000431}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000432
Douglas Gregord2fa7662010-12-20 02:24:11 +0000433void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000434 Record.AddSourceLocation(TL.getEllipsisLoc());
Douglas Gregord2fa7662010-12-20 02:24:11 +0000435}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000436
John McCall17001972009-10-18 01:05:36 +0000437void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000438 Record.AddSourceLocation(TL.getNameLoc());
John McCall8b07ec22010-05-15 11:32:37 +0000439}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000440
John McCall8b07ec22010-05-15 11:32:37 +0000441void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
442 Record.push_back(TL.hasBaseTypeAsWritten());
Richard Smith69c82bf2016-04-01 22:52:03 +0000443 Record.AddSourceLocation(TL.getTypeArgsLAngleLoc());
444 Record.AddSourceLocation(TL.getTypeArgsRAngleLoc());
Douglas Gregore9d95f12015-07-07 03:57:35 +0000445 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000446 Record.AddTypeSourceInfo(TL.getTypeArgTInfo(i));
447 Record.AddSourceLocation(TL.getProtocolLAngleLoc());
448 Record.AddSourceLocation(TL.getProtocolRAngleLoc());
John McCall17001972009-10-18 01:05:36 +0000449 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000450 Record.AddSourceLocation(TL.getProtocolLoc(i));
John McCall8f115c62009-10-16 21:56:05 +0000451}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000452
John McCallfc93cf92009-10-22 22:37:11 +0000453void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000454 Record.AddSourceLocation(TL.getStarLoc());
John McCallfc93cf92009-10-22 22:37:11 +0000455}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000456
Eli Friedman0dfb8892011-10-06 23:00:33 +0000457void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000458 Record.AddSourceLocation(TL.getKWLoc());
459 Record.AddSourceLocation(TL.getLParenLoc());
460 Record.AddSourceLocation(TL.getRParenLoc());
Eli Friedman0dfb8892011-10-06 23:00:33 +0000461}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000462
Xiuli Pan9c14e282016-01-09 12:53:17 +0000463void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000464 Record.AddSourceLocation(TL.getKWLoc());
Xiuli Pan9c14e282016-01-09 12:53:17 +0000465}
John McCall8f115c62009-10-16 21:56:05 +0000466
Richard Smith01b2cb42014-07-26 06:37:51 +0000467void ASTWriter::WriteTypeAbbrevs() {
468 using namespace llvm;
469
David Blaikieb44f0bf2017-01-04 22:36:43 +0000470 std::shared_ptr<BitCodeAbbrev> Abv;
Richard Smith01b2cb42014-07-26 06:37:51 +0000471
472 // Abbreviation for TYPE_EXT_QUAL
David Blaikieb44f0bf2017-01-04 22:36:43 +0000473 Abv = std::make_shared<BitCodeAbbrev>();
Richard Smith01b2cb42014-07-26 06:37:51 +0000474 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
475 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
476 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals
David Blaikieb44f0bf2017-01-04 22:36:43 +0000477 TypeExtQualAbbrev = Stream.EmitAbbrev(std::move(Abv));
Richard Smith01b2cb42014-07-26 06:37:51 +0000478
479 // Abbreviation for TYPE_FUNCTION_PROTO
David Blaikieb44f0bf2017-01-04 22:36:43 +0000480 Abv = std::make_shared<BitCodeAbbrev>();
Richard Smith01b2cb42014-07-26 06:37:51 +0000481 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_FUNCTION_PROTO));
482 // FunctionType
483 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ReturnType
484 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NoReturn
485 Abv->Add(BitCodeAbbrevOp(0)); // HasRegParm
486 Abv->Add(BitCodeAbbrevOp(0)); // RegParm
487 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // CC
488 Abv->Add(BitCodeAbbrevOp(0)); // ProducesResult
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +0000489 Abv->Add(BitCodeAbbrevOp(0)); // NoCallerSavedRegs
Oren Ben Simhon220671a2018-03-17 13:31:35 +0000490 Abv->Add(BitCodeAbbrevOp(0)); // NoCfCheck
Richard Smith01b2cb42014-07-26 06:37:51 +0000491 // FunctionProtoType
492 Abv->Add(BitCodeAbbrevOp(0)); // IsVariadic
493 Abv->Add(BitCodeAbbrevOp(0)); // HasTrailingReturn
494 Abv->Add(BitCodeAbbrevOp(0)); // TypeQuals
495 Abv->Add(BitCodeAbbrevOp(0)); // RefQualifier
496 Abv->Add(BitCodeAbbrevOp(EST_None)); // ExceptionSpec
497 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // NumParams
498 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
499 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Params
David Blaikieb44f0bf2017-01-04 22:36:43 +0000500 TypeFunctionProtoAbbrev = Stream.EmitAbbrev(std::move(Abv));
Richard Smith01b2cb42014-07-26 06:37:51 +0000501}
502
Chris Lattner19cea4e2009-04-22 05:57:30 +0000503//===----------------------------------------------------------------------===//
Sebastian Redl55c0ad52010-08-18 23:56:21 +0000504// ASTWriter Implementation
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000505//===----------------------------------------------------------------------===//
506
Chris Lattner28fa4e62009-04-26 22:26:21 +0000507static void EmitBlockID(unsigned ID, const char *Name,
508 llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000509 ASTWriter::RecordDataImpl &Record) {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000510 Record.clear();
511 Record.push_back(ID);
512 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
513
514 // Emit the block name if present.
Craig Toppera13603a2014-05-22 05:54:18 +0000515 if (!Name || Name[0] == 0)
516 return;
Chris Lattner28fa4e62009-04-26 22:26:21 +0000517 Record.clear();
518 while (*Name)
519 Record.push_back(*Name++);
520 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
521}
522
523static void EmitRecordID(unsigned ID, const char *Name,
524 llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000525 ASTWriter::RecordDataImpl &Record) {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000526 Record.clear();
527 Record.push_back(ID);
528 while (*Name)
529 Record.push_back(*Name++);
530 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000531}
532
533static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000534 ASTWriter::RecordDataImpl &Record) {
Sebastian Redl539c5062010-08-18 23:57:32 +0000535#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
Chris Lattnerccac3a62009-04-27 00:49:53 +0000536 RECORD(STMT_STOP);
537 RECORD(STMT_NULL_PTR);
Richard Smith01b2cb42014-07-26 06:37:51 +0000538 RECORD(STMT_REF_PTR);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000539 RECORD(STMT_NULL);
540 RECORD(STMT_COMPOUND);
541 RECORD(STMT_CASE);
542 RECORD(STMT_DEFAULT);
543 RECORD(STMT_LABEL);
Richard Smithc202b282012-04-14 00:33:13 +0000544 RECORD(STMT_ATTRIBUTED);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000545 RECORD(STMT_IF);
546 RECORD(STMT_SWITCH);
547 RECORD(STMT_WHILE);
548 RECORD(STMT_DO);
549 RECORD(STMT_FOR);
550 RECORD(STMT_GOTO);
551 RECORD(STMT_INDIRECT_GOTO);
552 RECORD(STMT_CONTINUE);
553 RECORD(STMT_BREAK);
554 RECORD(STMT_RETURN);
555 RECORD(STMT_DECL);
Chad Rosierde70e0e2012-08-25 00:11:56 +0000556 RECORD(STMT_GCCASM);
Chad Rosiere30d4992012-08-24 23:51:02 +0000557 RECORD(STMT_MSASM);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000558 RECORD(EXPR_PREDEFINED);
559 RECORD(EXPR_DECL_REF);
560 RECORD(EXPR_INTEGER_LITERAL);
561 RECORD(EXPR_FLOATING_LITERAL);
562 RECORD(EXPR_IMAGINARY_LITERAL);
563 RECORD(EXPR_STRING_LITERAL);
564 RECORD(EXPR_CHARACTER_LITERAL);
565 RECORD(EXPR_PAREN);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000566 RECORD(EXPR_PAREN_LIST);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000567 RECORD(EXPR_UNARY_OPERATOR);
568 RECORD(EXPR_SIZEOF_ALIGN_OF);
569 RECORD(EXPR_ARRAY_SUBSCRIPT);
570 RECORD(EXPR_CALL);
571 RECORD(EXPR_MEMBER);
572 RECORD(EXPR_BINARY_OPERATOR);
573 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
574 RECORD(EXPR_CONDITIONAL_OPERATOR);
575 RECORD(EXPR_IMPLICIT_CAST);
576 RECORD(EXPR_CSTYLE_CAST);
577 RECORD(EXPR_COMPOUND_LITERAL);
578 RECORD(EXPR_EXT_VECTOR_ELEMENT);
579 RECORD(EXPR_INIT_LIST);
580 RECORD(EXPR_DESIGNATED_INIT);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000581 RECORD(EXPR_DESIGNATED_INIT_UPDATE);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000582 RECORD(EXPR_IMPLICIT_VALUE_INIT);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000583 RECORD(EXPR_NO_INIT);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000584 RECORD(EXPR_VA_ARG);
585 RECORD(EXPR_ADDR_LABEL);
586 RECORD(EXPR_STMT);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000587 RECORD(EXPR_CHOOSE);
588 RECORD(EXPR_GNU_NULL);
589 RECORD(EXPR_SHUFFLE_VECTOR);
590 RECORD(EXPR_BLOCK);
Peter Collingbourne91147592011-04-15 00:35:48 +0000591 RECORD(EXPR_GENERIC_SELECTION);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000592 RECORD(EXPR_OBJC_STRING_LITERAL);
Patrick Beard0caa3942012-04-19 00:25:12 +0000593 RECORD(EXPR_OBJC_BOXED_EXPRESSION);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000594 RECORD(EXPR_OBJC_ARRAY_LITERAL);
595 RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000596 RECORD(EXPR_OBJC_ENCODE);
597 RECORD(EXPR_OBJC_SELECTOR_EXPR);
598 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
599 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
600 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
601 RECORD(EXPR_OBJC_KVC_REF_EXPR);
602 RECORD(EXPR_OBJC_MESSAGE_EXPR);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000603 RECORD(STMT_OBJC_FOR_COLLECTION);
604 RECORD(STMT_OBJC_CATCH);
605 RECORD(STMT_OBJC_FINALLY);
606 RECORD(STMT_OBJC_AT_TRY);
607 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
608 RECORD(STMT_OBJC_AT_THROW);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000609 RECORD(EXPR_OBJC_BOOL_LITERAL);
Richard Smith01b2cb42014-07-26 06:37:51 +0000610 RECORD(STMT_CXX_CATCH);
611 RECORD(STMT_CXX_TRY);
612 RECORD(STMT_CXX_FOR_RANGE);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000613 RECORD(EXPR_CXX_OPERATOR_CALL);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000614 RECORD(EXPR_CXX_MEMBER_CALL);
Richard Smith778dc0f2019-10-19 00:04:38 +0000615 RECORD(EXPR_CXX_REWRITTEN_BINARY_OPERATOR);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000616 RECORD(EXPR_CXX_CONSTRUCT);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000617 RECORD(EXPR_CXX_TEMPORARY_OBJECT);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000618 RECORD(EXPR_CXX_STATIC_CAST);
619 RECORD(EXPR_CXX_DYNAMIC_CAST);
620 RECORD(EXPR_CXX_REINTERPRET_CAST);
621 RECORD(EXPR_CXX_CONST_CAST);
622 RECORD(EXPR_CXX_FUNCTIONAL_CAST);
Richard Smithc67fdd42012-03-07 08:35:16 +0000623 RECORD(EXPR_USER_DEFINED_LITERAL);
Richard Smithcc1b96d2013-06-12 22:31:48 +0000624 RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000625 RECORD(EXPR_CXX_BOOL_LITERAL);
626 RECORD(EXPR_CXX_NULL_PTR_LITERAL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000627 RECORD(EXPR_CXX_TYPEID_EXPR);
628 RECORD(EXPR_CXX_TYPEID_TYPE);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000629 RECORD(EXPR_CXX_THIS);
630 RECORD(EXPR_CXX_THROW);
631 RECORD(EXPR_CXX_DEFAULT_ARG);
Richard Smith01b2cb42014-07-26 06:37:51 +0000632 RECORD(EXPR_CXX_DEFAULT_INIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000633 RECORD(EXPR_CXX_BIND_TEMPORARY);
634 RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
635 RECORD(EXPR_CXX_NEW);
636 RECORD(EXPR_CXX_DELETE);
637 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
638 RECORD(EXPR_EXPR_WITH_CLEANUPS);
639 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
640 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
641 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
642 RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
643 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
Richard Smith01b2cb42014-07-26 06:37:51 +0000644 RECORD(EXPR_CXX_EXPRESSION_TRAIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000645 RECORD(EXPR_CXX_NOEXCEPT);
646 RECORD(EXPR_OPAQUE_VALUE);
Richard Smith01b2cb42014-07-26 06:37:51 +0000647 RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR);
648 RECORD(EXPR_TYPE_TRAIT);
649 RECORD(EXPR_ARRAY_TYPE_TRAIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000650 RECORD(EXPR_PACK_EXPANSION);
651 RECORD(EXPR_SIZEOF_PACK);
Richard Smith01b2cb42014-07-26 06:37:51 +0000652 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000653 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
Richard Smith01b2cb42014-07-26 06:37:51 +0000654 RECORD(EXPR_FUNCTION_PARM_PACK);
655 RECORD(EXPR_MATERIALIZE_TEMPORARY);
Peter Collingbourne41f85462011-02-09 21:07:24 +0000656 RECORD(EXPR_CUDA_KERNEL_CALL);
Richard Smith01b2cb42014-07-26 06:37:51 +0000657 RECORD(EXPR_CXX_UUIDOF_EXPR);
658 RECORD(EXPR_CXX_UUIDOF_TYPE);
659 RECORD(EXPR_LAMBDA);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000660#undef RECORD
Chris Lattner28fa4e62009-04-26 22:26:21 +0000661}
Mike Stump11289f42009-09-09 15:08:12 +0000662
Sebastian Redl55c0ad52010-08-18 23:56:21 +0000663void ASTWriter::WriteBlockInfoBlock() {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000664 RecordData Record;
Peter Collingbourned3a6c702016-11-01 01:18:57 +0000665 Stream.EnterBlockInfoBlock();
Mike Stump11289f42009-09-09 15:08:12 +0000666
Sebastian Redl539c5062010-08-18 23:57:32 +0000667#define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
668#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
Mike Stump11289f42009-09-09 15:08:12 +0000669
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000670 // Control Block.
671 BLOCK(CONTROL_BLOCK);
672 RECORD(METADATA);
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000673 RECORD(MODULE_NAME);
Richard Smithfa715652015-08-31 22:43:10 +0000674 RECORD(MODULE_DIRECTORY);
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000675 RECORD(MODULE_MAP_FILE);
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000676 RECORD(IMPORTS);
Douglas Gregorfad10d82012-10-18 18:36:53 +0000677 RECORD(ORIGINAL_FILE);
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000678 RECORD(ORIGINAL_PCH_DIR);
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +0000679 RECORD(ORIGINAL_FILE_ID);
Douglas Gregor3120d2c2012-10-22 18:42:04 +0000680 RECORD(INPUT_FILE_OFFSETS);
Richard Smith0516b182015-09-08 19:40:14 +0000681
682 BLOCK(OPTIONS_BLOCK);
683 RECORD(LANGUAGE_OPTIONS);
684 RECORD(TARGET_OPTIONS);
Douglas Gregorc6317db2012-10-24 15:49:58 +0000685 RECORD(FILE_SYSTEM_OPTIONS);
Douglas Gregor2d302362012-10-24 16:50:34 +0000686 RECORD(HEADER_SEARCH_OPTIONS);
Douglas Gregorb6af6c22012-10-24 20:05:57 +0000687 RECORD(PREPROCESSOR_OPTIONS);
688
Douglas Gregor108cb222012-10-19 00:45:00 +0000689 BLOCK(INPUT_FILES_BLOCK);
690 RECORD(INPUT_FILE);
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +0000691 RECORD(INPUT_FILE_HASH);
Douglas Gregor108cb222012-10-19 00:45:00 +0000692
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000693 // AST Top-Level Block.
694 BLOCK(AST_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000695 RECORD(TYPE_OFFSET);
696 RECORD(DECL_OFFSET);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000697 RECORD(IDENTIFIER_OFFSET);
698 RECORD(IDENTIFIER_TABLE);
Ben Langmuir332aafe2014-01-31 01:06:56 +0000699 RECORD(EAGERLY_DESERIALIZED_DECLS);
David Blaikie9ffe5a32017-01-30 05:00:26 +0000700 RECORD(MODULAR_CODEGEN_DECLS);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000701 RECORD(SPECIAL_TYPES);
702 RECORD(STATISTICS);
703 RECORD(TENTATIVE_DEFINITIONS);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000704 RECORD(SELECTOR_OFFSETS);
705 RECORD(METHOD_POOL);
706 RECORD(PP_COUNTER_VALUE);
Douglas Gregor258ae542009-04-27 06:38:32 +0000707 RECORD(SOURCE_LOCATION_OFFSETS);
708 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor61cac2b2009-04-27 20:06:05 +0000709 RECORD(EXT_VECTOR_DECLS);
Richard Smithfa715652015-08-31 22:43:10 +0000710 RECORD(UNUSED_FILESCOPED_DECLS);
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +0000711 RECORD(PPD_ENTITIES_OFFSETS);
Richard Smithfa715652015-08-31 22:43:10 +0000712 RECORD(VTABLE_USES);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +0000713 RECORD(PPD_SKIPPED_RANGES);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +0000714 RECORD(REFERENCED_SELECTOR_POOL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000715 RECORD(TU_UPDATE_LEXICAL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000716 RECORD(SEMA_DECL_REFS);
717 RECORD(WEAK_UNDECLARED_IDENTIFIERS);
718 RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000719 RECORD(UPDATE_VISIBLE);
720 RECORD(DECL_UPDATE_OFFSETS);
721 RECORD(DECL_UPDATES);
Peter Collingbourne5df20e02011-02-15 19:46:30 +0000722 RECORD(CUDA_SPECIAL_DECL_REFS);
Douglas Gregor09b69892011-02-10 17:09:37 +0000723 RECORD(HEADER_SEARCH_TABLE);
Peter Collingbourne5df20e02011-02-15 19:46:30 +0000724 RECORD(FP_PRAGMA_OPTIONS);
725 RECORD(OPENCL_EXTENSIONS);
Yaxun Liu5b746652016-12-18 05:18:55 +0000726 RECORD(OPENCL_EXTENSION_TYPES);
727 RECORD(OPENCL_EXTENSION_DECLS);
Alexis Hunt27a761d2011-05-04 23:29:54 +0000728 RECORD(DELEGATING_CTORS);
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000729 RECORD(KNOWN_NAMESPACES);
Douglas Gregor78d0b572011-08-04 16:39:39 +0000730 RECORD(MODULE_OFFSET_MAP);
731 RECORD(SOURCE_MANAGER_LINE_TABLE);
Douglas Gregor404cdde2012-01-27 01:47:08 +0000732 RECORD(OBJC_CATEGORIES_MAP);
Douglas Gregor66e4add2011-12-19 21:09:25 +0000733 RECORD(FILE_SORTED_DECLS);
734 RECORD(IMPORTED_MODULES);
Douglas Gregor404cdde2012-01-27 01:47:08 +0000735 RECORD(OBJC_CATEGORIES);
Douglas Gregorcb28f9d2012-10-09 23:05:51 +0000736 RECORD(MACRO_OFFSET);
Richard Smithfa715652015-08-31 22:43:10 +0000737 RECORD(INTERESTING_IDENTIFIERS);
738 RECORD(UNDEFINED_BUT_USED);
Richard Smithe40f2ba2013-08-07 21:41:30 +0000739 RECORD(LATE_PARSED_TEMPLATE);
Dario Domizioli13a0a382014-05-23 12:13:25 +0000740 RECORD(OPTIMIZE_PRAGMA_OPTIONS);
Nico Weber779355f2016-03-02 23:22:00 +0000741 RECORD(MSSTRUCT_PRAGMA_OPTIONS);
Nico Weber42932312016-03-03 00:17:35 +0000742 RECORD(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS);
Richard Smithfa715652015-08-31 22:43:10 +0000743 RECORD(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES);
Richard Smithfa715652015-08-31 22:43:10 +0000744 RECORD(DELETE_EXPRS_TO_ANALYZE);
Justin Lebar67a78a62016-10-08 22:15:58 +0000745 RECORD(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH);
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000746 RECORD(PP_CONDITIONAL_STACK);
Douglas Gregor358cd442012-01-15 16:58:34 +0000747
Chris Lattner28fa4e62009-04-26 22:26:21 +0000748 // SourceManager Block.
Chris Lattner64031982009-04-27 00:40:25 +0000749 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000750 RECORD(SM_SLOC_FILE_ENTRY);
751 RECORD(SM_SLOC_BUFFER_ENTRY);
752 RECORD(SM_SLOC_BUFFER_BLOB);
Richard Smithaada85c2016-02-06 02:06:43 +0000753 RECORD(SM_SLOC_BUFFER_BLOB_COMPRESSED);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +0000754 RECORD(SM_SLOC_EXPANSION_ENTRY);
Mike Stump11289f42009-09-09 15:08:12 +0000755
Chris Lattner28fa4e62009-04-26 22:26:21 +0000756 // Preprocessor Block.
Chris Lattner64031982009-04-27 00:40:25 +0000757 BLOCK(PREPROCESSOR_BLOCK);
Richard Smithec216502015-02-13 19:48:37 +0000758 RECORD(PP_MACRO_DIRECTIVE_HISTORY);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000759 RECORD(PP_MACRO_FUNCTION_LIKE);
Richard Smithd7329392015-04-21 21:46:32 +0000760 RECORD(PP_MACRO_OBJECT_LIKE);
761 RECORD(PP_MODULE_MACRO);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000762 RECORD(PP_TOKEN);
Richard Smithec216502015-02-13 19:48:37 +0000763
Richard Smithfa715652015-08-31 22:43:10 +0000764 // Submodule Block.
765 BLOCK(SUBMODULE_BLOCK);
766 RECORD(SUBMODULE_METADATA);
767 RECORD(SUBMODULE_DEFINITION);
768 RECORD(SUBMODULE_UMBRELLA_HEADER);
769 RECORD(SUBMODULE_HEADER);
770 RECORD(SUBMODULE_TOPHEADER);
771 RECORD(SUBMODULE_UMBRELLA_DIR);
772 RECORD(SUBMODULE_IMPORTS);
773 RECORD(SUBMODULE_EXPORTS);
774 RECORD(SUBMODULE_REQUIRES);
775 RECORD(SUBMODULE_EXCLUDED_HEADER);
776 RECORD(SUBMODULE_LINK_LIBRARY);
777 RECORD(SUBMODULE_CONFIG_MACRO);
778 RECORD(SUBMODULE_CONFLICT);
779 RECORD(SUBMODULE_PRIVATE_HEADER);
780 RECORD(SUBMODULE_TEXTUAL_HEADER);
781 RECORD(SUBMODULE_PRIVATE_TEXTUAL_HEADER);
Richard Smithdc1f0422016-07-20 19:10:16 +0000782 RECORD(SUBMODULE_INITIALIZERS);
Douglas Gregorf0b11de2017-09-14 23:38:44 +0000783 RECORD(SUBMODULE_EXPORT_AS);
Richard Smithfa715652015-08-31 22:43:10 +0000784
785 // Comments Block.
786 BLOCK(COMMENTS_BLOCK);
787 RECORD(COMMENTS_RAW_COMMENT);
788
Douglas Gregor12bfa382009-10-17 00:13:19 +0000789 // Decls and Types block.
790 BLOCK(DECLTYPES_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000791 RECORD(TYPE_EXT_QUAL);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000792 RECORD(TYPE_COMPLEX);
793 RECORD(TYPE_POINTER);
794 RECORD(TYPE_BLOCK_POINTER);
795 RECORD(TYPE_LVALUE_REFERENCE);
796 RECORD(TYPE_RVALUE_REFERENCE);
797 RECORD(TYPE_MEMBER_POINTER);
798 RECORD(TYPE_CONSTANT_ARRAY);
799 RECORD(TYPE_INCOMPLETE_ARRAY);
800 RECORD(TYPE_VARIABLE_ARRAY);
801 RECORD(TYPE_VECTOR);
802 RECORD(TYPE_EXT_VECTOR);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000803 RECORD(TYPE_FUNCTION_NO_PROTO);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000804 RECORD(TYPE_FUNCTION_PROTO);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000805 RECORD(TYPE_TYPEDEF);
806 RECORD(TYPE_TYPEOF_EXPR);
807 RECORD(TYPE_TYPEOF);
808 RECORD(TYPE_RECORD);
809 RECORD(TYPE_ENUM);
810 RECORD(TYPE_OBJC_INTERFACE);
Steve Narofffb4330f2009-06-17 22:40:22 +0000811 RECORD(TYPE_OBJC_OBJECT_POINTER);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000812 RECORD(TYPE_DECLTYPE);
813 RECORD(TYPE_ELABORATED);
814 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
815 RECORD(TYPE_UNRESOLVED_USING);
816 RECORD(TYPE_INJECTED_CLASS_NAME);
817 RECORD(TYPE_OBJC_OBJECT);
818 RECORD(TYPE_TEMPLATE_TYPE_PARM);
819 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
820 RECORD(TYPE_DEPENDENT_NAME);
821 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
822 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
823 RECORD(TYPE_PAREN);
Leonard Chanc72aaf62019-05-07 03:20:17 +0000824 RECORD(TYPE_MACRO_QUALIFIED);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000825 RECORD(TYPE_PACK_EXPANSION);
826 RECORD(TYPE_ATTRIBUTED);
827 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000828 RECORD(TYPE_AUTO);
829 RECORD(TYPE_UNARY_TRANSFORM);
Eli Friedman0dfb8892011-10-06 23:00:33 +0000830 RECORD(TYPE_ATOMIC);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000831 RECORD(TYPE_DECAYED);
832 RECORD(TYPE_ADJUSTED);
Manman Rene6be26c2016-09-13 17:25:08 +0000833 RECORD(TYPE_OBJC_TYPE_PARAM);
Richard Smithd61d4ac2015-08-22 20:13:39 +0000834 RECORD(LOCAL_REDECLARATIONS);
Chris Lattnerdb397b62009-04-26 22:32:16 +0000835 RECORD(DECL_TYPEDEF);
Richard Smith01b2cb42014-07-26 06:37:51 +0000836 RECORD(DECL_TYPEALIAS);
Chris Lattnerdb397b62009-04-26 22:32:16 +0000837 RECORD(DECL_ENUM);
838 RECORD(DECL_RECORD);
839 RECORD(DECL_ENUM_CONSTANT);
840 RECORD(DECL_FUNCTION);
841 RECORD(DECL_OBJC_METHOD);
842 RECORD(DECL_OBJC_INTERFACE);
843 RECORD(DECL_OBJC_PROTOCOL);
844 RECORD(DECL_OBJC_IVAR);
845 RECORD(DECL_OBJC_AT_DEFS_FIELD);
Chris Lattnerdb397b62009-04-26 22:32:16 +0000846 RECORD(DECL_OBJC_CATEGORY);
847 RECORD(DECL_OBJC_CATEGORY_IMPL);
848 RECORD(DECL_OBJC_IMPLEMENTATION);
849 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
850 RECORD(DECL_OBJC_PROPERTY);
851 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000852 RECORD(DECL_FIELD);
John McCall5e77d762013-04-16 07:28:30 +0000853 RECORD(DECL_MS_PROPERTY);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000854 RECORD(DECL_VAR);
Chris Lattnerdb397b62009-04-26 22:32:16 +0000855 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000856 RECORD(DECL_PARM_VAR);
Chris Lattnerdb397b62009-04-26 22:32:16 +0000857 RECORD(DECL_FILE_SCOPE_ASM);
858 RECORD(DECL_BLOCK);
859 RECORD(DECL_CONTEXT_LEXICAL);
860 RECORD(DECL_CONTEXT_VISIBLE);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000861 RECORD(DECL_NAMESPACE);
862 RECORD(DECL_NAMESPACE_ALIAS);
863 RECORD(DECL_USING);
864 RECORD(DECL_USING_SHADOW);
865 RECORD(DECL_USING_DIRECTIVE);
866 RECORD(DECL_UNRESOLVED_USING_VALUE);
867 RECORD(DECL_UNRESOLVED_USING_TYPENAME);
868 RECORD(DECL_LINKAGE_SPEC);
869 RECORD(DECL_CXX_RECORD);
870 RECORD(DECL_CXX_METHOD);
871 RECORD(DECL_CXX_CONSTRUCTOR);
872 RECORD(DECL_CXX_DESTRUCTOR);
873 RECORD(DECL_CXX_CONVERSION);
874 RECORD(DECL_ACCESS_SPEC);
875 RECORD(DECL_FRIEND);
876 RECORD(DECL_FRIEND_TEMPLATE);
877 RECORD(DECL_CLASS_TEMPLATE);
878 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
879 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000880 RECORD(DECL_VAR_TEMPLATE);
881 RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
882 RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000883 RECORD(DECL_FUNCTION_TEMPLATE);
884 RECORD(DECL_TEMPLATE_TYPE_PARM);
885 RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
886 RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
Saar Razd7aae332019-07-10 21:25:49 +0000887 RECORD(DECL_CONCEPT);
Richard Smithefc884a2016-04-13 07:41:35 +0000888 RECORD(DECL_TYPE_ALIAS_TEMPLATE);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000889 RECORD(DECL_STATIC_ASSERT);
890 RECORD(DECL_CXX_BASE_SPECIFIERS);
Richard Smithefc884a2016-04-13 07:41:35 +0000891 RECORD(DECL_CXX_CTOR_INITIALIZERS);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000892 RECORD(DECL_INDIRECTFIELD);
893 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
Richard Smithefc884a2016-04-13 07:41:35 +0000894 RECORD(DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK);
895 RECORD(DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION);
896 RECORD(DECL_IMPORT);
897 RECORD(DECL_OMP_THREADPRIVATE);
898 RECORD(DECL_EMPTY);
899 RECORD(DECL_OBJC_TYPE_PARAM);
900 RECORD(DECL_OMP_CAPTUREDEXPR);
901 RECORD(DECL_PRAGMA_COMMENT);
902 RECORD(DECL_PRAGMA_DETECT_MISMATCH);
903 RECORD(DECL_OMP_DECLARE_REDUCTION);
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000904 RECORD(DECL_OMP_ALLOCATE);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000905
Douglas Gregor03412ba2011-06-03 02:27:19 +0000906 // Statements and Exprs can occur in the Decls and Types block.
907 AddStmtsExprs(Stream, Record);
908
Douglas Gregor92a96f52011-02-08 21:58:10 +0000909 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +0000910 RECORD(PPD_MACRO_EXPANSION);
Douglas Gregor92a96f52011-02-08 21:58:10 +0000911 RECORD(PPD_MACRO_DEFINITION);
912 RECORD(PPD_INCLUSION_DIRECTIVE);
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000913
914 // Decls and Types block.
915 BLOCK(EXTENSION_BLOCK);
916 RECORD(EXTENSION_METADATA);
917
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +0000918 BLOCK(UNHASHED_CONTROL_BLOCK);
919 RECORD(SIGNATURE);
920 RECORD(DIAGNOSTIC_OPTIONS);
921 RECORD(DIAG_PRAGMA_MAPPINGS);
922
Chris Lattner28fa4e62009-04-26 22:26:21 +0000923#undef RECORD
924#undef BLOCK
925 Stream.ExitBlock();
926}
927
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000928/// Prepares a path for being written to an AST file by converting it
Richard Smith54cc3c22014-12-11 20:50:24 +0000929/// to an absolute path and removing nested './'s.
930///
931/// \return \c true if the path was changed.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000932static bool cleanPathForOutput(FileManager &FileMgr,
933 SmallVectorImpl<char> &Path) {
Argyrios Kyrtzidis403cbcb2015-07-31 01:39:23 +0000934 bool Changed = FileMgr.makeAbsolutePath(Path);
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000935 return Changed | llvm::sys::path::remove_dots(Path);
Richard Smith54cc3c22014-12-11 20:50:24 +0000936}
937
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000938/// Adjusts the given filename to only write out the portion of the
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000939/// filename that is not part of the system root directory.
Mike Stump11289f42009-09-09 15:08:12 +0000940///
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000941/// \param Filename the file name to adjust.
942///
Richard Smith7ed1bc92014-12-05 22:42:13 +0000943/// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
944/// the returned filename will be adjusted by this root directory.
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000945///
946/// \returns either the original filename (if it needs no adjustment) or the
947/// adjusted filename (which points into the @p Filename parameter).
Mike Stump11289f42009-09-09 15:08:12 +0000948static const char *
Richard Smith7ed1bc92014-12-05 22:42:13 +0000949adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000950 assert(Filename && "No file name to adjust?");
Mike Stump11289f42009-09-09 15:08:12 +0000951
Richard Smith7ed1bc92014-12-05 22:42:13 +0000952 if (BaseDir.empty())
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000953 return Filename;
Mike Stump11289f42009-09-09 15:08:12 +0000954
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000955 // Verify that the filename and the system root have the same prefix.
956 unsigned Pos = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +0000957 for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
958 if (Filename[Pos] != BaseDir[Pos])
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000959 return Filename; // Prefixes don't match.
Mike Stump11289f42009-09-09 15:08:12 +0000960
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000961 // We hit the end of the filename before we hit the end of the system root.
962 if (!Filename[Pos])
963 return Filename;
Mike Stump11289f42009-09-09 15:08:12 +0000964
Richard Smith7ed1bc92014-12-05 22:42:13 +0000965 // If there's not a path separator at the end of the base directory nor
966 // immediately after it, then this isn't within the base directory.
967 if (!llvm::sys::path::is_separator(Filename[Pos])) {
968 if (!llvm::sys::path::is_separator(BaseDir.back()))
969 return Filename;
970 } else {
971 // If the file name has a '/' at the current position, skip over the '/'.
972 // We distinguish relative paths from absolute paths by the
973 // absence of '/' at the beginning of relative paths.
974 //
975 // FIXME: This is wrong. We distinguish them by asking if the path is
976 // absolute, which isn't the same thing. And there might be multiple '/'s
977 // in a row. Use a better mechanism to indicate whether we have emitted an
978 // absolute or relative path.
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000979 ++Pos;
Richard Smith7ed1bc92014-12-05 22:42:13 +0000980 }
Mike Stump11289f42009-09-09 15:08:12 +0000981
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000982 return Filename + Pos;
983}
Chris Lattner28fa4e62009-04-26 22:26:21 +0000984
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +0000985ASTFileSignature ASTWriter::createSignature(StringRef Bytes) {
986 // Calculate the hash till start of UNHASHED_CONTROL_BLOCK.
987 llvm::SHA1 Hasher;
988 Hasher.update(ArrayRef<uint8_t>(Bytes.bytes_begin(), Bytes.size()));
989 auto Hash = Hasher.result();
990
991 // Convert to an array [5*i32].
992 ASTFileSignature Signature;
993 auto LShift = [&](unsigned char Val, unsigned Shift) {
994 return (uint32_t)Val << Shift;
995 };
996 for (int I = 0; I != 5; ++I)
997 Signature[I] = LShift(Hash[I * 4 + 0], 24) | LShift(Hash[I * 4 + 1], 16) |
998 LShift(Hash[I * 4 + 2], 8) | LShift(Hash[I * 4 + 3], 0);
999
1000 return Signature;
1001}
1002
1003ASTFileSignature ASTWriter::writeUnhashedControlBlock(Preprocessor &PP,
1004 ASTContext &Context) {
1005 // Flush first to prepare the PCM hash (signature).
1006 Stream.FlushToWord();
1007 auto StartOfUnhashedControl = Stream.GetCurrentBitNo() >> 3;
1008
1009 // Enter the block and prepare to write records.
1010 RecordData Record;
1011 Stream.EnterSubblock(UNHASHED_CONTROL_BLOCK_ID, 5);
1012
1013 // For implicit modules, write the hash of the PCM as its signature.
1014 ASTFileSignature Signature;
1015 if (WritingModule &&
1016 PP.getHeaderSearchInfo().getHeaderSearchOpts().ModulesHashContent) {
1017 Signature = createSignature(StringRef(Buffer.begin(), StartOfUnhashedControl));
1018 Record.append(Signature.begin(), Signature.end());
1019 Stream.EmitRecord(SIGNATURE, Record);
1020 Record.clear();
Ben Langmuir487ea142014-10-23 18:05:36 +00001021 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001022
1023 // Diagnostic options.
1024 const auto &Diags = Context.getDiagnostics();
1025 const DiagnosticOptions &DiagOpts = Diags.getDiagnosticOptions();
1026#define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1027#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1028 Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1029#include "clang/Basic/DiagnosticOptions.def"
1030 Record.push_back(DiagOpts.Warnings.size());
1031 for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1032 AddString(DiagOpts.Warnings[I], Record);
1033 Record.push_back(DiagOpts.Remarks.size());
1034 for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1035 AddString(DiagOpts.Remarks[I], Record);
1036 // Note: we don't serialize the log or serialization file names, because they
1037 // are generally transient files and will almost always be overridden.
1038 Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1039
1040 // Write out the diagnostic/pragma mappings.
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001041 WritePragmaDiagnosticMappings(Diags, /* isModule = */ WritingModule);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001042
1043 // Leave the options block.
1044 Stream.ExitBlock();
1045 return Signature;
Ben Langmuir487ea142014-10-23 18:05:36 +00001046}
1047
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001048/// Write the control block.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001049void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context,
1050 StringRef isysroot,
1051 const std::string &OutputFile) {
Douglas Gregorbfbde532009-04-10 21:16:55 +00001052 using namespace llvm;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001053
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001054 Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001055 RecordData Record;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001056
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001057 // Metadata
David Blaikieb44f0bf2017-01-04 22:36:43 +00001058 auto MetadataAbbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001059 MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1060 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1061 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1062 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1063 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1064 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
Richard Smithe75ee0f2015-08-17 07:13:32 +00001065 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00001066 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // PCHHasObjectFile
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001067 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1068 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
David Blaikieb44f0bf2017-01-04 22:36:43 +00001069 unsigned MetadataAbbrevCode = Stream.EmitAbbrev(std::move(MetadataAbbrev));
Richard Smith7ed1bc92014-12-05 22:42:13 +00001070 assert((!WritingModule || isysroot.empty()) &&
1071 "writing module as a relocatable PCH?");
Mehdi Amini57a41912015-09-10 01:46:39 +00001072 {
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00001073 RecordData::value_type Record[] = {
1074 METADATA,
1075 VERSION_MAJOR,
1076 VERSION_MINOR,
1077 CLANG_VERSION_MAJOR,
1078 CLANG_VERSION_MINOR,
1079 !isysroot.empty(),
1080 IncludeTimestamps,
1081 Context.getLangOpts().BuildingPCHWithObjectFile,
1082 ASTHasCompilerErrors};
Mehdi Amini57a41912015-09-10 01:46:39 +00001083 Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1084 getClangFullRepositoryVersion());
1085 }
Chandler Carruth885e78c2015-03-24 21:18:10 +00001086
Richard Smith8b706102017-05-31 20:56:55 +00001087 if (WritingModule) {
Richard Smith7ed1bc92014-12-05 22:42:13 +00001088 // Module name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001089 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001090 Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1091 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001092 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00001093 RecordData::value_type Record[] = {MODULE_NAME};
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001094 Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1095 }
1096
Richard Smith7ed1bc92014-12-05 22:42:13 +00001097 if (WritingModule && WritingModule->Directory) {
Richard Smith7ed1bc92014-12-05 22:42:13 +00001098 SmallString<128> BaseDir(WritingModule->Directory->getName());
Richard Smith54cc3c22014-12-11 20:50:24 +00001099 cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
Richard Smithf7b41372015-08-13 23:47:44 +00001100
1101 // If the home of the module is the current working directory, then we
1102 // want to pick up the cwd of the build process loading the module, not
1103 // our cwd, when we load this module.
1104 if (!PP.getHeaderSearchInfo()
1105 .getHeaderSearchOpts()
1106 .ModuleMapFileHomeIsCwd ||
1107 WritingModule->Directory->getName() != StringRef(".")) {
1108 // Module directory.
David Blaikieb44f0bf2017-01-04 22:36:43 +00001109 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Richard Smithf7b41372015-08-13 23:47:44 +00001110 Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1111 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
David Blaikieb44f0bf2017-01-04 22:36:43 +00001112 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
Richard Smithf7b41372015-08-13 23:47:44 +00001113
Mehdi Amini57a41912015-09-10 01:46:39 +00001114 RecordData::value_type Record[] = {MODULE_DIRECTORY};
Richard Smithf7b41372015-08-13 23:47:44 +00001115 Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
1116 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001117
1118 // Write out all other paths relative to the base directory if possible.
1119 BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1120 } else if (!isysroot.empty()) {
1121 // Write out paths relative to the sysroot if possible.
1122 BaseDirectory = isysroot;
1123 }
1124
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001125 // Module map file
Richard Smithd19389a2017-07-05 07:47:11 +00001126 if (WritingModule && WritingModule->Kind == Module::ModuleMapModule) {
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001127 Record.clear();
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001128
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001129 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
Richard Smith8b706102017-05-31 20:56:55 +00001130 AddPath(WritingModule->PresumedModuleMapFile.empty()
1131 ? Map.getModuleMapFileForUniquing(WritingModule)->getName()
1132 : StringRef(WritingModule->PresumedModuleMapFile),
1133 Record);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001134
1135 // Additional module map files.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001136 if (auto *AdditionalModMaps =
1137 Map.getAdditionalModuleMapFiles(WritingModule)) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001138 Record.push_back(AdditionalModMaps->size());
1139 for (const FileEntry *F : *AdditionalModMaps)
Richard Smith7ed1bc92014-12-05 22:42:13 +00001140 AddPath(F->getName(), Record);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001141 } else {
1142 Record.push_back(0);
1143 }
1144
1145 Stream.EmitRecord(MODULE_MAP_FILE, Record);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001146 }
1147
Douglas Gregor112b9072012-10-18 05:31:06 +00001148 // Imports
Douglas Gregor29cc6422011-08-17 21:07:30 +00001149 if (Chain) {
Douglas Gregor29cc6422011-08-17 21:07:30 +00001150 serialization::ModuleManager &Mgr = Chain->getModuleManager();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001151 Record.clear();
Douglas Gregordf0c1512011-08-18 04:12:04 +00001152
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001153 for (ModuleFile &M : Mgr) {
Douglas Gregordf0c1512011-08-18 04:12:04 +00001154 // Skip modules that weren't directly imported.
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001155 if (!M.isDirectlyImported())
Douglas Gregordf0c1512011-08-18 04:12:04 +00001156 continue;
1157
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001158 Record.push_back((unsigned)M.Kind); // FIXME: Stable encoding
1159 AddSourceLocation(M.ImportLoc, Record);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001160
1161 // If we have calculated signature, there is no need to store
1162 // the size or timestamp.
1163 Record.push_back(M.Signature ? 0 : M.File->getSize());
1164 Record.push_back(M.Signature ? 0 : getTimestampForOutput(M.File));
1165
1166 for (auto I : M.Signature)
1167 Record.push_back(I);
1168
Boris Kolpackovd30446f2017-08-31 06:26:43 +00001169 AddString(M.ModuleName, Record);
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001170 AddPath(M.FileName, Record);
Douglas Gregordf0c1512011-08-18 04:12:04 +00001171 }
Douglas Gregor29cc6422011-08-17 21:07:30 +00001172 Stream.EmitRecord(IMPORTS, Record);
1173 }
Mike Stump11289f42009-09-09 15:08:12 +00001174
Richard Smith0516b182015-09-08 19:40:14 +00001175 // Write the options block.
1176 Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
1177
Douglas Gregor112b9072012-10-18 05:31:06 +00001178 // Language options.
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001179 Record.clear();
Douglas Gregor112b9072012-10-18 05:31:06 +00001180 const LangOptions &LangOpts = Context.getLangOpts();
1181#define LANGOPT(Name, Bits, Default, Description) \
1182 Record.push_back(LangOpts.Name);
1183#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1184 Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001185#include "clang/Basic/LangOptions.def"
1186#define SANITIZER(NAME, ID) \
1187 Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
Will Dietzf54319c2013-01-18 11:30:38 +00001188#include "clang/Basic/Sanitizers.def"
Douglas Gregor112b9072012-10-18 05:31:06 +00001189
Ben Langmuircd98cb72015-06-23 18:20:18 +00001190 Record.push_back(LangOpts.ModuleFeatures.size());
1191 for (StringRef Feature : LangOpts.ModuleFeatures)
1192 AddString(Feature, Record);
1193
Douglas Gregor112b9072012-10-18 05:31:06 +00001194 Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1195 AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
Ben Langmuird4a667a2015-06-23 18:20:23 +00001196
1197 AddString(LangOpts.CurrentModule, Record);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001198
1199 // Comment options.
1200 Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001201 for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1202 AddString(I, Record);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001203 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00001204 Record.push_back(LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001205
Samuel Antaoee8fb302016-01-06 13:42:12 +00001206 // OpenMP offloading options.
1207 Record.push_back(LangOpts.OMPTargetTriples.size());
1208 for (auto &T : LangOpts.OMPTargetTriples)
1209 AddString(T.getTriple(), Record);
1210
1211 AddString(LangOpts.OMPHostIRFile, Record);
1212
Douglas Gregor112b9072012-10-18 05:31:06 +00001213 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1214
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001215 // Target options.
1216 Record.clear();
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001217 const TargetInfo &Target = Context.getTargetInfo();
1218 const TargetOptions &TargetOpts = Target.getTargetOpts();
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001219 AddString(TargetOpts.Triple, Record);
1220 AddString(TargetOpts.CPU, Record);
1221 AddString(TargetOpts.ABI, Record);
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001222 Record.push_back(TargetOpts.FeaturesAsWritten.size());
1223 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1224 AddString(TargetOpts.FeaturesAsWritten[I], Record);
1225 }
1226 Record.push_back(TargetOpts.Features.size());
1227 for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1228 AddString(TargetOpts.Features[I], Record);
1229 }
1230 Stream.EmitRecord(TARGET_OPTIONS, Record);
1231
Douglas Gregorc6317db2012-10-24 15:49:58 +00001232 // File system options.
1233 Record.clear();
Yaron Keren8dec46c2015-08-26 08:10:22 +00001234 const FileSystemOptions &FSOpts =
1235 Context.getSourceManager().getFileManager().getFileSystemOpts();
Douglas Gregorc6317db2012-10-24 15:49:58 +00001236 AddString(FSOpts.WorkingDir, Record);
1237 Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1238
Douglas Gregor2d302362012-10-24 16:50:34 +00001239 // Header search options.
1240 Record.clear();
1241 const HeaderSearchOptions &HSOpts
1242 = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1243 AddString(HSOpts.Sysroot, Record);
1244
1245 // Include entries.
1246 Record.push_back(HSOpts.UserEntries.size());
1247 for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1248 const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1249 AddString(Entry.Path, Record);
1250 Record.push_back(static_cast<unsigned>(Entry.Group));
Douglas Gregor2d302362012-10-24 16:50:34 +00001251 Record.push_back(Entry.IsFramework);
1252 Record.push_back(Entry.IgnoreSysRoot);
Douglas Gregor2d302362012-10-24 16:50:34 +00001253 }
1254
1255 // System header prefixes.
1256 Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1257 for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1258 AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1259 Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1260 }
1261
1262 AddString(HSOpts.ResourceDir, Record);
1263 AddString(HSOpts.ModuleCachePath, Record);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00001264 AddString(HSOpts.ModuleUserBuildPath, Record);
Douglas Gregor2d302362012-10-24 16:50:34 +00001265 Record.push_back(HSOpts.DisableModuleHash);
Richard Smith18934752017-06-06 00:32:01 +00001266 Record.push_back(HSOpts.ImplicitModuleMaps);
1267 Record.push_back(HSOpts.ModuleMapFileHomeIsCwd);
Douglas Gregor2d302362012-10-24 16:50:34 +00001268 Record.push_back(HSOpts.UseBuiltinIncludes);
1269 Record.push_back(HSOpts.UseStandardSystemIncludes);
1270 Record.push_back(HSOpts.UseStandardCXXIncludes);
1271 Record.push_back(HSOpts.UseLibcxx);
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00001272 // Write out the specific module cache path that contains the module files.
1273 AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
Douglas Gregor2d302362012-10-24 16:50:34 +00001274 Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1275
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001276 // Preprocessor options.
1277 Record.clear();
1278 const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1279
1280 // Macro definitions.
1281 Record.push_back(PPOpts.Macros.size());
1282 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1283 AddString(PPOpts.Macros[I].first, Record);
1284 Record.push_back(PPOpts.Macros[I].second);
1285 }
1286
1287 // Includes
1288 Record.push_back(PPOpts.Includes.size());
1289 for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1290 AddString(PPOpts.Includes[I], Record);
1291
1292 // Macro includes
1293 Record.push_back(PPOpts.MacroIncludes.size());
1294 for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1295 AddString(PPOpts.MacroIncludes[I], Record);
1296
Douglas Gregorb6368752012-10-24 23:41:50 +00001297 Record.push_back(PPOpts.UsePredefines);
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00001298 // Detailed record is important since it is used for the module cache hash.
1299 Record.push_back(PPOpts.DetailedRecord);
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001300 AddString(PPOpts.ImplicitPCHInclude, Record);
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001301 Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1302 Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1303
Richard Smith0516b182015-09-08 19:40:14 +00001304 // Leave the options block.
1305 Stream.ExitBlock();
1306
Douglas Gregora3b20262011-05-06 21:43:30 +00001307 // Original file name and file ID
Douglas Gregor45fe0362009-05-12 01:31:05 +00001308 SourceManager &SM = Context.getSourceManager();
1309 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
David Blaikieb44f0bf2017-01-04 22:36:43 +00001310 auto FileAbbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregorfad10d82012-10-18 18:36:53 +00001311 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1312 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
Douglas Gregor45fe0362009-05-12 01:31:05 +00001313 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001314 unsigned FileAbbrevCode = Stream.EmitAbbrev(std::move(FileAbbrev));
Douglas Gregor45fe0362009-05-12 01:31:05 +00001315
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001316 Record.clear();
Douglas Gregorfad10d82012-10-18 18:36:53 +00001317 Record.push_back(ORIGINAL_FILE);
Douglas Gregora3b20262011-05-06 21:43:30 +00001318 Record.push_back(SM.getMainFileID().getOpaqueValue());
Richard Smith7ed1bc92014-12-05 22:42:13 +00001319 EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
Douglas Gregor45fe0362009-05-12 01:31:05 +00001320 }
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00001321
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +00001322 Record.clear();
1323 Record.push_back(SM.getMainFileID().getOpaqueValue());
1324 Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1325
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001326 // Original PCH directory
1327 if (!OutputFile.empty() && OutputFile != "-") {
David Blaikieb44f0bf2017-01-04 22:36:43 +00001328 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001329 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1330 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001331 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001332
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001333 SmallString<128> OutputPath(OutputFile);
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001334
Argyrios Kyrtzidisc56419e2015-07-31 00:58:32 +00001335 SM.getFileManager().makeAbsolutePath(OutputPath);
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001336 StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1337
Mehdi Amini57a41912015-09-10 01:46:39 +00001338 RecordData::value_type Record[] = {ORIGINAL_PCH_DIR};
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001339 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1340 }
1341
Douglas Gregor49491f72013-03-15 22:15:07 +00001342 WriteInputFiles(Context.SourceMgr,
1343 PP.getHeaderSearchInfo().getHeaderSearchOpts(),
Douglas Gregora3dd9002013-07-22 20:48:33 +00001344 PP.getLangOpts().Modules);
Douglas Gregor72be3902012-10-19 00:38:02 +00001345 Stream.ExitBlock();
1346}
1347
Douglas Gregor49491f72013-03-15 22:15:07 +00001348namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001349
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001350/// An input file.
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001351struct InputFileEntry {
1352 const FileEntry *File;
1353 bool IsSystemFile;
1354 bool IsTransient;
1355 bool BufferOverridden;
1356 bool IsTopLevelModuleMap;
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00001357 uint32_t ContentHash[2];
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001358};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001359
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001360} // namespace
Douglas Gregor49491f72013-03-15 22:15:07 +00001361
1362void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1363 HeaderSearchOptions &HSOpts,
Douglas Gregora3dd9002013-07-22 20:48:33 +00001364 bool Modules) {
Douglas Gregor72be3902012-10-19 00:38:02 +00001365 using namespace llvm;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001366
Douglas Gregor72be3902012-10-19 00:38:02 +00001367 Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
Mehdi Amini57a41912015-09-10 01:46:39 +00001368
Douglas Gregor72be3902012-10-19 00:38:02 +00001369 // Create input-file abbreviation.
David Blaikieb44f0bf2017-01-04 22:36:43 +00001370 auto IFAbbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor72be3902012-10-19 00:38:02 +00001371 IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001372 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
Douglas Gregor72be3902012-10-19 00:38:02 +00001373 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1374 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001375 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
Richard Smitha8cfffa2015-11-26 02:04:16 +00001376 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
Richard Smithf3f84612017-06-29 02:19:42 +00001377 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Module map
Douglas Gregor72be3902012-10-19 00:38:02 +00001378 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001379 unsigned IFAbbrevCode = Stream.EmitAbbrev(std::move(IFAbbrev));
Douglas Gregor72be3902012-10-19 00:38:02 +00001380
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00001381 // Create input file hash abbreviation.
1382 auto IFHAbbrev = std::make_shared<BitCodeAbbrev>();
1383 IFHAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_HASH));
1384 IFHAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1385 IFHAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1386 unsigned IFHAbbrevCode = Stream.EmitAbbrev(std::move(IFHAbbrev));
1387
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001388 // Get all ContentCache objects for files, sorted by whether the file is a
1389 // system one or not. System files go at the back, users files at the front.
Douglas Gregor49491f72013-03-15 22:15:07 +00001390 std::deque<InputFileEntry> SortedFiles;
Douglas Gregor72be3902012-10-19 00:38:02 +00001391 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1392 // Get this source location entry.
1393 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
NAKAMURA Takumideca50f2012-10-19 01:53:57 +00001394 assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
Douglas Gregor72be3902012-10-19 00:38:02 +00001395
1396 // We only care about file entries that were not overridden.
1397 if (!SLoc->isFile())
1398 continue;
Richard Smithf3f84612017-06-29 02:19:42 +00001399 const SrcMgr::FileInfo &File = SLoc->getFile();
1400 const SrcMgr::ContentCache *Cache = File.getContentCache();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001401 if (!Cache->OrigEntry)
Douglas Gregor72be3902012-10-19 00:38:02 +00001402 continue;
1403
Douglas Gregor49491f72013-03-15 22:15:07 +00001404 InputFileEntry Entry;
1405 Entry.File = Cache->OrigEntry;
Duncan P. N. Exon Smithf5848192019-08-26 20:32:05 +00001406 Entry.IsSystemFile = isSystem(File.getFileCharacteristic());
Richard Smitha8cfffa2015-11-26 02:04:16 +00001407 Entry.IsTransient = Cache->IsTransient;
Douglas Gregor49491f72013-03-15 22:15:07 +00001408 Entry.BufferOverridden = Cache->BufferOverridden;
Richard Smithf3f84612017-06-29 02:19:42 +00001409 Entry.IsTopLevelModuleMap = isModuleMap(File.getFileCharacteristic()) &&
1410 File.getIncludeLoc().isInvalid();
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00001411
1412 auto ContentHash = hash_code(-1);
1413 if (PP->getHeaderSearchInfo()
1414 .getHeaderSearchOpts()
1415 .ValidateASTInputFilesContent) {
1416 auto *MemBuff = Cache->getRawBuffer();
1417 if (MemBuff)
1418 ContentHash = hash_value(MemBuff->getBuffer());
1419 else
1420 // FIXME: The path should be taken from the FileEntryRef.
1421 PP->Diag(SourceLocation(), diag::err_module_unable_to_hash_content)
1422 << Entry.File->getName();
1423 }
1424 auto CH = llvm::APInt(64, ContentHash);
1425 Entry.ContentHash[0] =
1426 static_cast<uint32_t>(CH.getLoBits(32).getZExtValue());
1427 Entry.ContentHash[1] =
1428 static_cast<uint32_t>(CH.getHiBits(32).getZExtValue());
1429
Duncan P. N. Exon Smithf5848192019-08-26 20:32:05 +00001430 if (Entry.IsSystemFile)
Douglas Gregor49491f72013-03-15 22:15:07 +00001431 SortedFiles.push_back(Entry);
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001432 else
Douglas Gregor49491f72013-03-15 22:15:07 +00001433 SortedFiles.push_front(Entry);
1434 }
1435
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001436 unsigned UserFilesNum = 0;
1437 // Write out all of the input files.
Richard Smithec216502015-02-13 19:48:37 +00001438 std::vector<uint64_t> InputFileOffsets;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001439 for (const auto &Entry : SortedFiles) {
Douglas Gregor49491f72013-03-15 22:15:07 +00001440 uint32_t &InputFileID = InputFileIDs[Entry.File];
Argyrios Kyrtzidise65856f2012-12-11 07:48:08 +00001441 if (InputFileID != 0)
1442 continue; // already recorded this file.
1443
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001444 // Record this entry's offset.
1445 InputFileOffsets.push_back(Stream.GetCurrentBitNo());
Argyrios Kyrtzidise65856f2012-12-11 07:48:08 +00001446
1447 InputFileID = InputFileOffsets.size();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001448
Douglas Gregor49491f72013-03-15 22:15:07 +00001449 if (!Entry.IsSystemFile)
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001450 ++UserFilesNum;
1451
Douglas Gregor72be3902012-10-19 00:38:02 +00001452 // Emit size/modification time for this file.
Mehdi Amini57a41912015-09-10 01:46:39 +00001453 // And whether this file was overridden.
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00001454 {
1455 RecordData::value_type Record[] = {
1456 INPUT_FILE,
1457 InputFileOffsets.size(),
1458 (uint64_t)Entry.File->getSize(),
1459 (uint64_t)getTimestampForOutput(Entry.File),
1460 Entry.BufferOverridden,
1461 Entry.IsTransient,
1462 Entry.IsTopLevelModuleMap};
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001463
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00001464 // FIXME: The path should be taken from the FileEntryRef.
1465 EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
1466 }
1467
1468 // Emit content hash for this file.
1469 {
1470 RecordData::value_type Record[] = {INPUT_FILE_HASH, Entry.ContentHash[0],
1471 Entry.ContentHash[1]};
1472 Stream.EmitRecordWithAbbrev(IFHAbbrevCode, Record);
1473 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001474 }
Douglas Gregor49491f72013-03-15 22:15:07 +00001475
Douglas Gregor112b9072012-10-18 05:31:06 +00001476 Stream.ExitBlock();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001477
1478 // Create input file offsets abbreviation.
David Blaikieb44f0bf2017-01-04 22:36:43 +00001479 auto OffsetsAbbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001480 OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1481 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001482 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1483 // input files
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001484 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
David Blaikieb44f0bf2017-01-04 22:36:43 +00001485 unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(std::move(OffsetsAbbrev));
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001486
1487 // Write input file offsets.
Mehdi Amini57a41912015-09-10 01:46:39 +00001488 RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
1489 InputFileOffsets.size(), UserFilesNum};
Reid Kleckner012665e2015-05-21 00:13:09 +00001490 Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
Douglas Gregor55abb232009-04-10 20:39:37 +00001491}
1492
Douglas Gregora7f71a92009-04-10 03:52:48 +00001493//===----------------------------------------------------------------------===//
1494// Source Manager Serialization
1495//===----------------------------------------------------------------------===//
1496
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001497/// Create an abbreviation for the SLocEntry that refers to a
Douglas Gregora7f71a92009-04-10 03:52:48 +00001498/// file.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001499static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001500 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001501
David Blaikieb44f0bf2017-01-04 22:36:43 +00001502 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00001503 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001504 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1505 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
Richard Smithf3f84612017-06-29 02:19:42 +00001506 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
Douglas Gregora7f71a92009-04-10 03:52:48 +00001507 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregorb41ca8f2010-03-21 22:49:54 +00001508 // FileEntry fields.
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001509 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001510 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00001511 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1512 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
David Blaikieb44f0bf2017-01-04 22:36:43 +00001513 return Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001514}
1515
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001516/// Create an abbreviation for the SLocEntry that refers to a
Douglas Gregora7f71a92009-04-10 03:52:48 +00001517/// buffer.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001518static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001519 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001520
David Blaikieb44f0bf2017-01-04 22:36:43 +00001521 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00001522 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001523 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1524 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
Richard Smithf3f84612017-06-29 02:19:42 +00001525 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
Douglas Gregora7f71a92009-04-10 03:52:48 +00001526 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1527 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
David Blaikieb44f0bf2017-01-04 22:36:43 +00001528 return Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001529}
1530
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001531/// Create an abbreviation for the SLocEntry that refers to a
Douglas Gregora7f71a92009-04-10 03:52:48 +00001532/// buffer's blob.
Richard Smithaada85c2016-02-06 02:06:43 +00001533static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
1534 bool Compressed) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001535 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001536
David Blaikieb44f0bf2017-01-04 22:36:43 +00001537 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Richard Smithaada85c2016-02-06 02:06:43 +00001538 Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED
1539 : SM_SLOC_BUFFER_BLOB));
1540 if (Compressed)
1541 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
Douglas Gregora7f71a92009-04-10 03:52:48 +00001542 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
David Blaikieb44f0bf2017-01-04 22:36:43 +00001543 return Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001544}
1545
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001546/// Create an abbreviation for the SLocEntry that refers to a macro
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001547/// expansion.
1548static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001549 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001550
David Blaikieb44f0bf2017-01-04 22:36:43 +00001551 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001552 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001553 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1554 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1555 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1556 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Richard Smithb5f81712018-04-30 05:25:48 +00001557 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Is token range
Douglas Gregor83243272009-04-15 18:05:10 +00001558 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
David Blaikieb44f0bf2017-01-04 22:36:43 +00001559 return Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001560}
1561
Douglas Gregor09b69892011-02-10 17:09:37 +00001562namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001563
Douglas Gregor09b69892011-02-10 17:09:37 +00001564 // Trait used for the on-disk hash table of header search information.
1565 class HeaderFileInfoTrait {
1566 ASTWriter &Writer;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001567
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001568 // Keep track of the framework names we've used during serialization.
1569 SmallVector<char, 128> FrameworkStringData;
1570 llvm::StringMap<unsigned> FrameworkNameOffset;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001571
Douglas Gregor09b69892011-02-10 17:09:37 +00001572 public:
Richard Smith040e1262017-06-02 01:55:39 +00001573 HeaderFileInfoTrait(ASTWriter &Writer) : Writer(Writer) {}
1574
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001575 struct key_type {
Mehdi Amini004b9c72016-10-10 22:52:47 +00001576 StringRef Filename;
Richard Smith040e1262017-06-02 01:55:39 +00001577 off_t Size;
1578 time_t ModTime;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001579 };
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001580 using key_type_ref = const key_type &;
Richard Smith040e1262017-06-02 01:55:39 +00001581
1582 using UnresolvedModule =
1583 llvm::PointerIntPair<Module *, 2, ModuleMap::ModuleHeaderRole>;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001584
Richard Smith040e1262017-06-02 01:55:39 +00001585 struct data_type {
1586 const HeaderFileInfo &HFI;
1587 ArrayRef<ModuleMap::KnownHeader> KnownHeaders;
1588 UnresolvedModule Unresolved;
1589 };
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001590 using data_type_ref = const data_type &;
Richard Smith040e1262017-06-02 01:55:39 +00001591
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001592 using hash_value_type = unsigned;
1593 using offset_type = unsigned;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001594
Richard Smithe75ee0f2015-08-17 07:13:32 +00001595 hash_value_type ComputeHash(key_type_ref key) {
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001596 // The hash is based only on size/time of the file, so that the reader can
1597 // match even when symlinking or excess path elements ("foo/../", "../")
1598 // change the form of the name. However, complete path is still the key.
Richard Smith040e1262017-06-02 01:55:39 +00001599 return llvm::hash_combine(key.Size, key.ModTime);
Douglas Gregor09b69892011-02-10 17:09:37 +00001600 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001601
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001602 std::pair<unsigned, unsigned>
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001603 EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001604 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001605
Peter Collingbournee3f65292018-05-18 19:46:24 +00001606 endian::Writer LE(Out, little);
Mehdi Amini004b9c72016-10-10 22:52:47 +00001607 unsigned KeyLen = key.Filename.size() + 1 + 8 + 8;
Richard Smith386bb072015-08-18 23:42:23 +00001608 LE.write<uint16_t>(KeyLen);
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001609 unsigned DataLen = 1 + 2 + 4 + 4;
Richard Smith040e1262017-06-02 01:55:39 +00001610 for (auto ModInfo : Data.KnownHeaders)
Richard Smith386bb072015-08-18 23:42:23 +00001611 if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
1612 DataLen += 4;
Richard Smith040e1262017-06-02 01:55:39 +00001613 if (Data.Unresolved.getPointer())
1614 DataLen += 4;
Richard Smith386bb072015-08-18 23:42:23 +00001615 LE.write<uint8_t>(DataLen);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001616 return std::make_pair(KeyLen, DataLen);
Douglas Gregor09b69892011-02-10 17:09:37 +00001617 }
Richard Smith040e1262017-06-02 01:55:39 +00001618
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001619 void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001620 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001621
Peter Collingbournee3f65292018-05-18 19:46:24 +00001622 endian::Writer LE(Out, little);
Richard Smith040e1262017-06-02 01:55:39 +00001623 LE.write<uint64_t>(key.Size);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001624 KeyLen -= 8;
Richard Smith040e1262017-06-02 01:55:39 +00001625 LE.write<uint64_t>(key.ModTime);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001626 KeyLen -= 8;
Mehdi Amini004b9c72016-10-10 22:52:47 +00001627 Out.write(key.Filename.data(), KeyLen);
Douglas Gregor09b69892011-02-10 17:09:37 +00001628 }
Richard Smith040e1262017-06-02 01:55:39 +00001629
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001630 void EmitData(raw_ostream &Out, key_type_ref key,
Douglas Gregor09b69892011-02-10 17:09:37 +00001631 data_type_ref Data, unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001632 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001633
Peter Collingbournee3f65292018-05-18 19:46:24 +00001634 endian::Writer LE(Out, little);
Douglas Gregor09b69892011-02-10 17:09:37 +00001635 uint64_t Start = Out.tell(); (void)Start;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001636
Richard Smithf3f84612017-06-29 02:19:42 +00001637 unsigned char Flags = (Data.HFI.isImport << 5)
1638 | (Data.HFI.isPragmaOnce << 4)
Richard Smith040e1262017-06-02 01:55:39 +00001639 | (Data.HFI.DirInfo << 1)
1640 | Data.HFI.IndexHeaderMapHeader;
Justin Bognere1c147c2014-03-28 22:03:19 +00001641 LE.write<uint8_t>(Flags);
Richard Smith040e1262017-06-02 01:55:39 +00001642 LE.write<uint16_t>(Data.HFI.NumIncludes);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001643
Richard Smith040e1262017-06-02 01:55:39 +00001644 if (!Data.HFI.ControllingMacro)
1645 LE.write<uint32_t>(Data.HFI.ControllingMacroID);
Douglas Gregor09b69892011-02-10 17:09:37 +00001646 else
Richard Smith040e1262017-06-02 01:55:39 +00001647 LE.write<uint32_t>(Writer.getIdentifierRef(Data.HFI.ControllingMacro));
1648
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001649 unsigned Offset = 0;
Richard Smith040e1262017-06-02 01:55:39 +00001650 if (!Data.HFI.Framework.empty()) {
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001651 // If this header refers into a framework, save the framework name.
1652 llvm::StringMap<unsigned>::iterator Pos
Richard Smith040e1262017-06-02 01:55:39 +00001653 = FrameworkNameOffset.find(Data.HFI.Framework);
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001654 if (Pos == FrameworkNameOffset.end()) {
1655 Offset = FrameworkStringData.size() + 1;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001656 FrameworkStringData.append(Data.HFI.Framework.begin(),
Richard Smith040e1262017-06-02 01:55:39 +00001657 Data.HFI.Framework.end());
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001658 FrameworkStringData.push_back(0);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001659
Richard Smith040e1262017-06-02 01:55:39 +00001660 FrameworkNameOffset[Data.HFI.Framework] = Offset;
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001661 } else
1662 Offset = Pos->second;
1663 }
Justin Bognere1c147c2014-03-28 22:03:19 +00001664 LE.write<uint32_t>(Offset);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001665
Richard Smith040e1262017-06-02 01:55:39 +00001666 auto EmitModule = [&](Module *M, ModuleMap::ModuleHeaderRole Role) {
1667 if (uint32_t ModID = Writer.getLocalOrImportedSubmoduleID(M)) {
1668 uint32_t Value = (ModID << 2) | (unsigned)Role;
Richard Smith386bb072015-08-18 23:42:23 +00001669 assert((Value >> 2) == ModID && "overflow in header module info");
1670 LE.write<uint32_t>(Value);
1671 }
Richard Smith040e1262017-06-02 01:55:39 +00001672 };
1673
1674 // FIXME: If the header is excluded, we should write out some
1675 // record of that fact.
1676 for (auto ModInfo : Data.KnownHeaders)
1677 EmitModule(ModInfo.getModule(), ModInfo.getRole());
1678 if (Data.Unresolved.getPointer())
1679 EmitModule(Data.Unresolved.getPointer(), Data.Unresolved.getInt());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001680
Douglas Gregor09b69892011-02-10 17:09:37 +00001681 assert(Out.tell() - Start == DataLen && "Wrong data length");
1682 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001683
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001684 const char *strings_begin() const { return FrameworkStringData.begin(); }
1685 const char *strings_end() const { return FrameworkStringData.end(); }
Douglas Gregor09b69892011-02-10 17:09:37 +00001686 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001687
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001688} // namespace
Douglas Gregor09b69892011-02-10 17:09:37 +00001689
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001690/// Write the header search block for the list of files that
Douglas Gregor09b69892011-02-10 17:09:37 +00001691///
1692/// \param HS The header search structure to save.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001693void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
Richard Smith040e1262017-06-02 01:55:39 +00001694 HeaderFileInfoTrait GeneratorTrait(*this);
1695 llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
1696 SmallVector<const char *, 4> SavedStrings;
1697 unsigned NumHeaderSearchEntries = 0;
1698
1699 // Find all unresolved headers for the current module. We generally will
1700 // have resolved them before we get here, but not necessarily: we might be
1701 // compiling a preprocessed module, where there is no requirement for the
1702 // original files to exist any more.
Benjamin Krameree021d52017-06-02 17:30:24 +00001703 const HeaderFileInfo Empty; // So we can take a reference.
Richard Smith040e1262017-06-02 01:55:39 +00001704 if (WritingModule) {
1705 llvm::SmallVector<Module *, 16> Worklist(1, WritingModule);
1706 while (!Worklist.empty()) {
1707 Module *M = Worklist.pop_back_val();
1708 if (!M->isAvailable())
1709 continue;
1710
1711 // Map to disk files where possible, to pick up any missing stat
1712 // information. This also means we don't need to check the unresolved
1713 // headers list when emitting resolved headers in the first loop below.
1714 // FIXME: It'd be preferable to avoid doing this if we were given
1715 // sufficient stat information in the module map.
1716 HS.getModuleMap().resolveHeaderDirectives(M);
1717
1718 // If the file didn't exist, we can still create a module if we were given
1719 // enough information in the module map.
1720 for (auto U : M->MissingHeaders) {
1721 // Check that we were given enough information to build a module
1722 // without this file existing on disk.
1723 if (!U.Size || (!U.ModTime && IncludeTimestamps)) {
1724 PP->Diag(U.FileNameLoc, diag::err_module_no_size_mtime_for_header)
1725 << WritingModule->getFullModuleName() << U.Size.hasValue()
1726 << U.FileName;
1727 continue;
1728 }
1729
1730 // Form the effective relative pathname for the file.
1731 SmallString<128> Filename(M->Directory->getName());
1732 llvm::sys::path::append(Filename, U.FileName);
1733 PreparePathForOutput(Filename);
1734
1735 StringRef FilenameDup = strdup(Filename.c_str());
1736 SavedStrings.push_back(FilenameDup.data());
1737
1738 HeaderFileInfoTrait::key_type Key = {
1739 FilenameDup, *U.Size, IncludeTimestamps ? *U.ModTime : 0
1740 };
1741 HeaderFileInfoTrait::data_type Data = {
Benjamin Krameree021d52017-06-02 17:30:24 +00001742 Empty, {}, {M, ModuleMap::headerKindToRole(U.Kind)}
Richard Smith040e1262017-06-02 01:55:39 +00001743 };
1744 // FIXME: Deal with cases where there are multiple unresolved header
1745 // directives in different submodules for the same header.
1746 Generator.insert(Key, Data, GeneratorTrait);
1747 ++NumHeaderSearchEntries;
1748 }
1749
1750 Worklist.append(M->submodule_begin(), M->submodule_end());
1751 }
1752 }
1753
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001754 SmallVector<const FileEntry *, 16> FilesByUID;
Douglas Gregor09b69892011-02-10 17:09:37 +00001755 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001756
Douglas Gregor09b69892011-02-10 17:09:37 +00001757 if (FilesByUID.size() > HS.header_file_size())
1758 FilesByUID.resize(HS.header_file_size());
Richard Smith040e1262017-06-02 01:55:39 +00001759
Douglas Gregor09b69892011-02-10 17:09:37 +00001760 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1761 const FileEntry *File = FilesByUID[UID];
1762 if (!File)
1763 continue;
1764
Richard Smith386bb072015-08-18 23:42:23 +00001765 // Get the file info. This will load info from the external source if
1766 // necessary. Skip emitting this file if we have no information on it
1767 // as a header file (in which case HFI will be null) or if it hasn't
1768 // changed since it was loaded. Also skip it if it's for a modular header
1769 // from a different module; in that case, we rely on the module(s)
1770 // containing the header to provide this information.
Richard Smithd8879c82015-08-24 21:59:32 +00001771 const HeaderFileInfo *HFI =
1772 HS.getExistingFileInfo(File, /*WantExternal*/!Chain);
1773 if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001774 continue;
Douglas Gregor09b69892011-02-10 17:09:37 +00001775
Richard Smith7ed1bc92014-12-05 22:42:13 +00001776 // Massage the file path into an appropriate form.
Mehdi Amini004b9c72016-10-10 22:52:47 +00001777 StringRef Filename = File->getName();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001778 SmallString<128> FilenameTmp(Filename);
1779 if (PreparePathForOutput(FilenameTmp)) {
1780 // If we performed any translation on the file name at all, we need to
1781 // save this string, since the generator will refer to it later.
Mehdi Amini004b9c72016-10-10 22:52:47 +00001782 Filename = StringRef(strdup(FilenameTmp.c_str()));
1783 SavedStrings.push_back(Filename.data());
Douglas Gregor09b69892011-02-10 17:09:37 +00001784 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001785
Richard Smith040e1262017-06-02 01:55:39 +00001786 HeaderFileInfoTrait::key_type Key = {
1787 Filename, File->getSize(), getTimestampForOutput(File)
1788 };
1789 HeaderFileInfoTrait::data_type Data = {
1790 *HFI, HS.getModuleMap().findAllModulesForHeader(File), {}
1791 };
1792 Generator.insert(Key, Data, GeneratorTrait);
Douglas Gregor09b69892011-02-10 17:09:37 +00001793 ++NumHeaderSearchEntries;
1794 }
Richard Smith040e1262017-06-02 01:55:39 +00001795
Douglas Gregor09b69892011-02-10 17:09:37 +00001796 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001797 SmallString<4096> TableData;
Douglas Gregor09b69892011-02-10 17:09:37 +00001798 uint32_t BucketOffset;
1799 {
Justin Bognere1c147c2014-03-28 22:03:19 +00001800 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001801
Douglas Gregor09b69892011-02-10 17:09:37 +00001802 llvm::raw_svector_ostream Out(TableData);
1803 // Make sure that no bucket is at offset 0
Peter Collingbournee3f65292018-05-18 19:46:24 +00001804 endian::write<uint32_t>(Out, 0, little);
Douglas Gregor09b69892011-02-10 17:09:37 +00001805 BucketOffset = Generator.Emit(Out, GeneratorTrait);
1806 }
1807
1808 // Create a blob abbreviation
1809 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001810
David Blaikieb44f0bf2017-01-04 22:36:43 +00001811 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor09b69892011-02-10 17:09:37 +00001812 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1813 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1814 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001815 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor09b69892011-02-10 17:09:37 +00001816 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00001817 unsigned TableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001818
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001819 // Write the header search table
Mehdi Amini57a41912015-09-10 01:46:39 +00001820 RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
1821 NumHeaderSearchEntries, TableData.size()};
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001822 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
Yaron Keren92e1b622015-03-18 10:17:07 +00001823 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001824
Douglas Gregor09b69892011-02-10 17:09:37 +00001825 // Free all of the strings we had to duplicate.
1826 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
David Greenebae0e352013-01-15 22:09:43 +00001827 free(const_cast<char *>(SavedStrings[I]));
Douglas Gregor09b69892011-02-10 17:09:37 +00001828}
1829
George Rimarc39f5492017-01-17 15:45:31 +00001830static void emitBlob(llvm::BitstreamWriter &Stream, StringRef Blob,
1831 unsigned SLocBufferBlobCompressedAbbrv,
1832 unsigned SLocBufferBlobAbbrv) {
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001833 using RecordDataType = ASTWriter::RecordData::value_type;
George Rimarc39f5492017-01-17 15:45:31 +00001834
1835 // Compress the buffer if possible. We expect that almost all PCM
1836 // consumers will not want its contents.
1837 SmallString<0> CompressedBuffer;
1838 if (llvm::zlib::isAvailable()) {
1839 llvm::Error E = llvm::zlib::compress(Blob.drop_back(1), CompressedBuffer);
1840 if (!E) {
1841 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED,
1842 Blob.size() - 1};
1843 Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
1844 CompressedBuffer);
1845 return;
1846 }
1847 llvm::consumeError(std::move(E));
1848 }
1849
1850 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB};
1851 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob);
1852}
1853
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001854/// Writes the block containing the serialized form of the
Douglas Gregora7f71a92009-04-10 03:52:48 +00001855/// source manager.
1856///
1857/// TODO: We should probably use an on-disk hash table (stored in a
1858/// blob), indexed based on the file name, so that we only create
1859/// entries for files that we actually need. In the common case (no
1860/// errors), we probably won't have to create file entries for any of
1861/// the files in the AST.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00001862void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001863 const Preprocessor &PP) {
Douglas Gregor258ae542009-04-27 06:38:32 +00001864 RecordData Record;
1865
Chris Lattner0910e3b2009-04-10 17:16:57 +00001866 // Enter the source manager block.
Richard Smithaada85c2016-02-06 02:06:43 +00001867 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001868
1869 // Abbreviations for the various kinds of source-location entries.
Chris Lattnerc4976c732009-04-27 19:03:22 +00001870 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
1871 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
Richard Smithaada85c2016-02-06 02:06:43 +00001872 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
1873 unsigned SLocBufferBlobCompressedAbbrv =
1874 CreateSLocBufferBlobAbbrev(Stream, true);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001875 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001876
Douglas Gregor258ae542009-04-27 06:38:32 +00001877 // Write out the source location entry table. We skip the first
1878 // entry, which is always the same dummy entry.
Chris Lattner12d61d32009-04-27 19:01:47 +00001879 std::vector<uint32_t> SLocEntryOffsets;
Douglas Gregor258ae542009-04-27 06:38:32 +00001880 RecordData PreloadSLocs;
Douglas Gregor925296b2011-07-19 16:10:42 +00001881 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
1882 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
Sebastian Redl5c415f32010-07-22 17:01:13 +00001883 I != N; ++I) {
Douglas Gregor8655e882009-10-16 22:46:09 +00001884 // Get this source location entry.
Douglas Gregor925296b2011-07-19 16:10:42 +00001885 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00001886 FileID FID = FileID::get(I);
1887 assert(&SourceMgr.getSLocEntry(FID) == SLoc);
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00001888
Douglas Gregor258ae542009-04-27 06:38:32 +00001889 // Record the offset of this source-location entry.
1890 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
1891
1892 // Figure out which record code to use.
1893 unsigned Code;
1894 if (SLoc->isFile()) {
Douglas Gregor9dc32122011-11-16 20:05:18 +00001895 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1896 if (Cache->OrigEntry) {
Sebastian Redl539c5062010-08-18 23:57:32 +00001897 Code = SM_SLOC_FILE_ENTRY;
Argyrios Kyrtzidis92dd4662011-06-02 20:01:46 +00001898 } else
Sebastian Redl539c5062010-08-18 23:57:32 +00001899 Code = SM_SLOC_BUFFER_ENTRY;
Douglas Gregor258ae542009-04-27 06:38:32 +00001900 } else
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001901 Code = SM_SLOC_EXPANSION_ENTRY;
Douglas Gregor258ae542009-04-27 06:38:32 +00001902 Record.clear();
1903 Record.push_back(Code);
1904
Douglas Gregor925296b2011-07-19 16:10:42 +00001905 // Starting offset of this entry within this module, so skip the dummy.
1906 Record.push_back(SLoc->getOffset() - 2);
Douglas Gregor258ae542009-04-27 06:38:32 +00001907 if (SLoc->isFile()) {
1908 const SrcMgr::FileInfo &File = SLoc->getFile();
Richard Smithb22a1d12016-03-27 20:13:24 +00001909 AddSourceLocation(File.getIncludeLoc(), Record);
Douglas Gregor258ae542009-04-27 06:38:32 +00001910 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
1911 Record.push_back(File.hasLineDirectives());
1912
1913 const SrcMgr::ContentCache *Content = File.getContentCache();
Richard Smithaada85c2016-02-06 02:06:43 +00001914 bool EmitBlob = false;
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001915 if (Content->OrigEntry) {
1916 assert(Content->OrigEntry == Content->ContentsEntry &&
Douglas Gregor9dc32122011-11-16 20:05:18 +00001917 "Writing to AST an overridden file is not supported");
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001918
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001919 // The source location entry is a file. Emit input file ID.
1920 assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
1921 Record.push_back(InputFileIDs[Content->OrigEntry]);
Mike Stump11289f42009-09-09 15:08:12 +00001922
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001923 Record.push_back(File.NumCreatedFIDs);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001924
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00001925 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00001926 if (FDI != FileDeclIDs.end()) {
1927 Record.push_back(FDI->second->FirstDeclIndex);
1928 Record.push_back(FDI->second->DeclIDs.size());
1929 } else {
1930 Record.push_back(0);
1931 Record.push_back(0);
1932 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001933
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001934 Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001935
Richard Smithaada85c2016-02-06 02:06:43 +00001936 if (Content->BufferOverridden || Content->IsTransient)
1937 EmitBlob = true;
Douglas Gregor258ae542009-04-27 06:38:32 +00001938 } else {
1939 // The source location entry is a buffer. The blob associated
1940 // with this entry contains the contents of the buffer.
1941
1942 // We add one to the size so that we capture the trailing NULL
1943 // that is required by llvm::MemoryBuffer::getMemBuffer (on
1944 // the reader side).
Duncan P. N. Exon Smithf5848192019-08-26 20:32:05 +00001945 const llvm::MemoryBuffer *Buffer =
1946 Content->getBuffer(PP.getDiagnostics(), PP.getFileManager());
Mehdi Amini99d1b292016-10-01 16:38:28 +00001947 StringRef Name = Buffer->getBufferIdentifier();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001948 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
Mehdi Amini99d1b292016-10-01 16:38:28 +00001949 StringRef(Name.data(), Name.size() + 1));
Richard Smithaada85c2016-02-06 02:06:43 +00001950 EmitBlob = true;
Douglas Gregor258ae542009-04-27 06:38:32 +00001951
Mehdi Amini99d1b292016-10-01 16:38:28 +00001952 if (Name == "<built-in>")
Douglas Gregor925296b2011-07-19 16:10:42 +00001953 PreloadSLocs.push_back(SLocEntryOffsets.size());
Douglas Gregor258ae542009-04-27 06:38:32 +00001954 }
Richard Smithaada85c2016-02-06 02:06:43 +00001955
1956 if (EmitBlob) {
1957 // Include the implicit terminating null character in the on-disk buffer
1958 // if we're writing it uncompressed.
1959 const llvm::MemoryBuffer *Buffer =
Duncan P. N. Exon Smithf5848192019-08-26 20:32:05 +00001960 Content->getBuffer(PP.getDiagnostics(), PP.getFileManager());
Richard Smithaada85c2016-02-06 02:06:43 +00001961 StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
George Rimarc39f5492017-01-17 15:45:31 +00001962 emitBlob(Stream, Blob, SLocBufferBlobCompressedAbbrv,
1963 SLocBufferBlobAbbrv);
Richard Smithaada85c2016-02-06 02:06:43 +00001964 }
Douglas Gregor258ae542009-04-27 06:38:32 +00001965 } else {
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001966 // The source location entry is a macro expansion.
Chandler Carruthee4c1d12011-07-26 04:56:51 +00001967 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
Richard Smithb22a1d12016-03-27 20:13:24 +00001968 AddSourceLocation(Expansion.getSpellingLoc(), Record);
1969 AddSourceLocation(Expansion.getExpansionLocStart(), Record);
1970 AddSourceLocation(Expansion.isMacroArgExpansion()
1971 ? SourceLocation()
1972 : Expansion.getExpansionLocEnd(),
1973 Record);
Richard Smithb5f81712018-04-30 05:25:48 +00001974 Record.push_back(Expansion.isExpansionTokenRange());
Douglas Gregor258ae542009-04-27 06:38:32 +00001975
1976 // Compute the token length for this macro expansion.
Douglas Gregor925296b2011-07-19 16:10:42 +00001977 unsigned NextOffset = SourceMgr.getNextLocalOffset();
Douglas Gregor8655e882009-10-16 22:46:09 +00001978 if (I + 1 != N)
Douglas Gregor925296b2011-07-19 16:10:42 +00001979 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
Douglas Gregor258ae542009-04-27 06:38:32 +00001980 Record.push_back(NextOffset - SLoc->getOffset() - 1);
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001981 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
Douglas Gregor258ae542009-04-27 06:38:32 +00001982 }
1983 }
1984
Douglas Gregor8f45df52009-04-16 22:23:12 +00001985 Stream.ExitBlock();
Douglas Gregor258ae542009-04-27 06:38:32 +00001986
1987 if (SLocEntryOffsets.empty())
1988 return;
1989
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00001990 // Write the source-location offsets table into the AST block. This
Douglas Gregor258ae542009-04-27 06:38:32 +00001991 // table is used for lazily loading source-location information.
1992 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001993
David Blaikieb44f0bf2017-01-04 22:36:43 +00001994 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00001995 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
Douglas Gregor258ae542009-04-27 06:38:32 +00001996 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
Douglas Gregor925296b2011-07-19 16:10:42 +00001997 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
Douglas Gregor258ae542009-04-27 06:38:32 +00001998 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
David Blaikieb44f0bf2017-01-04 22:36:43 +00001999 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00002000 {
2001 RecordData::value_type Record[] = {
2002 SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
2003 SourceMgr.getNextLocalOffset() - 1 /* skip dummy */};
2004 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
2005 bytes(SLocEntryOffsets));
2006 }
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002007 // Write the source location entry preloads array, telling the AST
Douglas Gregor258ae542009-04-27 06:38:32 +00002008 // reader which source locations entries it should load eagerly.
Sebastian Redl539c5062010-08-18 23:57:32 +00002009 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregor925296b2011-07-19 16:10:42 +00002010
2011 // Write the line table. It depends on remapping working, so it must come
2012 // after the source location offsets.
2013 if (SourceMgr.hasLineTable()) {
2014 LineTableInfo &LineTable = SourceMgr.getLineTable();
2015
2016 Record.clear();
Richard Smith63078492015-09-01 07:41:55 +00002017
2018 // Emit the needed file names.
2019 llvm::DenseMap<int, int> FilenameMap;
Hans Wennborg14487362017-12-04 22:28:45 +00002020 FilenameMap[-1] = -1; // For unspecified filenames.
Richard Smith63078492015-09-01 07:41:55 +00002021 for (const auto &L : LineTable) {
2022 if (L.first.ID < 0)
2023 continue;
2024 for (auto &LE : L.second) {
2025 if (FilenameMap.insert(std::make_pair(LE.FilenameID,
Hans Wennborg14487362017-12-04 22:28:45 +00002026 FilenameMap.size() - 1)).second)
Richard Smith63078492015-09-01 07:41:55 +00002027 AddPath(LineTable.getFilename(LE.FilenameID), Record);
2028 }
2029 }
2030 Record.push_back(0);
Douglas Gregor925296b2011-07-19 16:10:42 +00002031
2032 // Emit the line entries
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002033 for (const auto &L : LineTable) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002034 // Only emit entries for local files.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002035 if (L.first.ID < 0)
Douglas Gregor925296b2011-07-19 16:10:42 +00002036 continue;
2037
2038 // Emit the file ID
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002039 Record.push_back(L.first.ID);
Douglas Gregor925296b2011-07-19 16:10:42 +00002040
2041 // Emit the line entries
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002042 Record.push_back(L.second.size());
2043 for (const auto &LE : L.second) {
2044 Record.push_back(LE.FileOffset);
2045 Record.push_back(LE.LineNo);
2046 Record.push_back(FilenameMap[LE.FilenameID]);
2047 Record.push_back((unsigned)LE.FileKind);
2048 Record.push_back(LE.IncludeOffset);
Douglas Gregor925296b2011-07-19 16:10:42 +00002049 }
2050 }
Richard Smith63078492015-09-01 07:41:55 +00002051
Douglas Gregor925296b2011-07-19 16:10:42 +00002052 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
2053 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00002054}
2055
Douglas Gregorc5046832009-04-27 18:38:38 +00002056//===----------------------------------------------------------------------===//
2057// Preprocessor Serialization
2058//===----------------------------------------------------------------------===//
2059
Argyrios Kyrtzidis0aef0f02013-03-15 22:43:10 +00002060static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
2061 const Preprocessor &PP) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002062 if (MacroInfo *MI = MD->getMacroInfo())
2063 if (MI->isBuiltinMacro())
2064 return true;
Argyrios Kyrtzidis0aef0f02013-03-15 22:43:10 +00002065
2066 if (IsModule) {
2067 SourceLocation Loc = MD->getLocation();
2068 if (Loc.isInvalid())
2069 return true;
2070 if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
2071 return true;
2072 }
2073
2074 return false;
2075}
2076
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002077/// Writes the block containing the serialized form of the
Chris Lattnereeffaef2009-04-10 17:15:23 +00002078/// preprocessor.
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00002079void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002080 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
2081 if (PPRec)
2082 WritePreprocessorDetail(*PPRec);
2083
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002084 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00002085 RecordData ModuleMacroRecord;
Chris Lattner0910e3b2009-04-10 17:16:57 +00002086
Chris Lattner0af3ba12009-04-13 01:29:17 +00002087 // If the preprocessor __COUNTER__ value has been bumped, remember it.
2088 if (PP.getCounterValue() != 0) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002089 RecordData::value_type Record[] = {PP.getCounterValue()};
Sebastian Redl539c5062010-08-18 23:57:32 +00002090 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
Douglas Gregoreda6a892009-04-26 00:07:37 +00002091 }
2092
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00002093 if (PP.isRecordingPreamble() && PP.hasRecordedPreamble()) {
2094 assert(!IsModule);
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00002095 auto SkipInfo = PP.getPreambleSkipInfo();
2096 if (SkipInfo.hasValue()) {
2097 Record.push_back(true);
2098 AddSourceLocation(SkipInfo->HashTokenLoc, Record);
2099 AddSourceLocation(SkipInfo->IfTokenLoc, Record);
2100 Record.push_back(SkipInfo->FoundNonSkipPortion);
2101 Record.push_back(SkipInfo->FoundElse);
2102 AddSourceLocation(SkipInfo->ElseLoc, Record);
2103 } else {
2104 Record.push_back(false);
2105 }
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00002106 for (const auto &Cond : PP.getPreambleConditionalStack()) {
2107 AddSourceLocation(Cond.IfLoc, Record);
2108 Record.push_back(Cond.WasSkipping);
2109 Record.push_back(Cond.FoundNonSkip);
2110 Record.push_back(Cond.FoundElse);
2111 }
2112 Stream.EmitRecord(PP_CONDITIONAL_STACK, Record);
2113 Record.clear();
2114 }
2115
Douglas Gregoreda6a892009-04-26 00:07:37 +00002116 // Enter the preprocessor block.
Douglas Gregor796d76a2010-10-20 22:00:55 +00002117 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
Mike Stump11289f42009-09-09 15:08:12 +00002118
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002119 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
Richard Smithb5aaf5a2015-09-01 02:35:58 +00002120 // FIXME: Include a location for the use, and say which one was used.
Douglas Gregoreda6a892009-04-26 00:07:37 +00002121 if (PP.SawDateOrTime())
Richard Smithb5aaf5a2015-09-01 02:35:58 +00002122 PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
Douglas Gregor796d76a2010-10-20 22:00:55 +00002123
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002124 // Loop over all the macro directives that are live at the end of the file,
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002125 // emitting each to the PP section.
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002126
Richard Smithee977932015-05-01 21:22:17 +00002127 // Construct the list of identifiers with macro directives that need to be
2128 // serialized.
2129 SmallVector<const IdentifierInfo *, 128> MacroIdentifiers;
2130 for (auto &Id : PP.getIdentifierTable())
2131 if (Id.second->hadMacroDefinition() &&
2132 (!Id.second->isFromAST() ||
2133 Id.second->hasChangedSinceDeserialization()))
2134 MacroIdentifiers.push_back(Id.second);
Douglas Gregor2e5571d2011-02-10 18:20:09 +00002135 // Sort the set of macro definitions that need to be serialized by the
2136 // name of the macro, to provide a stable ordering.
Benjamin Kramercd2bae32019-08-22 17:32:16 +00002137 llvm::sort(MacroIdentifiers, llvm::deref<std::less<>>());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002138
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002139 // Emit the macro directives as a list and associate the offset with the
2140 // identifier they belong to.
Richard Smithee977932015-05-01 21:22:17 +00002141 for (const IdentifierInfo *Name : MacroIdentifiers) {
2142 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name);
Richard Smithd7329392015-04-21 21:46:32 +00002143 auto StartOffset = Stream.GetCurrentBitNo();
2144
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002145 // Emit the macro directives in reverse source order.
2146 for (; MD; MD = MD->getPrevious()) {
Richard Smithd7329392015-04-21 21:46:32 +00002147 // Once we hit an ignored macro, we're done: the rest of the chain
2148 // will all be ignored macros.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002149 if (shouldIgnoreMacro(MD, IsModule, PP))
Richard Smithd7329392015-04-21 21:46:32 +00002150 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002151
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002152 AddSourceLocation(MD->getLocation(), Record);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002153 Record.push_back(MD->getKind());
Richard Smithdaa69e02014-07-25 04:40:03 +00002154 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
Richard Smith3981b172015-04-30 02:16:23 +00002155 Record.push_back(getMacroRef(DefMD->getInfo(), Name));
Richard Smith713369b2015-04-23 20:40:50 +00002156 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002157 Record.push_back(VisMD->isPublic());
2158 }
Richard Smithb8b2ed62015-04-23 18:18:26 +00002159 }
Richard Smithd7329392015-04-21 21:46:32 +00002160
Richard Smithb8b2ed62015-04-23 18:18:26 +00002161 // Write out any exported module macros.
Richard Smithee977932015-05-01 21:22:17 +00002162 bool EmittedModuleMacros = false;
Manman Ren33d80292016-05-31 18:19:32 +00002163 // We write out exported module macros for PCH as well.
2164 auto Leafs = PP.getLeafModuleMacros(Name);
2165 SmallVector<ModuleMacro*, 8> Worklist(Leafs.begin(), Leafs.end());
2166 llvm::DenseMap<ModuleMacro*, unsigned> Visits;
2167 while (!Worklist.empty()) {
2168 auto *Macro = Worklist.pop_back_val();
Richard Smithd7329392015-04-21 21:46:32 +00002169
Manman Ren33d80292016-05-31 18:19:32 +00002170 // Emit a record indicating this submodule exports this macro.
2171 ModuleMacroRecord.push_back(
2172 getSubmoduleID(Macro->getOwningModule()));
2173 ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
2174 for (auto *M : Macro->overrides())
2175 ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
Richard Smithd7329392015-04-21 21:46:32 +00002176
Manman Ren33d80292016-05-31 18:19:32 +00002177 Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2178 ModuleMacroRecord.clear();
Richard Smithd7329392015-04-21 21:46:32 +00002179
Manman Ren33d80292016-05-31 18:19:32 +00002180 // Enqueue overridden macros once we've visited all their ancestors.
2181 for (auto *M : Macro->overrides())
2182 if (++Visits[M] == M->getNumOverridingMacros())
2183 Worklist.push_back(M);
Richard Smithee977932015-05-01 21:22:17 +00002184
Manman Ren33d80292016-05-31 18:19:32 +00002185 EmittedModuleMacros = true;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002186 }
Richard Smithd7329392015-04-21 21:46:32 +00002187
Richard Smithee977932015-05-01 21:22:17 +00002188 if (Record.empty() && !EmittedModuleMacros)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002189 continue;
2190
Richard Smithd7329392015-04-21 21:46:32 +00002191 IdentMacroDirectivesOffsetMap[Name] = StartOffset;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002192 Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2193 Record.clear();
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002194 }
Alexander Kornienko1d26c022012-09-25 17:18:14 +00002195
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002196 /// Offsets of each of the macros into the bitstream, indexed by
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002197 /// the local macro ID
2198 ///
2199 /// For each identifier that is associated with a macro, this map
2200 /// provides the offset into the bitstream where that macro is
2201 /// defined.
2202 std::vector<uint32_t> MacroOffsets;
2203
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002204 for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2205 const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2206 MacroInfo *MI = MacroInfosToEmit[I].MI;
2207 MacroID ID = MacroInfosToEmit[I].ID;
Douglas Gregoreb114da2010-10-01 01:03:07 +00002208
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002209 if (ID < FirstMacroID) {
2210 assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2211 continue;
Chris Lattner2199f5b2009-04-10 18:08:30 +00002212 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002213
2214 // Record the local offset of this macro.
2215 unsigned Index = ID - FirstMacroID;
2216 if (Index == MacroOffsets.size())
2217 MacroOffsets.push_back(Stream.GetCurrentBitNo());
2218 else {
2219 if (Index > MacroOffsets.size())
2220 MacroOffsets.resize(Index + 1);
2221
2222 MacroOffsets[Index] = Stream.GetCurrentBitNo();
2223 }
2224
2225 AddIdentifierRef(Name, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002226 AddSourceLocation(MI->getDefinitionLoc(), Record);
2227 AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2228 Record.push_back(MI->isUsed());
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00002229 Record.push_back(MI->isUsedForHeaderGuard());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002230 unsigned Code;
2231 if (MI->isObjectLike()) {
2232 Code = PP_MACRO_OBJECT_LIKE;
2233 } else {
2234 Code = PP_MACRO_FUNCTION_LIKE;
2235
2236 Record.push_back(MI->isC99Varargs());
2237 Record.push_back(MI->isGNUVarargs());
2238 Record.push_back(MI->hasCommaPasting());
Faisal Valiac506d72017-07-17 17:18:43 +00002239 Record.push_back(MI->getNumParams());
2240 for (const IdentifierInfo *Param : MI->params())
2241 AddIdentifierRef(Param, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002242 }
2243
2244 // If we have a detailed preprocessing record, record the macro definition
2245 // ID that corresponds to this macro.
2246 if (PPRec)
2247 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2248
2249 Stream.EmitRecord(Code, Record);
2250 Record.clear();
2251
2252 // Emit the tokens array.
2253 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2254 // Note that we know that the preprocessor does not have any annotation
2255 // tokens in it because they are created by the parser, and thus can't
2256 // be in a macro definition.
2257 const Token &Tok = MI->getReplacementToken(TokNo);
John McCallf413f5e2013-05-03 00:10:13 +00002258 AddToken(Tok, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002259 Stream.EmitRecord(PP_TOKEN, Record);
2260 Record.clear();
2261 }
2262 ++NumMacros;
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002263 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002264
Douglas Gregor92a96f52011-02-08 21:58:10 +00002265 Stream.ExitBlock();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002266
2267 // Write the offsets table for macro IDs.
2268 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002269
David Blaikieb44f0bf2017-01-04 22:36:43 +00002270 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002271 Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2272 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2273 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2274 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2275
David Blaikieb44f0bf2017-01-04 22:36:43 +00002276 unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00002277 {
2278 RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
2279 FirstMacroID - NUM_PREDEF_MACRO_IDS};
2280 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
2281 }
Douglas Gregor92a96f52011-02-08 21:58:10 +00002282}
2283
2284void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
Argyrios Kyrtzidis7f448362011-09-19 20:40:42 +00002285 if (PPRec.local_begin() == PPRec.local_end())
Douglas Gregor92a96f52011-02-08 21:58:10 +00002286 return;
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002287
Argyrios Kyrtzidis64f63812011-09-19 20:40:25 +00002288 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002289
Douglas Gregor92a96f52011-02-08 21:58:10 +00002290 // Enter the preprocessor block.
2291 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002292
Douglas Gregoraae92242010-03-19 21:51:54 +00002293 // If the preprocessor has a preprocessing record, emit it.
2294 unsigned NumPreprocessingRecords = 0;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002295 using namespace llvm;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002296
2297 // Set up the abbreviation for
Douglas Gregor92a96f52011-02-08 21:58:10 +00002298 unsigned InclusionAbbrev = 0;
2299 {
David Blaikieb44f0bf2017-01-04 22:36:43 +00002300 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor92a96f52011-02-08 21:58:10 +00002301 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
Douglas Gregor92a96f52011-02-08 21:58:10 +00002302 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2303 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2304 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
Argyrios Kyrtzidisf590e092012-10-02 16:10:46 +00002305 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
Douglas Gregor92a96f52011-02-08 21:58:10 +00002306 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00002307 InclusionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor92a96f52011-02-08 21:58:10 +00002308 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002309
2310 unsigned FirstPreprocessorEntityID
2311 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002312 + NUM_PREDEF_PP_ENTITY_IDS;
2313 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002314 RecordData Record;
Argyrios Kyrtzidis7f448362011-09-19 20:40:42 +00002315 for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2316 EEnd = PPRec.local_end();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002317 E != EEnd;
Douglas Gregor0d4b4312011-08-04 17:06:18 +00002318 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
Douglas Gregor92a96f52011-02-08 21:58:10 +00002319 Record.clear();
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002320
Richard Smith66a81862015-05-04 02:25:31 +00002321 PreprocessedEntityOffsets.push_back(
2322 PPEntityOffset((*E)->getSourceRange(), Stream.GetCurrentBitNo()));
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002323
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002324 if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002325 // Record this macro definition's ID.
2326 MacroDefinitions[MD] = NextPreprocessorEntityID;
Richard Smith66a81862015-05-04 02:25:31 +00002327
Douglas Gregor92a96f52011-02-08 21:58:10 +00002328 AddIdentifierRef(MD->getName(), Record);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002329 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2330 continue;
Douglas Gregoraae92242010-03-19 21:51:54 +00002331 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002332
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002333 if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
Argyrios Kyrtzidis80f78b92011-09-08 17:18:41 +00002334 Record.push_back(ME->isBuiltinMacro());
2335 if (ME->isBuiltinMacro())
2336 AddIdentifierRef(ME->getName(), Record);
2337 else
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002338 Record.push_back(MacroDefinitions[ME->getDefinition()]);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00002339 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002340 continue;
2341 }
2342
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002343 if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
Douglas Gregor92a96f52011-02-08 21:58:10 +00002344 Record.push_back(PPD_INCLUSION_DIRECTIVE);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002345 Record.push_back(ID->getFileName().size());
2346 Record.push_back(ID->wasInQuotes());
2347 Record.push_back(static_cast<unsigned>(ID->getKind()));
Argyrios Kyrtzidisf590e092012-10-02 16:10:46 +00002348 Record.push_back(ID->importedModule());
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002349 SmallString<64> Buffer;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002350 Buffer += ID->getFileName();
Argyrios Kyrtzidis8dbcfc32012-03-08 01:08:28 +00002351 // Check that the FileEntry is not null because it was not resolved and
2352 // we create a PCH even with compiler errors.
2353 if (ID->getFile())
2354 Buffer += ID->getFile()->getName();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00002355 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002356 continue;
2357 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002358
Douglas Gregor92a96f52011-02-08 21:58:10 +00002359 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2360 }
Douglas Gregor8f45df52009-04-16 22:23:12 +00002361 Stream.ExitBlock();
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002362
Douglas Gregoraae92242010-03-19 21:51:54 +00002363 // Write the offsets table for the preprocessing record.
2364 if (NumPreprocessingRecords > 0) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002365 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2366
Douglas Gregoraae92242010-03-19 21:51:54 +00002367 // Write the offsets table for identifier IDs.
2368 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002369
David Blaikieb44f0bf2017-01-04 22:36:43 +00002370 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002371 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002372 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
Douglas Gregoraae92242010-03-19 21:51:54 +00002373 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00002374 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002375
Mehdi Amini57a41912015-09-10 01:46:39 +00002376 RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
2377 FirstPreprocessorEntityID -
2378 NUM_PREDEF_PP_ENTITY_IDS};
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002379 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00002380 bytes(PreprocessedEntityOffsets));
Douglas Gregoraae92242010-03-19 21:51:54 +00002381 }
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00002382
2383 // Write the skipped region table for the preprocessing record.
2384 ArrayRef<SourceRange> SkippedRanges = PPRec.getSkippedRanges();
2385 if (SkippedRanges.size() > 0) {
2386 std::vector<PPSkippedRange> SerializedSkippedRanges;
2387 SerializedSkippedRanges.reserve(SkippedRanges.size());
2388 for (auto const& Range : SkippedRanges)
2389 SerializedSkippedRanges.emplace_back(Range);
2390
2391 using namespace llvm;
2392 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2393 Abbrev->Add(BitCodeAbbrevOp(PPD_SKIPPED_RANGES));
2394 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2395 unsigned PPESkippedRangeAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2396
2397 Record.clear();
2398 Record.push_back(PPD_SKIPPED_RANGES);
2399 Stream.EmitRecordWithBlob(PPESkippedRangeAbbrev, Record,
2400 bytes(SerializedSkippedRanges));
2401 }
Chris Lattnereeffaef2009-04-10 17:15:23 +00002402}
2403
Richard Smith386bb072015-08-18 23:42:23 +00002404unsigned ASTWriter::getLocalOrImportedSubmoduleID(Module *Mod) {
Richard Smith080056b2015-08-18 21:53:42 +00002405 if (!Mod)
2406 return 0;
2407
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002408 llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
2409 if (Known != SubmoduleIDs.end())
2410 return Known->second;
Richard Smith386bb072015-08-18 23:42:23 +00002411
Richard Smithdc1f0422016-07-20 19:10:16 +00002412 auto *Top = Mod->getTopLevelModule();
2413 if (Top != WritingModule &&
Bruno Cardoso Lopes17da34d2017-02-07 21:54:57 +00002414 (getLangOpts().CompilingPCH ||
2415 !Top->fullModuleNameIs(StringRef(getLangOpts().CurrentModule))))
Richard Smith386bb072015-08-18 23:42:23 +00002416 return 0;
2417
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002418 return SubmoduleIDs[Mod] = NextSubmoduleID++;
2419}
2420
Richard Smith386bb072015-08-18 23:42:23 +00002421unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2422 // FIXME: This can easily happen, if we have a reference to a submodule that
2423 // did not result in us loading a module file for that submodule. For
2424 // instance, a cross-top-level-module 'conflict' declaration will hit this.
2425 unsigned ID = getLocalOrImportedSubmoduleID(Mod);
2426 assert((ID || !Mod) &&
2427 "asked for module ID for non-local, non-imported module");
2428 return ID;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00002429}
2430
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002431/// Compute the number of modules within the given tree (including the
Douglas Gregor253eefe2011-12-01 00:59:36 +00002432/// given module).
2433static unsigned getNumberOfModules(Module *Mod) {
2434 unsigned ChildModules = 0;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002435 for (auto Sub = Mod->submodule_begin(), SubEnd = Mod->submodule_end();
Douglas Gregor253eefe2011-12-01 00:59:36 +00002436 Sub != SubEnd; ++Sub)
Douglas Gregoreb90e832012-01-04 23:32:19 +00002437 ChildModules += getNumberOfModules(*Sub);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002438
Douglas Gregor253eefe2011-12-01 00:59:36 +00002439 return ChildModules + 1;
2440}
2441
Douglas Gregorde3ef502011-11-30 23:21:26 +00002442void ASTWriter::WriteSubmodules(Module *WritingModule) {
Douglas Gregor69021972011-11-30 17:33:56 +00002443 // Enter the submodule description block.
Richard Smith202210b2014-10-24 20:23:01 +00002444 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002445
Douglas Gregor69021972011-11-30 17:33:56 +00002446 // Write the abbreviations needed for the submodules block.
2447 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002448
David Blaikieb44f0bf2017-01-04 22:36:43 +00002449 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor69021972011-11-30 17:33:56 +00002450 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002451 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
Douglas Gregor69021972011-11-30 17:33:56 +00002452 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
Richard Smithdd8b5332017-09-04 05:37:53 +00002453 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Kind
Douglas Gregor69021972011-11-30 17:33:56 +00002454 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2455 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
Richard Smith9bca2982014-03-08 00:03:56 +00002456 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2457 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
Douglas Gregora686e1b2012-01-27 19:52:33 +00002458 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
Douglas Gregor73441092011-12-05 22:27:44 +00002459 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
Douglas Gregor73441092011-12-05 22:27:44 +00002460 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002461 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
Jordan Rose90b0a1f2018-04-20 17:16:04 +00002462 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ModuleMapIsPriv...
Douglas Gregor69021972011-11-30 17:33:56 +00002463 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002464 unsigned DefinitionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor69021972011-11-30 17:33:56 +00002465
David Blaikieb44f0bf2017-01-04 22:36:43 +00002466 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor524e33e2011-12-08 19:11:24 +00002467 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
Douglas Gregor69021972011-11-30 17:33:56 +00002468 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002469 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor69021972011-11-30 17:33:56 +00002470
David Blaikieb44f0bf2017-01-04 22:36:43 +00002471 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor69021972011-11-30 17:33:56 +00002472 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2473 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002474 unsigned HeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor524e33e2011-12-08 19:11:24 +00002475
David Blaikieb44f0bf2017-01-04 22:36:43 +00002476 Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +00002477 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2478 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002479 unsigned TopHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +00002480
David Blaikieb44f0bf2017-01-04 22:36:43 +00002481 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor524e33e2011-12-08 19:11:24 +00002482 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2483 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002484 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor524e33e2011-12-08 19:11:24 +00002485
David Blaikieb44f0bf2017-01-04 22:36:43 +00002486 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002487 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
Richard Smitha3feee22013-10-28 22:18:19 +00002488 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2489 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
David Blaikieb44f0bf2017-01-04 22:36:43 +00002490 unsigned RequiresAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002491
David Blaikieb44f0bf2017-01-04 22:36:43 +00002492 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor59527662012-10-15 06:28:11 +00002493 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2494 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002495 unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor59527662012-10-15 06:28:11 +00002496
David Blaikieb44f0bf2017-01-04 22:36:43 +00002497 Abbrev = std::make_shared<BitCodeAbbrev>();
Richard Smith306d8922014-10-22 23:50:56 +00002498 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
2499 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002500 unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Richard Smith306d8922014-10-22 23:50:56 +00002501
David Blaikieb44f0bf2017-01-04 22:36:43 +00002502 Abbrev = std::make_shared<BitCodeAbbrev>();
Lawrence Crowlb53e5482013-06-20 21:14:14 +00002503 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2504 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002505 unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Lawrence Crowlb53e5482013-06-20 21:14:14 +00002506
David Blaikieb44f0bf2017-01-04 22:36:43 +00002507 Abbrev = std::make_shared<BitCodeAbbrev>();
Richard Smith202210b2014-10-24 20:23:01 +00002508 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
2509 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002510 unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Richard Smith202210b2014-10-24 20:23:01 +00002511
David Blaikieb44f0bf2017-01-04 22:36:43 +00002512 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002513 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2514 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2515 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002516 unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002517
David Blaikieb44f0bf2017-01-04 22:36:43 +00002518 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002519 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2520 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002521 unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002522
David Blaikieb44f0bf2017-01-04 22:36:43 +00002523 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregorfb912652013-03-20 21:10:35 +00002524 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2525 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
2526 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
David Blaikieb44f0bf2017-01-04 22:36:43 +00002527 unsigned ConflictAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregorfb912652013-03-20 21:10:35 +00002528
Douglas Gregorf0b11de2017-09-14 23:38:44 +00002529 Abbrev = std::make_shared<BitCodeAbbrev>();
2530 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXPORT_AS));
2531 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2532 unsigned ExportAsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2533
Douglas Gregor253eefe2011-12-01 00:59:36 +00002534 // Write the submodule metadata block.
Richard Smith145e15a2017-04-24 23:12:30 +00002535 RecordData::value_type Record[] = {
2536 getNumberOfModules(WritingModule),
Richard Smithdd8b5332017-09-04 05:37:53 +00002537 FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS};
Douglas Gregor253eefe2011-12-01 00:59:36 +00002538 Stream.EmitRecord(SUBMODULE_METADATA, Record);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002539
Douglas Gregor69021972011-11-30 17:33:56 +00002540 // Write all of the submodules.
Douglas Gregorde3ef502011-11-30 23:21:26 +00002541 std::queue<Module *> Q;
Douglas Gregor69021972011-11-30 17:33:56 +00002542 Q.push(WritingModule);
Douglas Gregor69021972011-11-30 17:33:56 +00002543 while (!Q.empty()) {
Douglas Gregorde3ef502011-11-30 23:21:26 +00002544 Module *Mod = Q.front();
Douglas Gregor69021972011-11-30 17:33:56 +00002545 Q.pop();
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002546 unsigned ID = getSubmoduleID(Mod);
Mehdi Amini57a41912015-09-10 01:46:39 +00002547
2548 uint64_t ParentID = 0;
Douglas Gregor69021972011-11-30 17:33:56 +00002549 if (Mod->Parent) {
2550 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
Mehdi Amini57a41912015-09-10 01:46:39 +00002551 ParentID = SubmoduleIDs[Mod->Parent];
Douglas Gregor69021972011-11-30 17:33:56 +00002552 }
Mehdi Amini57a41912015-09-10 01:46:39 +00002553
2554 // Emit the definition of the block.
2555 {
David Blaikie9ffe5a32017-01-30 05:00:26 +00002556 RecordData::value_type Record[] = {SUBMODULE_DEFINITION,
2557 ID,
2558 ParentID,
Simon Pilgrimf331a662017-09-04 10:54:39 +00002559 (RecordData::value_type)Mod->Kind,
David Blaikie9ffe5a32017-01-30 05:00:26 +00002560 Mod->IsFramework,
2561 Mod->IsExplicit,
2562 Mod->IsSystem,
2563 Mod->IsExternC,
2564 Mod->InferSubmodules,
2565 Mod->InferExplicitSubmodules,
2566 Mod->InferExportWildcard,
Jordan Rose90b0a1f2018-04-20 17:16:04 +00002567 Mod->ConfigMacrosExhaustive,
2568 Mod->ModuleMapIsPrivate};
Mehdi Amini57a41912015-09-10 01:46:39 +00002569 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2570 }
2571
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002572 // Emit the requirements.
Richard Smith080056b2015-08-18 21:53:42 +00002573 for (const auto &R : Mod->Requirements) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002574 RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.second};
Richard Smith080056b2015-08-18 21:53:42 +00002575 Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.first);
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002576 }
2577
Douglas Gregor69021972011-11-30 17:33:56 +00002578 // Emit the umbrella header, if there is one.
Richard Smith2b63d152015-05-16 02:28:53 +00002579 if (auto UmbrellaHeader = Mod->getUmbrellaHeader()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002580 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
Richard Smith2b63d152015-05-16 02:28:53 +00002581 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2582 UmbrellaHeader.NameAsWritten);
2583 } else if (auto UmbrellaDir = Mod->getUmbrellaDir()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002584 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
2585 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
Richard Smith2b63d152015-05-16 02:28:53 +00002586 UmbrellaDir.NameAsWritten);
Douglas Gregor69021972011-11-30 17:33:56 +00002587 }
Richard Smith306d8922014-10-22 23:50:56 +00002588
Douglas Gregor69021972011-11-30 17:33:56 +00002589 // Emit the headers.
Richard Smith202210b2014-10-24 20:23:01 +00002590 struct {
Richard Smith3c1a41a2014-12-02 00:08:08 +00002591 unsigned RecordKind;
Richard Smith202210b2014-10-24 20:23:01 +00002592 unsigned Abbrev;
Richard Smith3c1a41a2014-12-02 00:08:08 +00002593 Module::HeaderKind HeaderKind;
Richard Smith202210b2014-10-24 20:23:01 +00002594 } HeaderLists[] = {
Richard Smith3c1a41a2014-12-02 00:08:08 +00002595 {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
2596 {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
2597 {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
Richard Smith202210b2014-10-24 20:23:01 +00002598 {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
Richard Smith3c1a41a2014-12-02 00:08:08 +00002599 Module::HK_PrivateTextual},
2600 {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
Richard Smith202210b2014-10-24 20:23:01 +00002601 };
2602 for (auto &HL : HeaderLists) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002603 RecordData::value_type Record[] = {HL.RecordKind};
Richard Smith3c1a41a2014-12-02 00:08:08 +00002604 for (auto &H : Mod->Headers[HL.HeaderKind])
2605 Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
2606 }
2607
2608 // Emit the top headers.
2609 {
2610 auto TopHeaders = Mod->getTopHeaders(PP->getFileManager());
Mehdi Amini57a41912015-09-10 01:46:39 +00002611 RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
Richard Smith3c1a41a2014-12-02 00:08:08 +00002612 for (auto *H : TopHeaders)
2613 Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, H->getName());
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +00002614 }
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002615
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002616 // Emit the imports.
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002617 if (!Mod->Imports.empty()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002618 RecordData Record;
Richard Smith080056b2015-08-18 21:53:42 +00002619 for (auto *I : Mod->Imports)
2620 Record.push_back(getSubmoduleID(I));
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002621 Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2622 }
2623
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002624 // Emit the exports.
Douglas Gregor24bb9232011-12-02 18:58:38 +00002625 if (!Mod->Exports.empty()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002626 RecordData Record;
Richard Smith080056b2015-08-18 21:53:42 +00002627 for (const auto &E : Mod->Exports) {
2628 // FIXME: This may fail; we don't require that all exported modules
2629 // are local or imported.
2630 Record.push_back(getSubmoduleID(E.getPointer()));
2631 Record.push_back(E.getInt());
Douglas Gregor24bb9232011-12-02 18:58:38 +00002632 }
2633 Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2634 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002635
Daniel Jasperba7f2f72013-09-24 09:14:14 +00002636 //FIXME: How do we emit the 'use'd modules? They may not be submodules.
2637 // Might be unnecessary as use declarations are only used to build the
2638 // module itself.
2639
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002640 // Emit the link libraries.
Richard Smith080056b2015-08-18 21:53:42 +00002641 for (const auto &LL : Mod->LinkLibraries) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002642 RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
2643 LL.IsFramework};
Richard Smith080056b2015-08-18 21:53:42 +00002644 Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002645 }
2646
Douglas Gregorfb912652013-03-20 21:10:35 +00002647 // Emit the conflicts.
Richard Smith080056b2015-08-18 21:53:42 +00002648 for (const auto &C : Mod->Conflicts) {
Richard Smith080056b2015-08-18 21:53:42 +00002649 // FIXME: This may fail; we don't require that all conflicting modules
2650 // are local or imported.
Mehdi Amini57a41912015-09-10 01:46:39 +00002651 RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
2652 getSubmoduleID(C.Other)};
Richard Smith080056b2015-08-18 21:53:42 +00002653 Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message);
Douglas Gregorfb912652013-03-20 21:10:35 +00002654 }
2655
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002656 // Emit the configuration macros.
Richard Smith080056b2015-08-18 21:53:42 +00002657 for (const auto &CM : Mod->ConfigMacros) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002658 RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
Richard Smith080056b2015-08-18 21:53:42 +00002659 Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM);
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002660 }
2661
Richard Smithdc1f0422016-07-20 19:10:16 +00002662 // Emit the initializers, if any.
2663 RecordData Inits;
2664 for (Decl *D : Context->getModuleInitializers(Mod))
2665 Inits.push_back(GetDeclRef(D));
2666 if (!Inits.empty())
2667 Stream.EmitRecord(SUBMODULE_INITIALIZERS, Inits);
2668
Douglas Gregorf0b11de2017-09-14 23:38:44 +00002669 // Emit the name of the re-exported module, if any.
2670 if (!Mod->ExportAsModule.empty()) {
2671 RecordData::value_type Record[] = {SUBMODULE_EXPORT_AS};
2672 Stream.EmitRecordWithBlob(ExportAsAbbrev, Record, Mod->ExportAsModule);
2673 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002674
Douglas Gregor69021972011-11-30 17:33:56 +00002675 // Queue up the submodules of this module.
Richard Smith080056b2015-08-18 21:53:42 +00002676 for (auto *M : Mod->submodules())
2677 Q.push(M);
Douglas Gregor69021972011-11-30 17:33:56 +00002678 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002679
Douglas Gregor69021972011-11-30 17:33:56 +00002680 Stream.ExitBlock();
Richard Smith23d8d032015-05-14 00:45:20 +00002681
Richard Smith23d8d032015-05-14 00:45:20 +00002682 assert((NextSubmoduleID - FirstSubmoduleID ==
2683 getNumberOfModules(WritingModule)) &&
2684 "Wrong # of submodules; found a reference to a non-local, "
2685 "non-imported submodule?");
Douglas Gregor69021972011-11-30 17:33:56 +00002686}
2687
Argyrios Kyrtzidis0f06b982013-03-27 17:17:23 +00002688void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
2689 bool isModule) {
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002690 llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
2691 DiagStateIDMap;
2692 unsigned CurrID = 0;
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002693 RecordData Record;
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002694
Richard Smithe37391c2017-05-03 00:28:49 +00002695 auto EncodeDiagStateFlags =
2696 [](const DiagnosticsEngine::DiagState *DS) -> unsigned {
2697 unsigned Result = (unsigned)DS->ExtBehavior;
2698 for (unsigned Val :
Daniel Jasperba9aefc2017-05-03 07:48:27 +00002699 {(unsigned)DS->IgnoreAllWarnings, (unsigned)DS->EnableAllWarnings,
2700 (unsigned)DS->WarningsAsErrors, (unsigned)DS->ErrorsAsFatal,
2701 (unsigned)DS->SuppressSystemWarnings})
Richard Smithe37391c2017-05-03 00:28:49 +00002702 Result = (Result << 1) | Val;
2703 return Result;
2704 };
2705
2706 unsigned Flags = EncodeDiagStateFlags(Diag.DiagStatesByLoc.FirstDiagState);
2707 Record.push_back(Flags);
2708
Richard Smithd230de22017-01-26 01:01:01 +00002709 auto AddDiagState = [&](const DiagnosticsEngine::DiagState *State,
2710 bool IncludeNonPragmaStates) {
Richard Smithe37391c2017-05-03 00:28:49 +00002711 // Ensure that the diagnostic state wasn't modified since it was created.
2712 // We will not correctly round-trip this information otherwise.
2713 assert(Flags == EncodeDiagStateFlags(State) &&
2714 "diag state flags vary in single AST file");
2715
Richard Smithd230de22017-01-26 01:01:01 +00002716 unsigned &DiagStateID = DiagStateIDMap[State];
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002717 Record.push_back(DiagStateID);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002718
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002719 if (DiagStateID == 0) {
2720 DiagStateID = ++CurrID;
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00002721
2722 // Add a placeholder for the number of mappings.
2723 auto SizeIdx = Record.size();
2724 Record.emplace_back();
Richard Smithd230de22017-01-26 01:01:01 +00002725 for (const auto &I : *State) {
2726 if (I.second.isPragma() || IncludeNonPragmaStates) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002727 Record.push_back(I.first);
Richard Smithe37391c2017-05-03 00:28:49 +00002728 Record.push_back(I.second.serialize());
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002729 }
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002730 }
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00002731 // Update the placeholder.
2732 Record[SizeIdx] = (Record.size() - SizeIdx) / 2;
Richard Smithd230de22017-01-26 01:01:01 +00002733 }
2734 };
2735
2736 AddDiagState(Diag.DiagStatesByLoc.FirstDiagState, isModule);
Richard Smithd230de22017-01-26 01:01:01 +00002737
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00002738 // Reserve a spot for the number of locations with state transitions.
2739 auto NumLocationsIdx = Record.size();
2740 Record.emplace_back();
2741
2742 // Emit the state transitions.
2743 unsigned NumLocations = 0;
Richard Smithd230de22017-01-26 01:01:01 +00002744 for (auto &FileIDAndFile : Diag.DiagStatesByLoc.Files) {
2745 if (!FileIDAndFile.first.isValid() ||
2746 !FileIDAndFile.second.HasLocalTransitions)
2747 continue;
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00002748 ++NumLocations;
Richard Smith6c2b5a82018-02-09 01:15:13 +00002749
2750 SourceLocation Loc = Diag.SourceMgr->getComposedLoc(FileIDAndFile.first, 0);
2751 assert(!Loc.isInvalid() && "start loc for valid FileID is invalid");
2752 AddSourceLocation(Loc, Record);
2753
Richard Smithd230de22017-01-26 01:01:01 +00002754 Record.push_back(FileIDAndFile.second.StateTransitions.size());
2755 for (auto &StatePoint : FileIDAndFile.second.StateTransitions) {
2756 Record.push_back(StatePoint.Offset);
2757 AddDiagState(StatePoint.State, false);
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002758 }
2759 }
2760
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00002761 // Backpatch the number of locations.
2762 Record[NumLocationsIdx] = NumLocations;
2763
2764 // Emit CurDiagStateLoc. Do it last in order to match source order.
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00002765 //
2766 // This also protects against a hypothetical corner case with simulating
2767 // -Werror settings for implicit modules in the ASTReader, where reading
2768 // CurDiagState out of context could change whether warning pragmas are
2769 // treated as errors.
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00002770 AddSourceLocation(Diag.DiagStatesByLoc.CurDiagStateLoc, Record);
2771 AddDiagState(Diag.DiagStatesByLoc.CurDiagState, false);
2772
Duncan P. N. Exon Smithf2435b92017-04-12 02:31:17 +00002773 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002774}
2775
Douglas Gregorc5046832009-04-27 18:38:38 +00002776//===----------------------------------------------------------------------===//
2777// Type Serialization
2778//===----------------------------------------------------------------------===//
Chris Lattnereeffaef2009-04-10 17:15:23 +00002779
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002780/// Write the representation of a type to the AST stream.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002781void ASTWriter::WriteType(QualType T) {
Richard Smith290d8012016-04-06 17:06:00 +00002782 TypeIdx &IdxRef = TypeIdxs[T];
2783 if (IdxRef.getIndex() == 0) // we haven't seen this type before.
2784 IdxRef = TypeIdx(NextTypeID++);
2785 TypeIdx Idx = IdxRef;
Mike Stump11289f42009-09-09 15:08:12 +00002786
Douglas Gregor9b3932c2010-10-05 18:37:06 +00002787 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
Douglas Gregordc72caa2010-10-04 18:21:45 +00002788
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002789 // Emit the type's representation.
John McCalld505e572019-12-13 21:54:44 -05002790 uint64_t Offset = ASTTypeWriter(*this).write(T);
John McCall8ccfcb52009-09-24 19:53:00 +00002791
Richard Smith290d8012016-04-06 17:06:00 +00002792 // Record the offset for this type.
2793 unsigned Index = Idx.getIndex() - FirstTypeID;
2794 if (TypeOffsets.size() == Index)
2795 TypeOffsets.push_back(Offset);
2796 else if (TypeOffsets.size() < Index) {
2797 TypeOffsets.resize(Index + 1);
2798 TypeOffsets[Index] = Offset;
John McCall8ccfcb52009-09-24 19:53:00 +00002799 } else {
Richard Smith290d8012016-04-06 17:06:00 +00002800 llvm_unreachable("Types emitted in wrong order");
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002801 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002802}
2803
Douglas Gregorc5046832009-04-27 18:38:38 +00002804//===----------------------------------------------------------------------===//
2805// Declaration Serialization
2806//===----------------------------------------------------------------------===//
2807
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002808/// Write the block containing all of the declaration IDs
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002809/// lexically declared within the given DeclContext.
2810///
2811/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002812/// bitstream, or 0 if no block was written.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002813uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002814 DeclContext *DC) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002815 if (DC->decls_empty())
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002816 return 0;
2817
Douglas Gregor8f45df52009-04-16 22:23:12 +00002818 uint64_t Offset = Stream.GetCurrentBitNo();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002819 SmallVector<uint32_t, 128> KindDeclPairs;
2820 for (const auto *D : DC->decls()) {
2821 KindDeclPairs.push_back(D->getKind());
2822 KindDeclPairs.push_back(GetDeclRef(D));
2823 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002824
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002825 ++NumLexicalDeclContexts;
Mehdi Amini57a41912015-09-10 01:46:39 +00002826 RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
Richard Smith82f8fcd2015-08-06 22:07:25 +00002827 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
2828 bytes(KindDeclPairs));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002829 return Offset;
2830}
2831
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002832void ASTWriter::WriteTypeDeclOffsets() {
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002833 using namespace llvm;
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002834
2835 // Write the type offsets array
David Blaikieb44f0bf2017-01-04 22:36:43 +00002836 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00002837 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002838 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
Douglas Gregor5204bde2011-08-02 16:26:37 +00002839 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002840 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
David Blaikieb44f0bf2017-01-04 22:36:43 +00002841 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00002842 {
2843 RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(),
2844 FirstTypeID - NUM_PREDEF_TYPE_IDS};
2845 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
2846 }
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002847
2848 // Write the declaration offsets array
David Blaikieb44f0bf2017-01-04 22:36:43 +00002849 Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00002850 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002851 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
Douglas Gregorf7180622011-08-03 15:48:04 +00002852 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002853 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
David Blaikieb44f0bf2017-01-04 22:36:43 +00002854 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00002855 {
2856 RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(),
2857 FirstDeclID - NUM_PREDEF_DECL_IDS};
2858 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
2859 }
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002860}
2861
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002862void ASTWriter::WriteFileDeclIDsMap() {
2863 using namespace llvm;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002864
Chandler Carruthb306d732015-03-27 00:31:20 +00002865 SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs(
2866 FileDeclIDs.begin(), FileDeclIDs.end());
Fangrui Song55fab262018-09-26 22:16:28 +00002867 llvm::sort(SortedFileDeclIDs, llvm::less_first());
Chandler Carruthb306d732015-03-27 00:31:20 +00002868
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002869 // Join the vectors of DeclIDs from all files.
Chandler Carruthb306d732015-03-27 00:31:20 +00002870 SmallVector<DeclID, 256> FileGroupedDeclIDs;
2871 for (auto &FileDeclEntry : SortedFileDeclIDs) {
2872 DeclIDInFileInfo &Info = *FileDeclEntry.second;
2873 Info.FirstDeclIndex = FileGroupedDeclIDs.size();
2874 for (auto &LocDeclEntry : Info.DeclIDs)
2875 FileGroupedDeclIDs.push_back(LocDeclEntry.second);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002876 }
2877
David Blaikieb44f0bf2017-01-04 22:36:43 +00002878 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002879 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002880 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002881 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00002882 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00002883 RecordData::value_type Record[] = {FILE_SORTED_DECLS,
2884 FileGroupedDeclIDs.size()};
Reid Kleckner012665e2015-05-21 00:13:09 +00002885 Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002886}
2887
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002888void ASTWriter::WriteComments() {
2889 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
Ilya Biryukov45643102018-07-09 11:33:23 +00002890 auto _ = llvm::make_scope_exit([this] { Stream.ExitBlock(); });
2891 if (!PP->getPreprocessorOpts().WriteCommentListToPCH)
2892 return;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002893 RecordData Record;
Jan Korousf31d8df2019-08-13 18:11:44 +00002894 for (const auto &FO : Context->Comments.OrderedComments) {
2895 for (const auto &OC : FO.second) {
2896 const RawComment *I = OC.second;
2897 Record.clear();
2898 AddSourceRange(I->getSourceRange(), Record);
2899 Record.push_back(I->getKind());
2900 Record.push_back(I->isTrailingComment());
2901 Record.push_back(I->isAlmostTrailingComment());
2902 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
2903 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002904 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002905}
2906
Douglas Gregorc5046832009-04-27 18:38:38 +00002907//===----------------------------------------------------------------------===//
2908// Global Method Pool and Selector Serialization
2909//===----------------------------------------------------------------------===//
2910
Douglas Gregore84a9da2009-04-20 20:36:09 +00002911namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002912
Douglas Gregorc78d3462009-04-24 21:10:55 +00002913// Trait used for the on-disk hash table used in the method pool.
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002914class ASTMethodPoolTrait {
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002915 ASTWriter &Writer;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002916
2917public:
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002918 using key_type = Selector;
2919 using key_type_ref = key_type;
Mike Stump11289f42009-09-09 15:08:12 +00002920
Sebastian Redl834bb972010-08-04 17:20:04 +00002921 struct data_type {
Sebastian Redl539c5062010-08-18 23:57:32 +00002922 SelectorID ID;
Sebastian Redl834bb972010-08-04 17:20:04 +00002923 ObjCMethodList Instance, Factory;
2924 };
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002925 using data_type_ref = const data_type &;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002926
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002927 using hash_value_type = unsigned;
2928 using offset_type = unsigned;
Justin Bogner25463f12014-04-18 20:27:24 +00002929
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002930 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) {}
Mike Stump11289f42009-09-09 15:08:12 +00002931
Justin Bogner25463f12014-04-18 20:27:24 +00002932 static hash_value_type ComputeHash(Selector Sel) {
Argyrios Kyrtzidis4bd97102010-08-20 16:03:52 +00002933 return serialization::ComputeHash(Sel);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002934 }
Mike Stump11289f42009-09-09 15:08:12 +00002935
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002936 std::pair<unsigned, unsigned>
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002937 EmitKeyDataLength(raw_ostream& Out, Selector Sel,
Douglas Gregorc78d3462009-04-24 21:10:55 +00002938 data_type_ref Methods) {
Justin Bognere1c147c2014-03-28 22:03:19 +00002939 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002940
Peter Collingbournee3f65292018-05-18 19:46:24 +00002941 endian::Writer LE(Out, little);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002942 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
Justin Bognere1c147c2014-03-28 22:03:19 +00002943 LE.write<uint16_t>(KeyLen);
Sebastian Redl834bb972010-08-04 17:20:04 +00002944 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
2945 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002946 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002947 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002948 DataLen += 4;
Sebastian Redl834bb972010-08-04 17:20:04 +00002949 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002950 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002951 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002952 DataLen += 4;
Justin Bognere1c147c2014-03-28 22:03:19 +00002953 LE.write<uint16_t>(DataLen);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002954 return std::make_pair(KeyLen, DataLen);
2955 }
Mike Stump11289f42009-09-09 15:08:12 +00002956
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002957 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00002958 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002959
Peter Collingbournee3f65292018-05-18 19:46:24 +00002960 endian::Writer LE(Out, little);
Mike Stump11289f42009-09-09 15:08:12 +00002961 uint64_t Start = Out.tell();
Douglas Gregor95c13f52009-04-25 17:48:32 +00002962 assert((Start >> 32) == 0 && "Selector key offset too large");
2963 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002964 unsigned N = Sel.getNumArgs();
Justin Bognere1c147c2014-03-28 22:03:19 +00002965 LE.write<uint16_t>(N);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002966 if (N == 0)
2967 N = 1;
2968 for (unsigned I = 0; I != N; ++I)
Justin Bognere1c147c2014-03-28 22:03:19 +00002969 LE.write<uint32_t>(
2970 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
Douglas Gregorc78d3462009-04-24 21:10:55 +00002971 }
Mike Stump11289f42009-09-09 15:08:12 +00002972
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002973 void EmitData(raw_ostream& Out, key_type_ref,
Douglas Gregor4647cfa2009-04-24 21:49:02 +00002974 data_type_ref Methods, unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00002975 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002976
Peter Collingbournee3f65292018-05-18 19:46:24 +00002977 endian::Writer LE(Out, little);
Douglas Gregor4647cfa2009-04-24 21:49:02 +00002978 uint64_t Start = Out.tell(); (void)Start;
Justin Bognere1c147c2014-03-28 22:03:19 +00002979 LE.write<uint32_t>(Methods.ID);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002980 unsigned NumInstanceMethods = 0;
Sebastian Redl834bb972010-08-04 17:20:04 +00002981 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002982 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002983 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002984 ++NumInstanceMethods;
2985
2986 unsigned NumFactoryMethods = 0;
Sebastian Redl834bb972010-08-04 17:20:04 +00002987 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002988 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00002989 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00002990 ++NumFactoryMethods;
2991
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002992 unsigned InstanceBits = Methods.Instance.getBits();
2993 assert(InstanceBits < 4);
Nico Weberff4b35e2014-12-27 22:14:15 +00002994 unsigned InstanceHasMoreThanOneDeclBit =
2995 Methods.Instance.hasMoreThanOneDecl();
2996 unsigned FullInstanceBits = (NumInstanceMethods << 3) |
2997 (InstanceHasMoreThanOneDeclBit << 2) |
2998 InstanceBits;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002999 unsigned FactoryBits = Methods.Factory.getBits();
3000 assert(FactoryBits < 4);
Nico Weberff4b35e2014-12-27 22:14:15 +00003001 unsigned FactoryHasMoreThanOneDeclBit =
3002 Methods.Factory.hasMoreThanOneDecl();
3003 unsigned FullFactoryBits = (NumFactoryMethods << 3) |
3004 (FactoryHasMoreThanOneDeclBit << 2) |
3005 FactoryBits;
3006 LE.write<uint16_t>(FullInstanceBits);
3007 LE.write<uint16_t>(FullFactoryBits);
Sebastian Redl834bb972010-08-04 17:20:04 +00003008 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003009 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003010 if (Method->getMethod())
3011 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
Sebastian Redl834bb972010-08-04 17:20:04 +00003012 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003013 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003014 if (Method->getMethod())
3015 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
Douglas Gregor4647cfa2009-04-24 21:49:02 +00003016
3017 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorc78d3462009-04-24 21:10:55 +00003018 }
3019};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003020
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003021} // namespace
Douglas Gregorc78d3462009-04-24 21:10:55 +00003022
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003023/// Write ObjC data: selectors and the method pool.
Douglas Gregorc78d3462009-04-24 21:10:55 +00003024///
3025/// The method pool contains both instance and factory methods, stored
Sebastian Redla19a67f2010-08-03 21:58:15 +00003026/// in an on-disk hash table indexed by the selector. The hash table also
3027/// contains an empty entry for every other selector known to Sema.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003028void ASTWriter::WriteSelectors(Sema &SemaRef) {
Douglas Gregorc78d3462009-04-24 21:10:55 +00003029 using namespace llvm;
3030
Sebastian Redla19a67f2010-08-03 21:58:15 +00003031 // Do we have to do anything at all?
Sebastian Redl834bb972010-08-04 17:20:04 +00003032 if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
Sebastian Redla19a67f2010-08-03 21:58:15 +00003033 return;
Sebastian Redld95a56e2010-08-04 18:21:41 +00003034 unsigned NumTableEntries = 0;
Sebastian Redla19a67f2010-08-03 21:58:15 +00003035 // Create and write out the blob that contains selectors and the method pool.
Douglas Gregorc78d3462009-04-24 21:10:55 +00003036 {
Justin Bognerbb094f02014-04-18 19:57:06 +00003037 llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003038 ASTMethodPoolTrait Trait(*this);
Mike Stump11289f42009-09-09 15:08:12 +00003039
Sebastian Redla19a67f2010-08-03 21:58:15 +00003040 // Create the on-disk hash table representation. We walk through every
3041 // selector we've seen and look it up in the method pool.
Sebastian Redld95a56e2010-08-04 18:21:41 +00003042 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003043 for (auto &SelectorAndID : SelectorIDs) {
3044 Selector S = SelectorAndID.first;
3045 SelectorID ID = SelectorAndID.second;
Sebastian Redla19a67f2010-08-03 21:58:15 +00003046 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003047 ASTMethodPoolTrait::data_type Data = {
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003048 ID,
Sebastian Redl834bb972010-08-04 17:20:04 +00003049 ObjCMethodList(),
3050 ObjCMethodList()
3051 };
3052 if (F != SemaRef.MethodPool.end()) {
3053 Data.Instance = F->second.first;
3054 Data.Factory = F->second.second;
3055 }
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003056 // Only write this selector if it's not in an existing AST or something
Sebastian Redld95a56e2010-08-04 18:21:41 +00003057 // changed.
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003058 if (Chain && ID < FirstSelectorID) {
Sebastian Redld95a56e2010-08-04 18:21:41 +00003059 // Selector already exists. Did it change?
3060 bool changed = false;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003061 for (ObjCMethodList *M = &Data.Instance;
3062 !changed && M && M->getMethod(); M = M->getNext()) {
3063 if (!M->getMethod()->isFromASTFile())
Sebastian Redld95a56e2010-08-04 18:21:41 +00003064 changed = true;
3065 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003066 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003067 M = M->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003068 if (!M->getMethod()->isFromASTFile())
Sebastian Redld95a56e2010-08-04 18:21:41 +00003069 changed = true;
3070 }
3071 if (!changed)
3072 continue;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003073 } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
Sebastian Redl6e1a2a02010-08-04 21:22:45 +00003074 // A new method pool entry.
3075 ++NumTableEntries;
Sebastian Redld95a56e2010-08-04 18:21:41 +00003076 }
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003077 Generator.insert(S, Data, Trait);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003078 }
3079
Douglas Gregorc78d3462009-04-24 21:10:55 +00003080 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003081 SmallString<4096> MethodPool;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003082 uint32_t BucketOffset;
3083 {
Justin Bognere1c147c2014-03-28 22:03:19 +00003084 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003085
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003086 ASTMethodPoolTrait Trait(*this);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003087 llvm::raw_svector_ostream Out(MethodPool);
3088 // Make sure that no bucket is at offset 0
Peter Collingbournee3f65292018-05-18 19:46:24 +00003089 endian::write<uint32_t>(Out, 0, little);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003090 BucketOffset = Generator.Emit(Out, Trait);
3091 }
3092
3093 // Create a blob abbreviation
David Blaikieb44f0bf2017-01-04 22:36:43 +00003094 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00003095 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003096 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor95c13f52009-04-25 17:48:32 +00003097 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003098 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00003099 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003100
Douglas Gregor95c13f52009-04-25 17:48:32 +00003101 // Write the method pool
Mehdi Amini57a41912015-09-10 01:46:39 +00003102 {
3103 RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3104 NumTableEntries};
3105 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3106 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00003107
3108 // Create a blob abbreviation for the selector table offsets.
David Blaikieb44f0bf2017-01-04 22:36:43 +00003109 Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00003110 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
Douglas Gregord4c5ed02010-10-29 22:39:52 +00003111 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
Douglas Gregor8f364fb2011-08-03 23:28:44 +00003112 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
Douglas Gregor95c13f52009-04-25 17:48:32 +00003113 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00003114 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor95c13f52009-04-25 17:48:32 +00003115
3116 // Write the selector offsets table.
Mehdi Amini57a41912015-09-10 01:46:39 +00003117 {
3118 RecordData::value_type Record[] = {
3119 SELECTOR_OFFSETS, SelectorOffsets.size(),
3120 FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3121 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3122 bytes(SelectorOffsets));
3123 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00003124 }
3125}
3126
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003127/// Write the selectors referenced in @selector expression into AST file.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003128void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003129 using namespace llvm;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003130
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003131 if (SemaRef.ReferencedSelectors.empty())
3132 return;
Sebastian Redlada023c2010-08-04 20:40:17 +00003133
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003134 RecordData Record;
Richard Smithe64e7452016-04-18 21:54:58 +00003135 ASTRecordWriter Writer(*this, Record);
Sebastian Redlada023c2010-08-04 20:40:17 +00003136
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003137 // Note: this writes out all references even for a dependent AST. But it is
Sebastian Redl51c79d82010-08-04 22:21:29 +00003138 // very tricky to fix, and given that @selector shouldn't really appear in
3139 // headers, probably not worth it. It's not a correctness issue.
Chandler Carruth12c8f652015-03-27 00:55:05 +00003140 for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
3141 Selector Sel = SelectorAndLocation.first;
3142 SourceLocation Loc = SelectorAndLocation.second;
Richard Smithe64e7452016-04-18 21:54:58 +00003143 Writer.AddSelectorRef(Sel);
3144 Writer.AddSourceLocation(Loc);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003145 }
Richard Smithe64e7452016-04-18 21:54:58 +00003146 Writer.Emit(REFERENCED_SELECTOR_POOL);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003147}
3148
Douglas Gregorc5046832009-04-27 18:38:38 +00003149//===----------------------------------------------------------------------===//
3150// Identifier Table Serialization
3151//===----------------------------------------------------------------------===//
3152
Richard Smithb3761912015-02-05 23:08:52 +00003153/// Determine the declaration that should be put into the name lookup table to
3154/// represent the given declaration in this module. This is usually D itself,
3155/// but if D was imported and merged into a local declaration, we want the most
3156/// recent local declaration instead. The chosen declaration will be the most
3157/// recent declaration in any module that imports this one.
3158static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
3159 NamedDecl *D) {
3160 if (!LangOpts.Modules || !D->isFromASTFile())
3161 return D;
3162
3163 if (Decl *Redecl = D->getPreviousDecl()) {
3164 // For Redeclarable decls, a prior declaration might be local.
3165 for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
Richard Smithd49941b2016-04-26 23:40:43 +00003166 // If we find a local decl, we're done.
3167 if (!Redecl->isFromASTFile()) {
3168 // Exception: in very rare cases (for injected-class-names), not all
3169 // redeclarations are in the same semantic context. Skip ones in a
3170 // different context. They don't go in this lookup table at all.
3171 if (!Redecl->getDeclContext()->getRedeclContext()->Equals(
3172 D->getDeclContext()->getRedeclContext()))
3173 continue;
Richard Smithb3761912015-02-05 23:08:52 +00003174 return cast<NamedDecl>(Redecl);
Richard Smithd49941b2016-04-26 23:40:43 +00003175 }
3176
Richard Smithfe620d22015-03-05 23:24:12 +00003177 // If we find a decl from a (chained-)PCH stop since we won't find a
Richard Smithb3761912015-02-05 23:08:52 +00003178 // local one.
Richard Smithd49941b2016-04-26 23:40:43 +00003179 if (Redecl->getOwningModuleID() == 0)
Richard Smithb3761912015-02-05 23:08:52 +00003180 break;
3181 }
3182 } else if (Decl *First = D->getCanonicalDecl()) {
3183 // For Mergeable decls, the first decl might be local.
3184 if (!First->isFromASTFile())
3185 return cast<NamedDecl>(First);
3186 }
3187
3188 // All declarations are imported. Our most recent declaration will also be
3189 // the most recent one in anyone who imports us.
3190 return D;
3191}
3192
Douglas Gregorc78d3462009-04-24 21:10:55 +00003193namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003194
Richard Smithcf97cf62015-04-19 01:34:23 +00003195class ASTIdentifierTableTrait {
3196 ASTWriter &Writer;
3197 Preprocessor &PP;
3198 IdentifierResolver &IdResolver;
Richard Smith9c254182015-07-19 21:41:12 +00003199 bool IsModule;
Richard Smitha534a312015-07-21 23:54:07 +00003200 bool NeedDecls;
Richard Smith33e0f7e2015-07-22 02:08:40 +00003201 ASTWriter::RecordData *InterestingIdentifierOffsets;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003202
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003203 /// Determines whether this is an "interesting" identifier that needs a
Richard Smithcf97cf62015-04-19 01:34:23 +00003204 /// full IdentifierInfo structure written into the hash table. Notably, this
3205 /// doesn't check whether the name has macros defined; use PublicMacroIterator
3206 /// to check that.
Richard Smith9c254182015-07-19 21:41:12 +00003207 bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
Richard Smithd7329392015-04-21 21:46:32 +00003208 if (MacroOffset ||
3209 II->isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +00003210 (IsModule ? II->hasRevertedBuiltin() : II->getObjCOrBuiltinID()) ||
Richard Smithcf97cf62015-04-19 01:34:23 +00003211 II->hasRevertedTokenIDToIdentifier() ||
Bruno Ricci366ba732018-09-21 12:53:22 +00003212 (NeedDecls && II->getFETokenInfo()))
Richard Smithcf97cf62015-04-19 01:34:23 +00003213 return true;
3214
3215 return false;
3216 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003217
Douglas Gregore84a9da2009-04-20 20:36:09 +00003218public:
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003219 using key_type = IdentifierInfo *;
3220 using key_type_ref = key_type;
Mike Stump11289f42009-09-09 15:08:12 +00003221
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003222 using data_type = IdentID;
3223 using data_type_ref = data_type;
Mike Stump11289f42009-09-09 15:08:12 +00003224
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003225 using hash_value_type = unsigned;
3226 using offset_type = unsigned;
Justin Bogner25463f12014-04-18 20:27:24 +00003227
Richard Smithd7329392015-04-21 21:46:32 +00003228 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
Richard Smith33e0f7e2015-07-22 02:08:40 +00003229 IdentifierResolver &IdResolver, bool IsModule,
3230 ASTWriter::RecordData *InterestingIdentifierOffsets)
Richard Smitha534a312015-07-21 23:54:07 +00003231 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
Richard Smith33e0f7e2015-07-22 02:08:40 +00003232 NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3233 InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
Douglas Gregore84a9da2009-04-20 20:36:09 +00003234
Richard Smithd79514e2016-02-05 19:03:40 +00003235 bool needDecls() const { return NeedDecls; }
3236
Justin Bogner25463f12014-04-18 20:27:24 +00003237 static hash_value_type ComputeHash(const IdentifierInfo* II) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003238 return llvm::djbHash(II->getName());
Douglas Gregore84a9da2009-04-20 20:36:09 +00003239 }
Mike Stump11289f42009-09-09 15:08:12 +00003240
Richard Smith33e0f7e2015-07-22 02:08:40 +00003241 bool isInterestingIdentifier(const IdentifierInfo *II) {
3242 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3243 return isInterestingIdentifier(II, MacroOffset);
3244 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003245
Richard Smith9c254182015-07-19 21:41:12 +00003246 bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) {
3247 return isInterestingIdentifier(II, 0);
3248 }
3249
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003250 std::pair<unsigned, unsigned>
Douglas Gregor935bc7a22011-10-27 09:33:13 +00003251 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003252 unsigned KeyLen = II->getLength() + 1;
Douglas Gregor1d583f22009-04-28 21:18:29 +00003253 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
Richard Smithd7329392015-04-21 21:46:32 +00003254 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3255 if (isInterestingIdentifier(II, MacroOffset)) {
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003256 DataLen += 2; // 2 bytes for builtin ID
3257 DataLen += 2; // 2 bytes for flags
Richard Smithd7329392015-04-21 21:46:32 +00003258 if (MacroOffset)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003259 DataLen += 4; // MacroDirectives offset.
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003260
Richard Smitha534a312015-07-21 23:54:07 +00003261 if (NeedDecls) {
3262 for (IdentifierResolver::iterator D = IdResolver.begin(II),
3263 DEnd = IdResolver.end();
3264 D != DEnd; ++D)
3265 DataLen += 4;
3266 }
Douglas Gregor1d583f22009-04-28 21:18:29 +00003267 }
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003268
Justin Bognere1c147c2014-03-28 22:03:19 +00003269 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003270
Peter Collingbournee3f65292018-05-18 19:46:24 +00003271 endian::Writer LE(Out, little);
Justin Bognere1c147c2014-03-28 22:03:19 +00003272
Richard Smithdf8a8312015-03-13 04:05:01 +00003273 assert((uint16_t)DataLen == DataLen && (uint16_t)KeyLen == KeyLen);
Justin Bognere1c147c2014-03-28 22:03:19 +00003274 LE.write<uint16_t>(DataLen);
Douglas Gregorab4df582009-04-28 20:01:51 +00003275 // We emit the key length after the data length so that every
3276 // string is preceded by a 16-bit length. This matches the PTH
3277 // format for storing identifiers.
Justin Bognere1c147c2014-03-28 22:03:19 +00003278 LE.write<uint16_t>(KeyLen);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003279 return std::make_pair(KeyLen, DataLen);
3280 }
Mike Stump11289f42009-09-09 15:08:12 +00003281
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003282 void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
Douglas Gregore84a9da2009-04-20 20:36:09 +00003283 unsigned KeyLen) {
3284 // Record the location of the key data. This is used when generating
3285 // the mapping from persistent IDs to strings.
3286 Writer.SetIdentifierOffset(II, Out.tell());
Richard Smith33e0f7e2015-07-22 02:08:40 +00003287
3288 // Emit the offset of the key/data length information to the interesting
3289 // identifiers table if necessary.
3290 if (InterestingIdentifierOffsets && isInterestingIdentifier(II))
3291 InterestingIdentifierOffsets->push_back(Out.tell() - 4);
3292
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003293 Out.write(II->getNameStart(), KeyLen);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003294 }
Mike Stump11289f42009-09-09 15:08:12 +00003295
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00003296 void EmitData(raw_ostream& Out, IdentifierInfo* II,
Sebastian Redl539c5062010-08-18 23:57:32 +00003297 IdentID ID, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003298 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003299
Peter Collingbournee3f65292018-05-18 19:46:24 +00003300 endian::Writer LE(Out, little);
Richard Smithcf97cf62015-04-19 01:34:23 +00003301
Richard Smithd7329392015-04-21 21:46:32 +00003302 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3303 if (!isInterestingIdentifier(II, MacroOffset)) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003304 LE.write<uint32_t>(ID << 1);
Douglas Gregor1d583f22009-04-28 21:18:29 +00003305 return;
3306 }
Douglas Gregorb9256522009-04-28 21:32:13 +00003307
Justin Bognere1c147c2014-03-28 22:03:19 +00003308 LE.write<uint32_t>((ID << 1) | 0x01);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003309 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3310 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
Justin Bognere1c147c2014-03-28 22:03:19 +00003311 LE.write<uint16_t>(Bits);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003312 Bits = 0;
Richard Smithd7329392015-04-21 21:46:32 +00003313 bool HadMacroDefinition = MacroOffset != 0;
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003314 Bits = (Bits << 1) | unsigned(HadMacroDefinition);
Daniel Dunbar91b640a2009-12-18 20:58:47 +00003315 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3316 Bits = (Bits << 1) | unsigned(II->isPoisoned());
Richard Smith9c254182015-07-19 21:41:12 +00003317 Bits = (Bits << 1) | unsigned(II->hasRevertedBuiltin());
Argyrios Kyrtzidis3084a612010-08-11 22:55:12 +00003318 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
Daniel Dunbar91b640a2009-12-18 20:58:47 +00003319 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
Justin Bognere1c147c2014-03-28 22:03:19 +00003320 LE.write<uint16_t>(Bits);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003321
Richard Smithd7329392015-04-21 21:46:32 +00003322 if (HadMacroDefinition)
3323 LE.write<uint32_t>(MacroOffset);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003324
Richard Smitha534a312015-07-21 23:54:07 +00003325 if (NeedDecls) {
3326 // Emit the declaration IDs in reverse order, because the
3327 // IdentifierResolver provides the declarations as they would be
3328 // visible (e.g., the function "stat" would come before the struct
3329 // "stat"), but the ASTReader adds declarations to the end of the list
3330 // (so we need to see the struct "stat" before the function "stat").
3331 // Only emit declarations that aren't from a chained PCH, though.
3332 SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II),
3333 IdResolver.end());
3334 for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(),
3335 DEnd = Decls.rend();
3336 D != DEnd; ++D)
3337 LE.write<uint32_t>(
3338 Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D)));
3339 }
Douglas Gregore84a9da2009-04-20 20:36:09 +00003340 }
3341};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003342
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003343} // namespace
Douglas Gregore84a9da2009-04-20 20:36:09 +00003344
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003345/// Write the identifier table into the AST file.
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003346///
3347/// The identifier table consists of a blob containing string data
3348/// (the actual identifiers themselves) and a separate "offsets" index
3349/// that maps identifier IDs to locations within the blob.
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003350void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
Douglas Gregor935bc7a22011-10-27 09:33:13 +00003351 IdentifierResolver &IdResolver,
3352 bool IsModule) {
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003353 using namespace llvm;
3354
Richard Smith33e0f7e2015-07-22 02:08:40 +00003355 RecordData InterestingIdents;
3356
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003357 // Create and write out the blob that contains the identifier
3358 // strings.
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003359 {
Justin Bognerbb094f02014-04-18 19:57:06 +00003360 llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
Richard Smith33e0f7e2015-07-22 02:08:40 +00003361 ASTIdentifierTableTrait Trait(
3362 *this, PP, IdResolver, IsModule,
3363 (getLangOpts().CPlusPlus && IsModule) ? &InterestingIdents : nullptr);
Mike Stump11289f42009-09-09 15:08:12 +00003364
Douglas Gregore6648fb2009-04-28 20:33:11 +00003365 // Look for any identifiers that were named while processing the
3366 // headers, but are otherwise not needed. We add these to the hash
3367 // table to enable checking of the predefines buffer in the case
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003368 // where the user adds new macro definitions when building the AST
Douglas Gregore6648fb2009-04-28 20:33:11 +00003369 // file.
Chandler Carruth8440c982015-03-26 23:54:15 +00003370 SmallVector<const IdentifierInfo *, 128> IIs;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003371 for (const auto &ID : PP.getIdentifierTable())
3372 IIs.push_back(ID.second);
Chandler Carruth8440c982015-03-26 23:54:15 +00003373 // Sort the identifiers lexicographically before getting them references so
3374 // that their order is stable.
Benjamin Kramercd2bae32019-08-22 17:32:16 +00003375 llvm::sort(IIs, llvm::deref<std::less<>>());
Chandler Carruth8440c982015-03-26 23:54:15 +00003376 for (const IdentifierInfo *II : IIs)
Richard Smith9c254182015-07-19 21:41:12 +00003377 if (Trait.isInterestingNonMacroIdentifier(II))
3378 getIdentifierRef(II);
Douglas Gregore6648fb2009-04-28 20:33:11 +00003379
Sebastian Redlff4a2952010-07-23 23:49:55 +00003380 // Create the on-disk hash table representation. We only store offsets
3381 // for identifiers that appear here for the first time.
3382 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
Chandler Carruth885e78c2015-03-24 21:18:10 +00003383 for (auto IdentIDPair : IdentifierIDs) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003384 auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
Chandler Carruth885e78c2015-03-24 21:18:10 +00003385 IdentID ID = IdentIDPair.second;
3386 assert(II && "NULL identifier in identifier table");
Vassil Vassilev262f41e2016-03-30 20:16:03 +00003387 // Write out identifiers if either the ID is local or the identifier has
3388 // changed since it was loaded.
3389 if (ID >= FirstIdentID || !Chain || !II->isFromAST()
3390 || II->hasChangedSinceDeserialization() ||
Richard Smithd79514e2016-02-05 19:03:40 +00003391 (Trait.needDecls() &&
3392 II->hasFETokenInfoChangedSinceDeserialization()))
Chandler Carruth885e78c2015-03-24 21:18:10 +00003393 Generator.insert(II, ID, Trait);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003394 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003395
Douglas Gregore84a9da2009-04-20 20:36:09 +00003396 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003397 SmallString<4096> IdentifierTable;
Douglas Gregora868bbd2009-04-21 22:25:48 +00003398 uint32_t BucketOffset;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003399 {
Justin Bognere1c147c2014-03-28 22:03:19 +00003400 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003401
Douglas Gregore84a9da2009-04-20 20:36:09 +00003402 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003403 // Make sure that no bucket is at offset 0
Peter Collingbournee3f65292018-05-18 19:46:24 +00003404 endian::write<uint32_t>(Out, 0, little);
Douglas Gregora868bbd2009-04-21 22:25:48 +00003405 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003406 }
3407
3408 // Create a blob abbreviation
David Blaikieb44f0bf2017-01-04 22:36:43 +00003409 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00003410 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
Douglas Gregora868bbd2009-04-21 22:25:48 +00003411 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregore84a9da2009-04-20 20:36:09 +00003412 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00003413 unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003414
3415 // Write the identifier table
Mehdi Amini57a41912015-09-10 01:46:39 +00003416 RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
Yaron Keren92e1b622015-03-18 10:17:07 +00003417 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003418 }
3419
3420 // Write the offsets table for identifier IDs.
David Blaikieb44f0bf2017-01-04 22:36:43 +00003421 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00003422 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
Douglas Gregor0e149972009-04-25 19:10:14 +00003423 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
Douglas Gregor1ab036c2011-08-03 21:49:18 +00003424 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
Douglas Gregor0e149972009-04-25 19:10:14 +00003425 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00003426 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor0e149972009-04-25 19:10:14 +00003427
Douglas Gregor8d7edce2013-02-08 21:30:59 +00003428#ifndef NDEBUG
3429 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3430 assert(IdentifierOffsets[I] && "Missing identifier offset?");
3431#endif
Mehdi Amini57a41912015-09-10 01:46:39 +00003432
3433 RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
3434 IdentifierOffsets.size(),
3435 FirstIdentID - NUM_PREDEF_IDENT_IDS};
Douglas Gregor0e149972009-04-25 19:10:14 +00003436 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00003437 bytes(IdentifierOffsets));
Richard Smith33e0f7e2015-07-22 02:08:40 +00003438
3439 // In C++, write the list of interesting identifiers (those that are
3440 // defined as macros, poisoned, or similar unusual things).
3441 if (!InterestingIdents.empty())
3442 Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003443}
3444
Douglas Gregorc5046832009-04-27 18:38:38 +00003445//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003446// DeclContext's Name Lookup Table Serialization
3447//===----------------------------------------------------------------------===//
3448
3449namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003450
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003451// Trait used for the on-disk hash table used in the method pool.
3452class ASTDeclContextNameLookupTrait {
3453 ASTWriter &Writer;
Richard Smithd88a7f12015-09-01 20:35:42 +00003454 llvm::SmallVector<DeclID, 64> DeclIDs;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003455
3456public:
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003457 using key_type = DeclarationNameKey;
3458 using key_type_ref = key_type;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003459
Richard Smithd88a7f12015-09-01 20:35:42 +00003460 /// A start and end index into DeclIDs, representing a sequence of decls.
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003461 using data_type = std::pair<unsigned, unsigned>;
3462 using data_type_ref = const data_type &;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003463
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003464 using hash_value_type = unsigned;
3465 using offset_type = unsigned;
Justin Bogner25463f12014-04-18 20:27:24 +00003466
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003467 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) {}
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003468
Richard Smithd88a7f12015-09-01 20:35:42 +00003469 template<typename Coll>
3470 data_type getData(const Coll &Decls) {
3471 unsigned Start = DeclIDs.size();
3472 for (NamedDecl *D : Decls) {
3473 DeclIDs.push_back(
3474 Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3475 }
3476 return std::make_pair(Start, DeclIDs.size());
3477 }
3478
3479 data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
3480 unsigned Start = DeclIDs.size();
3481 for (auto ID : FromReader)
3482 DeclIDs.push_back(ID);
3483 return std::make_pair(Start, DeclIDs.size());
3484 }
3485
3486 static bool EqualKey(key_type_ref a, key_type_ref b) {
3487 return a == b;
3488 }
3489
Richard Smitha06c7e62015-08-26 23:55:49 +00003490 hash_value_type ComputeHash(DeclarationNameKey Name) {
3491 return Name.getHash();
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003492 }
3493
Richard Smithd88a7f12015-09-01 20:35:42 +00003494 void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
3495 assert(Writer.hasChain() &&
3496 "have reference to loaded module file but no chain?");
3497
3498 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003499
Peter Collingbournee3f65292018-05-18 19:46:24 +00003500 endian::write<uint32_t>(Out, Writer.getChain()->getModuleFileID(F), little);
Richard Smithd88a7f12015-09-01 20:35:42 +00003501 }
3502
Richard Smitha06c7e62015-08-26 23:55:49 +00003503 std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
3504 DeclarationNameKey Name,
3505 data_type_ref Lookup) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003506 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003507
Peter Collingbournee3f65292018-05-18 19:46:24 +00003508 endian::Writer LE(Out, little);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003509 unsigned KeyLen = 1;
Richard Smitha06c7e62015-08-26 23:55:49 +00003510 switch (Name.getKind()) {
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003511 case DeclarationName::Identifier:
3512 case DeclarationName::ObjCZeroArgSelector:
3513 case DeclarationName::ObjCOneArgSelector:
3514 case DeclarationName::ObjCMultiArgSelector:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003515 case DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00003516 case DeclarationName::CXXDeductionGuideName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003517 KeyLen += 4;
3518 break;
3519 case DeclarationName::CXXOperatorName:
3520 KeyLen += 1;
3521 break;
Douglas Gregor3b65ed02011-08-02 18:32:54 +00003522 case DeclarationName::CXXConstructorName:
3523 case DeclarationName::CXXDestructorName:
3524 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003525 case DeclarationName::CXXUsingDirective:
3526 break;
3527 }
Justin Bognere1c147c2014-03-28 22:03:19 +00003528 LE.write<uint16_t>(KeyLen);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003529
Richard Smithf02662d2015-07-30 03:17:16 +00003530 // 4 bytes for each DeclID.
Richard Smithd88a7f12015-09-01 20:35:42 +00003531 unsigned DataLen = 4 * (Lookup.second - Lookup.first);
3532 assert(uint16_t(DataLen) == DataLen &&
3533 "too many decls for serialized lookup result");
Justin Bognere1c147c2014-03-28 22:03:19 +00003534 LE.write<uint16_t>(DataLen);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003535
3536 return std::make_pair(KeyLen, DataLen);
3537 }
3538
Richard Smitha06c7e62015-08-26 23:55:49 +00003539 void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003540 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003541
Peter Collingbournee3f65292018-05-18 19:46:24 +00003542 endian::Writer LE(Out, little);
Richard Smitha06c7e62015-08-26 23:55:49 +00003543 LE.write<uint8_t>(Name.getKind());
3544 switch (Name.getKind()) {
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003545 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +00003546 case DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00003547 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00003548 LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier()));
Benjamin Kramer53750b12012-09-19 13:40:40 +00003549 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003550 case DeclarationName::ObjCZeroArgSelector:
3551 case DeclarationName::ObjCOneArgSelector:
3552 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00003553 LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
Benjamin Kramer53750b12012-09-19 13:40:40 +00003554 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003555 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00003556 assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
Benjamin Kramer53750b12012-09-19 13:40:40 +00003557 "Invalid operator?");
Richard Smitha06c7e62015-08-26 23:55:49 +00003558 LE.write<uint8_t>(Name.getOperatorKind());
Benjamin Kramer53750b12012-09-19 13:40:40 +00003559 return;
Douglas Gregor3b65ed02011-08-02 18:32:54 +00003560 case DeclarationName::CXXConstructorName:
3561 case DeclarationName::CXXDestructorName:
3562 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003563 case DeclarationName::CXXUsingDirective:
Benjamin Kramer53750b12012-09-19 13:40:40 +00003564 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003565 }
Benjamin Kramer53750b12012-09-19 13:40:40 +00003566
3567 llvm_unreachable("Invalid name kind?");
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003568 }
3569
Richard Smitha06c7e62015-08-26 23:55:49 +00003570 void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
3571 unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003572 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003573
Peter Collingbournee3f65292018-05-18 19:46:24 +00003574 endian::Writer LE(Out, little);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003575 uint64_t Start = Out.tell(); (void)Start;
Richard Smithd88a7f12015-09-01 20:35:42 +00003576 for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
3577 LE.write<uint32_t>(DeclIDs[I]);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003578 assert(Out.tell() - Start == DataLen && "Data length is wrong");
3579 }
3580};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003581
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003582} // namespace
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003583
Chandler Carruthe972c362015-03-26 03:11:40 +00003584bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
3585 DeclContext *DC) {
Erich Keanef92f31c2018-08-01 20:48:16 +00003586 return Result.hasExternalDecls() &&
3587 DC->hasNeedToReconcileExternalVisibleStorage();
Chandler Carruthe972c362015-03-26 03:11:40 +00003588}
3589
3590bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
3591 DeclContext *DC) {
3592 for (auto *D : Result.getLookupResult())
3593 if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
3594 return false;
3595
3596 return true;
3597}
3598
Richard Smithd88a7f12015-09-01 20:35:42 +00003599void
Chandler Carruthe972c362015-03-26 03:11:40 +00003600ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
Richard Smithcd45dbc2014-04-19 03:48:30 +00003601 llvm::SmallVectorImpl<char> &LookupTable) {
Erich Keanef92f31c2018-08-01 20:48:16 +00003602 assert(!ConstDC->hasLazyLocalLexicalLookups() &&
3603 !ConstDC->hasLazyExternalLexicalLookups() &&
Richard Smith9e2341d2015-03-23 03:25:59 +00003604 "must call buildLookups first");
Richard Smithcd45dbc2014-04-19 03:48:30 +00003605
Chandler Carruthe972c362015-03-26 03:11:40 +00003606 // FIXME: We need to build the lookups table, which is logically const.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003607 auto *DC = const_cast<DeclContext*>(ConstDC);
Chandler Carruthe972c362015-03-26 03:11:40 +00003608 assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
3609
3610 // Create the on-disk hash table representation.
Richard Smithd88a7f12015-09-01 20:35:42 +00003611 MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait,
3612 ASTDeclContextNameLookupTrait> Generator;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003613 ASTDeclContextNameLookupTrait Trait(*this);
3614
Chandler Carruthe972c362015-03-26 03:11:40 +00003615 // The first step is to collect the declaration names which we need to
3616 // serialize into the name lookup table, and to collect them in a stable
3617 // order.
3618 SmallVector<DeclarationName, 16> Names;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003619
Chandler Carruthe972c362015-03-26 03:11:40 +00003620 // We also build up small sets of the constructor and conversion function
3621 // names which are visible.
3622 llvm::SmallSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003623
Chandler Carruthe972c362015-03-26 03:11:40 +00003624 for (auto &Lookup : *DC->buildLookup()) {
3625 auto &Name = Lookup.first;
3626 auto &Result = Lookup.second;
3627
Douglas Gregor7dd37e52015-11-03 01:20:54 +00003628 // If there are no local declarations in our lookup result, we
3629 // don't need to write an entry for the name at all. If we can't
3630 // write out a lookup set without performing more deserialization,
3631 // just skip this entry.
3632 if (isLookupResultExternal(Result, DC) &&
Chandler Carruthe972c362015-03-26 03:11:40 +00003633 isLookupResultEntirelyExternal(Result, DC))
3634 continue;
3635
3636 // We also skip empty results. If any of the results could be external and
3637 // the currently available results are empty, then all of the results are
3638 // external and we skip it above. So the only way we get here with an empty
3639 // results is when no results could have been external *and* we have
3640 // external results.
3641 //
3642 // FIXME: While we might want to start emitting on-disk entries for negative
3643 // lookups into a decl context as an optimization, today we *have* to skip
3644 // them because there are names with empty lookup results in decl contexts
3645 // which we can't emit in any stable ordering: we lookup constructors and
3646 // conversion functions in the enclosing namespace scope creating empty
3647 // results for them. This in almost certainly a bug in Clang's name lookup,
3648 // but that is likely to be hard or impossible to fix and so we tolerate it
3649 // here by omitting lookups with empty results.
3650 if (Lookup.second.getLookupResult().empty())
3651 continue;
3652
3653 switch (Lookup.first.getNameKind()) {
3654 default:
3655 Names.push_back(Lookup.first);
3656 break;
3657
Richard Smithcd45dbc2014-04-19 03:48:30 +00003658 case DeclarationName::CXXConstructorName:
Chandler Carruthe972c362015-03-26 03:11:40 +00003659 assert(isa<CXXRecordDecl>(DC) &&
3660 "Cannot have a constructor name outside of a class!");
3661 ConstructorNameSet.insert(Name);
3662 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003663
3664 case DeclarationName::CXXConversionFunctionName:
Chandler Carruthe972c362015-03-26 03:11:40 +00003665 assert(isa<CXXRecordDecl>(DC) &&
3666 "Cannot have a conversion function name outside of a class!");
3667 ConversionNameSet.insert(Name);
Rafael Espindolac606b3e2015-03-25 04:43:15 +00003668 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003669 }
Chandler Carruth75c9f132015-03-25 00:34:51 +00003670 }
Chandler Carruth75c9f132015-03-25 00:34:51 +00003671
Chandler Carruthe972c362015-03-26 03:11:40 +00003672 // Sort the names into a stable order.
Fangrui Song55fab262018-09-26 22:16:28 +00003673 llvm::sort(Names);
Chandler Carruthe972c362015-03-26 03:11:40 +00003674
Chandler Carruthffbf7052015-03-26 22:27:09 +00003675 if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
Chandler Carruthe972c362015-03-26 03:11:40 +00003676 // We need to establish an ordering of constructor and conversion function
Chandler Carruthffbf7052015-03-26 22:27:09 +00003677 // names, and they don't have an intrinsic ordering.
Chandler Carruthe972c362015-03-26 03:11:40 +00003678
Chandler Carruthffbf7052015-03-26 22:27:09 +00003679 // First we try the easy case by forming the current context's constructor
3680 // name and adding that name first. This is a very useful optimization to
3681 // avoid walking the lexical declarations in many cases, and it also
3682 // handles the only case where a constructor name can come from some other
3683 // lexical context -- when that name is an implicit constructor merged from
3684 // another declaration in the redecl chain. Any non-implicit constructor or
3685 // conversion function which doesn't occur in all the lexical contexts
3686 // would be an ODR violation.
3687 auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
3688 Context->getCanonicalType(Context->getRecordType(D)));
3689 if (ConstructorNameSet.erase(ImplicitCtorName))
3690 Names.push_back(ImplicitCtorName);
Chandler Carruthe972c362015-03-26 03:11:40 +00003691
Chandler Carruthffbf7052015-03-26 22:27:09 +00003692 // If we still have constructors or conversion functions, we walk all the
3693 // names in the decl and add the constructors and conversion functions
3694 // which are visible in the order they lexically occur within the context.
3695 if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
3696 for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
3697 if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
3698 auto Name = ChildND->getDeclName();
3699 switch (Name.getNameKind()) {
3700 default:
3701 continue;
3702
3703 case DeclarationName::CXXConstructorName:
3704 if (ConstructorNameSet.erase(Name))
3705 Names.push_back(Name);
3706 break;
3707
3708 case DeclarationName::CXXConversionFunctionName:
3709 if (ConversionNameSet.erase(Name))
3710 Names.push_back(Name);
3711 break;
3712 }
3713
3714 if (ConstructorNameSet.empty() && ConversionNameSet.empty())
3715 break;
Chandler Carruthe972c362015-03-26 03:11:40 +00003716 }
3717
Chandler Carruthe972c362015-03-26 03:11:40 +00003718 assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
3719 "constructors by walking all the "
3720 "lexical members of the context.");
3721 assert(ConversionNameSet.empty() && "Failed to find all of the visible "
3722 "conversion functions by walking all "
3723 "the lexical members of the context.");
Richard Smith961eae52014-03-25 01:14:22 +00003724 }
3725
Chandler Carruthe972c362015-03-26 03:11:40 +00003726 // Next we need to do a lookup with each name into this decl context to fully
3727 // populate any results from external sources. We don't actually use the
3728 // results of these lookups because we only want to use the results after all
3729 // results have been loaded and the pointers into them will be stable.
3730 for (auto &Name : Names)
3731 DC->lookup(Name);
3732
3733 // Now we need to insert the results for each name into the hash table. For
3734 // constructor names and conversion function names, we actually need to merge
3735 // all of the results for them into one list of results each and insert
3736 // those.
3737 SmallVector<NamedDecl *, 8> ConstructorDecls;
3738 SmallVector<NamedDecl *, 8> ConversionDecls;
3739
3740 // Now loop over the names, either inserting them or appending for the two
3741 // special cases.
3742 for (auto &Name : Names) {
3743 DeclContext::lookup_result Result = DC->noload_lookup(Name);
3744
3745 switch (Name.getNameKind()) {
3746 default:
Richard Smithd88a7f12015-09-01 20:35:42 +00003747 Generator.insert(Name, Trait.getData(Result), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00003748 break;
3749
3750 case DeclarationName::CXXConstructorName:
3751 ConstructorDecls.append(Result.begin(), Result.end());
3752 break;
3753
3754 case DeclarationName::CXXConversionFunctionName:
3755 ConversionDecls.append(Result.begin(), Result.end());
3756 break;
3757 }
3758 }
3759
3760 // Handle our two special cases if we ended up having any. We arbitrarily use
3761 // the first declaration's name here because the name itself isn't part of
3762 // the key, only the kind of name is used.
3763 if (!ConstructorDecls.empty())
3764 Generator.insert(ConstructorDecls.front()->getDeclName(),
Richard Smithd88a7f12015-09-01 20:35:42 +00003765 Trait.getData(ConstructorDecls), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00003766 if (!ConversionDecls.empty())
3767 Generator.insert(ConversionDecls.front()->getDeclName(),
Richard Smithd88a7f12015-09-01 20:35:42 +00003768 Trait.getData(ConversionDecls), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00003769
Richard Smithd88a7f12015-09-01 20:35:42 +00003770 // Create the on-disk hash table. Also emit the existing imported and
3771 // merged table if there is one.
3772 auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr;
3773 Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr);
Richard Smith961eae52014-03-25 01:14:22 +00003774}
3775
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003776/// Write the block containing all of the declaration IDs
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003777/// visible from the given DeclContext.
3778///
3779/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
Sebastian Redla4071b42010-08-24 00:50:09 +00003780/// bitstream, or 0 if no block was written.
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003781uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
3782 DeclContext *DC) {
Richard Smith5fc18a92015-07-12 23:43:21 +00003783 // If we imported a key declaration of this namespace, write the visible
3784 // lookup results as an update record for it rather than including them
3785 // on this declaration. We will only look at key declarations on reload.
3786 if (isa<NamespaceDecl>(DC) && Chain &&
3787 Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) {
3788 // Only do this once, for the first local declaration of the namespace.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003789 for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
Richard Smith5fc18a92015-07-12 23:43:21 +00003790 Prev = Prev->getPreviousDecl())
3791 if (!Prev->isFromASTFile())
3792 return 0;
3793
3794 // Note that we need to emit an update record for the primary context.
3795 UpdatedDeclContexts.insert(DC->getPrimaryContext());
3796
3797 // Make sure all visible decls are written. They will be recorded later. We
3798 // do this using a side data structure so we can sort the names into
3799 // a deterministic order.
3800 StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup();
3801 SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16>
3802 LookupResults;
3803 if (Map) {
3804 LookupResults.reserve(Map->size());
3805 for (auto &Entry : *Map)
3806 LookupResults.push_back(
3807 std::make_pair(Entry.first, Entry.second.getLookupResult()));
3808 }
3809
Fangrui Song55fab262018-09-26 22:16:28 +00003810 llvm::sort(LookupResults, llvm::less_first());
Richard Smith5fc18a92015-07-12 23:43:21 +00003811 for (auto &NameAndResult : LookupResults) {
3812 DeclarationName Name = NameAndResult.first;
3813 DeclContext::lookup_result Result = NameAndResult.second;
3814 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
3815 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
3816 // We have to work around a name lookup bug here where negative lookup
3817 // results for these names get cached in namespace lookup tables (these
3818 // names should never be looked up in a namespace).
3819 assert(Result.empty() && "Cannot have a constructor or conversion "
3820 "function name in a namespace!");
3821 continue;
3822 }
3823
3824 for (NamedDecl *ND : Result)
3825 if (!ND->isFromASTFile())
3826 GetDeclRef(ND);
3827 }
3828
3829 return 0;
3830 }
3831
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003832 if (DC->getPrimaryContext() != DC)
3833 return 0;
3834
Chandler Carruthe972c362015-03-26 03:11:40 +00003835 // Skip contexts which don't support name lookup.
3836 if (!DC->isLookupContext())
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003837 return 0;
3838
3839 // If not in C++, we perform name lookup for the translation unit via the
3840 // IdentifierInfo chains, don't bother to build a visible-declarations table.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003841 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003842 return 0;
3843
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003844 // Serialize the contents of the mapping used for lookup. Note that,
3845 // although we have two very different code paths, the serialized
3846 // representation is the same for both cases: a declaration name,
3847 // followed by a size, followed by references to the visible
3848 // declarations that have that name.
3849 uint64_t Offset = Stream.GetCurrentBitNo();
Richard Smithf634c902012-03-16 06:12:59 +00003850 StoredDeclsMap *Map = DC->buildLookup();
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003851 if (!Map || Map->empty())
3852 return 0;
3853
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003854 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003855 SmallString<4096> LookupTable;
Richard Smithd88a7f12015-09-01 20:35:42 +00003856 GenerateNameLookupTable(DC, LookupTable);
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003857
3858 // Write the lookup table
Mehdi Amini57a41912015-09-10 01:46:39 +00003859 RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003860 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
Yaron Keren92e1b622015-03-18 10:17:07 +00003861 LookupTable);
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003862 ++NumVisibleDeclContexts;
3863 return Offset;
3864}
3865
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003866/// Write an UPDATE_VISIBLE block for the given context.
Sebastian Redla4071b42010-08-24 00:50:09 +00003867///
3868/// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
3869/// DeclContext in a dependent AST file. As such, they only exist for the TU
Richard Smithf634c902012-03-16 06:12:59 +00003870/// (in C++), for namespaces, and for classes with forward-declared unscoped
3871/// enumeration members (in C++11).
Sebastian Redla4071b42010-08-24 00:50:09 +00003872void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
Richard Smith961eae52014-03-25 01:14:22 +00003873 StoredDeclsMap *Map = DC->getLookupPtr();
Sebastian Redla4071b42010-08-24 00:50:09 +00003874 if (!Map || Map->empty())
3875 return;
3876
Sebastian Redla4071b42010-08-24 00:50:09 +00003877 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003878 SmallString<4096> LookupTable;
Richard Smithd88a7f12015-09-01 20:35:42 +00003879 GenerateNameLookupTable(DC, LookupTable);
Sebastian Redla4071b42010-08-24 00:50:09 +00003880
Richard Smith5fc18a92015-07-12 23:43:21 +00003881 // If we're updating a namespace, select a key declaration as the key for the
3882 // update record; those are the only ones that will be checked on reload.
3883 if (isa<NamespaceDecl>(DC))
3884 DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
3885
Sebastian Redla4071b42010-08-24 00:50:09 +00003886 // Write the lookup table
Mehdi Amini57a41912015-09-10 01:46:39 +00003887 RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))};
Yaron Keren92e1b622015-03-18 10:17:07 +00003888 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
Sebastian Redla4071b42010-08-24 00:50:09 +00003889}
3890
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003891/// Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003892void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
Adam Nemet484aa452017-03-27 19:17:25 +00003893 RecordData::value_type Record[] = {Opts.getInt()};
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003894 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
3895}
3896
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003897/// Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003898void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003899 if (!SemaRef.Context.getLangOpts().OpenCL)
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003900 return;
3901
3902 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
3903 RecordData Record;
Yaxun Liu5b746652016-12-18 05:18:55 +00003904 for (const auto &I:Opts.OptMap) {
3905 AddString(I.getKey(), Record);
3906 auto V = I.getValue();
Yaxun Liucc2741c2016-12-18 06:35:06 +00003907 Record.push_back(V.Supported ? 1 : 0);
3908 Record.push_back(V.Enabled ? 1 : 0);
Yaxun Liu5b746652016-12-18 05:18:55 +00003909 Record.push_back(V.Avail);
3910 Record.push_back(V.Core);
3911 }
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003912 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
3913}
3914
Yaxun Liu5b746652016-12-18 05:18:55 +00003915void ASTWriter::WriteOpenCLExtensionTypes(Sema &SemaRef) {
3916 if (!SemaRef.Context.getLangOpts().OpenCL)
3917 return;
3918
Bruno Ricci2751b692019-04-18 15:13:27 +00003919 // Sort the elements of the map OpenCLTypeExtMap by TypeIDs,
3920 // without copying them.
3921 const llvm::DenseMap<const Type *, std::set<std::string>> &OpenCLTypeExtMap =
3922 SemaRef.OpenCLTypeExtMap;
3923 using ElementTy = std::pair<TypeID, const std::set<std::string> *>;
3924 llvm::SmallVector<ElementTy, 8> StableOpenCLTypeExtMap;
3925 StableOpenCLTypeExtMap.reserve(OpenCLTypeExtMap.size());
3926
3927 for (const auto &I : OpenCLTypeExtMap)
3928 StableOpenCLTypeExtMap.emplace_back(
3929 getTypeID(I.first->getCanonicalTypeInternal()), &I.second);
3930
3931 auto CompareByTypeID = [](const ElementTy &E1, const ElementTy &E2) -> bool {
3932 return E1.first < E2.first;
3933 };
3934 llvm::sort(StableOpenCLTypeExtMap, CompareByTypeID);
3935
Yaxun Liu5b746652016-12-18 05:18:55 +00003936 RecordData Record;
Bruno Ricci2751b692019-04-18 15:13:27 +00003937 for (const ElementTy &E : StableOpenCLTypeExtMap) {
3938 Record.push_back(E.first); // TypeID
3939 const std::set<std::string> *ExtSet = E.second;
3940 Record.push_back(static_cast<unsigned>(ExtSet->size()));
3941 for (const std::string &Ext : *ExtSet)
Yaxun Liu5b746652016-12-18 05:18:55 +00003942 AddString(Ext, Record);
3943 }
Bruno Ricci2751b692019-04-18 15:13:27 +00003944
Yaxun Liu5b746652016-12-18 05:18:55 +00003945 Stream.EmitRecord(OPENCL_EXTENSION_TYPES, Record);
3946}
3947
3948void ASTWriter::WriteOpenCLExtensionDecls(Sema &SemaRef) {
3949 if (!SemaRef.Context.getLangOpts().OpenCL)
3950 return;
3951
Bruno Ricci2751b692019-04-18 15:13:27 +00003952 // Sort the elements of the map OpenCLDeclExtMap by DeclIDs,
3953 // without copying them.
3954 const llvm::DenseMap<const Decl *, std::set<std::string>> &OpenCLDeclExtMap =
3955 SemaRef.OpenCLDeclExtMap;
3956 using ElementTy = std::pair<DeclID, const std::set<std::string> *>;
3957 llvm::SmallVector<ElementTy, 8> StableOpenCLDeclExtMap;
3958 StableOpenCLDeclExtMap.reserve(OpenCLDeclExtMap.size());
3959
3960 for (const auto &I : OpenCLDeclExtMap)
3961 StableOpenCLDeclExtMap.emplace_back(getDeclID(I.first), &I.second);
3962
3963 auto CompareByDeclID = [](const ElementTy &E1, const ElementTy &E2) -> bool {
3964 return E1.first < E2.first;
3965 };
3966 llvm::sort(StableOpenCLDeclExtMap, CompareByDeclID);
3967
Yaxun Liu5b746652016-12-18 05:18:55 +00003968 RecordData Record;
Bruno Ricci2751b692019-04-18 15:13:27 +00003969 for (const ElementTy &E : StableOpenCLDeclExtMap) {
3970 Record.push_back(E.first); // DeclID
3971 const std::set<std::string> *ExtSet = E.second;
3972 Record.push_back(static_cast<unsigned>(ExtSet->size()));
3973 for (const std::string &Ext : *ExtSet)
Yaxun Liu5b746652016-12-18 05:18:55 +00003974 AddString(Ext, Record);
3975 }
Bruno Ricci2751b692019-04-18 15:13:27 +00003976
Yaxun Liu5b746652016-12-18 05:18:55 +00003977 Stream.EmitRecord(OPENCL_EXTENSION_DECLS, Record);
3978}
3979
Justin Lebar67a78a62016-10-08 22:15:58 +00003980void ASTWriter::WriteCUDAPragmas(Sema &SemaRef) {
3981 if (SemaRef.ForceCUDAHostDeviceDepth > 0) {
3982 RecordData::value_type Record[] = {SemaRef.ForceCUDAHostDeviceDepth};
3983 Stream.EmitRecord(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH, Record);
3984 }
3985}
3986
Douglas Gregor404cdde2012-01-27 01:47:08 +00003987void ASTWriter::WriteObjCCategories() {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003988 SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
Douglas Gregor404cdde2012-01-27 01:47:08 +00003989 RecordData Categories;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003990
Douglas Gregor404cdde2012-01-27 01:47:08 +00003991 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
3992 unsigned Size = 0;
3993 unsigned StartIndex = Categories.size();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003994
Douglas Gregor404cdde2012-01-27 01:47:08 +00003995 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003996
Douglas Gregor404cdde2012-01-27 01:47:08 +00003997 // Allocate space for the size.
3998 Categories.push_back(0);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003999
Douglas Gregor404cdde2012-01-27 01:47:08 +00004000 // Add the categories.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00004001 for (ObjCInterfaceDecl::known_categories_iterator
4002 Cat = Class->known_categories_begin(),
4003 CatEnd = Class->known_categories_end();
4004 Cat != CatEnd; ++Cat, ++Size) {
4005 assert(getDeclID(*Cat) != 0 && "Bogus category");
4006 AddDeclRef(*Cat, Categories);
Douglas Gregor404cdde2012-01-27 01:47:08 +00004007 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004008
Douglas Gregor404cdde2012-01-27 01:47:08 +00004009 // Update the size.
4010 Categories[StartIndex] = Size;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004011
Douglas Gregor404cdde2012-01-27 01:47:08 +00004012 // Record this interface -> category map.
4013 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
4014 CategoriesMap.push_back(CatInfo);
4015 }
4016
4017 // Sort the categories map by the definition ID, since the reader will be
4018 // performing binary searches on this information.
4019 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
4020
4021 // Emit the categories map.
4022 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004023
David Blaikieb44f0bf2017-01-04 22:36:43 +00004024 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor404cdde2012-01-27 01:47:08 +00004025 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
4026 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
4027 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004028 unsigned AbbrevID = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00004029
4030 RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
4031 Stream.EmitRecordWithBlob(AbbrevID, Record,
4032 reinterpret_cast<char *>(CategoriesMap.data()),
Douglas Gregor404cdde2012-01-27 01:47:08 +00004033 CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
Mehdi Amini57a41912015-09-10 01:46:39 +00004034
Douglas Gregor404cdde2012-01-27 01:47:08 +00004035 // Emit the category lists.
4036 Stream.EmitRecord(OBJC_CATEGORIES, Categories);
4037}
4038
Richard Smithe40f2ba2013-08-07 21:41:30 +00004039void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
4040 Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
4041
4042 if (LPTMap.empty())
4043 return;
4044
4045 RecordData Record;
Justin Lebar28f09c52016-10-10 16:26:08 +00004046 for (auto &LPTMapEntry : LPTMap) {
Chandler Carruth52cee4d2015-03-26 09:08:15 +00004047 const FunctionDecl *FD = LPTMapEntry.first;
Justin Lebar28f09c52016-10-10 16:26:08 +00004048 LateParsedTemplate &LPT = *LPTMapEntry.second;
Chandler Carruth52cee4d2015-03-26 09:08:15 +00004049 AddDeclRef(FD, Record);
Justin Lebar28f09c52016-10-10 16:26:08 +00004050 AddDeclRef(LPT.D, Record);
4051 Record.push_back(LPT.Toks.size());
Richard Smithe40f2ba2013-08-07 21:41:30 +00004052
Justin Lebar28f09c52016-10-10 16:26:08 +00004053 for (const auto &Tok : LPT.Toks) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004054 AddToken(Tok, Record);
Richard Smithe40f2ba2013-08-07 21:41:30 +00004055 }
4056 }
4057 Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
4058}
4059
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004060/// Write the state of 'pragma clang optimize' at the end of the module.
Dario Domizioli13a0a382014-05-23 12:13:25 +00004061void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
4062 RecordData Record;
4063 SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
4064 AddSourceLocation(PragmaLoc, Record);
4065 Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
4066}
4067
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004068/// Write the state of 'pragma ms_struct' at the end of the module.
Nico Weber779355f2016-03-02 23:22:00 +00004069void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
4070 RecordData Record;
4071 Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF);
4072 Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
4073}
4074
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004075/// Write the state of 'pragma pointers_to_members' at the end of the
Nico Weber42932312016-03-03 00:17:35 +00004076//module.
4077void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
4078 RecordData Record;
4079 Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod);
4080 AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record);
4081 Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
4082}
4083
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004084/// Write the state of 'pragma pack' at the end of the module.
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00004085void ASTWriter::WritePackPragmaOptions(Sema &SemaRef) {
Duncan P. N. Exon Smith03df14c2017-04-15 00:07:57 +00004086 // Don't serialize pragma pack state for modules, since it should only take
4087 // effect on a per-submodule basis.
4088 if (WritingModule)
4089 return;
4090
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00004091 RecordData Record;
4092 Record.push_back(SemaRef.PackStack.CurrentValue);
4093 AddSourceLocation(SemaRef.PackStack.CurrentPragmaLocation, Record);
4094 Record.push_back(SemaRef.PackStack.Stack.size());
4095 for (const auto &StackEntry : SemaRef.PackStack.Stack) {
4096 Record.push_back(StackEntry.Value);
4097 AddSourceLocation(StackEntry.PragmaLocation, Record);
Alex Lorenz45b40142017-07-28 14:41:21 +00004098 AddSourceLocation(StackEntry.PragmaPushLocation, Record);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00004099 AddString(StackEntry.StackSlotLabel, Record);
4100 }
4101 Stream.EmitRecord(PACK_PRAGMA_OPTIONS, Record);
4102}
4103
Douglas Gregor8f64ca12015-12-08 22:43:32 +00004104void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
4105 ModuleFileExtensionWriter &Writer) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004106 // Enter the extension block.
4107 Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
4108
4109 // Emit the metadata record abbreviation.
David Blaikieb44f0bf2017-01-04 22:36:43 +00004110 auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004111 Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
4112 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4113 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4114 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4115 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4116 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004117 unsigned Abbrev = Stream.EmitAbbrev(std::move(Abv));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004118
4119 // Emit the metadata record.
4120 RecordData Record;
4121 auto Metadata = Writer.getExtension()->getExtensionMetadata();
4122 Record.push_back(EXTENSION_METADATA);
4123 Record.push_back(Metadata.MajorVersion);
4124 Record.push_back(Metadata.MinorVersion);
4125 Record.push_back(Metadata.BlockName.size());
4126 Record.push_back(Metadata.UserInfo.size());
4127 SmallString<64> Buffer;
4128 Buffer += Metadata.BlockName;
4129 Buffer += Metadata.UserInfo;
4130 Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
4131
4132 // Emit the contents of the extension block.
Douglas Gregor8f64ca12015-12-08 22:43:32 +00004133 Writer.writeExtensionContents(SemaRef, Stream);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004134
4135 // Exit the extension block.
4136 Stream.ExitBlock();
4137}
4138
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00004139//===----------------------------------------------------------------------===//
Douglas Gregorc5046832009-04-27 18:38:38 +00004140// General Serialization Routines
4141//===----------------------------------------------------------------------===//
4142
Richard Smithe43e2b32018-08-20 21:47:29 +00004143void ASTRecordWriter::AddAttr(const Attr *A) {
Reid Kleckner11f9f8a2018-08-14 01:55:37 +00004144 auto &Record = *this;
Richard Smithe43e2b32018-08-20 21:47:29 +00004145 if (!A)
4146 return Record.push_back(0);
4147 Record.push_back(A->getKind() + 1); // FIXME: stable encoding, target attrs
Erich Keane6a24e802019-09-13 17:39:31 +00004148
4149 Record.AddIdentifierRef(A->getAttrName());
4150 Record.AddIdentifierRef(A->getScopeName());
Richard Smithe43e2b32018-08-20 21:47:29 +00004151 Record.AddSourceRange(A->getRange());
Erich Keane6a24e802019-09-13 17:39:31 +00004152 Record.AddSourceLocation(A->getScopeLoc());
4153 Record.push_back(A->getParsedKind());
4154 Record.push_back(A->getSyntax());
4155 Record.push_back(A->getAttributeSpellingListIndexRaw());
Reid Kleckner11f9f8a2018-08-14 01:55:37 +00004156
4157#include "clang/Serialization/AttrPCHWrite.inc"
Richard Smithe43e2b32018-08-20 21:47:29 +00004158}
4159
4160/// Emit the list of attributes to the specified record.
4161void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) {
4162 push_back(Attrs.size());
4163 for (const auto *A : Attrs)
4164 AddAttr(A);
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00004165}
4166
John McCallf413f5e2013-05-03 00:10:13 +00004167void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
4168 AddSourceLocation(Tok.getLocation(), Record);
4169 Record.push_back(Tok.getLength());
4170
4171 // FIXME: When reading literal tokens, reconstruct the literal pointer
4172 // if it is needed.
4173 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
4174 // FIXME: Should translate token kind to a stable encoding.
4175 Record.push_back(Tok.getKind());
4176 // FIXME: Should translate token flags to a stable encoding.
4177 Record.push_back(Tok.getFlags());
4178}
4179
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004180void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00004181 Record.push_back(Str.size());
4182 Record.insert(Record.end(), Str.begin(), Str.end());
4183}
4184
Richard Smith7ed1bc92014-12-05 22:42:13 +00004185bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
Richard Smith54cc3c22014-12-11 20:50:24 +00004186 assert(Context && "should have context when outputting path");
Richard Smith7ed1bc92014-12-05 22:42:13 +00004187
Richard Smith54cc3c22014-12-11 20:50:24 +00004188 bool Changed =
4189 cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004190
4191 // Remove a prefix to make the path relative, if relevant.
4192 const char *PathBegin = Path.data();
4193 const char *PathPtr =
4194 adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
4195 if (PathPtr != PathBegin) {
4196 Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
4197 Changed = true;
4198 }
4199
4200 return Changed;
4201}
4202
4203void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
4204 SmallString<128> FilePath(Path);
4205 PreparePathForOutput(FilePath);
4206 AddString(FilePath, Record);
4207}
4208
Mehdi Amini57a41912015-09-10 01:46:39 +00004209void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
Richard Smith7ed1bc92014-12-05 22:42:13 +00004210 StringRef Path) {
4211 SmallString<128> FilePath(Path);
4212 PreparePathForOutput(FilePath);
4213 Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
4214}
4215
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004216void ASTWriter::AddVersionTuple(const VersionTuple &Version,
4217 RecordDataImpl &Record) {
4218 Record.push_back(Version.getMajor());
David Blaikie05785d12013-02-20 22:23:23 +00004219 if (Optional<unsigned> Minor = Version.getMinor())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004220 Record.push_back(*Minor + 1);
4221 else
4222 Record.push_back(0);
David Blaikie05785d12013-02-20 22:23:23 +00004223 if (Optional<unsigned> Subminor = Version.getSubminor())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004224 Record.push_back(*Subminor + 1);
4225 else
4226 Record.push_back(0);
4227}
4228
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004229/// Note that the identifier II occurs at the given offset
Douglas Gregore84a9da2009-04-20 20:36:09 +00004230/// within the identifier table.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004231void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Sebastian Redl539c5062010-08-18 23:57:32 +00004232 IdentID ID = IdentifierIDs[II];
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00004233 // Only store offsets new to this AST file. Other identifier names are looked
Sebastian Redlff4a2952010-07-23 23:49:55 +00004234 // up earlier in the chain and thus don't need an offset.
4235 if (ID >= FirstIdentID)
4236 IdentifierOffsets[ID - FirstIdentID] = Offset;
Douglas Gregore84a9da2009-04-20 20:36:09 +00004237}
4238
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004239/// Note that the selector Sel occurs at the given offset
Douglas Gregor95c13f52009-04-25 17:48:32 +00004240/// within the method pool/selector table.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004241void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
Douglas Gregor95c13f52009-04-25 17:48:32 +00004242 unsigned ID = SelectorIDs[Sel];
4243 assert(ID && "Unknown selector");
Sebastian Redld95a56e2010-08-04 18:21:41 +00004244 // Don't record offsets for selectors that are also available in a different
4245 // file.
4246 if (ID < FirstSelectorID)
4247 return;
4248 SelectorOffsets[ID - FirstSelectorID] = Offset;
Douglas Gregor95c13f52009-04-25 17:48:32 +00004249}
4250
David Blaikie61137e12017-01-05 18:23:18 +00004251ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream,
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +00004252 SmallVectorImpl<char> &Buffer,
4253 InMemoryModuleCache &ModuleCache,
David Blaikie61137e12017-01-05 18:23:18 +00004254 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
4255 bool IncludeTimestamps)
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +00004256 : Stream(Stream), Buffer(Buffer), ModuleCache(ModuleCache),
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004257 IncludeTimestamps(IncludeTimestamps) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004258 for (const auto &Ext : Extensions) {
4259 if (auto Writer = Ext->createExtensionWriter(*this))
4260 ModuleFileExtensionWriters.push_back(std::move(Writer));
4261 }
4262}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004263
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004264ASTWriter::~ASTWriter() {
Reid Kleckner588c9372014-02-19 23:44:52 +00004265 llvm::DeleteContainerSeconds(FileDeclIDs);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004266}
4267
Richard Smithb3761912015-02-05 23:08:52 +00004268const LangOptions &ASTWriter::getLangOpts() const {
4269 assert(WritingAST && "can't determine lang opts when not writing AST");
4270 return Context->getLangOpts();
4271}
4272
Richard Smithe75ee0f2015-08-17 07:13:32 +00004273time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const {
4274 return IncludeTimestamps ? E->getModificationTime() : 0;
4275}
4276
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004277ASTFileSignature ASTWriter::WriteAST(Sema &SemaRef,
4278 const std::string &OutputFile,
4279 Module *WritingModule, StringRef isysroot,
Duncan P. N. Exon Smith70d759b2019-03-12 18:38:04 +00004280 bool hasErrors,
4281 bool ShouldCacheASTInMemory) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00004282 WritingAST = true;
Adrian Prantladbd2b12015-09-22 23:26:31 +00004283
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00004284 ASTHasCompilerErrors = hasErrors;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004285
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004286 // Emit the file header.
Douglas Gregor8f45df52009-04-16 22:23:12 +00004287 Stream.Emit((unsigned)'C', 8);
4288 Stream.Emit((unsigned)'P', 8);
4289 Stream.Emit((unsigned)'C', 8);
4290 Stream.Emit((unsigned)'H', 8);
Mike Stump11289f42009-09-09 15:08:12 +00004291
Chris Lattner28fa4e62009-04-26 22:26:21 +00004292 WriteBlockInfoBlock();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004293
Douglas Gregoreda8e122011-08-09 15:13:55 +00004294 Context = &SemaRef.Context;
Douglas Gregora28bcdd2011-12-01 02:07:58 +00004295 PP = &SemaRef.PP;
Douglas Gregora89c5ac2011-12-06 01:10:29 +00004296 this->WritingModule = WritingModule;
Adrian Prantladbd2b12015-09-22 23:26:31 +00004297 ASTFileSignature Signature =
4298 WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
Craig Toppera13603a2014-05-22 05:54:18 +00004299 Context = nullptr;
4300 PP = nullptr;
4301 this->WritingModule = nullptr;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004302 this->BaseDirectory.clear();
Craig Toppera13603a2014-05-22 05:54:18 +00004303
Douglas Gregor2fd3d402011-09-17 00:05:03 +00004304 WritingAST = false;
Duncan P. N. Exon Smith70d759b2019-03-12 18:38:04 +00004305 if (ShouldCacheASTInMemory) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004306 // Construct MemoryBuffer and update buffer manager.
Volodymyr Sapsai83f4c3a2020-01-16 17:12:41 -08004307 ModuleCache.addFinalPCM(OutputFile,
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004308 llvm::MemoryBuffer::getMemBufferCopy(
4309 StringRef(Buffer.begin(), Buffer.size())));
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004310 }
Adrian Prantladbd2b12015-09-22 23:26:31 +00004311 return Signature;
Sebastian Redl143413f2010-07-12 22:02:52 +00004312}
4313
Douglas Gregora94a1542011-07-27 21:45:57 +00004314template<typename Vector>
4315static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4316 ASTWriter::RecordData &Record) {
Craig Toppera13603a2014-05-22 05:54:18 +00004317 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4318 I != E; ++I) {
Douglas Gregora94a1542011-07-27 21:45:57 +00004319 Writer.AddDeclRef(*I, Record);
4320 }
4321}
4322
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004323ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
4324 const std::string &OutputFile,
4325 Module *WritingModule) {
Sebastian Redl143413f2010-07-12 22:02:52 +00004326 using namespace llvm;
4327
Craig Toppera13603a2014-05-22 05:54:18 +00004328 bool isModule = WritingModule != nullptr;
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004329
Douglas Gregorcf68c582011-12-01 22:20:10 +00004330 // Make sure that the AST reader knows to finalize itself.
4331 if (Chain)
4332 Chain->finalizeForWriting();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004333
Sebastian Redl143413f2010-07-12 22:02:52 +00004334 ASTContext &Context = SemaRef.Context;
4335 Preprocessor &PP = SemaRef.PP;
4336
Douglas Gregordab42432011-08-12 00:15:20 +00004337 // Set up predefined declaration IDs.
Richard Smith5fc18a92015-07-12 23:43:21 +00004338 auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
4339 if (D) {
4340 assert(D->isCanonicalDecl() && "predefined decl is not canonical");
4341 DeclIDs[D] = ID;
Richard Smith5fc18a92015-07-12 23:43:21 +00004342 }
4343 };
4344 RegisterPredefDecl(Context.getTranslationUnitDecl(),
4345 PREDEF_DECL_TRANSLATION_UNIT_ID);
4346 RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
4347 RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
4348 RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
4349 RegisterPredefDecl(Context.ObjCProtocolClassDecl,
4350 PREDEF_DECL_OBJC_PROTOCOL_ID);
4351 RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
4352 RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
4353 RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
4354 PREDEF_DECL_OBJC_INSTANCETYPE_ID);
4355 RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
Richard Smith9b88a4c2015-07-27 05:40:23 +00004356 RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
Charles Davisc7d5c942015-09-17 20:55:33 +00004357 RegisterPredefDecl(Context.BuiltinMSVaListDecl,
4358 PREDEF_DECL_BUILTIN_MS_VA_LIST_ID);
Richard Smith5fc18a92015-07-12 23:43:21 +00004359 RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
David Majnemerd9b1a4f2015-11-04 03:40:30 +00004360 RegisterPredefDecl(Context.MakeIntegerSeqDecl,
4361 PREDEF_DECL_MAKE_INTEGER_SEQ_ID);
Quentin Colombet043406b2016-02-03 22:41:00 +00004362 RegisterPredefDecl(Context.CFConstantStringTypeDecl,
4363 PREDEF_DECL_CF_CONSTANT_STRING_ID);
Ben Langmuirf5416742016-02-04 00:55:24 +00004364 RegisterPredefDecl(Context.CFConstantStringTagDecl,
4365 PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID);
Eric Fiselier6ad68552016-07-01 01:24:09 +00004366 RegisterPredefDecl(Context.TypePackElementDecl,
4367 PREDEF_DECL_TYPE_PACK_ELEMENT_ID);
Meador Inge5d3fb222012-06-16 03:34:49 +00004368
Chris Lattner0c797362009-09-08 18:19:27 +00004369 // Build a record containing all of the tentative definitions in this file, in
Sebastian Redl35351a92010-01-31 22:27:38 +00004370 // TentativeDefinitions order. Generally, this record will be empty for
Chris Lattner0c797362009-09-08 18:19:27 +00004371 // headers.
Douglas Gregord4df8652009-04-22 22:02:47 +00004372 RecordData TentativeDefinitions;
Douglas Gregora94a1542011-07-27 21:45:57 +00004373 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004374
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00004375 // Build a record containing all of the file scoped decls in this file.
4376 RecordData UnusedFileScopedDecls;
Argyrios Kyrtzidis59852362013-03-14 04:45:00 +00004377 if (!isModule)
4378 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
4379 UnusedFileScopedDecls);
Sebastian Redl08aca90252010-08-05 18:21:25 +00004380
Douglas Gregor851443c2011-08-12 01:39:19 +00004381 // Build a record containing all of the delegating constructors we still need
4382 // to resolve.
Alexis Hunt27a761d2011-05-04 23:29:54 +00004383 RecordData DelegatingCtorDecls;
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004384 if (!isModule)
4385 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
Alexis Hunt27a761d2011-05-04 23:29:54 +00004386
Douglas Gregor851443c2011-08-12 01:39:19 +00004387 // Write the set of weak, undeclared identifiers. We always write the
4388 // entire table, since later PCH files in a PCH chain are only interested in
4389 // the results at the end of the chain.
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004390 RecordData WeakUndeclaredIdentifiers;
Chandler Carruthf85d9822015-03-26 08:32:49 +00004391 for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) {
4392 IdentifierInfo *II = WeakUndeclaredIdentifier.first;
4393 WeakInfo &WI = WeakUndeclaredIdentifier.second;
4394 AddIdentifierRef(II, WeakUndeclaredIdentifiers);
4395 AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
4396 AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
4397 WeakUndeclaredIdentifiers.push_back(WI.getUsed());
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004398 }
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00004399
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004400 // Build a record containing all of the ext_vector declarations.
4401 RecordData ExtVectorDecls;
Douglas Gregorb7098a32011-07-28 00:39:29 +00004402 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004403
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004404 // Build a record containing all of the VTable uses information.
4405 RecordData VTableUses;
Argyrios Kyrtzidisedee67f2010-08-03 17:29:52 +00004406 if (!SemaRef.VTableUses.empty()) {
Argyrios Kyrtzidisedee67f2010-08-03 17:29:52 +00004407 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4408 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4409 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4410 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4411 }
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004412 }
4413
Nico Weber72889432014-09-06 01:25:55 +00004414 // Build a record containing all of the UnusedLocalTypedefNameCandidates.
4415 RecordData UnusedLocalTypedefNameCandidates;
4416 for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4417 AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
4418
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004419 // Build a record containing all of pending implicit instantiations.
Chandler Carruth54080172010-08-25 08:44:16 +00004420 RecordData PendingInstantiations;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004421 for (const auto &I : SemaRef.PendingInstantiations) {
4422 AddDeclRef(I.first, PendingInstantiations);
4423 AddSourceLocation(I.second, PendingInstantiations);
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004424 }
4425 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4426 "There are local ones at end of translation unit!");
4427
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004428 // Build a record containing some declaration references.
4429 RecordData SemaDeclRefs;
Richard Smith96269c52016-09-29 22:49:46 +00004430 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) {
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004431 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4432 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
Richard Smith96269c52016-09-29 22:49:46 +00004433 AddDeclRef(SemaRef.getStdAlignValT(), SemaDeclRefs);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004434 }
4435
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004436 RecordData CUDASpecialDeclRefs;
4437 if (Context.getcudaConfigureCallDecl()) {
4438 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4439 }
4440
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004441 // Build a record containing all of the known namespaces.
4442 RecordData KnownNamespaces;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004443 for (const auto &I : SemaRef.KnownNamespaces) {
4444 if (!I.second)
4445 AddDeclRef(I.first, KnownNamespaces);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004446 }
Douglas Gregor112b9072012-10-18 05:31:06 +00004447
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004448 // Build a record of all used, undefined objects that require definitions.
4449 RecordData UndefinedButUsed;
Nick Lewyckyf0f56162013-01-31 03:23:57 +00004450
4451 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004452 SemaRef.getUndefinedButUsed(Undefined);
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004453 for (const auto &I : Undefined) {
4454 AddDeclRef(I.first, UndefinedButUsed);
4455 AddSourceLocation(I.second, UndefinedButUsed);
Nick Lewycky8334af82013-01-26 00:35:08 +00004456 }
4457
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00004458 // Build a record containing all delete-expressions that we would like to
4459 // analyze later in AST.
4460 RecordData DeleteExprsToAnalyze;
4461
Richard Smithf5262c62018-06-28 01:57:04 +00004462 if (!isModule) {
4463 for (const auto &DeleteExprsInfo :
4464 SemaRef.getMismatchingDeleteExpressions()) {
4465 AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
4466 DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
4467 for (const auto &DeleteLoc : DeleteExprsInfo.second) {
4468 AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
4469 DeleteExprsToAnalyze.push_back(DeleteLoc.second);
4470 }
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00004471 }
4472 }
4473
Douglas Gregor112b9072012-10-18 05:31:06 +00004474 // Write the control block
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004475 WriteControlBlock(PP, Context, isysroot, OutputFile);
Douglas Gregor112b9072012-10-18 05:31:06 +00004476
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00004477 // Write the remaining AST contents.
Sebastian Redl539c5062010-08-18 23:57:32 +00004478 Stream.EnterSubblock(AST_BLOCK_ID, 5);
Douglas Gregor851443c2011-08-12 01:39:19 +00004479
Argyrios Kyrtzidis39605402012-12-13 21:38:23 +00004480 // This is so that older clang versions, before the introduction
4481 // of the control block, can read and reject the newer PCH format.
Mehdi Amini57a41912015-09-10 01:46:39 +00004482 {
4483 RecordData Record = {VERSION_MAJOR};
4484 Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4485 }
Argyrios Kyrtzidis39605402012-12-13 21:38:23 +00004486
Douglas Gregor851443c2011-08-12 01:39:19 +00004487 // Create a lexical update block containing all of the declarations in the
4488 // translation unit that do not come from other AST files.
4489 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00004490 SmallVector<uint32_t, 128> NewGlobalKindDeclPairs;
4491 for (const auto *D : TU->noload_decls()) {
4492 if (!D->isFromASTFile()) {
4493 NewGlobalKindDeclPairs.push_back(D->getKind());
4494 NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
4495 }
Douglas Gregor851443c2011-08-12 01:39:19 +00004496 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004497
David Blaikieb44f0bf2017-01-04 22:36:43 +00004498 auto Abv = std::make_shared<BitCodeAbbrev>();
Douglas Gregor851443c2011-08-12 01:39:19 +00004499 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4500 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004501 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv));
Mehdi Amini57a41912015-09-10 01:46:39 +00004502 {
4503 RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
4504 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4505 bytes(NewGlobalKindDeclPairs));
4506 }
4507
Douglas Gregor851443c2011-08-12 01:39:19 +00004508 // And a visible updates block for the translation unit.
David Blaikieb44f0bf2017-01-04 22:36:43 +00004509 Abv = std::make_shared<BitCodeAbbrev>();
Douglas Gregor851443c2011-08-12 01:39:19 +00004510 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4511 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
Douglas Gregor851443c2011-08-12 01:39:19 +00004512 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004513 UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv));
Douglas Gregor851443c2011-08-12 01:39:19 +00004514 WriteDeclContextVisibleUpdate(TU);
Richard Smithf19e1272015-03-07 00:04:49 +00004515
4516 // If we have any extern "C" names, write out a visible update for them.
4517 if (Context.ExternCContext)
4518 WriteDeclContextVisibleUpdate(Context.ExternCContext);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004519
Douglas Gregor851443c2011-08-12 01:39:19 +00004520 // If the translation unit has an anonymous namespace, and we don't already
4521 // have an update block for it, write it as an update block.
Richard Smith6ef42932014-03-20 21:02:00 +00004522 // FIXME: Why do we not do this if there's already an update block?
Douglas Gregor851443c2011-08-12 01:39:19 +00004523 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4524 ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
Richard Smith6ef42932014-03-20 21:02:00 +00004525 if (Record.empty())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004526 Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
Douglas Gregor851443c2011-08-12 01:39:19 +00004527 }
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004528
Richard Smith5652c0f2014-03-21 01:48:23 +00004529 // Add update records for all mangling numbers and static local numbers.
4530 // These aren't really update records, but this is a convenient way of
4531 // tagging this rare extra data onto the declarations.
4532 for (const auto &Number : Context.MangleNumbers)
4533 if (!Number.first->isFromASTFile())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004534 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4535 Number.second));
Richard Smith5652c0f2014-03-21 01:48:23 +00004536 for (const auto &Number : Context.StaticLocalNumbers)
4537 if (!Number.first->isFromASTFile())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004538 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4539 Number.second));
Richard Smith5652c0f2014-03-21 01:48:23 +00004540
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004541 // Make sure visible decls, added to DeclContexts previously loaded from
Richard Smithc26d9742016-10-06 20:30:51 +00004542 // an AST file, are registered for serialization. Likewise for template
4543 // specializations added to imported templates.
4544 for (const auto *I : DeclsToEmitEvenIfUnreferenced) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004545 GetDeclRef(I);
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004546 }
4547
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +00004548 // Make sure all decls associated with an identifier are registered for
Richard Smith79bf9202015-08-24 03:33:22 +00004549 // serialization, if we're storing decls with identifiers.
4550 if (!WritingModule || !getLangOpts().CPlusPlus) {
4551 llvm::SmallVector<const IdentifierInfo*, 256> IIs;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004552 for (const auto &ID : PP.getIdentifierTable()) {
4553 const IdentifierInfo *II = ID.second;
Richard Smith79bf9202015-08-24 03:33:22 +00004554 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
4555 IIs.push_back(II);
4556 }
4557 // Sort the identifiers to visit based on their name.
Benjamin Kramercd2bae32019-08-22 17:32:16 +00004558 llvm::sort(IIs, llvm::deref<std::less<>>());
Richard Smith79bf9202015-08-24 03:33:22 +00004559 for (const IdentifierInfo *II : IIs) {
4560 for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4561 DEnd = SemaRef.IdResolver.end();
4562 D != DEnd; ++D) {
4563 GetDeclRef(*D);
4564 }
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +00004565 }
4566 }
4567
Manman Rena0f31a02016-04-29 19:04:05 +00004568 // For method pool in the module, if it contains an entry for a selector,
4569 // the entry should be complete, containing everything introduced by that
4570 // module and all modules it imports. It's possible that the entry is out of
4571 // date, so we need to pull in the new content here.
4572
4573 // It's possible that updateOutOfDateSelector can update SelectorIDs. To be
4574 // safe, we copy all selectors out.
4575 llvm::SmallVector<Selector, 256> AllSelectors;
4576 for (auto &SelectorAndID : SelectorIDs)
4577 AllSelectors.push_back(SelectorAndID.first);
4578 for (auto &Selector : AllSelectors)
4579 SemaRef.updateOutOfDateSelector(Selector);
4580
Douglas Gregor5204bde2011-08-02 16:26:37 +00004581 // Form the record of special types.
4582 RecordData SpecialTypes;
Douglas Gregor5204bde2011-08-02 16:26:37 +00004583 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
Douglas Gregor5204bde2011-08-02 16:26:37 +00004584 AddTypeRef(Context.getFILEType(), SpecialTypes);
4585 AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4586 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4587 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4588 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
Douglas Gregor5204bde2011-08-02 16:26:37 +00004589 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00004590 AddTypeRef(Context.getucontext_tType(), SpecialTypes);
Douglas Gregora28bcdd2011-12-01 02:07:58 +00004591
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004592 if (Chain) {
4593 // Write the mapping information describing our module dependencies and how
4594 // each of those modules were mapped into our own offset/ID space, so that
4595 // the reader can build the appropriate mapping to its own offset/ID space.
4596 // The map consists solely of a blob with the following format:
Boris Kolpackovd30446f2017-08-31 06:26:43 +00004597 // *(module-kind:i8
4598 // module-name-len:i16 module-name:len*i8
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004599 // source-location-offset:i32
4600 // identifier-id:i32
4601 // preprocessed-entity-id:i32
4602 // macro-definition-id:i32
Douglas Gregor253eefe2011-12-01 00:59:36 +00004603 // submodule-id:i32
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004604 // selector-id:i32
4605 // declaration-id:i32
4606 // c++-base-specifiers-id:i32
4607 // type-id:i32)
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004608 //
Boris Kolpackovd30446f2017-08-31 06:26:43 +00004609 // module-kind is the ModuleKind enum value. If it is MK_PrebuiltModule or
4610 // MK_ExplicitModule, then the module-name is the module name. Otherwise,
4611 // it is the module file name.
David Blaikieb44f0bf2017-01-04 22:36:43 +00004612 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004613 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4614 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004615 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004616 SmallString<2048> Buffer;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004617 {
4618 llvm::raw_svector_ostream Out(Buffer);
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00004619 for (ModuleFile &M : Chain->ModuleMgr) {
Justin Bognere1c147c2014-03-28 22:03:19 +00004620 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00004621
Peter Collingbournee3f65292018-05-18 19:46:24 +00004622 endian::Writer LE(Out, little);
Boris Kolpackovd30446f2017-08-31 06:26:43 +00004623 LE.write<uint8_t>(static_cast<uint8_t>(M.Kind));
4624 StringRef Name =
4625 M.Kind == MK_PrebuiltModule || M.Kind == MK_ExplicitModule
4626 ? M.ModuleName
4627 : M.FileName;
4628 LE.write<uint16_t>(Name.size());
4629 Out.write(Name.data(), Name.size());
Ben Langmuirfe971d92014-08-16 04:54:18 +00004630
Ben Langmuir785180e2014-10-20 16:27:30 +00004631 // Note: if a base ID was uint max, it would not be possible to load
4632 // another module after it or have more than one entity inside it.
4633 uint32_t None = std::numeric_limits<uint32_t>::max();
4634
4635 auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) {
4636 assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
4637 if (ShouldWrite)
4638 LE.write<uint32_t>(BaseID);
4639 else
4640 LE.write<uint32_t>(None);
4641 };
4642
Ben Langmuirfe971d92014-08-16 04:54:18 +00004643 // These values should be unique within a chain, since they will be read
4644 // as keys into ContinuousRangeMaps.
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00004645 writeBaseIDOrNone(M.SLocEntryBaseOffset, M.LocalNumSLocEntries);
4646 writeBaseIDOrNone(M.BaseIdentifierID, M.LocalNumIdentifiers);
4647 writeBaseIDOrNone(M.BaseMacroID, M.LocalNumMacros);
4648 writeBaseIDOrNone(M.BasePreprocessedEntityID,
4649 M.NumPreprocessedEntities);
4650 writeBaseIDOrNone(M.BaseSubmoduleID, M.LocalNumSubmodules);
4651 writeBaseIDOrNone(M.BaseSelectorID, M.LocalNumSelectors);
4652 writeBaseIDOrNone(M.BaseDeclID, M.LocalNumDecls);
4653 writeBaseIDOrNone(M.BaseTypeIndex, M.LocalNumTypes);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004654 }
4655 }
Mehdi Amini57a41912015-09-10 01:46:39 +00004656 RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004657 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4658 Buffer.data(), Buffer.size());
4659 }
Richard Smithb9eab6d2014-03-20 19:44:17 +00004660
Richard Smithb9eab6d2014-03-20 19:44:17 +00004661 RecordData DeclUpdatesOffsetsRecord;
4662
Richard Smith59442b42014-03-20 20:07:19 +00004663 // Keep writing types, declarations, and declaration update records
4664 // until we've emitted all of them.
Richard Smith01b2cb42014-07-26 06:37:51 +00004665 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
4666 WriteTypeAbbrevs();
4667 WriteDeclAbbrevs();
Richard Smith59442b42014-03-20 20:07:19 +00004668 do {
4669 WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
4670 while (!DeclTypesToEmit.empty()) {
4671 DeclOrType DOT = DeclTypesToEmit.front();
4672 DeclTypesToEmit.pop();
4673 if (DOT.isType())
4674 WriteType(DOT.getType());
4675 else
4676 WriteDecl(Context, DOT.getDecl());
4677 }
4678 } while (!DeclUpdates.empty());
Richard Smithb9eab6d2014-03-20 19:44:17 +00004679 Stream.ExitBlock();
4680
Richard Smithb9eab6d2014-03-20 19:44:17 +00004681 DoneWritingDeclsAndTypes = true;
4682
4683 // These things can only be done once we've written out decls and types.
4684 WriteTypeDeclOffsets();
Richard Smith5652c0f2014-03-21 01:48:23 +00004685 if (!DeclUpdatesOffsetsRecord.empty())
4686 Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
Richard Smithb9eab6d2014-03-20 19:44:17 +00004687 WriteFileDeclIDsMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00004688 WriteSourceManagerBlock(Context.getSourceManager(), PP);
Richard Smithb9eab6d2014-03-20 19:44:17 +00004689 WriteComments();
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004690 WritePreprocessor(PP, isModule);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004691 WriteHeaderSearch(PP.getHeaderSearchInfo());
Sebastian Redla19a67f2010-08-03 21:58:15 +00004692 WriteSelectors(SemaRef);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00004693 WriteReferencedSelectorsPool(SemaRef);
Richard Smith9c254182015-07-19 21:41:12 +00004694 WriteLateParsedTemplates(SemaRef);
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004695 WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
Peter Collingbourne5df20e02011-02-15 19:46:30 +00004696 WriteFPPragmaOptions(SemaRef.getFPOptions());
4697 WriteOpenCLExtensions(SemaRef);
Yaxun Liu5b746652016-12-18 05:18:55 +00004698 WriteOpenCLExtensionTypes(SemaRef);
Justin Lebar67a78a62016-10-08 22:15:58 +00004699 WriteCUDAPragmas(SemaRef);
Douglas Gregor652d82a2009-04-18 05:55:16 +00004700
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004701 // If we're emitting a module, write out the submodule information.
Douglas Gregora89c5ac2011-12-06 01:10:29 +00004702 if (WritingModule)
4703 WriteSubmodules(WritingModule);
4704
Andrew Savonichev52d674d2018-10-29 11:14:01 +00004705 // We need to have information about submodules to correctly deserialize
4706 // decls from OpenCLExtensionDecls block
4707 WriteOpenCLExtensionDecls(SemaRef);
4708
Douglas Gregor5204bde2011-08-02 16:26:37 +00004709 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
4710
Douglas Gregord4df8652009-04-22 22:02:47 +00004711 // Write the record containing external, unnamed definitions.
Ben Langmuir332aafe2014-01-31 01:06:56 +00004712 if (!EagerlyDeserializedDecls.empty())
4713 Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
Douglas Gregord4df8652009-04-22 22:02:47 +00004714
David Blaikief63556d2017-04-12 20:58:33 +00004715 if (!ModularCodegenDecls.empty())
David Blaikie9ffe5a32017-01-30 05:00:26 +00004716 Stream.EmitRecord(MODULAR_CODEGEN_DECLS, ModularCodegenDecls);
4717
Douglas Gregord4df8652009-04-22 22:02:47 +00004718 // Write the record containing tentative definitions.
4719 if (!TentativeDefinitions.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004720 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregoracfc76c2009-04-22 22:18:58 +00004721
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00004722 // Write the record containing unused file scoped decls.
4723 if (!UnusedFileScopedDecls.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004724 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00004725
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004726 // Write the record containing weak undeclared identifiers.
4727 if (!WeakUndeclaredIdentifiers.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004728 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004729 WeakUndeclaredIdentifiers);
4730
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004731 // Write the record containing ext_vector type names.
4732 if (!ExtVectorDecls.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004733 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
Mike Stump11289f42009-09-09 15:08:12 +00004734
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004735 // Write the record containing VTable uses information.
4736 if (!VTableUses.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004737 Stream.EmitRecord(VTABLE_USES, VTableUses);
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004738
Nico Weber72889432014-09-06 01:25:55 +00004739 // Write the record containing potentially unused local typedefs.
4740 if (!UnusedLocalTypedefNameCandidates.empty())
4741 Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
4742 UnusedLocalTypedefNameCandidates);
4743
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004744 // Write the record containing pending implicit instantiations.
Chandler Carruth54080172010-08-25 08:44:16 +00004745 if (!PendingInstantiations.empty())
4746 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004747
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004748 // Write the record containing declaration references of Sema.
4749 if (!SemaDeclRefs.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004750 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004751
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004752 // Write the record containing CUDA-specific declaration references.
4753 if (!CUDASpecialDeclRefs.empty())
4754 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004755
Alexis Hunt27a761d2011-05-04 23:29:54 +00004756 // Write the delegating constructors.
4757 if (!DelegatingCtorDecls.empty())
4758 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004759
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004760 // Write the known namespaces.
4761 if (!KnownNamespaces.empty())
4762 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
Nick Lewycky8334af82013-01-26 00:35:08 +00004763
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004764 // Write the undefined internal functions and variables, and inline functions.
4765 if (!UndefinedButUsed.empty())
4766 Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00004767
4768 if (!DeleteExprsToAnalyze.empty())
4769 Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
4770
Douglas Gregor851443c2011-08-12 01:39:19 +00004771 // Write the visible updates to DeclContexts.
Richard Smithcd45dbc2014-04-19 03:48:30 +00004772 for (auto *DC : UpdatedDeclContexts)
4773 WriteDeclContextVisibleUpdate(DC);
Douglas Gregor851443c2011-08-12 01:39:19 +00004774
Douglas Gregor959bb062011-12-03 01:15:29 +00004775 if (!WritingModule) {
4776 // Write the submodules that were imported, if any.
Aaron Ballman4f45b712014-03-21 15:22:56 +00004777 struct ModuleInfo {
4778 uint64_t ID;
4779 Module *M;
4780 ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
4781 };
Richard Smith56be7542014-03-21 00:33:59 +00004782 llvm::SmallVector<ModuleInfo, 64> Imports;
Aaron Ballmanbbc31212014-03-14 20:59:21 +00004783 for (const auto *I : Context.local_imports()) {
Douglas Gregor959bb062011-12-03 01:15:29 +00004784 assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
Aaron Ballman4f45b712014-03-21 15:22:56 +00004785 Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
4786 I->getImportedModule()));
Douglas Gregor959bb062011-12-03 01:15:29 +00004787 }
Richard Smith56be7542014-03-21 00:33:59 +00004788
4789 if (!Imports.empty()) {
4790 auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
4791 return A.ID < B.ID;
4792 };
Ben Langmuir5f95c8f2014-09-08 20:36:26 +00004793 auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
4794 return A.ID == B.ID;
4795 };
Richard Smith56be7542014-03-21 00:33:59 +00004796
4797 // Sort and deduplicate module IDs.
Fangrui Song55fab262018-09-26 22:16:28 +00004798 llvm::sort(Imports, Cmp);
Ben Langmuir5f95c8f2014-09-08 20:36:26 +00004799 Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
Richard Smith56be7542014-03-21 00:33:59 +00004800 Imports.end());
4801
4802 RecordData ImportedModules;
4803 for (const auto &Import : Imports) {
4804 ImportedModules.push_back(Import.ID);
4805 // FIXME: If the module has macros imported then later has declarations
4806 // imported, this location won't be the right one as a location for the
4807 // declaration imports.
Richard Smith10434f32015-05-02 02:08:26 +00004808 AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
Richard Smith56be7542014-03-21 00:33:59 +00004809 }
4810
Douglas Gregor959bb062011-12-03 01:15:29 +00004811 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
4812 }
Douglas Gregor0a839132011-12-03 00:59:55 +00004813 }
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004814
Douglas Gregor404cdde2012-01-27 01:47:08 +00004815 WriteObjCCategories();
Nico Weber779355f2016-03-02 23:22:00 +00004816 if(!WritingModule) {
Dario Domizioli13a0a382014-05-23 12:13:25 +00004817 WriteOptimizePragmaOptions(SemaRef);
Nico Weber779355f2016-03-02 23:22:00 +00004818 WriteMSStructPragmaOptions(SemaRef);
Nico Weber42932312016-03-03 00:17:35 +00004819 WriteMSPointersToMembersPragmaOptions(SemaRef);
Nico Weber779355f2016-03-02 23:22:00 +00004820 }
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00004821 WritePackPragmaOptions(SemaRef);
Richard Smithe40f2ba2013-08-07 21:41:30 +00004822
Douglas Gregor08f01292009-04-17 22:13:46 +00004823 // Some simple statistics
Mehdi Amini57a41912015-09-10 01:46:39 +00004824 RecordData::value_type Record[] = {
4825 NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts};
Sebastian Redl539c5062010-08-18 23:57:32 +00004826 Stream.EmitRecord(STATISTICS, Record);
Douglas Gregor8f45df52009-04-16 22:23:12 +00004827 Stream.ExitBlock();
Adrian Prantladbd2b12015-09-22 23:26:31 +00004828
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004829 // Write the module file extension blocks.
4830 for (const auto &ExtWriter : ModuleFileExtensionWriters)
Douglas Gregor8f64ca12015-12-08 22:43:32 +00004831 WriteModuleFileExtension(SemaRef, *ExtWriter);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004832
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004833 return writeUnhashedControlBlock(PP, Context);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004834}
4835
Richard Smithb9eab6d2014-03-20 19:44:17 +00004836void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00004837 if (DeclUpdates.empty())
4838 return;
4839
Richard Smith59442b42014-03-20 20:07:19 +00004840 DeclUpdateMap LocalUpdates;
4841 LocalUpdates.swap(DeclUpdates);
4842
Richard Smith6ef42932014-03-20 21:02:00 +00004843 for (auto &DeclUpdate : LocalUpdates) {
4844 const Decl *D = DeclUpdate.first;
Argyrios Kyrtzidis3ba70b82010-10-24 17:26:46 +00004845
Richard Smithd28ac5b2014-03-22 23:33:22 +00004846 bool HasUpdatedBody = false;
Richard Smith69c82bf2016-04-01 22:52:03 +00004847 RecordData RecordData;
4848 ASTRecordWriter Record(*this, RecordData);
Richard Smith6ef42932014-03-20 21:02:00 +00004849 for (auto &Update : DeclUpdate.second) {
4850 DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
4851
Richard Smith69c82bf2016-04-01 22:52:03 +00004852 // An updated body is emitted last, so that the reader doesn't need
4853 // to skip over the lazy body to reach statements for other records.
4854 if (Kind == UPD_CXX_ADDED_FUNCTION_DEFINITION)
4855 HasUpdatedBody = true;
4856 else
4857 Record.push_back(Kind);
4858
Richard Smith6ef42932014-03-20 21:02:00 +00004859 switch (Kind) {
4860 case UPD_CXX_ADDED_IMPLICIT_MEMBER:
4861 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4862 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
Richard Smithcd45dbc2014-04-19 03:48:30 +00004863 assert(Update.getDecl() && "no decl to add?");
Richard Smith6ef42932014-03-20 21:02:00 +00004864 Record.push_back(GetDeclRef(Update.getDecl()));
4865 break;
4866
Richard Smith4d235792014-08-07 18:53:08 +00004867 case UPD_CXX_ADDED_FUNCTION_DEFINITION:
Richard Smithd28ac5b2014-03-22 23:33:22 +00004868 break;
4869
Richard Smith891fc7f2017-12-05 01:31:47 +00004870 case UPD_CXX_POINT_OF_INSTANTIATION:
4871 // FIXME: Do we need to also save the template specialization kind here?
Richard Smith69c82bf2016-04-01 22:52:03 +00004872 Record.AddSourceLocation(Update.getLoc());
Richard Smith891fc7f2017-12-05 01:31:47 +00004873 break;
4874
4875 case UPD_CXX_ADDED_VAR_DEFINITION: {
4876 const VarDecl *VD = cast<VarDecl>(D);
Richard Smithf5017592017-11-02 01:06:00 +00004877 Record.push_back(VD->isInline());
4878 Record.push_back(VD->isInlineSpecified());
Richard Smith05a21352017-06-22 22:18:46 +00004879 if (VD->getInit()) {
4880 Record.push_back(!VD->isInitKnownICE() ? 1
4881 : (VD->isInitICE() ? 3 : 2));
4882 Record.AddStmt(const_cast<Expr*>(VD->getInit()));
4883 } else {
4884 Record.push_back(0);
4885 }
Richard Smith4d235792014-08-07 18:53:08 +00004886 break;
Richard Smith05a21352017-06-22 22:18:46 +00004887 }
Richard Smith4d235792014-08-07 18:53:08 +00004888
John McCall32791cc2016-01-06 22:34:54 +00004889 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT:
Richard Smith290d8012016-04-06 17:06:00 +00004890 Record.AddStmt(const_cast<Expr *>(
4891 cast<ParmVarDecl>(Update.getDecl())->getDefaultArg()));
John McCall32791cc2016-01-06 22:34:54 +00004892 break;
4893
Richard Smith4b054b22016-08-24 21:25:37 +00004894 case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER:
4895 Record.AddStmt(
4896 cast<FieldDecl>(Update.getDecl())->getInClassInitializer());
4897 break;
4898
Richard Smithcd45dbc2014-04-19 03:48:30 +00004899 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
4900 auto *RD = cast<CXXRecordDecl>(D);
Chandler Carruth8a3d24d2015-03-26 04:27:10 +00004901 UpdatedDeclContexts.insert(RD->getPrimaryContext());
Akira Hatanakafcbe17c2018-03-28 21:13:14 +00004902 Record.push_back(RD->isParamDestroyedInCallee());
Akira Hatanakae6313ac2018-04-09 22:48:22 +00004903 Record.push_back(RD->getArgPassingRestrictions());
Richard Smith69c82bf2016-04-01 22:52:03 +00004904 Record.AddCXXDefinitionData(RD);
Richard Smith72e50fe2016-04-14 00:50:18 +00004905 Record.AddOffset(WriteDeclContextLexicalBlock(
Richard Smithcd45dbc2014-04-19 03:48:30 +00004906 *Context, const_cast<CXXRecordDecl *>(RD)));
4907
4908 // This state is sometimes updated by template instantiation, when we
4909 // switch from the specialization referring to the template declaration
4910 // to it referring to the template definition.
4911 if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
4912 Record.push_back(MSInfo->getTemplateSpecializationKind());
Richard Smith69c82bf2016-04-01 22:52:03 +00004913 Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
Richard Smithcd45dbc2014-04-19 03:48:30 +00004914 } else {
4915 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
4916 Record.push_back(Spec->getTemplateSpecializationKind());
Richard Smith69c82bf2016-04-01 22:52:03 +00004917 Record.AddSourceLocation(Spec->getPointOfInstantiation());
Richard Smithdf352052014-05-22 20:59:29 +00004918
4919 // The instantiation might have been resolved to a partial
4920 // specialization. If so, record which one.
4921 auto From = Spec->getInstantiatedFrom();
4922 if (auto PartialSpec =
4923 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
4924 Record.push_back(true);
Richard Smith69c82bf2016-04-01 22:52:03 +00004925 Record.AddDeclRef(PartialSpec);
4926 Record.AddTemplateArgumentList(
4927 &Spec->getTemplateInstantiationArgs());
Richard Smithdf352052014-05-22 20:59:29 +00004928 } else {
4929 Record.push_back(false);
4930 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00004931 }
4932 Record.push_back(RD->getTagKind());
Richard Smith69c82bf2016-04-01 22:52:03 +00004933 Record.AddSourceLocation(RD->getLocation());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004934 Record.AddSourceLocation(RD->getBeginLoc());
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00004935 Record.AddSourceRange(RD->getBraceRange());
Richard Smithcd45dbc2014-04-19 03:48:30 +00004936
4937 // Instantiation may change attributes; write them all out afresh.
4938 Record.push_back(D->hasAttrs());
Richard Smith69c82bf2016-04-01 22:52:03 +00004939 if (D->hasAttrs())
4940 Record.AddAttributes(D->getAttrs());
Richard Smithcd45dbc2014-04-19 03:48:30 +00004941
4942 // FIXME: Ensure we don't get here for explicit instantiations.
4943 break;
4944 }
4945
Richard Smithf8134002015-03-10 01:41:22 +00004946 case UPD_CXX_RESOLVED_DTOR_DELETE:
Richard Smith69c82bf2016-04-01 22:52:03 +00004947 Record.AddDeclRef(Update.getDecl());
Richard Smith5b349582017-10-13 01:55:36 +00004948 Record.AddStmt(cast<CXXDestructorDecl>(D)->getOperatorDeleteThisArg());
Richard Smithf8134002015-03-10 01:41:22 +00004949 break;
4950
John McCalld505e572019-12-13 21:54:44 -05004951 case UPD_CXX_RESOLVED_EXCEPTION_SPEC: {
4952 auto prototype =
4953 cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>();
4954 Record.writeExceptionSpecInfo(prototype->getExceptionSpecInfo());
Richard Smith564417a2014-03-20 21:47:22 +00004955 break;
John McCalld505e572019-12-13 21:54:44 -05004956 }
Richard Smith564417a2014-03-20 21:47:22 +00004957
Richard Smith6ef42932014-03-20 21:02:00 +00004958 case UPD_CXX_DEDUCED_RETURN_TYPE:
4959 Record.push_back(GetOrCreateTypeID(Update.getType()));
4960 break;
4961
4962 case UPD_DECL_MARKED_USED:
4963 break;
Richard Smith5652c0f2014-03-21 01:48:23 +00004964
4965 case UPD_MANGLING_NUMBER:
4966 case UPD_STATIC_LOCAL_NUMBER:
4967 Record.push_back(Update.getNumber());
4968 break;
Richard Smith65ebb4a2015-03-26 04:09:53 +00004969
Alexey Bataev97720002014-11-11 04:05:39 +00004970 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
Richard Smith69c82bf2016-04-01 22:52:03 +00004971 Record.AddSourceRange(
4972 D->getAttr<OMPThreadPrivateDeclAttr>()->getRange());
Alexey Bataev97720002014-11-11 04:05:39 +00004973 break;
Richard Smith65ebb4a2015-03-26 04:09:53 +00004974
Alexey Bataev27ef9512019-03-20 20:14:22 +00004975 case UPD_DECL_MARKED_OPENMP_ALLOCATE: {
4976 auto *A = D->getAttr<OMPAllocateDeclAttr>();
4977 Record.push_back(A->getAllocatorType());
4978 Record.AddStmt(A->getAllocator());
4979 Record.AddSourceRange(A->getRange());
Alexey Bataev25ed0c02019-03-07 17:54:44 +00004980 break;
Alexey Bataev27ef9512019-03-20 20:14:22 +00004981 }
Alexey Bataev25ed0c02019-03-07 17:54:44 +00004982
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00004983 case UPD_DECL_MARKED_OPENMP_DECLARETARGET:
Alexey Bataevd01b7492018-08-15 19:45:12 +00004984 Record.push_back(D->getAttr<OMPDeclareTargetDeclAttr>()->getMapType());
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00004985 Record.AddSourceRange(
4986 D->getAttr<OMPDeclareTargetDeclAttr>()->getRange());
4987 break;
4988
Richard Smith65ebb4a2015-03-26 04:09:53 +00004989 case UPD_DECL_EXPORTED:
Richard Smith4caa4492015-05-15 02:34:32 +00004990 Record.push_back(getSubmoduleID(Update.getModule()));
Richard Smith65ebb4a2015-03-26 04:09:53 +00004991 break;
Alex Denisovfde64952015-06-26 05:28:36 +00004992
4993 case UPD_ADDED_ATTR_TO_RECORD:
Richard Smith69c82bf2016-04-01 22:52:03 +00004994 Record.AddAttributes(llvm::makeArrayRef(Update.getAttr()));
Alex Denisovfde64952015-06-26 05:28:36 +00004995 break;
Richard Smith6ef42932014-03-20 21:02:00 +00004996 }
4997 }
4998
Richard Smithd28ac5b2014-03-22 23:33:22 +00004999 if (HasUpdatedBody) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005000 const auto *Def = cast<FunctionDecl>(D);
Richard Smith4d235792014-08-07 18:53:08 +00005001 Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
Richard Smithd28ac5b2014-03-22 23:33:22 +00005002 Record.push_back(Def->isInlined());
Richard Smith69c82bf2016-04-01 22:52:03 +00005003 Record.AddSourceLocation(Def->getInnerLocStart());
Richard Smith290d8012016-04-06 17:06:00 +00005004 Record.AddFunctionDefinition(Def);
Richard Smithd28ac5b2014-03-22 23:33:22 +00005005 }
5006
Richard Smithcd45dbc2014-04-19 03:48:30 +00005007 OffsetsRecord.push_back(GetDeclRef(D));
Richard Smith69c82bf2016-04-01 22:52:03 +00005008 OffsetsRecord.push_back(Record.Emit(DECL_UPDATES));
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005009 }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005010}
5011
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005012void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
Richard Smithb22a1d12016-03-27 20:13:24 +00005013 uint32_t Raw = Loc.getRawEncoding();
5014 Record.push_back((Raw << 1) | (Raw >> 31));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005015}
5016
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005017void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
Chris Lattnerca025db2010-05-07 21:43:38 +00005018 AddSourceLocation(Range.getBegin(), Record);
5019 AddSourceLocation(Range.getEnd(), Record);
5020}
5021
Richard Smithf144b542016-04-08 21:54:32 +00005022void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) {
5023 AddAPInt(Value.bitcastToAPInt());
Douglas Gregore0a3a512009-04-14 21:55:33 +00005024}
5025
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00005026static void WriteFixedPointSemantics(ASTRecordWriter &Record,
5027 FixedPointSemantics FPSema) {
5028 Record.push_back(FPSema.getWidth());
5029 Record.push_back(FPSema.getScale());
5030 Record.push_back(FPSema.isSigned() | FPSema.isSaturated() << 1 |
5031 FPSema.hasUnsignedPadding() << 2);
5032}
5033
5034void ASTRecordWriter::AddAPValue(const APValue &Value) {
5035 APValue::ValueKind Kind = Value.getKind();
5036 push_back(static_cast<uint64_t>(Kind));
5037 switch (Kind) {
5038 case APValue::None:
5039 case APValue::Indeterminate:
5040 return;
5041 case APValue::Int:
5042 AddAPSInt(Value.getInt());
5043 return;
5044 case APValue::Float:
5045 push_back(static_cast<uint64_t>(
5046 llvm::APFloatBase::SemanticsToEnum(Value.getFloat().getSemantics())));
5047 AddAPFloat(Value.getFloat());
5048 return;
5049 case APValue::FixedPoint: {
5050 WriteFixedPointSemantics(*this, Value.getFixedPoint().getSemantics());
5051 AddAPSInt(Value.getFixedPoint().getValue());
5052 return;
5053 }
5054 case APValue::ComplexInt: {
5055 AddAPSInt(Value.getComplexIntReal());
5056 AddAPSInt(Value.getComplexIntImag());
5057 return;
5058 }
5059 case APValue::ComplexFloat: {
5060 push_back(static_cast<uint64_t>(llvm::APFloatBase::SemanticsToEnum(
5061 Value.getComplexFloatReal().getSemantics())));
5062 AddAPFloat(Value.getComplexFloatReal());
5063 push_back(static_cast<uint64_t>(llvm::APFloatBase::SemanticsToEnum(
5064 Value.getComplexFloatImag().getSemantics())));
5065 AddAPFloat(Value.getComplexFloatImag());
5066 return;
5067 }
5068 case APValue::LValue:
5069 case APValue::Vector:
5070 case APValue::Array:
5071 case APValue::Struct:
5072 case APValue::Union:
5073 case APValue::MemberPointer:
5074 case APValue::AddrLabelDiff:
5075 // TODO : Handle all these APValue::ValueKind.
5076 return;
5077 }
5078 llvm_unreachable("Invalid APValue::ValueKind");
5079}
5080
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005081void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
Douglas Gregor4621c6a2009-04-22 18:49:13 +00005082 Record.push_back(getIdentifierRef(II));
5083}
5084
Sebastian Redl539c5062010-08-18 23:57:32 +00005085IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
Craig Toppera13603a2014-05-22 05:54:18 +00005086 if (!II)
Douglas Gregor4621c6a2009-04-22 18:49:13 +00005087 return 0;
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00005088
Sebastian Redl539c5062010-08-18 23:57:32 +00005089 IdentID &ID = IdentifierIDs[II];
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00005090 if (ID == 0)
Sebastian Redlff4a2952010-07-23 23:49:55 +00005091 ID = NextIdentID++;
Douglas Gregor4621c6a2009-04-22 18:49:13 +00005092 return ID;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005093}
5094
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005095MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005096 // Don't emit builtin macros like __LINE__ to the AST file unless they
5097 // have been redefined by the header (in which case they are not
5098 // isBuiltinMacro).
Craig Toppera13603a2014-05-22 05:54:18 +00005099 if (!MI || MI->isBuiltinMacro())
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005100 return 0;
5101
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005102 MacroID &ID = MacroIDs[MI];
5103 if (ID == 0) {
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005104 ID = NextMacroID++;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005105 MacroInfoToEmitData Info = { Name, MI, ID };
5106 MacroInfosToEmit.push_back(Info);
5107 }
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005108 return ID;
5109}
5110
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005111MacroID ASTWriter::getMacroID(MacroInfo *MI) {
Craig Toppera13603a2014-05-22 05:54:18 +00005112 if (!MI || MI->isBuiltinMacro())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005113 return 0;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005114
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005115 assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
5116 return MacroIDs[MI];
5117}
5118
5119uint64_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
Richard Smithd7329392015-04-21 21:46:32 +00005120 return IdentMacroDirectivesOffsetMap.lookup(Name);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005121}
5122
Richard Smithe64e7452016-04-18 21:54:58 +00005123void ASTRecordWriter::AddSelectorRef(const Selector SelRef) {
5124 Record->push_back(Writer->getSelectorRef(SelRef));
Sebastian Redl834bb972010-08-04 17:20:04 +00005125}
5126
Sebastian Redl539c5062010-08-18 23:57:32 +00005127SelectorID ASTWriter::getSelectorRef(Selector Sel) {
Craig Toppera13603a2014-05-22 05:54:18 +00005128 if (Sel.getAsOpaquePtr() == nullptr) {
Sebastian Redl834bb972010-08-04 17:20:04 +00005129 return 0;
Steve Naroff2ddea052009-04-23 10:39:46 +00005130 }
5131
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005132 SelectorID SID = SelectorIDs[Sel];
Sebastian Redld95a56e2010-08-04 18:21:41 +00005133 if (SID == 0 && Chain) {
5134 // This might trigger a ReadSelector callback, which will set the ID for
5135 // this selector.
5136 Chain->LoadSelector(Sel);
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005137 SID = SelectorIDs[Sel];
Sebastian Redld95a56e2010-08-04 18:21:41 +00005138 }
Steve Naroff2ddea052009-04-23 10:39:46 +00005139 if (SID == 0) {
Sebastian Redld95a56e2010-08-04 18:21:41 +00005140 SID = NextSelectorID++;
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005141 SelectorIDs[Sel] = SID;
Steve Naroff2ddea052009-04-23 10:39:46 +00005142 }
Sebastian Redl834bb972010-08-04 17:20:04 +00005143 return SID;
Steve Naroff2ddea052009-04-23 10:39:46 +00005144}
5145
Richard Smithe64e7452016-04-18 21:54:58 +00005146void ASTRecordWriter::AddCXXTemporary(const CXXTemporary *Temp) {
5147 AddDeclRef(Temp->getDestructor());
Chris Lattnercba86142010-05-10 00:25:06 +00005148}
5149
Richard Smith290d8012016-04-06 17:06:00 +00005150void ASTRecordWriter::AddTemplateArgumentLocInfo(
5151 TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg) {
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00005152 switch (Kind) {
John McCall0ad16662009-10-29 08:12:44 +00005153 case TemplateArgument::Expression:
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00005154 AddStmt(Arg.getAsExpr());
John McCall0ad16662009-10-29 08:12:44 +00005155 break;
5156 case TemplateArgument::Type:
Richard Smith290d8012016-04-06 17:06:00 +00005157 AddTypeSourceInfo(Arg.getAsTypeSourceInfo());
John McCall0ad16662009-10-29 08:12:44 +00005158 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005159 case TemplateArgument::Template:
Richard Smith290d8012016-04-06 17:06:00 +00005160 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5161 AddSourceLocation(Arg.getTemplateNameLoc());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005162 break;
5163 case TemplateArgument::TemplateExpansion:
Richard Smith290d8012016-04-06 17:06:00 +00005164 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5165 AddSourceLocation(Arg.getTemplateNameLoc());
5166 AddSourceLocation(Arg.getTemplateEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005167 break;
John McCall0ad16662009-10-29 08:12:44 +00005168 case TemplateArgument::Null:
5169 case TemplateArgument::Integral:
5170 case TemplateArgument::Declaration:
Eli Friedmanb826a002012-09-26 02:36:12 +00005171 case TemplateArgument::NullPtr:
John McCall0ad16662009-10-29 08:12:44 +00005172 case TemplateArgument::Pack:
Eli Friedmanb826a002012-09-26 02:36:12 +00005173 // FIXME: Is this right?
John McCall0ad16662009-10-29 08:12:44 +00005174 break;
5175 }
5176}
5177
Richard Smith290d8012016-04-06 17:06:00 +00005178void ASTRecordWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg) {
5179 AddTemplateArgument(Arg.getArgument());
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00005180
5181 if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
5182 bool InfoHasSameExpr
5183 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
Richard Smith290d8012016-04-06 17:06:00 +00005184 Record->push_back(InfoHasSameExpr);
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00005185 if (InfoHasSameExpr)
5186 return; // Avoid storing the same expr twice.
5187 }
Richard Smith290d8012016-04-06 17:06:00 +00005188 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo());
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00005189}
5190
Richard Smith290d8012016-04-06 17:06:00 +00005191void ASTRecordWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo) {
Craig Toppera13603a2014-05-22 05:54:18 +00005192 if (!TInfo) {
Richard Smith290d8012016-04-06 17:06:00 +00005193 AddTypeRef(QualType());
John McCall8f115c62009-10-16 21:56:05 +00005194 return;
5195 }
5196
Richard Smithc23d7342018-06-29 20:46:25 +00005197 AddTypeRef(TInfo->getType());
Richard Smith290d8012016-04-06 17:06:00 +00005198 AddTypeLoc(TInfo->getTypeLoc());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005199}
5200
Richard Smith290d8012016-04-06 17:06:00 +00005201void ASTRecordWriter::AddTypeLoc(TypeLoc TL) {
Richard Smith290d8012016-04-06 17:06:00 +00005202 TypeLocWriter TLW(*this);
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005203 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00005204 TLW.Visit(TL);
John McCall8f115c62009-10-16 21:56:05 +00005205}
5206
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005207void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
Argyrios Kyrtzidis9ab44ea2010-08-20 16:04:14 +00005208 Record.push_back(GetOrCreateTypeID(T));
5209}
5210
Richard Smith2095ffe2015-03-16 20:11:03 +00005211TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
Richard Smith1fa5d642013-05-11 05:45:24 +00005212 assert(Context);
Richard Smith2095ffe2015-03-16 20:11:03 +00005213 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5214 if (T.isNull())
5215 return TypeIdx();
5216 assert(!T.getLocalFastQualifiers());
5217
5218 TypeIdx &Idx = TypeIdxs[T];
5219 if (Idx.getIndex() == 0) {
5220 if (DoneWritingDeclsAndTypes) {
5221 assert(0 && "New type seen after serializing all the types to emit!");
5222 return TypeIdx();
5223 }
5224
5225 // We haven't seen this type before. Assign it a new ID and put it
5226 // into the queue of types to emit.
5227 Idx = TypeIdx(NextTypeID++);
5228 DeclTypesToEmit.push(T);
5229 }
5230 return Idx;
5231 });
Argyrios Kyrtzidis082e4612010-08-20 16:04:20 +00005232}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005233
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00005234TypeID ASTWriter::getTypeID(QualType T) const {
Richard Smith1fa5d642013-05-11 05:45:24 +00005235 assert(Context);
Richard Smith2095ffe2015-03-16 20:11:03 +00005236 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5237 if (T.isNull())
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005238 return TypeIdx();
Richard Smith2095ffe2015-03-16 20:11:03 +00005239 assert(!T.getLocalFastQualifiers());
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005240
Richard Smith2095ffe2015-03-16 20:11:03 +00005241 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
5242 assert(I != TypeIdxs.end() && "Type not emitted!");
5243 return I->second;
5244 });
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005245}
5246
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005247void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005248 Record.push_back(GetDeclRef(D));
5249}
5250
Sebastian Redl539c5062010-08-18 23:57:32 +00005251DeclID ASTWriter::GetDeclRef(const Decl *D) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005252 assert(WritingAST && "Cannot request a declaration ID before AST writing");
Craig Toppera13603a2014-05-22 05:54:18 +00005253
5254 if (!D) {
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005255 return 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005256 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005257
Douglas Gregorb3163e52012-01-05 22:33:30 +00005258 // If D comes from an AST file, its declaration ID is already known and
5259 // fixed.
5260 if (D->isFromASTFile())
5261 return D->getGlobalID();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005262
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005263 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
Sebastian Redl539c5062010-08-18 23:57:32 +00005264 DeclID &ID = DeclIDs[D];
Mike Stump11289f42009-09-09 15:08:12 +00005265 if (ID == 0) {
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005266 if (DoneWritingDeclsAndTypes) {
5267 assert(0 && "New decl seen after serializing all the decls to emit!");
5268 return 0;
5269 }
5270
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005271 // We haven't seen this declaration before. Give it a new ID and
5272 // enqueue it in the list of declarations to emit.
Sebastian Redlff4a2952010-07-23 23:49:55 +00005273 ID = NextDeclID++;
Douglas Gregor12bfa382009-10-17 00:13:19 +00005274 DeclTypesToEmit.push(const_cast<Decl *>(D));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005275 }
5276
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005277 return ID;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005278}
5279
Sebastian Redl539c5062010-08-18 23:57:32 +00005280DeclID ASTWriter::getDeclID(const Decl *D) {
Craig Toppera13603a2014-05-22 05:54:18 +00005281 if (!D)
Douglas Gregore84a9da2009-04-20 20:36:09 +00005282 return 0;
5283
Douglas Gregorb3163e52012-01-05 22:33:30 +00005284 // If D comes from an AST file, its declaration ID is already known and
5285 // fixed.
5286 if (D->isFromASTFile())
5287 return D->getGlobalID();
5288
Douglas Gregore84a9da2009-04-20 20:36:09 +00005289 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
5290 return DeclIDs[D];
5291}
5292
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005293void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005294 assert(ID);
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005295 assert(D);
5296
5297 SourceLocation Loc = D->getLocation();
5298 if (Loc.isInvalid())
5299 return;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005300
5301 // We only keep track of the file-level declarations of each file.
5302 if (!D->getLexicalDeclContext()->isFileContext())
5303 return;
Argyrios Kyrtzidise1bc99e2012-02-24 19:45:46 +00005304 // FIXME: ParmVarDecls that are part of a function type of a parameter of
5305 // a function/objc method, should not have TU as lexical context.
Argyrios Kyrtzidis71b74eb2018-01-26 19:26:12 +00005306 // TemplateTemplateParmDecls that are part of an alias template, should not
5307 // have TU as lexical context.
5308 if (isa<ParmVarDecl>(D) || isa<TemplateTemplateParmDecl>(D))
Argyrios Kyrtzidisffe055a82012-02-24 01:12:38 +00005309 return;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005310
5311 SourceManager &SM = Context->getSourceManager();
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005312 SourceLocation FileLoc = SM.getFileLoc(Loc);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005313 assert(SM.isLocalSourceLocation(FileLoc));
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005314 FileID FID;
5315 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00005316 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005317 if (FID.isInvalid())
5318 return;
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00005319 assert(SM.getSLocEntry(FID).isFile());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005320
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00005321 DeclIDInFileInfo *&Info = FileDeclIDs[FID];
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005322 if (!Info)
5323 Info = new DeclIDInFileInfo();
5324
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005325 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005326 LocDeclIDsTy &Decls = Info->DeclIDs;
5327
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005328 if (Decls.empty() || Decls.back().first <= Offset) {
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005329 Decls.push_back(LocDecl);
5330 return;
5331 }
5332
Benjamin Kramer45025c02013-08-24 13:22:59 +00005333 LocDeclIDsTy::iterator I =
Fangrui Song7264a472019-07-03 08:13:17 +00005334 llvm::upper_bound(Decls, LocDecl, llvm::less_first());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005335
5336 Decls.insert(I, LocDecl);
5337}
5338
Richard Smithd08aeb62014-08-28 01:33:39 +00005339unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
5340 assert(needsAnonymousDeclarationNumber(D) &&
5341 "expected an anonymous declaration");
5342
5343 // Number the anonymous declarations within this context, if we've not
5344 // already done so.
5345 auto It = AnonymousDeclarationNumbers.find(D);
5346 if (It == AnonymousDeclarationNumbers.end()) {
Richard Smith2b560572015-02-07 03:11:11 +00005347 auto *DC = D->getLexicalDeclContext();
5348 numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
5349 AnonymousDeclarationNumbers[ND] = Number;
5350 });
Richard Smithd08aeb62014-08-28 01:33:39 +00005351
5352 It = AnonymousDeclarationNumbers.find(D);
5353 assert(It != AnonymousDeclarationNumbers.end() &&
5354 "declaration not found within its lexical context");
5355 }
5356
5357 return It->second;
5358}
5359
Richard Smith290d8012016-04-06 17:06:00 +00005360void ASTRecordWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
5361 DeclarationName Name) {
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005362 switch (Name.getNameKind()) {
5363 case DeclarationName::CXXConstructorName:
5364 case DeclarationName::CXXDestructorName:
5365 case DeclarationName::CXXConversionFunctionName:
Richard Smith290d8012016-04-06 17:06:00 +00005366 AddTypeSourceInfo(DNLoc.NamedType.TInfo);
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005367 break;
5368
5369 case DeclarationName::CXXOperatorName:
Richard Smith290d8012016-04-06 17:06:00 +00005370 AddSourceLocation(SourceLocation::getFromRawEncoding(
5371 DNLoc.CXXOperatorName.BeginOpNameLoc));
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005372 AddSourceLocation(
Richard Smith290d8012016-04-06 17:06:00 +00005373 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc));
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005374 break;
5375
5376 case DeclarationName::CXXLiteralOperatorName:
Richard Smith290d8012016-04-06 17:06:00 +00005377 AddSourceLocation(SourceLocation::getFromRawEncoding(
5378 DNLoc.CXXLiteralOperatorName.OpNameLoc));
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005379 break;
5380
5381 case DeclarationName::Identifier:
5382 case DeclarationName::ObjCZeroArgSelector:
5383 case DeclarationName::ObjCOneArgSelector:
5384 case DeclarationName::ObjCMultiArgSelector:
5385 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00005386 case DeclarationName::CXXDeductionGuideName:
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005387 break;
5388 }
5389}
5390
Richard Smith290d8012016-04-06 17:06:00 +00005391void ASTRecordWriter::AddDeclarationNameInfo(
5392 const DeclarationNameInfo &NameInfo) {
5393 AddDeclarationName(NameInfo.getName());
5394 AddSourceLocation(NameInfo.getLoc());
5395 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName());
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005396}
5397
Richard Smith290d8012016-04-06 17:06:00 +00005398void ASTRecordWriter::AddQualifierInfo(const QualifierInfo &Info) {
5399 AddNestedNameSpecifierLoc(Info.QualifierLoc);
5400 Record->push_back(Info.NumTemplParamLists);
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005401 for (unsigned i = 0, e = Info.NumTemplParamLists; i != e; ++i)
Richard Smith290d8012016-04-06 17:06:00 +00005402 AddTemplateParameterList(Info.TemplParamLists[i]);
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005403}
5404
Richard Smith290d8012016-04-06 17:06:00 +00005405void ASTRecordWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005406 // Nested name specifiers usually aren't too long. I think that 8 would
Chris Lattner57540c52011-04-15 05:22:18 +00005407 // typically accommodate the vast majority.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005408 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005409
5410 // Push each of the nested-name-specifiers's onto a stack for
5411 // serialization in reverse order.
5412 while (NNS) {
5413 NestedNames.push_back(NNS);
5414 NNS = NNS.getPrefix();
5415 }
5416
Richard Smith290d8012016-04-06 17:06:00 +00005417 Record->push_back(NestedNames.size());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005418 while(!NestedNames.empty()) {
5419 NNS = NestedNames.pop_back_val();
5420 NestedNameSpecifier::SpecifierKind Kind
5421 = NNS.getNestedNameSpecifier()->getKind();
Richard Smith290d8012016-04-06 17:06:00 +00005422 Record->push_back(Kind);
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005423 switch (Kind) {
5424 case NestedNameSpecifier::Identifier:
Richard Smith290d8012016-04-06 17:06:00 +00005425 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier());
5426 AddSourceRange(NNS.getLocalSourceRange());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005427 break;
5428
5429 case NestedNameSpecifier::Namespace:
Richard Smith290d8012016-04-06 17:06:00 +00005430 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace());
5431 AddSourceRange(NNS.getLocalSourceRange());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005432 break;
5433
5434 case NestedNameSpecifier::NamespaceAlias:
Richard Smith290d8012016-04-06 17:06:00 +00005435 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias());
5436 AddSourceRange(NNS.getLocalSourceRange());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005437 break;
5438
5439 case NestedNameSpecifier::TypeSpec:
5440 case NestedNameSpecifier::TypeSpecWithTemplate:
Richard Smith290d8012016-04-06 17:06:00 +00005441 Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
Richard Smithc23d7342018-06-29 20:46:25 +00005442 AddTypeRef(NNS.getTypeLoc().getType());
Richard Smith290d8012016-04-06 17:06:00 +00005443 AddTypeLoc(NNS.getTypeLoc());
5444 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005445 break;
5446
5447 case NestedNameSpecifier::Global:
Richard Smith290d8012016-04-06 17:06:00 +00005448 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005449 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00005450
5451 case NestedNameSpecifier::Super:
Richard Smith290d8012016-04-06 17:06:00 +00005452 AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl());
5453 AddSourceRange(NNS.getLocalSourceRange());
Nikola Smiljanic67860242014-09-26 00:28:20 +00005454 break;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005455 }
5456 }
5457}
5458
Richard Smithe64e7452016-04-18 21:54:58 +00005459void ASTRecordWriter::AddTemplateParameterList(
5460 const TemplateParameterList *TemplateParams) {
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005461 assert(TemplateParams && "No TemplateParams!");
Richard Smithe64e7452016-04-18 21:54:58 +00005462 AddSourceLocation(TemplateParams->getTemplateLoc());
5463 AddSourceLocation(TemplateParams->getLAngleLoc());
5464 AddSourceLocation(TemplateParams->getRAngleLoc());
Saar Raz0330fba2019-10-15 18:44:06 +00005465
Richard Smithe64e7452016-04-18 21:54:58 +00005466 Record->push_back(TemplateParams->size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005467 for (const auto &P : *TemplateParams)
Richard Smithe64e7452016-04-18 21:54:58 +00005468 AddDeclRef(P);
Saar Raz0330fba2019-10-15 18:44:06 +00005469 if (const Expr *RequiresClause = TemplateParams->getRequiresClause()) {
5470 Record->push_back(true);
5471 AddStmt(const_cast<Expr*>(RequiresClause));
5472 } else {
5473 Record->push_back(false);
5474 }
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005475}
5476
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005477/// Emit a template argument list.
Richard Smith290d8012016-04-06 17:06:00 +00005478void ASTRecordWriter::AddTemplateArgumentList(
5479 const TemplateArgumentList *TemplateArgs) {
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005480 assert(TemplateArgs && "No TemplateArgs!");
Richard Smith290d8012016-04-06 17:06:00 +00005481 Record->push_back(TemplateArgs->size());
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005482 for (int i = 0, e = TemplateArgs->size(); i != e; ++i)
Richard Smith290d8012016-04-06 17:06:00 +00005483 AddTemplateArgument(TemplateArgs->get(i));
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005484}
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005485
Richard Smith290d8012016-04-06 17:06:00 +00005486void ASTRecordWriter::AddASTTemplateArgumentListInfo(
5487 const ASTTemplateArgumentListInfo *ASTTemplArgList) {
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005488 assert(ASTTemplArgList && "No ASTTemplArgList!");
Richard Smith290d8012016-04-06 17:06:00 +00005489 AddSourceLocation(ASTTemplArgList->LAngleLoc);
5490 AddSourceLocation(ASTTemplArgList->RAngleLoc);
5491 Record->push_back(ASTTemplArgList->NumTemplateArgs);
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005492 const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005493 for (int i = 0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
Richard Smith290d8012016-04-06 17:06:00 +00005494 AddTemplateArgumentLoc(TemplArgs[i]);
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005495}
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005496
Richard Smithe64e7452016-04-18 21:54:58 +00005497void ASTRecordWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set) {
5498 Record->push_back(Set.size());
Argyrios Kyrtzidis0f05fb92012-11-28 03:56:16 +00005499 for (ASTUnresolvedSet::const_iterator
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005500 I = Set.begin(), E = Set.end(); I != E; ++I) {
Richard Smithe64e7452016-04-18 21:54:58 +00005501 AddDeclRef(I.getDecl());
5502 Record->push_back(I.getAccess());
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005503 }
5504}
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005505
Richard Smith290d8012016-04-06 17:06:00 +00005506// FIXME: Move this out of the main ASTRecordWriter interface.
5507void ASTRecordWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
5508 Record->push_back(Base.isVirtual());
5509 Record->push_back(Base.isBaseOfClass());
5510 Record->push_back(Base.getAccessSpecifierAsWritten());
5511 Record->push_back(Base.getInheritConstructors());
5512 AddTypeSourceInfo(Base.getTypeSourceInfo());
5513 AddSourceRange(Base.getSourceRange());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005514 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
Richard Smith290d8012016-04-06 17:06:00 +00005515 : SourceLocation());
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005516}
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00005517
Richard Smith645d2cf2016-04-14 00:29:55 +00005518static uint64_t EmitCXXBaseSpecifiers(ASTWriter &W,
5519 ArrayRef<CXXBaseSpecifier> Bases) {
5520 ASTWriter::RecordData Record;
5521 ASTRecordWriter Writer(W, Record);
5522 Writer.push_back(Bases.size());
Dmitry Polukhin790b5402016-04-06 10:01:46 +00005523
Richard Smith645d2cf2016-04-14 00:29:55 +00005524 for (auto &Base : Bases)
5525 Writer.AddCXXBaseSpecifier(Base);
Richard Smith290d8012016-04-06 17:06:00 +00005526
Richard Smith645d2cf2016-04-14 00:29:55 +00005527 return Writer.Emit(serialization::DECL_CXX_BASE_SPECIFIERS);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005528}
5529
Richard Smith290d8012016-04-06 17:06:00 +00005530// FIXME: Move this out of the main ASTRecordWriter interface.
Richard Smith645d2cf2016-04-14 00:29:55 +00005531void ASTRecordWriter::AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases) {
5532 AddOffset(EmitCXXBaseSpecifiers(*Writer, Bases));
5533}
5534
Richard Smithaa165cf2016-04-13 21:57:08 +00005535static uint64_t
5536EmitCXXCtorInitializers(ASTWriter &W,
5537 ArrayRef<CXXCtorInitializer *> CtorInits) {
5538 ASTWriter::RecordData Record;
5539 ASTRecordWriter Writer(W, Record);
5540 Writer.push_back(CtorInits.size());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005541
Richard Smithaa165cf2016-04-13 21:57:08 +00005542 for (auto *Init : CtorInits) {
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005543 if (Init->isBaseInitializer()) {
Richard Smithaa165cf2016-04-13 21:57:08 +00005544 Writer.push_back(CTOR_INITIALIZER_BASE);
5545 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
5546 Writer.push_back(Init->isBaseVirtual());
Alexis Hunt37a477f2011-05-04 01:19:08 +00005547 } else if (Init->isDelegatingInitializer()) {
Richard Smithaa165cf2016-04-13 21:57:08 +00005548 Writer.push_back(CTOR_INITIALIZER_DELEGATING);
5549 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
Alexis Hunt37a477f2011-05-04 01:19:08 +00005550 } else if (Init->isMemberInitializer()){
Richard Smithaa165cf2016-04-13 21:57:08 +00005551 Writer.push_back(CTOR_INITIALIZER_MEMBER);
5552 Writer.AddDeclRef(Init->getMember());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005553 } else {
Richard Smithaa165cf2016-04-13 21:57:08 +00005554 Writer.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
5555 Writer.AddDeclRef(Init->getIndirectMember());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005556 }
Francois Pichetd583da02010-12-04 09:14:42 +00005557
Richard Smithaa165cf2016-04-13 21:57:08 +00005558 Writer.AddSourceLocation(Init->getMemberLocation());
5559 Writer.AddStmt(Init->getInit());
5560 Writer.AddSourceLocation(Init->getLParenLoc());
5561 Writer.AddSourceLocation(Init->getRParenLoc());
5562 Writer.push_back(Init->isWritten());
Richard Smith30e304e2016-12-14 00:03:17 +00005563 if (Init->isWritten())
Richard Smithaa165cf2016-04-13 21:57:08 +00005564 Writer.push_back(Init->getSourceOrder());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005565 }
Richard Smithaa165cf2016-04-13 21:57:08 +00005566
5567 return Writer.Emit(serialization::DECL_CXX_CTOR_INITIALIZERS);
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005568}
5569
Richard Smithaa165cf2016-04-13 21:57:08 +00005570// FIXME: Move this out of the main ASTRecordWriter interface.
5571void ASTRecordWriter::AddCXXCtorInitializers(
5572 ArrayRef<CXXCtorInitializer *> CtorInits) {
5573 AddOffset(EmitCXXCtorInitializers(*Writer, CtorInits));
Richard Smithc2bb8182015-03-24 06:36:48 +00005574}
5575
Richard Smith290d8012016-04-06 17:06:00 +00005576void ASTRecordWriter::AddCXXDefinitionData(const CXXRecordDecl *D) {
Richard Smith053f6c62014-05-16 23:01:30 +00005577 auto &Data = D->data();
Richard Smith290d8012016-04-06 17:06:00 +00005578 Record->push_back(Data.IsLambda);
Richard Smith91aeacc2019-10-11 00:29:04 +00005579
5580 #define FIELD(Name, Width, Merge) \
5581 Record->push_back(Data.Name);
5582 #include "clang/AST/CXXRecordDeclDefinitionBits.def"
Richard Trieufd1acbb2017-04-11 21:31:00 +00005583
5584 // getODRHash will compute the ODRHash if it has not been previously computed.
5585 Record->push_back(D->getODRHash());
Luboš Luňákcbc9d222019-11-03 21:15:03 +01005586 bool ModulesDebugInfo =
5587 Writer->Context->getLangOpts().ModulesDebugInfo && !D->isDependentType();
David Blaikief63556d2017-04-12 20:58:33 +00005588 Record->push_back(ModulesDebugInfo);
5589 if (ModulesDebugInfo)
David Blaikie1ac9c982017-04-11 21:13:37 +00005590 Writer->ModularCodegenDecls.push_back(Writer->GetDeclRef(D));
5591
Richard Smith561fb152012-02-25 07:33:38 +00005592 // IsLambda bit is already saved.
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005593
Richard Smith290d8012016-04-06 17:06:00 +00005594 Record->push_back(Data.NumBases);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005595 if (Data.NumBases > 0)
Richard Smith645d2cf2016-04-14 00:29:55 +00005596 AddCXXBaseSpecifiers(Data.bases());
5597
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005598 // FIXME: Make VBases lazily computed when needed to avoid storing them.
Richard Smith290d8012016-04-06 17:06:00 +00005599 Record->push_back(Data.NumVBases);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005600 if (Data.NumVBases > 0)
Richard Smith645d2cf2016-04-14 00:29:55 +00005601 AddCXXBaseSpecifiers(Data.vbases());
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005602
Richard Smith290d8012016-04-06 17:06:00 +00005603 AddUnresolvedSet(Data.Conversions.get(*Writer->Context));
Richard Smith91aeacc2019-10-11 00:29:04 +00005604 Record->push_back(Data.ComputedVisibleConversions);
5605 if (Data.ComputedVisibleConversions)
5606 AddUnresolvedSet(Data.VisibleConversions.get(*Writer->Context));
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005607 // Data.Definition is the owning decl, no need to write it.
Richard Smith290d8012016-04-06 17:06:00 +00005608 AddDeclRef(D->getFirstFriend());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005609
Douglas Gregor99ae8062012-02-14 17:54:36 +00005610 // Add lambda-specific data.
5611 if (Data.IsLambda) {
Richard Smith053f6c62014-05-16 23:01:30 +00005612 auto &Lambda = D->getLambdaData();
Richard Smith290d8012016-04-06 17:06:00 +00005613 Record->push_back(Lambda.Dependent);
5614 Record->push_back(Lambda.IsGenericLambda);
5615 Record->push_back(Lambda.CaptureDefault);
5616 Record->push_back(Lambda.NumCaptures);
5617 Record->push_back(Lambda.NumExplicitCaptures);
Michael Liao243ebfb2019-10-19 00:15:19 +00005618 Record->push_back(Lambda.HasKnownInternalLinkage);
Richard Smith290d8012016-04-06 17:06:00 +00005619 Record->push_back(Lambda.ManglingNumber);
Richard Smith0bae6242016-08-25 00:34:00 +00005620 AddDeclRef(D->getLambdaContextDecl());
Richard Smith290d8012016-04-06 17:06:00 +00005621 AddTypeSourceInfo(Lambda.MethodTyInfo);
Douglas Gregor99ae8062012-02-14 17:54:36 +00005622 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00005623 const LambdaCapture &Capture = Lambda.Captures[I];
Richard Smith290d8012016-04-06 17:06:00 +00005624 AddSourceLocation(Capture.getLocation());
5625 Record->push_back(Capture.isImplicit());
5626 Record->push_back(Capture.getCaptureKind());
Richard Smithba71c082013-05-16 06:20:58 +00005627 switch (Capture.getCaptureKind()) {
Faisal Validc6b5962016-03-21 09:25:37 +00005628 case LCK_StarThis:
Richard Smithba71c082013-05-16 06:20:58 +00005629 case LCK_This:
Alexey Bataev39c81e22014-08-28 04:28:19 +00005630 case LCK_VLAType:
Richard Smithba71c082013-05-16 06:20:58 +00005631 break;
5632 case LCK_ByCopy:
Richard Smithbb13c9a2013-09-28 04:02:39 +00005633 case LCK_ByRef:
Richard Smithba71c082013-05-16 06:20:58 +00005634 VarDecl *Var =
Craig Toppera13603a2014-05-22 05:54:18 +00005635 Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
Richard Smith290d8012016-04-06 17:06:00 +00005636 AddDeclRef(Var);
Richard Smithba71c082013-05-16 06:20:58 +00005637 AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
Richard Smith290d8012016-04-06 17:06:00 +00005638 : SourceLocation());
Richard Smithba71c082013-05-16 06:20:58 +00005639 break;
5640 }
Douglas Gregor99ae8062012-02-14 17:54:36 +00005641 }
5642 }
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005643}
5644
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005645void ASTWriter::ReaderInitialized(ASTReader *Reader) {
Sebastian Redl07a89a82010-07-30 00:29:29 +00005646 assert(Reader && "Cannot remove chain");
Douglas Gregordf0c1512011-08-18 04:12:04 +00005647 assert((!Chain || Chain == Reader) && "Cannot replace chain");
Sebastian Redl07a89a82010-07-30 00:29:29 +00005648 assert(FirstDeclID == NextDeclID &&
5649 FirstTypeID == NextTypeID &&
5650 FirstIdentID == NextIdentID &&
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005651 FirstMacroID == NextMacroID &&
Douglas Gregor253eefe2011-12-01 00:59:36 +00005652 FirstSubmoduleID == NextSubmoduleID &&
Sebastian Redld95a56e2010-08-04 18:21:41 +00005653 FirstSelectorID == NextSelectorID &&
Sebastian Redl07a89a82010-07-30 00:29:29 +00005654 "Setting chain after writing has started.");
Douglas Gregor925296b2011-07-19 16:10:42 +00005655
Sebastian Redl07a89a82010-07-30 00:29:29 +00005656 Chain = Reader;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005657
Richard Smith7f330cd2015-03-18 01:42:29 +00005658 // Note, this will get called multiple times, once one the reader starts up
5659 // and again each time it's done reading a PCH or module.
Douglas Gregordf0c1512011-08-18 04:12:04 +00005660 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
5661 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
5662 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005663 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
Douglas Gregor253eefe2011-12-01 00:59:36 +00005664 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
Douglas Gregordf0c1512011-08-18 04:12:04 +00005665 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005666 NextDeclID = FirstDeclID;
5667 NextTypeID = FirstTypeID;
5668 NextIdentID = FirstIdentID;
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005669 NextMacroID = FirstMacroID;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005670 NextSelectorID = FirstSelectorID;
Douglas Gregor253eefe2011-12-01 00:59:36 +00005671 NextSubmoduleID = FirstSubmoduleID;
Sebastian Redl07a89a82010-07-30 00:29:29 +00005672}
5673
Sebastian Redl539c5062010-08-18 23:57:32 +00005674void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005675 // Always keep the highest ID. See \p TypeRead() for more information.
5676 IdentID &StoredID = IdentifierIDs[II];
5677 if (ID > StoredID)
5678 StoredID = ID;
Sebastian Redlff4a2952010-07-23 23:49:55 +00005679}
5680
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005681void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005682 // Always keep the highest ID. See \p TypeRead() for more information.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005683 MacroID &StoredID = MacroIDs[MI];
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005684 if (ID > StoredID)
5685 StoredID = ID;
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005686}
5687
Argyrios Kyrtzidisbb5c7eae2010-08-20 16:03:59 +00005688void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005689 // Always take the highest-numbered type index. This copes with an interesting
5690 // case for chained AST writing where we schedule writing the type and then,
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005691 // later, deserialize the type from another AST. In this case, we want to
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005692 // keep the higher-numbered entry so that we can properly write it out to
5693 // the AST file.
5694 TypeIdx &StoredIdx = TypeIdxs[T];
5695 if (Idx.getIndex() >= StoredIdx.getIndex())
5696 StoredIdx = Idx;
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00005697}
5698
Sebastian Redl539c5062010-08-18 23:57:32 +00005699void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005700 // Always keep the highest ID. See \p TypeRead() for more information.
5701 SelectorID &StoredID = SelectorIDs[S];
5702 if (ID > StoredID)
5703 StoredID = ID;
Sebastian Redl834bb972010-08-04 17:20:04 +00005704}
Douglas Gregor91096292010-10-02 19:29:26 +00005705
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00005706void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
Richard Smith66a81862015-05-04 02:25:31 +00005707 MacroDefinitionRecord *MD) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00005708 assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
Douglas Gregor91096292010-10-02 19:29:26 +00005709 MacroDefinitions[MD] = ID;
5710}
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005711
Douglas Gregore37a85a2011-12-02 17:30:13 +00005712void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
5713 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
5714 SubmoduleIDs[Mod] = ID;
5715}
5716
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005717void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005718 if (Chain && Chain->isProcessingUpdateRecords()) return;
John McCallf937c022011-10-07 06:10:15 +00005719 assert(D->isCompleteDefinition());
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005720 assert(!WritingAST && "Already writing the AST!");
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005721 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005722 // We are interested when a PCH decl is modified.
Douglas Gregorb3722e22011-09-09 23:01:35 +00005723 if (RD->isFromASTFile()) {
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005724 // A forward reference was mutated into a definition. Rewrite it.
5725 // FIXME: This happens during template instantiation, should we
5726 // have created a new definition decl instead ?
Richard Smithcd45dbc2014-04-19 03:48:30 +00005727 assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
5728 "completed a tag from another module but not by instantiation?");
5729 DeclUpdates[RD].push_back(
5730 DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION));
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005731 }
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005732 }
5733}
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005734
Richard Smithf983f7f2015-10-13 00:23:25 +00005735static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) {
5736 if (D->isFromASTFile())
5737 return true;
5738
Richard Smithf983f7f2015-10-13 00:23:25 +00005739 // The predefined __va_list_tag struct is imported if we imported any decls.
5740 // FIXME: This is a gross hack.
5741 return D == D->getASTContext().getVaListTagDecl();
5742}
5743
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005744void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005745 if (Chain && Chain->isProcessingUpdateRecords()) return;
5746 assert(DC->isLookupContext() &&
Vassil Vassilev71eafde2016-04-06 20:56:03 +00005747 "Should not add lookup results to non-lookup contexts!");
5748
Vassil Vassilev632eac32016-03-16 11:17:04 +00005749 // TU is handled elsewhere.
5750 if (isa<TranslationUnitDecl>(DC))
5751 return;
5752
5753 // Namespaces are handled elsewhere, except for template instantiations of
5754 // FunctionTemplateDecls in namespaces. We are interested in cases where the
5755 // local instantiations are added to an imported context. Only happens when
5756 // adding ADL lookup candidates, for example templated friends.
5757 if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None &&
5758 !isa<FunctionTemplateDecl>(D))
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005759 return;
5760
Richard Smithf983f7f2015-10-13 00:23:25 +00005761 // We're only interested in cases where a local declaration is added to an
5762 // imported context.
5763 if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC)))
5764 return;
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005765
Richard Smith0f4e2c42015-08-06 04:23:48 +00005766 assert(DC == DC->getPrimaryContext() && "added to non-primary context");
Douglas Gregor9f782892013-01-21 15:25:38 +00005767 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
Richard Smithe9a8bc32014-09-30 00:45:29 +00005768 assert(!WritingAST && "Already writing the AST!");
Richard Smithf983f7f2015-10-13 00:23:25 +00005769 if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) {
5770 // We're adding a visible declaration to a predefined decl context. Ensure
5771 // that we write out all of its lookup results so we don't get a nasty
5772 // surprise when we try to emit its lookup table.
5773 for (auto *Child : DC->decls())
Richard Smithc26d9742016-10-06 20:30:51 +00005774 DeclsToEmitEvenIfUnreferenced.push_back(Child);
Richard Smithf983f7f2015-10-13 00:23:25 +00005775 }
Richard Smithc26d9742016-10-06 20:30:51 +00005776 DeclsToEmitEvenIfUnreferenced.push_back(D);
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005777}
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005778
5779void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005780 if (Chain && Chain->isProcessingUpdateRecords()) return;
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005781 assert(D->isImplicit());
Richard Smithf983f7f2015-10-13 00:23:25 +00005782
5783 // We're only interested in cases where a local declaration is added to an
5784 // imported context.
5785 if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD))
5786 return;
5787
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005788 if (!isa<CXXMethodDecl>(D))
Richard Smithf983f7f2015-10-13 00:23:25 +00005789 return;
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005790
5791 // A decl coming from PCH was modified.
John McCallf937c022011-10-07 06:10:15 +00005792 assert(RD->isCompleteDefinition());
Richard Smithe9a8bc32014-09-30 00:45:29 +00005793 assert(!WritingAST && "Already writing the AST!");
Aaron Ballman4f45b712014-03-21 15:22:56 +00005794 DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005795}
Argyrios Kyrtzidis402dbbb2010-10-28 07:38:42 +00005796
Richard Smith564417a2014-03-20 21:47:22 +00005797void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005798 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smith9e2341d2015-03-23 03:25:59 +00005799 assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
5800 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00005801 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005802 // If we don't already know the exception specification for this redecl
5803 // chain, add an update record for it.
5804 if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
5805 ->getType()
5806 ->castAs<FunctionProtoType>()
5807 ->getExceptionSpecType()))
5808 DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
5809 });
Richard Smith564417a2014-03-20 21:47:22 +00005810}
5811
Richard Smith1fa5d642013-05-11 05:45:24 +00005812void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005813 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smith1fa5d642013-05-11 05:45:24 +00005814 assert(!WritingAST && "Already writing the AST!");
Richard Smith9e2341d2015-03-23 03:25:59 +00005815 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00005816 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005817 DeclUpdates[D].push_back(
5818 DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
5819 });
Richard Smith1fa5d642013-05-11 05:45:24 +00005820}
5821
Richard Smithf8134002015-03-10 01:41:22 +00005822void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
Richard Smith5b349582017-10-13 01:55:36 +00005823 const FunctionDecl *Delete,
5824 Expr *ThisArg) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005825 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smithf8134002015-03-10 01:41:22 +00005826 assert(!WritingAST && "Already writing the AST!");
5827 assert(Delete && "Not given an operator delete");
Richard Smith9e2341d2015-03-23 03:25:59 +00005828 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00005829 Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005830 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete));
5831 });
Richard Smithf8134002015-03-10 01:41:22 +00005832}
5833
Sebastian Redlab238a72011-04-24 16:28:06 +00005834void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005835 if (Chain && Chain->isProcessingUpdateRecords()) return;
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005836 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005837 if (!D->isFromASTFile())
Sebastian Redlab238a72011-04-24 16:28:06 +00005838 return; // Declaration not imported from PCH.
5839
Richard Smith4d235792014-08-07 18:53:08 +00005840 // Implicit function decl from a PCH was defined.
5841 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
Sebastian Redlab238a72011-04-24 16:28:06 +00005842}
5843
Richard Smith891fc7f2017-12-05 01:31:47 +00005844void ASTWriter::VariableDefinitionInstantiated(const VarDecl *D) {
5845 if (Chain && Chain->isProcessingUpdateRecords()) return;
5846 assert(!WritingAST && "Already writing the AST!");
5847 if (!D->isFromASTFile())
5848 return;
5849
5850 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_VAR_DEFINITION));
5851}
5852
Richard Smithd28ac5b2014-03-22 23:33:22 +00005853void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005854 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smithd28ac5b2014-03-22 23:33:22 +00005855 assert(!WritingAST && "Already writing the AST!");
5856 if (!D->isFromASTFile())
5857 return;
5858
Richard Smith9e2341d2015-03-23 03:25:59 +00005859 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
Richard Smithd28ac5b2014-03-22 23:33:22 +00005860}
5861
Richard Smith891fc7f2017-12-05 01:31:47 +00005862void ASTWriter::InstantiationRequested(const ValueDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005863 if (Chain && Chain->isProcessingUpdateRecords()) return;
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005864 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005865 if (!D->isFromASTFile())
Sebastian Redl2ac2c722011-04-29 08:19:30 +00005866 return;
5867
5868 // Since the actual instantiation is delayed, this really means that we need
5869 // to update the instantiation location.
Richard Smith891fc7f2017-12-05 01:31:47 +00005870 SourceLocation POI;
5871 if (auto *VD = dyn_cast<VarDecl>(D))
5872 POI = VD->getPointOfInstantiation();
5873 else
5874 POI = cast<FunctionDecl>(D)->getPointOfInstantiation();
5875 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_POINT_OF_INSTANTIATION, POI));
Sebastian Redl2ac2c722011-04-29 08:19:30 +00005876}
5877
John McCall32791cc2016-01-06 22:34:54 +00005878void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005879 if (Chain && Chain->isProcessingUpdateRecords()) return;
John McCall32791cc2016-01-06 22:34:54 +00005880 assert(!WritingAST && "Already writing the AST!");
5881 if (!D->isFromASTFile())
5882 return;
5883
5884 DeclUpdates[D].push_back(
5885 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D));
5886}
5887
Richard Smith4b054b22016-08-24 21:25:37 +00005888void ASTWriter::DefaultMemberInitializerInstantiated(const FieldDecl *D) {
5889 assert(!WritingAST && "Already writing the AST!");
5890 if (!D->isFromASTFile())
5891 return;
5892
5893 DeclUpdates[D].push_back(
5894 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER, D));
5895}
5896
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00005897void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
5898 const ObjCInterfaceDecl *IFD) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005899 if (Chain && Chain->isProcessingUpdateRecords()) return;
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005900 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005901 if (!IFD->isFromASTFile())
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00005902 return; // Declaration not imported from PCH.
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005903
Douglas Gregor404cdde2012-01-27 01:47:08 +00005904 assert(IFD->getDefinition() && "Category on a class without a definition?");
5905 ObjCClassesWithCategories.insert(
5906 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00005907}
Argyrios Kyrtzidisb97a4022011-11-12 21:07:46 +00005908
Eli Friedman276dd182013-09-05 00:02:25 +00005909void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005910 if (Chain && Chain->isProcessingUpdateRecords()) return;
Eli Friedman276dd182013-09-05 00:02:25 +00005911 assert(!WritingAST && "Already writing the AST!");
Vassil Vassilev928c8252016-04-28 14:13:28 +00005912
5913 // If there is *any* declaration of the entity that's not from an AST file,
5914 // we can skip writing the update record. We make sure that isUsed() triggers
5915 // completion of the redeclaration chain of the entity.
5916 for (auto Prev = D->getMostRecentDecl(); Prev; Prev = Prev->getPreviousDecl())
5917 if (IsLocalDecl(Prev))
5918 return;
Eli Friedman276dd182013-09-05 00:02:25 +00005919
Aaron Ballman4f45b712014-03-21 15:22:56 +00005920 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
Eli Friedman276dd182013-09-05 00:02:25 +00005921}
Alexey Bataev97720002014-11-11 04:05:39 +00005922
5923void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005924 if (Chain && Chain->isProcessingUpdateRecords()) return;
Alexey Bataev97720002014-11-11 04:05:39 +00005925 assert(!WritingAST && "Already writing the AST!");
5926 if (!D->isFromASTFile())
5927 return;
5928
5929 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE));
5930}
Richard Smith65ebb4a2015-03-26 04:09:53 +00005931
Alexey Bataev25ed0c02019-03-07 17:54:44 +00005932void ASTWriter::DeclarationMarkedOpenMPAllocate(const Decl *D, const Attr *A) {
5933 if (Chain && Chain->isProcessingUpdateRecords()) return;
5934 assert(!WritingAST && "Already writing the AST!");
5935 if (!D->isFromASTFile())
5936 return;
5937
5938 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_ALLOCATE, A));
5939}
5940
Dmitry Polukhind69b5052016-05-09 14:59:13 +00005941void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
5942 const Attr *Attr) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005943 if (Chain && Chain->isProcessingUpdateRecords()) return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00005944 assert(!WritingAST && "Already writing the AST!");
5945 if (!D->isFromASTFile())
5946 return;
5947
Dmitry Polukhind69b5052016-05-09 14:59:13 +00005948 DeclUpdates[D].push_back(
5949 DeclUpdate(UPD_DECL_MARKED_OPENMP_DECLARETARGET, Attr));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00005950}
5951
Richard Smith4caa4492015-05-15 02:34:32 +00005952void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005953 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smith65ebb4a2015-03-26 04:09:53 +00005954 assert(!WritingAST && "Already writing the AST!");
5955 assert(D->isHidden() && "expected a hidden declaration");
Richard Smith4caa4492015-05-15 02:34:32 +00005956 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M));
Richard Smith65ebb4a2015-03-26 04:09:53 +00005957}
Alex Denisovfde64952015-06-26 05:28:36 +00005958
5959void ASTWriter::AddedAttributeToRecord(const Attr *Attr,
5960 const RecordDecl *Record) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005961 if (Chain && Chain->isProcessingUpdateRecords()) return;
Alex Denisovfde64952015-06-26 05:28:36 +00005962 assert(!WritingAST && "Already writing the AST!");
5963 if (!Record->isFromASTFile())
5964 return;
5965 DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr));
5966}
Richard Smithc26d9742016-10-06 20:30:51 +00005967
5968void ASTWriter::AddedCXXTemplateSpecialization(
5969 const ClassTemplateDecl *TD, const ClassTemplateSpecializationDecl *D) {
5970 assert(!WritingAST && "Already writing the AST!");
5971
5972 if (!TD->getFirstDecl()->isFromASTFile())
5973 return;
5974 if (Chain && Chain->isProcessingUpdateRecords())
5975 return;
5976
5977 DeclsToEmitEvenIfUnreferenced.push_back(D);
5978}
5979
5980void ASTWriter::AddedCXXTemplateSpecialization(
5981 const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) {
5982 assert(!WritingAST && "Already writing the AST!");
5983
5984 if (!TD->getFirstDecl()->isFromASTFile())
5985 return;
5986 if (Chain && Chain->isProcessingUpdateRecords())
5987 return;
5988
5989 DeclsToEmitEvenIfUnreferenced.push_back(D);
5990}
5991
5992void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
5993 const FunctionDecl *D) {
5994 assert(!WritingAST && "Already writing the AST!");
5995
5996 if (!TD->getFirstDecl()->isFromASTFile())
5997 return;
5998 if (Chain && Chain->isProcessingUpdateRecords())
5999 return;
6000
6001 DeclsToEmitEvenIfUnreferenced.push_back(D);
6002}
Kelvin Libe286f52018-09-15 13:54:15 +00006003
6004//===----------------------------------------------------------------------===//
6005//// OMPClause Serialization
6006////===----------------------------------------------------------------------===//
6007
John McCall2ac702a2019-12-14 03:17:03 -05006008namespace {
6009
6010class OMPClauseWriter : public OMPClauseVisitor<OMPClauseWriter> {
6011 ASTRecordWriter &Record;
6012
6013public:
6014 OMPClauseWriter(ASTRecordWriter &Record) : Record(Record) {}
6015#define OPENMP_CLAUSE(Name, Class) void Visit##Class(Class *S);
6016#include "clang/Basic/OpenMPKinds.def"
6017 void writeClause(OMPClause *C);
6018 void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C);
6019 void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C);
6020};
6021
6022}
6023
6024void ASTRecordWriter::writeOMPClause(OMPClause *C) {
6025 OMPClauseWriter(*this).writeClause(C);
6026}
6027
Kelvin Libe286f52018-09-15 13:54:15 +00006028void OMPClauseWriter::writeClause(OMPClause *C) {
6029 Record.push_back(C->getClauseKind());
6030 Visit(C);
6031 Record.AddSourceLocation(C->getBeginLoc());
6032 Record.AddSourceLocation(C->getEndLoc());
6033}
6034
6035void OMPClauseWriter::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
Johannes Doerferteb3e81f2019-11-04 22:00:49 -06006036 Record.push_back(uint64_t(C->getCaptureRegion()));
Kelvin Libe286f52018-09-15 13:54:15 +00006037 Record.AddStmt(C->getPreInitStmt());
6038}
6039
6040void OMPClauseWriter::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
6041 VisitOMPClauseWithPreInit(C);
6042 Record.AddStmt(C->getPostUpdateExpr());
6043}
6044
6045void OMPClauseWriter::VisitOMPIfClause(OMPIfClause *C) {
6046 VisitOMPClauseWithPreInit(C);
Johannes Doerferteb3e81f2019-11-04 22:00:49 -06006047 Record.push_back(uint64_t(C->getNameModifier()));
Kelvin Libe286f52018-09-15 13:54:15 +00006048 Record.AddSourceLocation(C->getNameModifierLoc());
6049 Record.AddSourceLocation(C->getColonLoc());
6050 Record.AddStmt(C->getCondition());
6051 Record.AddSourceLocation(C->getLParenLoc());
6052}
6053
6054void OMPClauseWriter::VisitOMPFinalClause(OMPFinalClause *C) {
Alexey Bataev3a842ec2019-10-15 19:37:05 +00006055 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +00006056 Record.AddStmt(C->getCondition());
6057 Record.AddSourceLocation(C->getLParenLoc());
6058}
6059
6060void OMPClauseWriter::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
6061 VisitOMPClauseWithPreInit(C);
6062 Record.AddStmt(C->getNumThreads());
6063 Record.AddSourceLocation(C->getLParenLoc());
6064}
6065
6066void OMPClauseWriter::VisitOMPSafelenClause(OMPSafelenClause *C) {
6067 Record.AddStmt(C->getSafelen());
6068 Record.AddSourceLocation(C->getLParenLoc());
6069}
6070
6071void OMPClauseWriter::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
6072 Record.AddStmt(C->getSimdlen());
6073 Record.AddSourceLocation(C->getLParenLoc());
6074}
6075
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00006076void OMPClauseWriter::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
6077 Record.AddStmt(C->getAllocator());
6078 Record.AddSourceLocation(C->getLParenLoc());
6079}
6080
Kelvin Libe286f52018-09-15 13:54:15 +00006081void OMPClauseWriter::VisitOMPCollapseClause(OMPCollapseClause *C) {
6082 Record.AddStmt(C->getNumForLoops());
6083 Record.AddSourceLocation(C->getLParenLoc());
6084}
6085
6086void OMPClauseWriter::VisitOMPDefaultClause(OMPDefaultClause *C) {
6087 Record.push_back(C->getDefaultKind());
6088 Record.AddSourceLocation(C->getLParenLoc());
6089 Record.AddSourceLocation(C->getDefaultKindKwLoc());
6090}
6091
6092void OMPClauseWriter::VisitOMPProcBindClause(OMPProcBindClause *C) {
Johannes Doerfert6c5d1f402019-12-25 18:15:36 -06006093 Record.push_back(unsigned(C->getProcBindKind()));
Kelvin Libe286f52018-09-15 13:54:15 +00006094 Record.AddSourceLocation(C->getLParenLoc());
6095 Record.AddSourceLocation(C->getProcBindKindKwLoc());
6096}
6097
6098void OMPClauseWriter::VisitOMPScheduleClause(OMPScheduleClause *C) {
6099 VisitOMPClauseWithPreInit(C);
6100 Record.push_back(C->getScheduleKind());
6101 Record.push_back(C->getFirstScheduleModifier());
6102 Record.push_back(C->getSecondScheduleModifier());
6103 Record.AddStmt(C->getChunkSize());
6104 Record.AddSourceLocation(C->getLParenLoc());
6105 Record.AddSourceLocation(C->getFirstScheduleModifierLoc());
6106 Record.AddSourceLocation(C->getSecondScheduleModifierLoc());
6107 Record.AddSourceLocation(C->getScheduleKindLoc());
6108 Record.AddSourceLocation(C->getCommaLoc());
6109}
6110
6111void OMPClauseWriter::VisitOMPOrderedClause(OMPOrderedClause *C) {
6112 Record.push_back(C->getLoopNumIterations().size());
6113 Record.AddStmt(C->getNumForLoops());
6114 for (Expr *NumIter : C->getLoopNumIterations())
6115 Record.AddStmt(NumIter);
6116 for (unsigned I = 0, E = C->getLoopNumIterations().size(); I <E; ++I)
Mike Rice0ed46662018-09-20 17:19:41 +00006117 Record.AddStmt(C->getLoopCounter(I));
Kelvin Libe286f52018-09-15 13:54:15 +00006118 Record.AddSourceLocation(C->getLParenLoc());
6119}
6120
6121void OMPClauseWriter::VisitOMPNowaitClause(OMPNowaitClause *) {}
6122
6123void OMPClauseWriter::VisitOMPUntiedClause(OMPUntiedClause *) {}
6124
6125void OMPClauseWriter::VisitOMPMergeableClause(OMPMergeableClause *) {}
6126
6127void OMPClauseWriter::VisitOMPReadClause(OMPReadClause *) {}
6128
6129void OMPClauseWriter::VisitOMPWriteClause(OMPWriteClause *) {}
6130
6131void OMPClauseWriter::VisitOMPUpdateClause(OMPUpdateClause *) {}
6132
6133void OMPClauseWriter::VisitOMPCaptureClause(OMPCaptureClause *) {}
6134
6135void OMPClauseWriter::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
6136
6137void OMPClauseWriter::VisitOMPThreadsClause(OMPThreadsClause *) {}
6138
6139void OMPClauseWriter::VisitOMPSIMDClause(OMPSIMDClause *) {}
6140
6141void OMPClauseWriter::VisitOMPNogroupClause(OMPNogroupClause *) {}
6142
6143void OMPClauseWriter::VisitOMPPrivateClause(OMPPrivateClause *C) {
6144 Record.push_back(C->varlist_size());
6145 Record.AddSourceLocation(C->getLParenLoc());
6146 for (auto *VE : C->varlists()) {
6147 Record.AddStmt(VE);
6148 }
6149 for (auto *VE : C->private_copies()) {
6150 Record.AddStmt(VE);
6151 }
6152}
6153
6154void OMPClauseWriter::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
6155 Record.push_back(C->varlist_size());
6156 VisitOMPClauseWithPreInit(C);
6157 Record.AddSourceLocation(C->getLParenLoc());
6158 for (auto *VE : C->varlists()) {
6159 Record.AddStmt(VE);
6160 }
6161 for (auto *VE : C->private_copies()) {
6162 Record.AddStmt(VE);
6163 }
6164 for (auto *VE : C->inits()) {
6165 Record.AddStmt(VE);
6166 }
6167}
6168
6169void OMPClauseWriter::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
6170 Record.push_back(C->varlist_size());
6171 VisitOMPClauseWithPostUpdate(C);
6172 Record.AddSourceLocation(C->getLParenLoc());
Alexey Bataev93dc40d2019-12-20 11:04:57 -05006173 Record.writeEnum(C->getKind());
6174 Record.AddSourceLocation(C->getKindLoc());
6175 Record.AddSourceLocation(C->getColonLoc());
Kelvin Libe286f52018-09-15 13:54:15 +00006176 for (auto *VE : C->varlists())
6177 Record.AddStmt(VE);
6178 for (auto *E : C->private_copies())
6179 Record.AddStmt(E);
6180 for (auto *E : C->source_exprs())
6181 Record.AddStmt(E);
6182 for (auto *E : C->destination_exprs())
6183 Record.AddStmt(E);
6184 for (auto *E : C->assignment_ops())
6185 Record.AddStmt(E);
6186}
6187
6188void OMPClauseWriter::VisitOMPSharedClause(OMPSharedClause *C) {
6189 Record.push_back(C->varlist_size());
6190 Record.AddSourceLocation(C->getLParenLoc());
6191 for (auto *VE : C->varlists())
6192 Record.AddStmt(VE);
6193}
6194
6195void OMPClauseWriter::VisitOMPReductionClause(OMPReductionClause *C) {
6196 Record.push_back(C->varlist_size());
6197 VisitOMPClauseWithPostUpdate(C);
6198 Record.AddSourceLocation(C->getLParenLoc());
6199 Record.AddSourceLocation(C->getColonLoc());
6200 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
6201 Record.AddDeclarationNameInfo(C->getNameInfo());
6202 for (auto *VE : C->varlists())
6203 Record.AddStmt(VE);
6204 for (auto *VE : C->privates())
6205 Record.AddStmt(VE);
6206 for (auto *E : C->lhs_exprs())
6207 Record.AddStmt(E);
6208 for (auto *E : C->rhs_exprs())
6209 Record.AddStmt(E);
6210 for (auto *E : C->reduction_ops())
6211 Record.AddStmt(E);
6212}
6213
6214void OMPClauseWriter::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
6215 Record.push_back(C->varlist_size());
6216 VisitOMPClauseWithPostUpdate(C);
6217 Record.AddSourceLocation(C->getLParenLoc());
6218 Record.AddSourceLocation(C->getColonLoc());
6219 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
6220 Record.AddDeclarationNameInfo(C->getNameInfo());
6221 for (auto *VE : C->varlists())
6222 Record.AddStmt(VE);
6223 for (auto *VE : C->privates())
6224 Record.AddStmt(VE);
6225 for (auto *E : C->lhs_exprs())
6226 Record.AddStmt(E);
6227 for (auto *E : C->rhs_exprs())
6228 Record.AddStmt(E);
6229 for (auto *E : C->reduction_ops())
6230 Record.AddStmt(E);
6231}
6232
6233void OMPClauseWriter::VisitOMPInReductionClause(OMPInReductionClause *C) {
6234 Record.push_back(C->varlist_size());
6235 VisitOMPClauseWithPostUpdate(C);
6236 Record.AddSourceLocation(C->getLParenLoc());
6237 Record.AddSourceLocation(C->getColonLoc());
6238 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
6239 Record.AddDeclarationNameInfo(C->getNameInfo());
6240 for (auto *VE : C->varlists())
6241 Record.AddStmt(VE);
6242 for (auto *VE : C->privates())
6243 Record.AddStmt(VE);
6244 for (auto *E : C->lhs_exprs())
6245 Record.AddStmt(E);
6246 for (auto *E : C->rhs_exprs())
6247 Record.AddStmt(E);
6248 for (auto *E : C->reduction_ops())
6249 Record.AddStmt(E);
6250 for (auto *E : C->taskgroup_descriptors())
6251 Record.AddStmt(E);
6252}
6253
6254void OMPClauseWriter::VisitOMPLinearClause(OMPLinearClause *C) {
6255 Record.push_back(C->varlist_size());
6256 VisitOMPClauseWithPostUpdate(C);
6257 Record.AddSourceLocation(C->getLParenLoc());
6258 Record.AddSourceLocation(C->getColonLoc());
6259 Record.push_back(C->getModifier());
6260 Record.AddSourceLocation(C->getModifierLoc());
6261 for (auto *VE : C->varlists()) {
6262 Record.AddStmt(VE);
6263 }
6264 for (auto *VE : C->privates()) {
6265 Record.AddStmt(VE);
6266 }
6267 for (auto *VE : C->inits()) {
6268 Record.AddStmt(VE);
6269 }
6270 for (auto *VE : C->updates()) {
6271 Record.AddStmt(VE);
6272 }
6273 for (auto *VE : C->finals()) {
6274 Record.AddStmt(VE);
6275 }
6276 Record.AddStmt(C->getStep());
6277 Record.AddStmt(C->getCalcStep());
Alexey Bataev195ae902019-08-08 13:42:45 +00006278 for (auto *VE : C->used_expressions())
6279 Record.AddStmt(VE);
Kelvin Libe286f52018-09-15 13:54:15 +00006280}
6281
6282void OMPClauseWriter::VisitOMPAlignedClause(OMPAlignedClause *C) {
6283 Record.push_back(C->varlist_size());
6284 Record.AddSourceLocation(C->getLParenLoc());
6285 Record.AddSourceLocation(C->getColonLoc());
6286 for (auto *VE : C->varlists())
6287 Record.AddStmt(VE);
6288 Record.AddStmt(C->getAlignment());
6289}
6290
6291void OMPClauseWriter::VisitOMPCopyinClause(OMPCopyinClause *C) {
6292 Record.push_back(C->varlist_size());
6293 Record.AddSourceLocation(C->getLParenLoc());
6294 for (auto *VE : C->varlists())
6295 Record.AddStmt(VE);
6296 for (auto *E : C->source_exprs())
6297 Record.AddStmt(E);
6298 for (auto *E : C->destination_exprs())
6299 Record.AddStmt(E);
6300 for (auto *E : C->assignment_ops())
6301 Record.AddStmt(E);
6302}
6303
6304void OMPClauseWriter::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
6305 Record.push_back(C->varlist_size());
6306 Record.AddSourceLocation(C->getLParenLoc());
6307 for (auto *VE : C->varlists())
6308 Record.AddStmt(VE);
6309 for (auto *E : C->source_exprs())
6310 Record.AddStmt(E);
6311 for (auto *E : C->destination_exprs())
6312 Record.AddStmt(E);
6313 for (auto *E : C->assignment_ops())
6314 Record.AddStmt(E);
6315}
6316
6317void OMPClauseWriter::VisitOMPFlushClause(OMPFlushClause *C) {
6318 Record.push_back(C->varlist_size());
6319 Record.AddSourceLocation(C->getLParenLoc());
6320 for (auto *VE : C->varlists())
6321 Record.AddStmt(VE);
6322}
6323
6324void OMPClauseWriter::VisitOMPDependClause(OMPDependClause *C) {
6325 Record.push_back(C->varlist_size());
6326 Record.push_back(C->getNumLoops());
6327 Record.AddSourceLocation(C->getLParenLoc());
6328 Record.push_back(C->getDependencyKind());
6329 Record.AddSourceLocation(C->getDependencyLoc());
6330 Record.AddSourceLocation(C->getColonLoc());
6331 for (auto *VE : C->varlists())
6332 Record.AddStmt(VE);
6333 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
6334 Record.AddStmt(C->getLoopData(I));
6335}
6336
6337void OMPClauseWriter::VisitOMPDeviceClause(OMPDeviceClause *C) {
6338 VisitOMPClauseWithPreInit(C);
6339 Record.AddStmt(C->getDevice());
6340 Record.AddSourceLocation(C->getLParenLoc());
6341}
6342
6343void OMPClauseWriter::VisitOMPMapClause(OMPMapClause *C) {
6344 Record.push_back(C->varlist_size());
6345 Record.push_back(C->getUniqueDeclarationsNum());
6346 Record.push_back(C->getTotalComponentListNum());
6347 Record.push_back(C->getTotalComponentsNum());
6348 Record.AddSourceLocation(C->getLParenLoc());
Kelvin Lief579432018-12-18 22:18:41 +00006349 for (unsigned I = 0; I < OMPMapClause::NumberOfModifiers; ++I) {
6350 Record.push_back(C->getMapTypeModifier(I));
6351 Record.AddSourceLocation(C->getMapTypeModifierLoc(I));
6352 }
Michael Kruse4304e9d2019-02-19 16:38:20 +00006353 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
6354 Record.AddDeclarationNameInfo(C->getMapperIdInfo());
Kelvin Libe286f52018-09-15 13:54:15 +00006355 Record.push_back(C->getMapType());
6356 Record.AddSourceLocation(C->getMapLoc());
6357 Record.AddSourceLocation(C->getColonLoc());
6358 for (auto *E : C->varlists())
6359 Record.AddStmt(E);
Michael Kruse4304e9d2019-02-19 16:38:20 +00006360 for (auto *E : C->mapperlists())
6361 Record.AddStmt(E);
Kelvin Libe286f52018-09-15 13:54:15 +00006362 for (auto *D : C->all_decls())
6363 Record.AddDeclRef(D);
6364 for (auto N : C->all_num_lists())
6365 Record.push_back(N);
6366 for (auto N : C->all_lists_sizes())
6367 Record.push_back(N);
6368 for (auto &M : C->all_components()) {
6369 Record.AddStmt(M.getAssociatedExpression());
6370 Record.AddDeclRef(M.getAssociatedDeclaration());
6371 }
6372}
6373
Alexey Bataeve04483e2019-03-27 14:14:31 +00006374void OMPClauseWriter::VisitOMPAllocateClause(OMPAllocateClause *C) {
6375 Record.push_back(C->varlist_size());
6376 Record.AddSourceLocation(C->getLParenLoc());
6377 Record.AddSourceLocation(C->getColonLoc());
6378 Record.AddStmt(C->getAllocator());
6379 for (auto *VE : C->varlists())
6380 Record.AddStmt(VE);
6381}
6382
Kelvin Libe286f52018-09-15 13:54:15 +00006383void OMPClauseWriter::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
6384 VisitOMPClauseWithPreInit(C);
6385 Record.AddStmt(C->getNumTeams());
6386 Record.AddSourceLocation(C->getLParenLoc());
6387}
6388
6389void OMPClauseWriter::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
6390 VisitOMPClauseWithPreInit(C);
6391 Record.AddStmt(C->getThreadLimit());
6392 Record.AddSourceLocation(C->getLParenLoc());
6393}
6394
6395void OMPClauseWriter::VisitOMPPriorityClause(OMPPriorityClause *C) {
Alexey Bataev31ba4762019-10-16 18:09:37 +00006396 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +00006397 Record.AddStmt(C->getPriority());
6398 Record.AddSourceLocation(C->getLParenLoc());
6399}
6400
6401void OMPClauseWriter::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
Alexey Bataevb9c55e22019-10-14 19:29:52 +00006402 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +00006403 Record.AddStmt(C->getGrainsize());
6404 Record.AddSourceLocation(C->getLParenLoc());
6405}
6406
6407void OMPClauseWriter::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
Alexey Bataevd88c7de2019-10-14 20:44:34 +00006408 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +00006409 Record.AddStmt(C->getNumTasks());
6410 Record.AddSourceLocation(C->getLParenLoc());
6411}
6412
6413void OMPClauseWriter::VisitOMPHintClause(OMPHintClause *C) {
6414 Record.AddStmt(C->getHint());
6415 Record.AddSourceLocation(C->getLParenLoc());
6416}
6417
6418void OMPClauseWriter::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
6419 VisitOMPClauseWithPreInit(C);
6420 Record.push_back(C->getDistScheduleKind());
6421 Record.AddStmt(C->getChunkSize());
6422 Record.AddSourceLocation(C->getLParenLoc());
6423 Record.AddSourceLocation(C->getDistScheduleKindLoc());
6424 Record.AddSourceLocation(C->getCommaLoc());
6425}
6426
6427void OMPClauseWriter::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
6428 Record.push_back(C->getDefaultmapKind());
6429 Record.push_back(C->getDefaultmapModifier());
6430 Record.AddSourceLocation(C->getLParenLoc());
6431 Record.AddSourceLocation(C->getDefaultmapModifierLoc());
6432 Record.AddSourceLocation(C->getDefaultmapKindLoc());
6433}
6434
6435void OMPClauseWriter::VisitOMPToClause(OMPToClause *C) {
6436 Record.push_back(C->varlist_size());
6437 Record.push_back(C->getUniqueDeclarationsNum());
6438 Record.push_back(C->getTotalComponentListNum());
6439 Record.push_back(C->getTotalComponentsNum());
6440 Record.AddSourceLocation(C->getLParenLoc());
Michael Kruse01f670d2019-02-22 22:29:42 +00006441 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
6442 Record.AddDeclarationNameInfo(C->getMapperIdInfo());
Kelvin Libe286f52018-09-15 13:54:15 +00006443 for (auto *E : C->varlists())
6444 Record.AddStmt(E);
Michael Kruse01f670d2019-02-22 22:29:42 +00006445 for (auto *E : C->mapperlists())
6446 Record.AddStmt(E);
Kelvin Libe286f52018-09-15 13:54:15 +00006447 for (auto *D : C->all_decls())
6448 Record.AddDeclRef(D);
6449 for (auto N : C->all_num_lists())
6450 Record.push_back(N);
6451 for (auto N : C->all_lists_sizes())
6452 Record.push_back(N);
6453 for (auto &M : C->all_components()) {
6454 Record.AddStmt(M.getAssociatedExpression());
6455 Record.AddDeclRef(M.getAssociatedDeclaration());
6456 }
6457}
6458
6459void OMPClauseWriter::VisitOMPFromClause(OMPFromClause *C) {
6460 Record.push_back(C->varlist_size());
6461 Record.push_back(C->getUniqueDeclarationsNum());
6462 Record.push_back(C->getTotalComponentListNum());
6463 Record.push_back(C->getTotalComponentsNum());
6464 Record.AddSourceLocation(C->getLParenLoc());
Michael Kruse0336c752019-02-25 20:34:15 +00006465 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
6466 Record.AddDeclarationNameInfo(C->getMapperIdInfo());
Kelvin Libe286f52018-09-15 13:54:15 +00006467 for (auto *E : C->varlists())
6468 Record.AddStmt(E);
Michael Kruse0336c752019-02-25 20:34:15 +00006469 for (auto *E : C->mapperlists())
6470 Record.AddStmt(E);
Kelvin Libe286f52018-09-15 13:54:15 +00006471 for (auto *D : C->all_decls())
6472 Record.AddDeclRef(D);
6473 for (auto N : C->all_num_lists())
6474 Record.push_back(N);
6475 for (auto N : C->all_lists_sizes())
6476 Record.push_back(N);
6477 for (auto &M : C->all_components()) {
6478 Record.AddStmt(M.getAssociatedExpression());
6479 Record.AddDeclRef(M.getAssociatedDeclaration());
6480 }
6481}
6482
6483void OMPClauseWriter::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
6484 Record.push_back(C->varlist_size());
6485 Record.push_back(C->getUniqueDeclarationsNum());
6486 Record.push_back(C->getTotalComponentListNum());
6487 Record.push_back(C->getTotalComponentsNum());
6488 Record.AddSourceLocation(C->getLParenLoc());
6489 for (auto *E : C->varlists())
6490 Record.AddStmt(E);
6491 for (auto *VE : C->private_copies())
6492 Record.AddStmt(VE);
6493 for (auto *VE : C->inits())
6494 Record.AddStmt(VE);
6495 for (auto *D : C->all_decls())
6496 Record.AddDeclRef(D);
6497 for (auto N : C->all_num_lists())
6498 Record.push_back(N);
6499 for (auto N : C->all_lists_sizes())
6500 Record.push_back(N);
6501 for (auto &M : C->all_components()) {
6502 Record.AddStmt(M.getAssociatedExpression());
6503 Record.AddDeclRef(M.getAssociatedDeclaration());
6504 }
6505}
6506
6507void OMPClauseWriter::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
6508 Record.push_back(C->varlist_size());
6509 Record.push_back(C->getUniqueDeclarationsNum());
6510 Record.push_back(C->getTotalComponentListNum());
6511 Record.push_back(C->getTotalComponentsNum());
6512 Record.AddSourceLocation(C->getLParenLoc());
6513 for (auto *E : C->varlists())
6514 Record.AddStmt(E);
6515 for (auto *D : C->all_decls())
6516 Record.AddDeclRef(D);
6517 for (auto N : C->all_num_lists())
6518 Record.push_back(N);
6519 for (auto N : C->all_lists_sizes())
6520 Record.push_back(N);
6521 for (auto &M : C->all_components()) {
6522 Record.AddStmt(M.getAssociatedExpression());
6523 Record.AddDeclRef(M.getAssociatedDeclaration());
6524 }
6525}
Kelvin Li1408f912018-09-26 04:28:39 +00006526
6527void OMPClauseWriter::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
Patrick Lyster4a370b92018-10-01 13:47:43 +00006528
6529void OMPClauseWriter::VisitOMPUnifiedSharedMemoryClause(
6530 OMPUnifiedSharedMemoryClause *) {}
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00006531
6532void OMPClauseWriter::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
Patrick Lyster3fe9e392018-10-11 14:41:10 +00006533
6534void
6535OMPClauseWriter::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
6536}
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00006537
6538void OMPClauseWriter::VisitOMPAtomicDefaultMemOrderClause(
6539 OMPAtomicDefaultMemOrderClause *C) {
6540 Record.push_back(C->getAtomicDefaultMemOrderKind());
6541 Record.AddSourceLocation(C->getLParenLoc());
6542 Record.AddSourceLocation(C->getAtomicDefaultMemOrderKindKwLoc());
6543}
Alexey Bataevb6e70842019-12-16 15:54:17 -05006544
6545void OMPClauseWriter::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
6546 Record.push_back(C->varlist_size());
6547 Record.AddSourceLocation(C->getLParenLoc());
6548 for (auto *VE : C->varlists())
6549 Record.AddStmt(VE);
Alexey Bataev0860db92019-12-19 10:01:10 -05006550 for (auto *E : C->private_refs())
6551 Record.AddStmt(E);
Alexey Bataevb6e70842019-12-16 15:54:17 -05006552}