blob: f4e54e4358f9d113be4649f001fd462b27aa8652 [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
Florian Hahn10658692020-05-11 17:45:51 +0100291void TypeLocWriter::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
292 Record.AddSourceLocation(TL.getAttrNameLoc());
293 SourceRange range = TL.getAttrOperandParensRange();
294 Record.AddSourceLocation(range.getBegin());
295 Record.AddSourceLocation(range.getEnd());
296 Record.AddStmt(TL.getAttrRowOperand());
297 Record.AddStmt(TL.getAttrColumnOperand());
298}
299
300void TypeLocWriter::VisitDependentSizedMatrixTypeLoc(
301 DependentSizedMatrixTypeLoc TL) {
302 Record.AddSourceLocation(TL.getAttrNameLoc());
303 SourceRange range = TL.getAttrOperandParensRange();
304 Record.AddSourceLocation(range.getBegin());
305 Record.AddSourceLocation(range.getEnd());
306 Record.AddStmt(TL.getAttrRowOperand());
307 Record.AddStmt(TL.getAttrColumnOperand());
308}
309
John McCall17001972009-10-18 01:05:36 +0000310void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000311 Record.AddSourceLocation(TL.getLocalRangeBegin());
312 Record.AddSourceLocation(TL.getLParenLoc());
313 Record.AddSourceLocation(TL.getRParenLoc());
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +0000314 Record.AddSourceRange(TL.getExceptionSpecRange());
Richard Smith69c82bf2016-04-01 22:52:03 +0000315 Record.AddSourceLocation(TL.getLocalRangeEnd());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +0000316 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000317 Record.AddDeclRef(TL.getParam(i));
John McCall17001972009-10-18 01:05:36 +0000318}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000319
John McCall17001972009-10-18 01:05:36 +0000320void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
321 VisitFunctionTypeLoc(TL);
322}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000323
John McCall17001972009-10-18 01:05:36 +0000324void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
325 VisitFunctionTypeLoc(TL);
326}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000327
John McCallb96ec562009-12-04 22:46:56 +0000328void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000329 Record.AddSourceLocation(TL.getNameLoc());
John McCallb96ec562009-12-04 22:46:56 +0000330}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000331
John McCall17001972009-10-18 01:05:36 +0000332void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000333 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000334}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000335
Manman Rene6be26c2016-09-13 17:25:08 +0000336void TypeLocWriter::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
337 if (TL.getNumProtocols()) {
338 Record.AddSourceLocation(TL.getProtocolLAngleLoc());
339 Record.AddSourceLocation(TL.getProtocolRAngleLoc());
340 }
341 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
342 Record.AddSourceLocation(TL.getProtocolLoc(i));
343}
Eugene Zelenkob7d89102017-11-11 00:08:50 +0000344
John McCall17001972009-10-18 01:05:36 +0000345void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000346 Record.AddSourceLocation(TL.getTypeofLoc());
347 Record.AddSourceLocation(TL.getLParenLoc());
348 Record.AddSourceLocation(TL.getRParenLoc());
John McCall17001972009-10-18 01:05:36 +0000349}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000350
John McCall17001972009-10-18 01:05:36 +0000351void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000352 Record.AddSourceLocation(TL.getTypeofLoc());
353 Record.AddSourceLocation(TL.getLParenLoc());
354 Record.AddSourceLocation(TL.getRParenLoc());
355 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
John McCall17001972009-10-18 01:05:36 +0000356}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000357
John McCall17001972009-10-18 01:05:36 +0000358void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000359 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000360}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000361
Alexis Hunte852b102011-05-24 22:41:36 +0000362void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000363 Record.AddSourceLocation(TL.getKWLoc());
364 Record.AddSourceLocation(TL.getLParenLoc());
365 Record.AddSourceLocation(TL.getRParenLoc());
366 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
Alexis Hunte852b102011-05-24 22:41:36 +0000367}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000368
Richard Smith30482bc2011-02-20 03:19:35 +0000369void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000370 Record.AddSourceLocation(TL.getNameLoc());
Saar Razb481f022020-01-22 02:03:05 +0200371 Record.push_back(TL.isConstrained());
372 if (TL.isConstrained()) {
373 Record.AddNestedNameSpecifierLoc(TL.getNestedNameSpecifierLoc());
374 Record.AddSourceLocation(TL.getTemplateKWLoc());
375 Record.AddSourceLocation(TL.getConceptNameLoc());
376 Record.AddDeclRef(TL.getFoundDecl());
377 Record.AddSourceLocation(TL.getLAngleLoc());
378 Record.AddSourceLocation(TL.getRAngleLoc());
379 for (unsigned I = 0; I < TL.getNumArgs(); ++I)
380 Record.AddTemplateArgumentLocInfo(TL.getTypePtr()->getArg(I).getKind(),
381 TL.getArgLocInfo(I));
382 }
Richard Smith30482bc2011-02-20 03:19:35 +0000383}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000384
Richard Smith600b5262017-01-26 20:40:47 +0000385void TypeLocWriter::VisitDeducedTemplateSpecializationTypeLoc(
386 DeducedTemplateSpecializationTypeLoc TL) {
387 Record.AddSourceLocation(TL.getTemplateNameLoc());
388}
389
John McCall17001972009-10-18 01:05:36 +0000390void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000391 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000392}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000393
John McCall17001972009-10-18 01:05:36 +0000394void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000395 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000396}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000397
John McCall81904512011-01-06 01:58:22 +0000398void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
Richard Smithe43e2b32018-08-20 21:47:29 +0000399 Record.AddAttr(TL.getAttr());
John McCall81904512011-01-06 01:58:22 +0000400}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000401
John McCall17001972009-10-18 01:05:36 +0000402void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000403 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000404}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000405
John McCallcebee162009-10-18 09:09:24 +0000406void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
407 SubstTemplateTypeParmTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000408 Record.AddSourceLocation(TL.getNameLoc());
John McCallcebee162009-10-18 09:09:24 +0000409}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000410
Douglas Gregorada4b792011-01-14 02:55:32 +0000411void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
412 SubstTemplateTypeParmPackTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000413 Record.AddSourceLocation(TL.getNameLoc());
Douglas Gregorada4b792011-01-14 02:55:32 +0000414}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000415
John McCall17001972009-10-18 01:05:36 +0000416void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
417 TemplateSpecializationTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000418 Record.AddSourceLocation(TL.getTemplateKeywordLoc());
419 Record.AddSourceLocation(TL.getTemplateNameLoc());
420 Record.AddSourceLocation(TL.getLAngleLoc());
421 Record.AddSourceLocation(TL.getRAngleLoc());
John McCall0ad16662009-10-29 08:12:44 +0000422 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000423 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
424 TL.getArgLoc(i).getLocInfo());
John McCall17001972009-10-18 01:05:36 +0000425}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000426
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000427void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000428 Record.AddSourceLocation(TL.getLParenLoc());
429 Record.AddSourceLocation(TL.getRParenLoc());
Abramo Bagnara924a8f32010-12-10 16:29:40 +0000430}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000431
Leonard Chanc72aaf62019-05-07 03:20:17 +0000432void TypeLocWriter::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
433 Record.AddSourceLocation(TL.getExpansionLoc());
434}
435
Abramo Bagnara6150c882010-05-11 21:36:43 +0000436void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000437 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
438 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
John McCall17001972009-10-18 01:05:36 +0000439}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000440
John McCalle78aac42010-03-10 03:28:59 +0000441void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000442 Record.AddSourceLocation(TL.getNameLoc());
John McCalle78aac42010-03-10 03:28:59 +0000443}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000444
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +0000445void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000446 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
447 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
448 Record.AddSourceLocation(TL.getNameLoc());
John McCall17001972009-10-18 01:05:36 +0000449}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000450
John McCallc392f372010-06-11 00:33:02 +0000451void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
452 DependentTemplateSpecializationTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000453 Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
454 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
455 Record.AddSourceLocation(TL.getTemplateKeywordLoc());
456 Record.AddSourceLocation(TL.getTemplateNameLoc());
457 Record.AddSourceLocation(TL.getLAngleLoc());
458 Record.AddSourceLocation(TL.getRAngleLoc());
John McCallc392f372010-06-11 00:33:02 +0000459 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
Richard Smith69c82bf2016-04-01 22:52:03 +0000460 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
461 TL.getArgLoc(I).getLocInfo());
John McCallc392f372010-06-11 00:33:02 +0000462}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000463
Douglas Gregord2fa7662010-12-20 02:24:11 +0000464void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000465 Record.AddSourceLocation(TL.getEllipsisLoc());
Douglas Gregord2fa7662010-12-20 02:24:11 +0000466}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000467
John McCall17001972009-10-18 01:05:36 +0000468void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000469 Record.AddSourceLocation(TL.getNameLoc());
John McCall8b07ec22010-05-15 11:32:37 +0000470}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000471
John McCall8b07ec22010-05-15 11:32:37 +0000472void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
473 Record.push_back(TL.hasBaseTypeAsWritten());
Richard Smith69c82bf2016-04-01 22:52:03 +0000474 Record.AddSourceLocation(TL.getTypeArgsLAngleLoc());
475 Record.AddSourceLocation(TL.getTypeArgsRAngleLoc());
Douglas Gregore9d95f12015-07-07 03:57:35 +0000476 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000477 Record.AddTypeSourceInfo(TL.getTypeArgTInfo(i));
478 Record.AddSourceLocation(TL.getProtocolLAngleLoc());
479 Record.AddSourceLocation(TL.getProtocolRAngleLoc());
John McCall17001972009-10-18 01:05:36 +0000480 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
Richard Smith69c82bf2016-04-01 22:52:03 +0000481 Record.AddSourceLocation(TL.getProtocolLoc(i));
John McCall8f115c62009-10-16 21:56:05 +0000482}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000483
John McCallfc93cf92009-10-22 22:37:11 +0000484void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000485 Record.AddSourceLocation(TL.getStarLoc());
John McCallfc93cf92009-10-22 22:37:11 +0000486}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000487
Eli Friedman0dfb8892011-10-06 23:00:33 +0000488void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000489 Record.AddSourceLocation(TL.getKWLoc());
490 Record.AddSourceLocation(TL.getLParenLoc());
491 Record.AddSourceLocation(TL.getRParenLoc());
Eli Friedman0dfb8892011-10-06 23:00:33 +0000492}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000493
Xiuli Pan9c14e282016-01-09 12:53:17 +0000494void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
Richard Smith69c82bf2016-04-01 22:52:03 +0000495 Record.AddSourceLocation(TL.getKWLoc());
Xiuli Pan9c14e282016-01-09 12:53:17 +0000496}
John McCall8f115c62009-10-16 21:56:05 +0000497
Erich Keane5f0903e2020-04-17 10:44:19 -0700498void TypeLocWriter::VisitExtIntTypeLoc(clang::ExtIntTypeLoc TL) {
499 Record.AddSourceLocation(TL.getNameLoc());
500}
501void TypeLocWriter::VisitDependentExtIntTypeLoc(
502 clang::DependentExtIntTypeLoc TL) {
503 Record.AddSourceLocation(TL.getNameLoc());
504}
505
Richard Smith01b2cb42014-07-26 06:37:51 +0000506void ASTWriter::WriteTypeAbbrevs() {
507 using namespace llvm;
508
David Blaikieb44f0bf2017-01-04 22:36:43 +0000509 std::shared_ptr<BitCodeAbbrev> Abv;
Richard Smith01b2cb42014-07-26 06:37:51 +0000510
511 // Abbreviation for TYPE_EXT_QUAL
David Blaikieb44f0bf2017-01-04 22:36:43 +0000512 Abv = std::make_shared<BitCodeAbbrev>();
Richard Smith01b2cb42014-07-26 06:37:51 +0000513 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
514 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
515 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals
David Blaikieb44f0bf2017-01-04 22:36:43 +0000516 TypeExtQualAbbrev = Stream.EmitAbbrev(std::move(Abv));
Richard Smith01b2cb42014-07-26 06:37:51 +0000517
518 // Abbreviation for TYPE_FUNCTION_PROTO
David Blaikieb44f0bf2017-01-04 22:36:43 +0000519 Abv = std::make_shared<BitCodeAbbrev>();
Richard Smith01b2cb42014-07-26 06:37:51 +0000520 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_FUNCTION_PROTO));
521 // FunctionType
522 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ReturnType
523 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NoReturn
524 Abv->Add(BitCodeAbbrevOp(0)); // HasRegParm
525 Abv->Add(BitCodeAbbrevOp(0)); // RegParm
526 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // CC
527 Abv->Add(BitCodeAbbrevOp(0)); // ProducesResult
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +0000528 Abv->Add(BitCodeAbbrevOp(0)); // NoCallerSavedRegs
Oren Ben Simhon220671a2018-03-17 13:31:35 +0000529 Abv->Add(BitCodeAbbrevOp(0)); // NoCfCheck
Momchil Velikov080d0462020-03-24 09:32:51 +0000530 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // CmseNSCall
Richard Smith01b2cb42014-07-26 06:37:51 +0000531 // FunctionProtoType
532 Abv->Add(BitCodeAbbrevOp(0)); // IsVariadic
533 Abv->Add(BitCodeAbbrevOp(0)); // HasTrailingReturn
534 Abv->Add(BitCodeAbbrevOp(0)); // TypeQuals
535 Abv->Add(BitCodeAbbrevOp(0)); // RefQualifier
536 Abv->Add(BitCodeAbbrevOp(EST_None)); // ExceptionSpec
537 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // NumParams
538 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
539 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Params
David Blaikieb44f0bf2017-01-04 22:36:43 +0000540 TypeFunctionProtoAbbrev = Stream.EmitAbbrev(std::move(Abv));
Richard Smith01b2cb42014-07-26 06:37:51 +0000541}
542
Chris Lattner19cea4e2009-04-22 05:57:30 +0000543//===----------------------------------------------------------------------===//
Sebastian Redl55c0ad52010-08-18 23:56:21 +0000544// ASTWriter Implementation
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000545//===----------------------------------------------------------------------===//
546
Chris Lattner28fa4e62009-04-26 22:26:21 +0000547static void EmitBlockID(unsigned ID, const char *Name,
548 llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000549 ASTWriter::RecordDataImpl &Record) {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000550 Record.clear();
551 Record.push_back(ID);
552 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
553
554 // Emit the block name if present.
Craig Toppera13603a2014-05-22 05:54:18 +0000555 if (!Name || Name[0] == 0)
556 return;
Chris Lattner28fa4e62009-04-26 22:26:21 +0000557 Record.clear();
558 while (*Name)
559 Record.push_back(*Name++);
560 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
561}
562
563static void EmitRecordID(unsigned ID, const char *Name,
564 llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000565 ASTWriter::RecordDataImpl &Record) {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000566 Record.clear();
567 Record.push_back(ID);
568 while (*Name)
569 Record.push_back(*Name++);
570 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000571}
572
573static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +0000574 ASTWriter::RecordDataImpl &Record) {
Sebastian Redl539c5062010-08-18 23:57:32 +0000575#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
Chris Lattnerccac3a62009-04-27 00:49:53 +0000576 RECORD(STMT_STOP);
577 RECORD(STMT_NULL_PTR);
Richard Smith01b2cb42014-07-26 06:37:51 +0000578 RECORD(STMT_REF_PTR);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000579 RECORD(STMT_NULL);
580 RECORD(STMT_COMPOUND);
581 RECORD(STMT_CASE);
582 RECORD(STMT_DEFAULT);
583 RECORD(STMT_LABEL);
Richard Smithc202b282012-04-14 00:33:13 +0000584 RECORD(STMT_ATTRIBUTED);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000585 RECORD(STMT_IF);
586 RECORD(STMT_SWITCH);
587 RECORD(STMT_WHILE);
588 RECORD(STMT_DO);
589 RECORD(STMT_FOR);
590 RECORD(STMT_GOTO);
591 RECORD(STMT_INDIRECT_GOTO);
592 RECORD(STMT_CONTINUE);
593 RECORD(STMT_BREAK);
594 RECORD(STMT_RETURN);
595 RECORD(STMT_DECL);
Chad Rosierde70e0e2012-08-25 00:11:56 +0000596 RECORD(STMT_GCCASM);
Chad Rosiere30d4992012-08-24 23:51:02 +0000597 RECORD(STMT_MSASM);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000598 RECORD(EXPR_PREDEFINED);
599 RECORD(EXPR_DECL_REF);
600 RECORD(EXPR_INTEGER_LITERAL);
Vince Bridgers161fc1d2020-04-07 14:46:08 -0500601 RECORD(EXPR_FIXEDPOINT_LITERAL);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000602 RECORD(EXPR_FLOATING_LITERAL);
603 RECORD(EXPR_IMAGINARY_LITERAL);
604 RECORD(EXPR_STRING_LITERAL);
605 RECORD(EXPR_CHARACTER_LITERAL);
606 RECORD(EXPR_PAREN);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000607 RECORD(EXPR_PAREN_LIST);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000608 RECORD(EXPR_UNARY_OPERATOR);
609 RECORD(EXPR_SIZEOF_ALIGN_OF);
610 RECORD(EXPR_ARRAY_SUBSCRIPT);
611 RECORD(EXPR_CALL);
612 RECORD(EXPR_MEMBER);
613 RECORD(EXPR_BINARY_OPERATOR);
614 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
615 RECORD(EXPR_CONDITIONAL_OPERATOR);
616 RECORD(EXPR_IMPLICIT_CAST);
617 RECORD(EXPR_CSTYLE_CAST);
618 RECORD(EXPR_COMPOUND_LITERAL);
619 RECORD(EXPR_EXT_VECTOR_ELEMENT);
620 RECORD(EXPR_INIT_LIST);
621 RECORD(EXPR_DESIGNATED_INIT);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000622 RECORD(EXPR_DESIGNATED_INIT_UPDATE);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000623 RECORD(EXPR_IMPLICIT_VALUE_INIT);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000624 RECORD(EXPR_NO_INIT);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000625 RECORD(EXPR_VA_ARG);
626 RECORD(EXPR_ADDR_LABEL);
627 RECORD(EXPR_STMT);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000628 RECORD(EXPR_CHOOSE);
629 RECORD(EXPR_GNU_NULL);
630 RECORD(EXPR_SHUFFLE_VECTOR);
631 RECORD(EXPR_BLOCK);
Peter Collingbourne91147592011-04-15 00:35:48 +0000632 RECORD(EXPR_GENERIC_SELECTION);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000633 RECORD(EXPR_OBJC_STRING_LITERAL);
Patrick Beard0caa3942012-04-19 00:25:12 +0000634 RECORD(EXPR_OBJC_BOXED_EXPRESSION);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000635 RECORD(EXPR_OBJC_ARRAY_LITERAL);
636 RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000637 RECORD(EXPR_OBJC_ENCODE);
638 RECORD(EXPR_OBJC_SELECTOR_EXPR);
639 RECORD(EXPR_OBJC_PROTOCOL_EXPR);
640 RECORD(EXPR_OBJC_IVAR_REF_EXPR);
641 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
642 RECORD(EXPR_OBJC_KVC_REF_EXPR);
643 RECORD(EXPR_OBJC_MESSAGE_EXPR);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000644 RECORD(STMT_OBJC_FOR_COLLECTION);
645 RECORD(STMT_OBJC_CATCH);
646 RECORD(STMT_OBJC_FINALLY);
647 RECORD(STMT_OBJC_AT_TRY);
648 RECORD(STMT_OBJC_AT_SYNCHRONIZED);
649 RECORD(STMT_OBJC_AT_THROW);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000650 RECORD(EXPR_OBJC_BOOL_LITERAL);
Richard Smith01b2cb42014-07-26 06:37:51 +0000651 RECORD(STMT_CXX_CATCH);
652 RECORD(STMT_CXX_TRY);
653 RECORD(STMT_CXX_FOR_RANGE);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000654 RECORD(EXPR_CXX_OPERATOR_CALL);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000655 RECORD(EXPR_CXX_MEMBER_CALL);
Richard Smith778dc0f2019-10-19 00:04:38 +0000656 RECORD(EXPR_CXX_REWRITTEN_BINARY_OPERATOR);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000657 RECORD(EXPR_CXX_CONSTRUCT);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000658 RECORD(EXPR_CXX_TEMPORARY_OBJECT);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000659 RECORD(EXPR_CXX_STATIC_CAST);
660 RECORD(EXPR_CXX_DYNAMIC_CAST);
661 RECORD(EXPR_CXX_REINTERPRET_CAST);
662 RECORD(EXPR_CXX_CONST_CAST);
663 RECORD(EXPR_CXX_FUNCTIONAL_CAST);
Richard Smithc67fdd42012-03-07 08:35:16 +0000664 RECORD(EXPR_USER_DEFINED_LITERAL);
Richard Smithcc1b96d2013-06-12 22:31:48 +0000665 RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
Sam Weinige83b3ac2010-02-07 06:32:43 +0000666 RECORD(EXPR_CXX_BOOL_LITERAL);
667 RECORD(EXPR_CXX_NULL_PTR_LITERAL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000668 RECORD(EXPR_CXX_TYPEID_EXPR);
669 RECORD(EXPR_CXX_TYPEID_TYPE);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000670 RECORD(EXPR_CXX_THIS);
671 RECORD(EXPR_CXX_THROW);
672 RECORD(EXPR_CXX_DEFAULT_ARG);
Richard Smith01b2cb42014-07-26 06:37:51 +0000673 RECORD(EXPR_CXX_DEFAULT_INIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000674 RECORD(EXPR_CXX_BIND_TEMPORARY);
675 RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
676 RECORD(EXPR_CXX_NEW);
677 RECORD(EXPR_CXX_DELETE);
678 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
679 RECORD(EXPR_EXPR_WITH_CLEANUPS);
680 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
681 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
682 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
683 RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
684 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
Richard Smith01b2cb42014-07-26 06:37:51 +0000685 RECORD(EXPR_CXX_EXPRESSION_TRAIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000686 RECORD(EXPR_CXX_NOEXCEPT);
687 RECORD(EXPR_OPAQUE_VALUE);
Richard Smith01b2cb42014-07-26 06:37:51 +0000688 RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR);
689 RECORD(EXPR_TYPE_TRAIT);
690 RECORD(EXPR_ARRAY_TYPE_TRAIT);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000691 RECORD(EXPR_PACK_EXPANSION);
692 RECORD(EXPR_SIZEOF_PACK);
Richard Smith01b2cb42014-07-26 06:37:51 +0000693 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000694 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
Richard Smith01b2cb42014-07-26 06:37:51 +0000695 RECORD(EXPR_FUNCTION_PARM_PACK);
696 RECORD(EXPR_MATERIALIZE_TEMPORARY);
Peter Collingbourne41f85462011-02-09 21:07:24 +0000697 RECORD(EXPR_CUDA_KERNEL_CALL);
Richard Smith01b2cb42014-07-26 06:37:51 +0000698 RECORD(EXPR_CXX_UUIDOF_EXPR);
699 RECORD(EXPR_CXX_UUIDOF_TYPE);
700 RECORD(EXPR_LAMBDA);
Chris Lattnerccac3a62009-04-27 00:49:53 +0000701#undef RECORD
Chris Lattner28fa4e62009-04-26 22:26:21 +0000702}
Mike Stump11289f42009-09-09 15:08:12 +0000703
Sebastian Redl55c0ad52010-08-18 23:56:21 +0000704void ASTWriter::WriteBlockInfoBlock() {
Chris Lattner28fa4e62009-04-26 22:26:21 +0000705 RecordData Record;
Peter Collingbourned3a6c702016-11-01 01:18:57 +0000706 Stream.EnterBlockInfoBlock();
Mike Stump11289f42009-09-09 15:08:12 +0000707
Sebastian Redl539c5062010-08-18 23:57:32 +0000708#define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
709#define RECORD(X) EmitRecordID(X, #X, Stream, Record)
Mike Stump11289f42009-09-09 15:08:12 +0000710
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000711 // Control Block.
712 BLOCK(CONTROL_BLOCK);
713 RECORD(METADATA);
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000714 RECORD(MODULE_NAME);
Richard Smithfa715652015-08-31 22:43:10 +0000715 RECORD(MODULE_DIRECTORY);
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000716 RECORD(MODULE_MAP_FILE);
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000717 RECORD(IMPORTS);
Douglas Gregorfad10d82012-10-18 18:36:53 +0000718 RECORD(ORIGINAL_FILE);
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000719 RECORD(ORIGINAL_PCH_DIR);
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +0000720 RECORD(ORIGINAL_FILE_ID);
Douglas Gregor3120d2c2012-10-22 18:42:04 +0000721 RECORD(INPUT_FILE_OFFSETS);
Richard Smith0516b182015-09-08 19:40:14 +0000722
723 BLOCK(OPTIONS_BLOCK);
724 RECORD(LANGUAGE_OPTIONS);
725 RECORD(TARGET_OPTIONS);
Douglas Gregorc6317db2012-10-24 15:49:58 +0000726 RECORD(FILE_SYSTEM_OPTIONS);
Douglas Gregor2d302362012-10-24 16:50:34 +0000727 RECORD(HEADER_SEARCH_OPTIONS);
Douglas Gregorb6af6c22012-10-24 20:05:57 +0000728 RECORD(PREPROCESSOR_OPTIONS);
729
Douglas Gregor108cb222012-10-19 00:45:00 +0000730 BLOCK(INPUT_FILES_BLOCK);
731 RECORD(INPUT_FILE);
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +0000732 RECORD(INPUT_FILE_HASH);
Douglas Gregor108cb222012-10-19 00:45:00 +0000733
Douglas Gregor0aa21c92012-10-18 18:27:37 +0000734 // AST Top-Level Block.
735 BLOCK(AST_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000736 RECORD(TYPE_OFFSET);
737 RECORD(DECL_OFFSET);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000738 RECORD(IDENTIFIER_OFFSET);
739 RECORD(IDENTIFIER_TABLE);
Ben Langmuir332aafe2014-01-31 01:06:56 +0000740 RECORD(EAGERLY_DESERIALIZED_DECLS);
David Blaikie9ffe5a32017-01-30 05:00:26 +0000741 RECORD(MODULAR_CODEGEN_DECLS);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000742 RECORD(SPECIAL_TYPES);
743 RECORD(STATISTICS);
744 RECORD(TENTATIVE_DEFINITIONS);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000745 RECORD(SELECTOR_OFFSETS);
746 RECORD(METHOD_POOL);
747 RECORD(PP_COUNTER_VALUE);
Douglas Gregor258ae542009-04-27 06:38:32 +0000748 RECORD(SOURCE_LOCATION_OFFSETS);
749 RECORD(SOURCE_LOCATION_PRELOADS);
Douglas Gregor61cac2b2009-04-27 20:06:05 +0000750 RECORD(EXT_VECTOR_DECLS);
Richard Smithfa715652015-08-31 22:43:10 +0000751 RECORD(UNUSED_FILESCOPED_DECLS);
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +0000752 RECORD(PPD_ENTITIES_OFFSETS);
Richard Smithfa715652015-08-31 22:43:10 +0000753 RECORD(VTABLE_USES);
Cameron Desrochersb60f1b62018-01-15 19:14:16 +0000754 RECORD(PPD_SKIPPED_RANGES);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +0000755 RECORD(REFERENCED_SELECTOR_POOL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000756 RECORD(TU_UPDATE_LEXICAL);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000757 RECORD(SEMA_DECL_REFS);
758 RECORD(WEAK_UNDECLARED_IDENTIFIERS);
759 RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000760 RECORD(UPDATE_VISIBLE);
761 RECORD(DECL_UPDATE_OFFSETS);
762 RECORD(DECL_UPDATES);
Peter Collingbourne5df20e02011-02-15 19:46:30 +0000763 RECORD(CUDA_SPECIAL_DECL_REFS);
Douglas Gregor09b69892011-02-10 17:09:37 +0000764 RECORD(HEADER_SEARCH_TABLE);
Peter Collingbourne5df20e02011-02-15 19:46:30 +0000765 RECORD(FP_PRAGMA_OPTIONS);
766 RECORD(OPENCL_EXTENSIONS);
Yaxun Liu5b746652016-12-18 05:18:55 +0000767 RECORD(OPENCL_EXTENSION_TYPES);
768 RECORD(OPENCL_EXTENSION_DECLS);
Alexis Hunt27a761d2011-05-04 23:29:54 +0000769 RECORD(DELEGATING_CTORS);
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000770 RECORD(KNOWN_NAMESPACES);
Douglas Gregor78d0b572011-08-04 16:39:39 +0000771 RECORD(MODULE_OFFSET_MAP);
772 RECORD(SOURCE_MANAGER_LINE_TABLE);
Douglas Gregor404cdde2012-01-27 01:47:08 +0000773 RECORD(OBJC_CATEGORIES_MAP);
Douglas Gregor66e4add2011-12-19 21:09:25 +0000774 RECORD(FILE_SORTED_DECLS);
775 RECORD(IMPORTED_MODULES);
Douglas Gregor404cdde2012-01-27 01:47:08 +0000776 RECORD(OBJC_CATEGORIES);
Douglas Gregorcb28f9d2012-10-09 23:05:51 +0000777 RECORD(MACRO_OFFSET);
Richard Smithfa715652015-08-31 22:43:10 +0000778 RECORD(INTERESTING_IDENTIFIERS);
779 RECORD(UNDEFINED_BUT_USED);
Richard Smithe40f2ba2013-08-07 21:41:30 +0000780 RECORD(LATE_PARSED_TEMPLATE);
Dario Domizioli13a0a382014-05-23 12:13:25 +0000781 RECORD(OPTIMIZE_PRAGMA_OPTIONS);
Nico Weber779355f2016-03-02 23:22:00 +0000782 RECORD(MSSTRUCT_PRAGMA_OPTIONS);
Nico Weber42932312016-03-03 00:17:35 +0000783 RECORD(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS);
Richard Smithfa715652015-08-31 22:43:10 +0000784 RECORD(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES);
Richard Smithfa715652015-08-31 22:43:10 +0000785 RECORD(DELETE_EXPRS_TO_ANALYZE);
Justin Lebar67a78a62016-10-08 22:15:58 +0000786 RECORD(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH);
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000787 RECORD(PP_CONDITIONAL_STACK);
Yaxun (Sam) Liub670ab72020-02-26 10:57:39 -0500788 RECORD(DECLS_TO_CHECK_FOR_DEFERRED_DIAGS);
Douglas Gregor358cd442012-01-15 16:58:34 +0000789
Chris Lattner28fa4e62009-04-26 22:26:21 +0000790 // SourceManager Block.
Chris Lattner64031982009-04-27 00:40:25 +0000791 BLOCK(SOURCE_MANAGER_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000792 RECORD(SM_SLOC_FILE_ENTRY);
793 RECORD(SM_SLOC_BUFFER_ENTRY);
794 RECORD(SM_SLOC_BUFFER_BLOB);
Richard Smithaada85c2016-02-06 02:06:43 +0000795 RECORD(SM_SLOC_BUFFER_BLOB_COMPRESSED);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +0000796 RECORD(SM_SLOC_EXPANSION_ENTRY);
Mike Stump11289f42009-09-09 15:08:12 +0000797
Chris Lattner28fa4e62009-04-26 22:26:21 +0000798 // Preprocessor Block.
Chris Lattner64031982009-04-27 00:40:25 +0000799 BLOCK(PREPROCESSOR_BLOCK);
Richard Smithec216502015-02-13 19:48:37 +0000800 RECORD(PP_MACRO_DIRECTIVE_HISTORY);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000801 RECORD(PP_MACRO_FUNCTION_LIKE);
Richard Smithd7329392015-04-21 21:46:32 +0000802 RECORD(PP_MACRO_OBJECT_LIKE);
803 RECORD(PP_MODULE_MACRO);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000804 RECORD(PP_TOKEN);
Richard Smithec216502015-02-13 19:48:37 +0000805
Richard Smithfa715652015-08-31 22:43:10 +0000806 // Submodule Block.
807 BLOCK(SUBMODULE_BLOCK);
808 RECORD(SUBMODULE_METADATA);
809 RECORD(SUBMODULE_DEFINITION);
810 RECORD(SUBMODULE_UMBRELLA_HEADER);
811 RECORD(SUBMODULE_HEADER);
812 RECORD(SUBMODULE_TOPHEADER);
813 RECORD(SUBMODULE_UMBRELLA_DIR);
814 RECORD(SUBMODULE_IMPORTS);
815 RECORD(SUBMODULE_EXPORTS);
816 RECORD(SUBMODULE_REQUIRES);
817 RECORD(SUBMODULE_EXCLUDED_HEADER);
818 RECORD(SUBMODULE_LINK_LIBRARY);
819 RECORD(SUBMODULE_CONFIG_MACRO);
820 RECORD(SUBMODULE_CONFLICT);
821 RECORD(SUBMODULE_PRIVATE_HEADER);
822 RECORD(SUBMODULE_TEXTUAL_HEADER);
823 RECORD(SUBMODULE_PRIVATE_TEXTUAL_HEADER);
Richard Smithdc1f0422016-07-20 19:10:16 +0000824 RECORD(SUBMODULE_INITIALIZERS);
Douglas Gregorf0b11de2017-09-14 23:38:44 +0000825 RECORD(SUBMODULE_EXPORT_AS);
Richard Smithfa715652015-08-31 22:43:10 +0000826
827 // Comments Block.
828 BLOCK(COMMENTS_BLOCK);
829 RECORD(COMMENTS_RAW_COMMENT);
830
Douglas Gregor12bfa382009-10-17 00:13:19 +0000831 // Decls and Types block.
832 BLOCK(DECLTYPES_BLOCK);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000833 RECORD(TYPE_EXT_QUAL);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000834 RECORD(TYPE_COMPLEX);
835 RECORD(TYPE_POINTER);
836 RECORD(TYPE_BLOCK_POINTER);
837 RECORD(TYPE_LVALUE_REFERENCE);
838 RECORD(TYPE_RVALUE_REFERENCE);
839 RECORD(TYPE_MEMBER_POINTER);
840 RECORD(TYPE_CONSTANT_ARRAY);
841 RECORD(TYPE_INCOMPLETE_ARRAY);
842 RECORD(TYPE_VARIABLE_ARRAY);
843 RECORD(TYPE_VECTOR);
844 RECORD(TYPE_EXT_VECTOR);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000845 RECORD(TYPE_FUNCTION_NO_PROTO);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000846 RECORD(TYPE_FUNCTION_PROTO);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000847 RECORD(TYPE_TYPEDEF);
848 RECORD(TYPE_TYPEOF_EXPR);
849 RECORD(TYPE_TYPEOF);
850 RECORD(TYPE_RECORD);
851 RECORD(TYPE_ENUM);
852 RECORD(TYPE_OBJC_INTERFACE);
Steve Narofffb4330f2009-06-17 22:40:22 +0000853 RECORD(TYPE_OBJC_OBJECT_POINTER);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000854 RECORD(TYPE_DECLTYPE);
855 RECORD(TYPE_ELABORATED);
856 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
857 RECORD(TYPE_UNRESOLVED_USING);
858 RECORD(TYPE_INJECTED_CLASS_NAME);
859 RECORD(TYPE_OBJC_OBJECT);
860 RECORD(TYPE_TEMPLATE_TYPE_PARM);
861 RECORD(TYPE_TEMPLATE_SPECIALIZATION);
862 RECORD(TYPE_DEPENDENT_NAME);
863 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
864 RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
865 RECORD(TYPE_PAREN);
Leonard Chanc72aaf62019-05-07 03:20:17 +0000866 RECORD(TYPE_MACRO_QUALIFIED);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000867 RECORD(TYPE_PACK_EXPANSION);
868 RECORD(TYPE_ATTRIBUTED);
869 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000870 RECORD(TYPE_AUTO);
871 RECORD(TYPE_UNARY_TRANSFORM);
Eli Friedman0dfb8892011-10-06 23:00:33 +0000872 RECORD(TYPE_ATOMIC);
Richard Smithf1b4b8b2014-07-27 04:29:04 +0000873 RECORD(TYPE_DECAYED);
874 RECORD(TYPE_ADJUSTED);
Manman Rene6be26c2016-09-13 17:25:08 +0000875 RECORD(TYPE_OBJC_TYPE_PARAM);
Richard Smithd61d4ac2015-08-22 20:13:39 +0000876 RECORD(LOCAL_REDECLARATIONS);
Chris Lattnerdb397b62009-04-26 22:32:16 +0000877 RECORD(DECL_TYPEDEF);
Richard Smith01b2cb42014-07-26 06:37:51 +0000878 RECORD(DECL_TYPEALIAS);
Chris Lattnerdb397b62009-04-26 22:32:16 +0000879 RECORD(DECL_ENUM);
880 RECORD(DECL_RECORD);
881 RECORD(DECL_ENUM_CONSTANT);
882 RECORD(DECL_FUNCTION);
883 RECORD(DECL_OBJC_METHOD);
884 RECORD(DECL_OBJC_INTERFACE);
885 RECORD(DECL_OBJC_PROTOCOL);
886 RECORD(DECL_OBJC_IVAR);
887 RECORD(DECL_OBJC_AT_DEFS_FIELD);
Chris Lattnerdb397b62009-04-26 22:32:16 +0000888 RECORD(DECL_OBJC_CATEGORY);
889 RECORD(DECL_OBJC_CATEGORY_IMPL);
890 RECORD(DECL_OBJC_IMPLEMENTATION);
891 RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
892 RECORD(DECL_OBJC_PROPERTY);
893 RECORD(DECL_OBJC_PROPERTY_IMPL);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000894 RECORD(DECL_FIELD);
John McCall5e77d762013-04-16 07:28:30 +0000895 RECORD(DECL_MS_PROPERTY);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000896 RECORD(DECL_VAR);
Chris Lattnerdb397b62009-04-26 22:32:16 +0000897 RECORD(DECL_IMPLICIT_PARAM);
Chris Lattner28fa4e62009-04-26 22:26:21 +0000898 RECORD(DECL_PARM_VAR);
Chris Lattnerdb397b62009-04-26 22:32:16 +0000899 RECORD(DECL_FILE_SCOPE_ASM);
900 RECORD(DECL_BLOCK);
901 RECORD(DECL_CONTEXT_LEXICAL);
902 RECORD(DECL_CONTEXT_VISIBLE);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000903 RECORD(DECL_NAMESPACE);
904 RECORD(DECL_NAMESPACE_ALIAS);
905 RECORD(DECL_USING);
906 RECORD(DECL_USING_SHADOW);
907 RECORD(DECL_USING_DIRECTIVE);
908 RECORD(DECL_UNRESOLVED_USING_VALUE);
909 RECORD(DECL_UNRESOLVED_USING_TYPENAME);
910 RECORD(DECL_LINKAGE_SPEC);
911 RECORD(DECL_CXX_RECORD);
912 RECORD(DECL_CXX_METHOD);
913 RECORD(DECL_CXX_CONSTRUCTOR);
914 RECORD(DECL_CXX_DESTRUCTOR);
915 RECORD(DECL_CXX_CONVERSION);
916 RECORD(DECL_ACCESS_SPEC);
917 RECORD(DECL_FRIEND);
918 RECORD(DECL_FRIEND_TEMPLATE);
919 RECORD(DECL_CLASS_TEMPLATE);
920 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
921 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000922 RECORD(DECL_VAR_TEMPLATE);
923 RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
924 RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000925 RECORD(DECL_FUNCTION_TEMPLATE);
926 RECORD(DECL_TEMPLATE_TYPE_PARM);
927 RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
928 RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
Saar Razd7aae332019-07-10 21:25:49 +0000929 RECORD(DECL_CONCEPT);
Saar Raza0f50d72020-01-18 09:11:43 +0200930 RECORD(DECL_REQUIRES_EXPR_BODY);
Richard Smithefc884a2016-04-13 07:41:35 +0000931 RECORD(DECL_TYPE_ALIAS_TEMPLATE);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000932 RECORD(DECL_STATIC_ASSERT);
933 RECORD(DECL_CXX_BASE_SPECIFIERS);
Richard Smithefc884a2016-04-13 07:41:35 +0000934 RECORD(DECL_CXX_CTOR_INITIALIZERS);
Douglas Gregor0beaec02011-02-08 16:34:17 +0000935 RECORD(DECL_INDIRECTFIELD);
936 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
Richard Smithefc884a2016-04-13 07:41:35 +0000937 RECORD(DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK);
938 RECORD(DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION);
939 RECORD(DECL_IMPORT);
940 RECORD(DECL_OMP_THREADPRIVATE);
941 RECORD(DECL_EMPTY);
942 RECORD(DECL_OBJC_TYPE_PARAM);
943 RECORD(DECL_OMP_CAPTUREDEXPR);
944 RECORD(DECL_PRAGMA_COMMENT);
945 RECORD(DECL_PRAGMA_DETECT_MISMATCH);
946 RECORD(DECL_OMP_DECLARE_REDUCTION);
Alexey Bataev25ed0c02019-03-07 17:54:44 +0000947 RECORD(DECL_OMP_ALLOCATE);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000948
Douglas Gregor03412ba2011-06-03 02:27:19 +0000949 // Statements and Exprs can occur in the Decls and Types block.
950 AddStmtsExprs(Stream, Record);
951
Douglas Gregor92a96f52011-02-08 21:58:10 +0000952 BLOCK(PREPROCESSOR_DETAIL_BLOCK);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +0000953 RECORD(PPD_MACRO_EXPANSION);
Douglas Gregor92a96f52011-02-08 21:58:10 +0000954 RECORD(PPD_MACRO_DEFINITION);
955 RECORD(PPD_INCLUSION_DIRECTIVE);
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000956
957 // Decls and Types block.
958 BLOCK(EXTENSION_BLOCK);
959 RECORD(EXTENSION_METADATA);
960
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +0000961 BLOCK(UNHASHED_CONTROL_BLOCK);
962 RECORD(SIGNATURE);
963 RECORD(DIAGNOSTIC_OPTIONS);
964 RECORD(DIAG_PRAGMA_MAPPINGS);
965
Chris Lattner28fa4e62009-04-26 22:26:21 +0000966#undef RECORD
967#undef BLOCK
968 Stream.ExitBlock();
969}
970
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000971/// Prepares a path for being written to an AST file by converting it
Richard Smith54cc3c22014-12-11 20:50:24 +0000972/// to an absolute path and removing nested './'s.
973///
974/// \return \c true if the path was changed.
Benjamin Kramer6a96ae52015-02-06 18:36:04 +0000975static bool cleanPathForOutput(FileManager &FileMgr,
976 SmallVectorImpl<char> &Path) {
Argyrios Kyrtzidis403cbcb2015-07-31 01:39:23 +0000977 bool Changed = FileMgr.makeAbsolutePath(Path);
Mike Aizatskyaeb9dd92015-11-09 19:12:18 +0000978 return Changed | llvm::sys::path::remove_dots(Path);
Richard Smith54cc3c22014-12-11 20:50:24 +0000979}
980
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000981/// Adjusts the given filename to only write out the portion of the
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000982/// filename that is not part of the system root directory.
Mike Stump11289f42009-09-09 15:08:12 +0000983///
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000984/// \param Filename the file name to adjust.
985///
Richard Smith7ed1bc92014-12-05 22:42:13 +0000986/// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
987/// the returned filename will be adjusted by this root directory.
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000988///
989/// \returns either the original filename (if it needs no adjustment) or the
990/// adjusted filename (which points into the @p Filename parameter).
Mike Stump11289f42009-09-09 15:08:12 +0000991static const char *
Richard Smith7ed1bc92014-12-05 22:42:13 +0000992adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000993 assert(Filename && "No file name to adjust?");
Mike Stump11289f42009-09-09 15:08:12 +0000994
Richard Smith7ed1bc92014-12-05 22:42:13 +0000995 if (BaseDir.empty())
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000996 return Filename;
Mike Stump11289f42009-09-09 15:08:12 +0000997
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000998 // Verify that the filename and the system root have the same prefix.
999 unsigned Pos = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001000 for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
1001 if (Filename[Pos] != BaseDir[Pos])
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001002 return Filename; // Prefixes don't match.
Mike Stump11289f42009-09-09 15:08:12 +00001003
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001004 // We hit the end of the filename before we hit the end of the system root.
1005 if (!Filename[Pos])
1006 return Filename;
Mike Stump11289f42009-09-09 15:08:12 +00001007
Richard Smith7ed1bc92014-12-05 22:42:13 +00001008 // If there's not a path separator at the end of the base directory nor
1009 // immediately after it, then this isn't within the base directory.
1010 if (!llvm::sys::path::is_separator(Filename[Pos])) {
1011 if (!llvm::sys::path::is_separator(BaseDir.back()))
1012 return Filename;
1013 } else {
1014 // If the file name has a '/' at the current position, skip over the '/'.
1015 // We distinguish relative paths from absolute paths by the
1016 // absence of '/' at the beginning of relative paths.
1017 //
1018 // FIXME: This is wrong. We distinguish them by asking if the path is
1019 // absolute, which isn't the same thing. And there might be multiple '/'s
1020 // in a row. Use a better mechanism to indicate whether we have emitted an
1021 // absolute or relative path.
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001022 ++Pos;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001023 }
Mike Stump11289f42009-09-09 15:08:12 +00001024
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001025 return Filename + Pos;
1026}
Chris Lattner28fa4e62009-04-26 22:26:21 +00001027
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001028ASTFileSignature ASTWriter::createSignature(StringRef Bytes) {
1029 // Calculate the hash till start of UNHASHED_CONTROL_BLOCK.
1030 llvm::SHA1 Hasher;
1031 Hasher.update(ArrayRef<uint8_t>(Bytes.bytes_begin(), Bytes.size()));
1032 auto Hash = Hasher.result();
1033
1034 // Convert to an array [5*i32].
1035 ASTFileSignature Signature;
1036 auto LShift = [&](unsigned char Val, unsigned Shift) {
1037 return (uint32_t)Val << Shift;
1038 };
1039 for (int I = 0; I != 5; ++I)
1040 Signature[I] = LShift(Hash[I * 4 + 0], 24) | LShift(Hash[I * 4 + 1], 16) |
1041 LShift(Hash[I * 4 + 2], 8) | LShift(Hash[I * 4 + 3], 0);
1042
1043 return Signature;
1044}
1045
1046ASTFileSignature ASTWriter::writeUnhashedControlBlock(Preprocessor &PP,
1047 ASTContext &Context) {
1048 // Flush first to prepare the PCM hash (signature).
1049 Stream.FlushToWord();
1050 auto StartOfUnhashedControl = Stream.GetCurrentBitNo() >> 3;
1051
1052 // Enter the block and prepare to write records.
1053 RecordData Record;
1054 Stream.EnterSubblock(UNHASHED_CONTROL_BLOCK_ID, 5);
1055
1056 // For implicit modules, write the hash of the PCM as its signature.
1057 ASTFileSignature Signature;
1058 if (WritingModule &&
1059 PP.getHeaderSearchInfo().getHeaderSearchOpts().ModulesHashContent) {
1060 Signature = createSignature(StringRef(Buffer.begin(), StartOfUnhashedControl));
1061 Record.append(Signature.begin(), Signature.end());
1062 Stream.EmitRecord(SIGNATURE, Record);
1063 Record.clear();
Ben Langmuir487ea142014-10-23 18:05:36 +00001064 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001065
1066 // Diagnostic options.
1067 const auto &Diags = Context.getDiagnostics();
1068 const DiagnosticOptions &DiagOpts = Diags.getDiagnosticOptions();
1069#define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1070#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1071 Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1072#include "clang/Basic/DiagnosticOptions.def"
1073 Record.push_back(DiagOpts.Warnings.size());
1074 for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1075 AddString(DiagOpts.Warnings[I], Record);
1076 Record.push_back(DiagOpts.Remarks.size());
1077 for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1078 AddString(DiagOpts.Remarks[I], Record);
1079 // Note: we don't serialize the log or serialization file names, because they
1080 // are generally transient files and will almost always be overridden.
1081 Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1082
1083 // Write out the diagnostic/pragma mappings.
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001084 WritePragmaDiagnosticMappings(Diags, /* isModule = */ WritingModule);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001085
1086 // Leave the options block.
1087 Stream.ExitBlock();
1088 return Signature;
Ben Langmuir487ea142014-10-23 18:05:36 +00001089}
1090
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001091/// Write the control block.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001092void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context,
1093 StringRef isysroot,
1094 const std::string &OutputFile) {
Douglas Gregorbfbde532009-04-10 21:16:55 +00001095 using namespace llvm;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001096
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001097 Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001098 RecordData Record;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001099
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001100 // Metadata
David Blaikieb44f0bf2017-01-04 22:36:43 +00001101 auto MetadataAbbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001102 MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1103 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1104 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1105 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1106 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1107 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
Richard Smithe75ee0f2015-08-17 07:13:32 +00001108 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00001109 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // PCHHasObjectFile
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001110 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1111 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
David Blaikieb44f0bf2017-01-04 22:36:43 +00001112 unsigned MetadataAbbrevCode = Stream.EmitAbbrev(std::move(MetadataAbbrev));
Richard Smith7ed1bc92014-12-05 22:42:13 +00001113 assert((!WritingModule || isysroot.empty()) &&
1114 "writing module as a relocatable PCH?");
Mehdi Amini57a41912015-09-10 01:46:39 +00001115 {
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00001116 RecordData::value_type Record[] = {
1117 METADATA,
1118 VERSION_MAJOR,
1119 VERSION_MINOR,
1120 CLANG_VERSION_MAJOR,
1121 CLANG_VERSION_MINOR,
1122 !isysroot.empty(),
1123 IncludeTimestamps,
1124 Context.getLangOpts().BuildingPCHWithObjectFile,
1125 ASTHasCompilerErrors};
Mehdi Amini57a41912015-09-10 01:46:39 +00001126 Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1127 getClangFullRepositoryVersion());
1128 }
Chandler Carruth885e78c2015-03-24 21:18:10 +00001129
Richard Smith8b706102017-05-31 20:56:55 +00001130 if (WritingModule) {
Richard Smith7ed1bc92014-12-05 22:42:13 +00001131 // Module name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001132 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001133 Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1134 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001135 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00001136 RecordData::value_type Record[] = {MODULE_NAME};
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001137 Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1138 }
1139
Richard Smith7ed1bc92014-12-05 22:42:13 +00001140 if (WritingModule && WritingModule->Directory) {
Richard Smith7ed1bc92014-12-05 22:42:13 +00001141 SmallString<128> BaseDir(WritingModule->Directory->getName());
Richard Smith54cc3c22014-12-11 20:50:24 +00001142 cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
Richard Smithf7b41372015-08-13 23:47:44 +00001143
1144 // If the home of the module is the current working directory, then we
1145 // want to pick up the cwd of the build process loading the module, not
1146 // our cwd, when we load this module.
1147 if (!PP.getHeaderSearchInfo()
1148 .getHeaderSearchOpts()
1149 .ModuleMapFileHomeIsCwd ||
1150 WritingModule->Directory->getName() != StringRef(".")) {
1151 // Module directory.
David Blaikieb44f0bf2017-01-04 22:36:43 +00001152 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Richard Smithf7b41372015-08-13 23:47:44 +00001153 Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1154 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
David Blaikieb44f0bf2017-01-04 22:36:43 +00001155 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
Richard Smithf7b41372015-08-13 23:47:44 +00001156
Mehdi Amini57a41912015-09-10 01:46:39 +00001157 RecordData::value_type Record[] = {MODULE_DIRECTORY};
Richard Smithf7b41372015-08-13 23:47:44 +00001158 Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
1159 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001160
1161 // Write out all other paths relative to the base directory if possible.
1162 BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1163 } else if (!isysroot.empty()) {
1164 // Write out paths relative to the sysroot if possible.
Benjamin Krameradcd0262020-01-28 20:23:46 +01001165 BaseDirectory = std::string(isysroot);
Richard Smith7ed1bc92014-12-05 22:42:13 +00001166 }
1167
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001168 // Module map file
Richard Smithd19389a2017-07-05 07:47:11 +00001169 if (WritingModule && WritingModule->Kind == Module::ModuleMapModule) {
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001170 Record.clear();
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001171
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001172 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
Richard Smith8b706102017-05-31 20:56:55 +00001173 AddPath(WritingModule->PresumedModuleMapFile.empty()
1174 ? Map.getModuleMapFileForUniquing(WritingModule)->getName()
1175 : StringRef(WritingModule->PresumedModuleMapFile),
1176 Record);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001177
1178 // Additional module map files.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001179 if (auto *AdditionalModMaps =
1180 Map.getAdditionalModuleMapFiles(WritingModule)) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001181 Record.push_back(AdditionalModMaps->size());
1182 for (const FileEntry *F : *AdditionalModMaps)
Richard Smith7ed1bc92014-12-05 22:42:13 +00001183 AddPath(F->getName(), Record);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00001184 } else {
1185 Record.push_back(0);
1186 }
1187
1188 Stream.EmitRecord(MODULE_MAP_FILE, Record);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001189 }
1190
Douglas Gregor112b9072012-10-18 05:31:06 +00001191 // Imports
Douglas Gregor29cc6422011-08-17 21:07:30 +00001192 if (Chain) {
Douglas Gregor29cc6422011-08-17 21:07:30 +00001193 serialization::ModuleManager &Mgr = Chain->getModuleManager();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001194 Record.clear();
Douglas Gregordf0c1512011-08-18 04:12:04 +00001195
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001196 for (ModuleFile &M : Mgr) {
Douglas Gregordf0c1512011-08-18 04:12:04 +00001197 // Skip modules that weren't directly imported.
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001198 if (!M.isDirectlyImported())
Douglas Gregordf0c1512011-08-18 04:12:04 +00001199 continue;
1200
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001201 Record.push_back((unsigned)M.Kind); // FIXME: Stable encoding
1202 AddSourceLocation(M.ImportLoc, Record);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00001203
1204 // If we have calculated signature, there is no need to store
1205 // the size or timestamp.
1206 Record.push_back(M.Signature ? 0 : M.File->getSize());
1207 Record.push_back(M.Signature ? 0 : getTimestampForOutput(M.File));
1208
1209 for (auto I : M.Signature)
1210 Record.push_back(I);
1211
Boris Kolpackovd30446f2017-08-31 06:26:43 +00001212 AddString(M.ModuleName, Record);
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001213 AddPath(M.FileName, Record);
Douglas Gregordf0c1512011-08-18 04:12:04 +00001214 }
Douglas Gregor29cc6422011-08-17 21:07:30 +00001215 Stream.EmitRecord(IMPORTS, Record);
1216 }
Mike Stump11289f42009-09-09 15:08:12 +00001217
Richard Smith0516b182015-09-08 19:40:14 +00001218 // Write the options block.
1219 Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
1220
Douglas Gregor112b9072012-10-18 05:31:06 +00001221 // Language options.
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001222 Record.clear();
Douglas Gregor112b9072012-10-18 05:31:06 +00001223 const LangOptions &LangOpts = Context.getLangOpts();
1224#define LANGOPT(Name, Bits, Default, Description) \
1225 Record.push_back(LangOpts.Name);
1226#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1227 Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001228#include "clang/Basic/LangOptions.def"
1229#define SANITIZER(NAME, ID) \
1230 Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
Will Dietzf54319c2013-01-18 11:30:38 +00001231#include "clang/Basic/Sanitizers.def"
Douglas Gregor112b9072012-10-18 05:31:06 +00001232
Ben Langmuircd98cb72015-06-23 18:20:18 +00001233 Record.push_back(LangOpts.ModuleFeatures.size());
1234 for (StringRef Feature : LangOpts.ModuleFeatures)
1235 AddString(Feature, Record);
1236
Douglas Gregor112b9072012-10-18 05:31:06 +00001237 Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1238 AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
Ben Langmuird4a667a2015-06-23 18:20:23 +00001239
1240 AddString(LangOpts.CurrentModule, Record);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001241
1242 // Comment options.
1243 Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001244 for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1245 AddString(I, Record);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001246 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00001247 Record.push_back(LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00001248
Samuel Antaoee8fb302016-01-06 13:42:12 +00001249 // OpenMP offloading options.
1250 Record.push_back(LangOpts.OMPTargetTriples.size());
1251 for (auto &T : LangOpts.OMPTargetTriples)
1252 AddString(T.getTriple(), Record);
1253
1254 AddString(LangOpts.OMPHostIRFile, Record);
1255
Douglas Gregor112b9072012-10-18 05:31:06 +00001256 Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1257
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001258 // Target options.
1259 Record.clear();
Douglas Gregor0aa21c92012-10-18 18:27:37 +00001260 const TargetInfo &Target = Context.getTargetInfo();
1261 const TargetOptions &TargetOpts = Target.getTargetOpts();
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001262 AddString(TargetOpts.Triple, Record);
1263 AddString(TargetOpts.CPU, Record);
1264 AddString(TargetOpts.ABI, Record);
Douglas Gregor4d3611c2012-10-18 17:58:09 +00001265 Record.push_back(TargetOpts.FeaturesAsWritten.size());
1266 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1267 AddString(TargetOpts.FeaturesAsWritten[I], Record);
1268 }
1269 Record.push_back(TargetOpts.Features.size());
1270 for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1271 AddString(TargetOpts.Features[I], Record);
1272 }
1273 Stream.EmitRecord(TARGET_OPTIONS, Record);
1274
Douglas Gregorc6317db2012-10-24 15:49:58 +00001275 // File system options.
1276 Record.clear();
Yaron Keren8dec46c2015-08-26 08:10:22 +00001277 const FileSystemOptions &FSOpts =
1278 Context.getSourceManager().getFileManager().getFileSystemOpts();
Douglas Gregorc6317db2012-10-24 15:49:58 +00001279 AddString(FSOpts.WorkingDir, Record);
1280 Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1281
Douglas Gregor2d302362012-10-24 16:50:34 +00001282 // Header search options.
1283 Record.clear();
1284 const HeaderSearchOptions &HSOpts
1285 = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1286 AddString(HSOpts.Sysroot, Record);
1287
1288 // Include entries.
1289 Record.push_back(HSOpts.UserEntries.size());
1290 for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1291 const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1292 AddString(Entry.Path, Record);
1293 Record.push_back(static_cast<unsigned>(Entry.Group));
Douglas Gregor2d302362012-10-24 16:50:34 +00001294 Record.push_back(Entry.IsFramework);
1295 Record.push_back(Entry.IgnoreSysRoot);
Douglas Gregor2d302362012-10-24 16:50:34 +00001296 }
1297
1298 // System header prefixes.
1299 Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1300 for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1301 AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1302 Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1303 }
1304
1305 AddString(HSOpts.ResourceDir, Record);
1306 AddString(HSOpts.ModuleCachePath, Record);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00001307 AddString(HSOpts.ModuleUserBuildPath, Record);
Douglas Gregor2d302362012-10-24 16:50:34 +00001308 Record.push_back(HSOpts.DisableModuleHash);
Richard Smith18934752017-06-06 00:32:01 +00001309 Record.push_back(HSOpts.ImplicitModuleMaps);
1310 Record.push_back(HSOpts.ModuleMapFileHomeIsCwd);
Douglas Gregor2d302362012-10-24 16:50:34 +00001311 Record.push_back(HSOpts.UseBuiltinIncludes);
1312 Record.push_back(HSOpts.UseStandardSystemIncludes);
1313 Record.push_back(HSOpts.UseStandardCXXIncludes);
1314 Record.push_back(HSOpts.UseLibcxx);
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00001315 // Write out the specific module cache path that contains the module files.
1316 AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
Douglas Gregor2d302362012-10-24 16:50:34 +00001317 Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1318
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001319 // Preprocessor options.
1320 Record.clear();
1321 const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1322
1323 // Macro definitions.
1324 Record.push_back(PPOpts.Macros.size());
1325 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1326 AddString(PPOpts.Macros[I].first, Record);
1327 Record.push_back(PPOpts.Macros[I].second);
1328 }
1329
1330 // Includes
1331 Record.push_back(PPOpts.Includes.size());
1332 for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1333 AddString(PPOpts.Includes[I], Record);
1334
1335 // Macro includes
1336 Record.push_back(PPOpts.MacroIncludes.size());
1337 for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1338 AddString(PPOpts.MacroIncludes[I], Record);
1339
Douglas Gregorb6368752012-10-24 23:41:50 +00001340 Record.push_back(PPOpts.UsePredefines);
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00001341 // Detailed record is important since it is used for the module cache hash.
1342 Record.push_back(PPOpts.DetailedRecord);
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001343 AddString(PPOpts.ImplicitPCHInclude, Record);
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001344 Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1345 Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1346
Richard Smith0516b182015-09-08 19:40:14 +00001347 // Leave the options block.
1348 Stream.ExitBlock();
1349
Douglas Gregora3b20262011-05-06 21:43:30 +00001350 // Original file name and file ID
Douglas Gregor45fe0362009-05-12 01:31:05 +00001351 SourceManager &SM = Context.getSourceManager();
1352 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
David Blaikieb44f0bf2017-01-04 22:36:43 +00001353 auto FileAbbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregorfad10d82012-10-18 18:36:53 +00001354 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1355 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
Douglas Gregor45fe0362009-05-12 01:31:05 +00001356 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001357 unsigned FileAbbrevCode = Stream.EmitAbbrev(std::move(FileAbbrev));
Douglas Gregor45fe0362009-05-12 01:31:05 +00001358
Douglas Gregorb6af6c22012-10-24 20:05:57 +00001359 Record.clear();
Douglas Gregorfad10d82012-10-18 18:36:53 +00001360 Record.push_back(ORIGINAL_FILE);
Douglas Gregora3b20262011-05-06 21:43:30 +00001361 Record.push_back(SM.getMainFileID().getOpaqueValue());
Richard Smith7ed1bc92014-12-05 22:42:13 +00001362 EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
Douglas Gregor45fe0362009-05-12 01:31:05 +00001363 }
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00001364
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +00001365 Record.clear();
1366 Record.push_back(SM.getMainFileID().getOpaqueValue());
1367 Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1368
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001369 // Original PCH directory
1370 if (!OutputFile.empty() && OutputFile != "-") {
David Blaikieb44f0bf2017-01-04 22:36:43 +00001371 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001372 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1373 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001374 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001375
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001376 SmallString<128> OutputPath(OutputFile);
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001377
Argyrios Kyrtzidisc56419e2015-07-31 00:58:32 +00001378 SM.getFileManager().makeAbsolutePath(OutputPath);
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001379 StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1380
Mehdi Amini57a41912015-09-10 01:46:39 +00001381 RecordData::value_type Record[] = {ORIGINAL_PCH_DIR};
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00001382 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1383 }
1384
Douglas Gregor49491f72013-03-15 22:15:07 +00001385 WriteInputFiles(Context.SourceMgr,
1386 PP.getHeaderSearchInfo().getHeaderSearchOpts(),
Douglas Gregora3dd9002013-07-22 20:48:33 +00001387 PP.getLangOpts().Modules);
Douglas Gregor72be3902012-10-19 00:38:02 +00001388 Stream.ExitBlock();
1389}
1390
Douglas Gregor49491f72013-03-15 22:15:07 +00001391namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001392
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001393/// An input file.
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001394struct InputFileEntry {
1395 const FileEntry *File;
1396 bool IsSystemFile;
1397 bool IsTransient;
1398 bool BufferOverridden;
1399 bool IsTopLevelModuleMap;
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00001400 uint32_t ContentHash[2];
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001401};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001402
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001403} // namespace
Douglas Gregor49491f72013-03-15 22:15:07 +00001404
1405void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1406 HeaderSearchOptions &HSOpts,
Douglas Gregora3dd9002013-07-22 20:48:33 +00001407 bool Modules) {
Douglas Gregor72be3902012-10-19 00:38:02 +00001408 using namespace llvm;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001409
Douglas Gregor72be3902012-10-19 00:38:02 +00001410 Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
Mehdi Amini57a41912015-09-10 01:46:39 +00001411
Douglas Gregor72be3902012-10-19 00:38:02 +00001412 // Create input-file abbreviation.
David Blaikieb44f0bf2017-01-04 22:36:43 +00001413 auto IFAbbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor72be3902012-10-19 00:38:02 +00001414 IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001415 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
Douglas Gregor72be3902012-10-19 00:38:02 +00001416 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1417 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001418 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
Richard Smitha8cfffa2015-11-26 02:04:16 +00001419 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
Richard Smithf3f84612017-06-29 02:19:42 +00001420 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Module map
Douglas Gregor72be3902012-10-19 00:38:02 +00001421 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
David Blaikieb44f0bf2017-01-04 22:36:43 +00001422 unsigned IFAbbrevCode = Stream.EmitAbbrev(std::move(IFAbbrev));
Douglas Gregor72be3902012-10-19 00:38:02 +00001423
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00001424 // Create input file hash abbreviation.
1425 auto IFHAbbrev = std::make_shared<BitCodeAbbrev>();
1426 IFHAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_HASH));
1427 IFHAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1428 IFHAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1429 unsigned IFHAbbrevCode = Stream.EmitAbbrev(std::move(IFHAbbrev));
1430
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001431 // Get all ContentCache objects for files, sorted by whether the file is a
1432 // system one or not. System files go at the back, users files at the front.
Douglas Gregor49491f72013-03-15 22:15:07 +00001433 std::deque<InputFileEntry> SortedFiles;
Douglas Gregor72be3902012-10-19 00:38:02 +00001434 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1435 // Get this source location entry.
1436 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
NAKAMURA Takumideca50f2012-10-19 01:53:57 +00001437 assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
Douglas Gregor72be3902012-10-19 00:38:02 +00001438
1439 // We only care about file entries that were not overridden.
1440 if (!SLoc->isFile())
1441 continue;
Richard Smithf3f84612017-06-29 02:19:42 +00001442 const SrcMgr::FileInfo &File = SLoc->getFile();
1443 const SrcMgr::ContentCache *Cache = File.getContentCache();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001444 if (!Cache->OrigEntry)
Douglas Gregor72be3902012-10-19 00:38:02 +00001445 continue;
1446
Douglas Gregor49491f72013-03-15 22:15:07 +00001447 InputFileEntry Entry;
1448 Entry.File = Cache->OrigEntry;
Duncan P. N. Exon Smithf5848192019-08-26 20:32:05 +00001449 Entry.IsSystemFile = isSystem(File.getFileCharacteristic());
Richard Smitha8cfffa2015-11-26 02:04:16 +00001450 Entry.IsTransient = Cache->IsTransient;
Douglas Gregor49491f72013-03-15 22:15:07 +00001451 Entry.BufferOverridden = Cache->BufferOverridden;
Richard Smithf3f84612017-06-29 02:19:42 +00001452 Entry.IsTopLevelModuleMap = isModuleMap(File.getFileCharacteristic()) &&
1453 File.getIncludeLoc().isInvalid();
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00001454
1455 auto ContentHash = hash_code(-1);
1456 if (PP->getHeaderSearchInfo()
1457 .getHeaderSearchOpts()
1458 .ValidateASTInputFilesContent) {
1459 auto *MemBuff = Cache->getRawBuffer();
1460 if (MemBuff)
1461 ContentHash = hash_value(MemBuff->getBuffer());
1462 else
1463 // FIXME: The path should be taken from the FileEntryRef.
1464 PP->Diag(SourceLocation(), diag::err_module_unable_to_hash_content)
1465 << Entry.File->getName();
1466 }
1467 auto CH = llvm::APInt(64, ContentHash);
1468 Entry.ContentHash[0] =
1469 static_cast<uint32_t>(CH.getLoBits(32).getZExtValue());
1470 Entry.ContentHash[1] =
1471 static_cast<uint32_t>(CH.getHiBits(32).getZExtValue());
1472
Duncan P. N. Exon Smithf5848192019-08-26 20:32:05 +00001473 if (Entry.IsSystemFile)
Douglas Gregor49491f72013-03-15 22:15:07 +00001474 SortedFiles.push_back(Entry);
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001475 else
Douglas Gregor49491f72013-03-15 22:15:07 +00001476 SortedFiles.push_front(Entry);
1477 }
1478
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001479 unsigned UserFilesNum = 0;
1480 // Write out all of the input files.
Richard Smithec216502015-02-13 19:48:37 +00001481 std::vector<uint64_t> InputFileOffsets;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001482 for (const auto &Entry : SortedFiles) {
Douglas Gregor49491f72013-03-15 22:15:07 +00001483 uint32_t &InputFileID = InputFileIDs[Entry.File];
Argyrios Kyrtzidise65856f2012-12-11 07:48:08 +00001484 if (InputFileID != 0)
1485 continue; // already recorded this file.
1486
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001487 // Record this entry's offset.
1488 InputFileOffsets.push_back(Stream.GetCurrentBitNo());
Argyrios Kyrtzidise65856f2012-12-11 07:48:08 +00001489
1490 InputFileID = InputFileOffsets.size();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001491
Douglas Gregor49491f72013-03-15 22:15:07 +00001492 if (!Entry.IsSystemFile)
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001493 ++UserFilesNum;
1494
Douglas Gregor72be3902012-10-19 00:38:02 +00001495 // Emit size/modification time for this file.
Mehdi Amini57a41912015-09-10 01:46:39 +00001496 // And whether this file was overridden.
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00001497 {
1498 RecordData::value_type Record[] = {
1499 INPUT_FILE,
1500 InputFileOffsets.size(),
1501 (uint64_t)Entry.File->getSize(),
1502 (uint64_t)getTimestampForOutput(Entry.File),
1503 Entry.BufferOverridden,
1504 Entry.IsTransient,
1505 Entry.IsTopLevelModuleMap};
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001506
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00001507 // FIXME: The path should be taken from the FileEntryRef.
1508 EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
1509 }
1510
1511 // Emit content hash for this file.
1512 {
1513 RecordData::value_type Record[] = {INPUT_FILE_HASH, Entry.ContentHash[0],
1514 Entry.ContentHash[1]};
1515 Stream.EmitRecordWithAbbrev(IFHAbbrevCode, Record);
1516 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001517 }
Douglas Gregor49491f72013-03-15 22:15:07 +00001518
Douglas Gregor112b9072012-10-18 05:31:06 +00001519 Stream.ExitBlock();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001520
1521 // Create input file offsets abbreviation.
David Blaikieb44f0bf2017-01-04 22:36:43 +00001522 auto OffsetsAbbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001523 OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1524 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
Argyrios Kyrtzidis7d238572013-03-06 18:12:50 +00001525 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1526 // input files
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001527 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
David Blaikieb44f0bf2017-01-04 22:36:43 +00001528 unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(std::move(OffsetsAbbrev));
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001529
1530 // Write input file offsets.
Mehdi Amini57a41912015-09-10 01:46:39 +00001531 RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
1532 InputFileOffsets.size(), UserFilesNum};
Reid Kleckner012665e2015-05-21 00:13:09 +00001533 Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
Douglas Gregor55abb232009-04-10 20:39:37 +00001534}
1535
Douglas Gregora7f71a92009-04-10 03:52:48 +00001536//===----------------------------------------------------------------------===//
1537// Source Manager Serialization
1538//===----------------------------------------------------------------------===//
1539
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001540/// Create an abbreviation for the SLocEntry that refers to a
Douglas Gregora7f71a92009-04-10 03:52:48 +00001541/// file.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001542static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001543 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001544
David Blaikieb44f0bf2017-01-04 22:36:43 +00001545 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00001546 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001547 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1548 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
Richard Smithf3f84612017-06-29 02:19:42 +00001549 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
Douglas Gregora7f71a92009-04-10 03:52:48 +00001550 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
Douglas Gregorb41ca8f2010-03-21 22:49:54 +00001551 // FileEntry fields.
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001552 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001553 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00001554 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1555 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
David Blaikieb44f0bf2017-01-04 22:36:43 +00001556 return Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001557}
1558
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001559/// Create an abbreviation for the SLocEntry that refers to a
Douglas Gregora7f71a92009-04-10 03:52:48 +00001560/// buffer.
Douglas Gregor8f45df52009-04-16 22:23:12 +00001561static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001562 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001563
David Blaikieb44f0bf2017-01-04 22:36:43 +00001564 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00001565 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001566 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1567 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
Richard Smithf3f84612017-06-29 02:19:42 +00001568 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
Douglas Gregora7f71a92009-04-10 03:52:48 +00001569 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1570 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
David Blaikieb44f0bf2017-01-04 22:36:43 +00001571 return Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001572}
1573
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001574/// Create an abbreviation for the SLocEntry that refers to a
Douglas Gregora7f71a92009-04-10 03:52:48 +00001575/// buffer's blob.
Richard Smithaada85c2016-02-06 02:06:43 +00001576static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
1577 bool Compressed) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001578 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001579
David Blaikieb44f0bf2017-01-04 22:36:43 +00001580 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Richard Smithaada85c2016-02-06 02:06:43 +00001581 Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED
1582 : SM_SLOC_BUFFER_BLOB));
1583 if (Compressed)
1584 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
Douglas Gregora7f71a92009-04-10 03:52:48 +00001585 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
David Blaikieb44f0bf2017-01-04 22:36:43 +00001586 return Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001587}
1588
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001589/// Create an abbreviation for the SLocEntry that refers to a macro
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001590/// expansion.
1591static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
Douglas Gregora7f71a92009-04-10 03:52:48 +00001592 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001593
David Blaikieb44f0bf2017-01-04 22:36:43 +00001594 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001595 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001596 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1597 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1598 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1599 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
Richard Smithb5f81712018-04-30 05:25:48 +00001600 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Is token range
Douglas Gregor83243272009-04-15 18:05:10 +00001601 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
David Blaikieb44f0bf2017-01-04 22:36:43 +00001602 return Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregora7f71a92009-04-10 03:52:48 +00001603}
1604
Douglas Gregor09b69892011-02-10 17:09:37 +00001605namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001606
Douglas Gregor09b69892011-02-10 17:09:37 +00001607 // Trait used for the on-disk hash table of header search information.
1608 class HeaderFileInfoTrait {
1609 ASTWriter &Writer;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001610
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001611 // Keep track of the framework names we've used during serialization.
1612 SmallVector<char, 128> FrameworkStringData;
1613 llvm::StringMap<unsigned> FrameworkNameOffset;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001614
Douglas Gregor09b69892011-02-10 17:09:37 +00001615 public:
Richard Smith040e1262017-06-02 01:55:39 +00001616 HeaderFileInfoTrait(ASTWriter &Writer) : Writer(Writer) {}
1617
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001618 struct key_type {
Mehdi Amini004b9c72016-10-10 22:52:47 +00001619 StringRef Filename;
Richard Smith040e1262017-06-02 01:55:39 +00001620 off_t Size;
1621 time_t ModTime;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001622 };
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001623 using key_type_ref = const key_type &;
Richard Smith040e1262017-06-02 01:55:39 +00001624
1625 using UnresolvedModule =
1626 llvm::PointerIntPair<Module *, 2, ModuleMap::ModuleHeaderRole>;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001627
Richard Smith040e1262017-06-02 01:55:39 +00001628 struct data_type {
1629 const HeaderFileInfo &HFI;
1630 ArrayRef<ModuleMap::KnownHeader> KnownHeaders;
1631 UnresolvedModule Unresolved;
1632 };
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001633 using data_type_ref = const data_type &;
Richard Smith040e1262017-06-02 01:55:39 +00001634
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001635 using hash_value_type = unsigned;
1636 using offset_type = unsigned;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001637
Richard Smithe75ee0f2015-08-17 07:13:32 +00001638 hash_value_type ComputeHash(key_type_ref key) {
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001639 // The hash is based only on size/time of the file, so that the reader can
1640 // match even when symlinking or excess path elements ("foo/../", "../")
1641 // change the form of the name. However, complete path is still the key.
Richard Smith040e1262017-06-02 01:55:39 +00001642 return llvm::hash_combine(key.Size, key.ModTime);
Douglas Gregor09b69892011-02-10 17:09:37 +00001643 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001644
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001645 std::pair<unsigned, unsigned>
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001646 EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001647 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001648
Peter Collingbournee3f65292018-05-18 19:46:24 +00001649 endian::Writer LE(Out, little);
Mehdi Amini004b9c72016-10-10 22:52:47 +00001650 unsigned KeyLen = key.Filename.size() + 1 + 8 + 8;
Richard Smith386bb072015-08-18 23:42:23 +00001651 LE.write<uint16_t>(KeyLen);
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001652 unsigned DataLen = 1 + 2 + 4 + 4;
Richard Smith040e1262017-06-02 01:55:39 +00001653 for (auto ModInfo : Data.KnownHeaders)
Richard Smith386bb072015-08-18 23:42:23 +00001654 if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
1655 DataLen += 4;
Richard Smith040e1262017-06-02 01:55:39 +00001656 if (Data.Unresolved.getPointer())
1657 DataLen += 4;
Richard Smith386bb072015-08-18 23:42:23 +00001658 LE.write<uint8_t>(DataLen);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001659 return std::make_pair(KeyLen, DataLen);
Douglas Gregor09b69892011-02-10 17:09:37 +00001660 }
Richard Smith040e1262017-06-02 01:55:39 +00001661
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001662 void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001663 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001664
Peter Collingbournee3f65292018-05-18 19:46:24 +00001665 endian::Writer LE(Out, little);
Richard Smith040e1262017-06-02 01:55:39 +00001666 LE.write<uint64_t>(key.Size);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001667 KeyLen -= 8;
Richard Smith040e1262017-06-02 01:55:39 +00001668 LE.write<uint64_t>(key.ModTime);
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001669 KeyLen -= 8;
Mehdi Amini004b9c72016-10-10 22:52:47 +00001670 Out.write(key.Filename.data(), KeyLen);
Douglas Gregor09b69892011-02-10 17:09:37 +00001671 }
Richard Smith040e1262017-06-02 01:55:39 +00001672
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001673 void EmitData(raw_ostream &Out, key_type_ref key,
Douglas Gregor09b69892011-02-10 17:09:37 +00001674 data_type_ref Data, unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00001675 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001676
Peter Collingbournee3f65292018-05-18 19:46:24 +00001677 endian::Writer LE(Out, little);
Douglas Gregor09b69892011-02-10 17:09:37 +00001678 uint64_t Start = Out.tell(); (void)Start;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001679
Richard Smithf3f84612017-06-29 02:19:42 +00001680 unsigned char Flags = (Data.HFI.isImport << 5)
1681 | (Data.HFI.isPragmaOnce << 4)
Richard Smith040e1262017-06-02 01:55:39 +00001682 | (Data.HFI.DirInfo << 1)
1683 | Data.HFI.IndexHeaderMapHeader;
Justin Bognere1c147c2014-03-28 22:03:19 +00001684 LE.write<uint8_t>(Flags);
Richard Smith040e1262017-06-02 01:55:39 +00001685 LE.write<uint16_t>(Data.HFI.NumIncludes);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001686
Richard Smith040e1262017-06-02 01:55:39 +00001687 if (!Data.HFI.ControllingMacro)
1688 LE.write<uint32_t>(Data.HFI.ControllingMacroID);
Douglas Gregor09b69892011-02-10 17:09:37 +00001689 else
Richard Smith040e1262017-06-02 01:55:39 +00001690 LE.write<uint32_t>(Writer.getIdentifierRef(Data.HFI.ControllingMacro));
1691
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001692 unsigned Offset = 0;
Richard Smith040e1262017-06-02 01:55:39 +00001693 if (!Data.HFI.Framework.empty()) {
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001694 // If this header refers into a framework, save the framework name.
1695 llvm::StringMap<unsigned>::iterator Pos
Richard Smith040e1262017-06-02 01:55:39 +00001696 = FrameworkNameOffset.find(Data.HFI.Framework);
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001697 if (Pos == FrameworkNameOffset.end()) {
1698 Offset = FrameworkStringData.size() + 1;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001699 FrameworkStringData.append(Data.HFI.Framework.begin(),
Richard Smith040e1262017-06-02 01:55:39 +00001700 Data.HFI.Framework.end());
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001701 FrameworkStringData.push_back(0);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001702
Richard Smith040e1262017-06-02 01:55:39 +00001703 FrameworkNameOffset[Data.HFI.Framework] = Offset;
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001704 } else
1705 Offset = Pos->second;
1706 }
Justin Bognere1c147c2014-03-28 22:03:19 +00001707 LE.write<uint32_t>(Offset);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001708
Richard Smith040e1262017-06-02 01:55:39 +00001709 auto EmitModule = [&](Module *M, ModuleMap::ModuleHeaderRole Role) {
1710 if (uint32_t ModID = Writer.getLocalOrImportedSubmoduleID(M)) {
1711 uint32_t Value = (ModID << 2) | (unsigned)Role;
Richard Smith386bb072015-08-18 23:42:23 +00001712 assert((Value >> 2) == ModID && "overflow in header module info");
1713 LE.write<uint32_t>(Value);
1714 }
Richard Smith040e1262017-06-02 01:55:39 +00001715 };
1716
1717 // FIXME: If the header is excluded, we should write out some
1718 // record of that fact.
1719 for (auto ModInfo : Data.KnownHeaders)
1720 EmitModule(ModInfo.getModule(), ModInfo.getRole());
1721 if (Data.Unresolved.getPointer())
1722 EmitModule(Data.Unresolved.getPointer(), Data.Unresolved.getInt());
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001723
Douglas Gregor09b69892011-02-10 17:09:37 +00001724 assert(Out.tell() - Start == DataLen && "Wrong data length");
1725 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001726
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001727 const char *strings_begin() const { return FrameworkStringData.begin(); }
1728 const char *strings_end() const { return FrameworkStringData.end(); }
Douglas Gregor09b69892011-02-10 17:09:37 +00001729 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001730
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001731} // namespace
Douglas Gregor09b69892011-02-10 17:09:37 +00001732
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001733/// Write the header search block for the list of files that
Douglas Gregor09b69892011-02-10 17:09:37 +00001734///
1735/// \param HS The header search structure to save.
Richard Smith7ed1bc92014-12-05 22:42:13 +00001736void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
Richard Smith040e1262017-06-02 01:55:39 +00001737 HeaderFileInfoTrait GeneratorTrait(*this);
1738 llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
1739 SmallVector<const char *, 4> SavedStrings;
1740 unsigned NumHeaderSearchEntries = 0;
1741
1742 // Find all unresolved headers for the current module. We generally will
1743 // have resolved them before we get here, but not necessarily: we might be
1744 // compiling a preprocessed module, where there is no requirement for the
1745 // original files to exist any more.
Benjamin Krameree021d52017-06-02 17:30:24 +00001746 const HeaderFileInfo Empty; // So we can take a reference.
Richard Smith040e1262017-06-02 01:55:39 +00001747 if (WritingModule) {
1748 llvm::SmallVector<Module *, 16> Worklist(1, WritingModule);
1749 while (!Worklist.empty()) {
1750 Module *M = Worklist.pop_back_val();
Richard Smith6bc75022020-04-17 20:25:15 -07001751 // We don't care about headers in unimportable submodules.
1752 if (M->isUnimportable())
Richard Smith040e1262017-06-02 01:55:39 +00001753 continue;
1754
1755 // Map to disk files where possible, to pick up any missing stat
1756 // information. This also means we don't need to check the unresolved
1757 // headers list when emitting resolved headers in the first loop below.
1758 // FIXME: It'd be preferable to avoid doing this if we were given
1759 // sufficient stat information in the module map.
1760 HS.getModuleMap().resolveHeaderDirectives(M);
1761
1762 // If the file didn't exist, we can still create a module if we were given
1763 // enough information in the module map.
1764 for (auto U : M->MissingHeaders) {
1765 // Check that we were given enough information to build a module
1766 // without this file existing on disk.
1767 if (!U.Size || (!U.ModTime && IncludeTimestamps)) {
1768 PP->Diag(U.FileNameLoc, diag::err_module_no_size_mtime_for_header)
1769 << WritingModule->getFullModuleName() << U.Size.hasValue()
1770 << U.FileName;
1771 continue;
1772 }
1773
1774 // Form the effective relative pathname for the file.
1775 SmallString<128> Filename(M->Directory->getName());
1776 llvm::sys::path::append(Filename, U.FileName);
1777 PreparePathForOutput(Filename);
1778
1779 StringRef FilenameDup = strdup(Filename.c_str());
1780 SavedStrings.push_back(FilenameDup.data());
1781
1782 HeaderFileInfoTrait::key_type Key = {
1783 FilenameDup, *U.Size, IncludeTimestamps ? *U.ModTime : 0
1784 };
1785 HeaderFileInfoTrait::data_type Data = {
Benjamin Krameree021d52017-06-02 17:30:24 +00001786 Empty, {}, {M, ModuleMap::headerKindToRole(U.Kind)}
Richard Smith040e1262017-06-02 01:55:39 +00001787 };
1788 // FIXME: Deal with cases where there are multiple unresolved header
1789 // directives in different submodules for the same header.
1790 Generator.insert(Key, Data, GeneratorTrait);
1791 ++NumHeaderSearchEntries;
1792 }
1793
1794 Worklist.append(M->submodule_begin(), M->submodule_end());
1795 }
1796 }
1797
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001798 SmallVector<const FileEntry *, 16> FilesByUID;
Douglas Gregor09b69892011-02-10 17:09:37 +00001799 HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001800
Douglas Gregor09b69892011-02-10 17:09:37 +00001801 if (FilesByUID.size() > HS.header_file_size())
1802 FilesByUID.resize(HS.header_file_size());
Richard Smith040e1262017-06-02 01:55:39 +00001803
Douglas Gregor09b69892011-02-10 17:09:37 +00001804 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1805 const FileEntry *File = FilesByUID[UID];
1806 if (!File)
1807 continue;
1808
Richard Smith386bb072015-08-18 23:42:23 +00001809 // Get the file info. This will load info from the external source if
1810 // necessary. Skip emitting this file if we have no information on it
1811 // as a header file (in which case HFI will be null) or if it hasn't
1812 // changed since it was loaded. Also skip it if it's for a modular header
1813 // from a different module; in that case, we rely on the module(s)
1814 // containing the header to provide this information.
Richard Smithd8879c82015-08-24 21:59:32 +00001815 const HeaderFileInfo *HFI =
1816 HS.getExistingFileInfo(File, /*WantExternal*/!Chain);
1817 if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
Argyrios Kyrtzidis6f722b42013-05-08 23:46:46 +00001818 continue;
Douglas Gregor09b69892011-02-10 17:09:37 +00001819
Richard Smith7ed1bc92014-12-05 22:42:13 +00001820 // Massage the file path into an appropriate form.
Mehdi Amini004b9c72016-10-10 22:52:47 +00001821 StringRef Filename = File->getName();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001822 SmallString<128> FilenameTmp(Filename);
1823 if (PreparePathForOutput(FilenameTmp)) {
1824 // If we performed any translation on the file name at all, we need to
1825 // save this string, since the generator will refer to it later.
Mehdi Amini004b9c72016-10-10 22:52:47 +00001826 Filename = StringRef(strdup(FilenameTmp.c_str()));
1827 SavedStrings.push_back(Filename.data());
Douglas Gregor09b69892011-02-10 17:09:37 +00001828 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001829
Richard Smith040e1262017-06-02 01:55:39 +00001830 HeaderFileInfoTrait::key_type Key = {
1831 Filename, File->getSize(), getTimestampForOutput(File)
1832 };
1833 HeaderFileInfoTrait::data_type Data = {
Richard Smith0a088ea2020-04-28 18:22:34 -07001834 *HFI, HS.getModuleMap().findResolvedModulesForHeader(File), {}
Richard Smith040e1262017-06-02 01:55:39 +00001835 };
1836 Generator.insert(Key, Data, GeneratorTrait);
Douglas Gregor09b69892011-02-10 17:09:37 +00001837 ++NumHeaderSearchEntries;
1838 }
Richard Smith040e1262017-06-02 01:55:39 +00001839
Douglas Gregor09b69892011-02-10 17:09:37 +00001840 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001841 SmallString<4096> TableData;
Douglas Gregor09b69892011-02-10 17:09:37 +00001842 uint32_t BucketOffset;
1843 {
Justin Bognere1c147c2014-03-28 22:03:19 +00001844 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001845
Douglas Gregor09b69892011-02-10 17:09:37 +00001846 llvm::raw_svector_ostream Out(TableData);
1847 // Make sure that no bucket is at offset 0
Peter Collingbournee3f65292018-05-18 19:46:24 +00001848 endian::write<uint32_t>(Out, 0, little);
Douglas Gregor09b69892011-02-10 17:09:37 +00001849 BucketOffset = Generator.Emit(Out, GeneratorTrait);
1850 }
1851
1852 // Create a blob abbreviation
1853 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00001854
David Blaikieb44f0bf2017-01-04 22:36:43 +00001855 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor09b69892011-02-10 17:09:37 +00001856 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1857 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1858 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001859 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor09b69892011-02-10 17:09:37 +00001860 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00001861 unsigned TableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001862
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001863 // Write the header search table
Mehdi Amini57a41912015-09-10 01:46:39 +00001864 RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
1865 NumHeaderSearchEntries, TableData.size()};
Douglas Gregor4b123cb2011-07-28 04:50:02 +00001866 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
Yaron Keren92e1b622015-03-18 10:17:07 +00001867 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001868
Douglas Gregor09b69892011-02-10 17:09:37 +00001869 // Free all of the strings we had to duplicate.
1870 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
David Greenebae0e352013-01-15 22:09:43 +00001871 free(const_cast<char *>(SavedStrings[I]));
Douglas Gregor09b69892011-02-10 17:09:37 +00001872}
1873
George Rimarc39f5492017-01-17 15:45:31 +00001874static void emitBlob(llvm::BitstreamWriter &Stream, StringRef Blob,
1875 unsigned SLocBufferBlobCompressedAbbrv,
1876 unsigned SLocBufferBlobAbbrv) {
Eugene Zelenkob7d89102017-11-11 00:08:50 +00001877 using RecordDataType = ASTWriter::RecordData::value_type;
George Rimarc39f5492017-01-17 15:45:31 +00001878
1879 // Compress the buffer if possible. We expect that almost all PCM
1880 // consumers will not want its contents.
1881 SmallString<0> CompressedBuffer;
1882 if (llvm::zlib::isAvailable()) {
1883 llvm::Error E = llvm::zlib::compress(Blob.drop_back(1), CompressedBuffer);
1884 if (!E) {
1885 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED,
1886 Blob.size() - 1};
1887 Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
1888 CompressedBuffer);
1889 return;
1890 }
1891 llvm::consumeError(std::move(E));
1892 }
1893
1894 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB};
1895 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob);
1896}
1897
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001898/// Writes the block containing the serialized form of the
Douglas Gregora7f71a92009-04-10 03:52:48 +00001899/// source manager.
1900///
1901/// TODO: We should probably use an on-disk hash table (stored in a
1902/// blob), indexed based on the file name, so that we only create
1903/// entries for files that we actually need. In the common case (no
1904/// errors), we probably won't have to create file entries for any of
1905/// the files in the AST.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00001906void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001907 const Preprocessor &PP) {
Douglas Gregor258ae542009-04-27 06:38:32 +00001908 RecordData Record;
1909
Chris Lattner0910e3b2009-04-10 17:16:57 +00001910 // Enter the source manager block.
Richard Smithaada85c2016-02-06 02:06:43 +00001911 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001912
1913 // Abbreviations for the various kinds of source-location entries.
Chris Lattnerc4976c732009-04-27 19:03:22 +00001914 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
1915 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
Richard Smithaada85c2016-02-06 02:06:43 +00001916 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
1917 unsigned SLocBufferBlobCompressedAbbrv =
1918 CreateSLocBufferBlobAbbrev(Stream, true);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001919 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
Douglas Gregora7f71a92009-04-10 03:52:48 +00001920
Douglas Gregor258ae542009-04-27 06:38:32 +00001921 // Write out the source location entry table. We skip the first
1922 // entry, which is always the same dummy entry.
Chris Lattner12d61d32009-04-27 19:01:47 +00001923 std::vector<uint32_t> SLocEntryOffsets;
Dmitry Polukhina7afb212020-04-16 09:24:46 -07001924 uint64_t SLocEntryOffsetsBase = Stream.GetCurrentBitNo();
Douglas Gregor258ae542009-04-27 06:38:32 +00001925 RecordData PreloadSLocs;
Douglas Gregor925296b2011-07-19 16:10:42 +00001926 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
1927 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
Sebastian Redl5c415f32010-07-22 17:01:13 +00001928 I != N; ++I) {
Douglas Gregor8655e882009-10-16 22:46:09 +00001929 // Get this source location entry.
Douglas Gregor925296b2011-07-19 16:10:42 +00001930 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00001931 FileID FID = FileID::get(I);
1932 assert(&SourceMgr.getSLocEntry(FID) == SLoc);
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00001933
Douglas Gregor258ae542009-04-27 06:38:32 +00001934 // Record the offset of this source-location entry.
Dmitry Polukhina7afb212020-04-16 09:24:46 -07001935 uint64_t Offset = Stream.GetCurrentBitNo() - SLocEntryOffsetsBase;
1936 assert((Offset >> 32) == 0 && "SLocEntry offset too large");
1937 SLocEntryOffsets.push_back(Offset);
Douglas Gregor258ae542009-04-27 06:38:32 +00001938
1939 // Figure out which record code to use.
1940 unsigned Code;
1941 if (SLoc->isFile()) {
Douglas Gregor9dc32122011-11-16 20:05:18 +00001942 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1943 if (Cache->OrigEntry) {
Sebastian Redl539c5062010-08-18 23:57:32 +00001944 Code = SM_SLOC_FILE_ENTRY;
Argyrios Kyrtzidis92dd4662011-06-02 20:01:46 +00001945 } else
Sebastian Redl539c5062010-08-18 23:57:32 +00001946 Code = SM_SLOC_BUFFER_ENTRY;
Douglas Gregor258ae542009-04-27 06:38:32 +00001947 } else
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00001948 Code = SM_SLOC_EXPANSION_ENTRY;
Douglas Gregor258ae542009-04-27 06:38:32 +00001949 Record.clear();
1950 Record.push_back(Code);
1951
Douglas Gregor925296b2011-07-19 16:10:42 +00001952 // Starting offset of this entry within this module, so skip the dummy.
1953 Record.push_back(SLoc->getOffset() - 2);
Douglas Gregor258ae542009-04-27 06:38:32 +00001954 if (SLoc->isFile()) {
1955 const SrcMgr::FileInfo &File = SLoc->getFile();
Richard Smithb22a1d12016-03-27 20:13:24 +00001956 AddSourceLocation(File.getIncludeLoc(), Record);
Douglas Gregor258ae542009-04-27 06:38:32 +00001957 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
1958 Record.push_back(File.hasLineDirectives());
1959
1960 const SrcMgr::ContentCache *Content = File.getContentCache();
Richard Smithaada85c2016-02-06 02:06:43 +00001961 bool EmitBlob = false;
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001962 if (Content->OrigEntry) {
1963 assert(Content->OrigEntry == Content->ContentsEntry &&
Douglas Gregor9dc32122011-11-16 20:05:18 +00001964 "Writing to AST an overridden file is not supported");
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001965
Douglas Gregor3120d2c2012-10-22 18:42:04 +00001966 // The source location entry is a file. Emit input file ID.
1967 assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
1968 Record.push_back(InputFileIDs[Content->OrigEntry]);
Mike Stump11289f42009-09-09 15:08:12 +00001969
Argyrios Kyrtzidis61ef3db2011-08-21 23:33:04 +00001970 Record.push_back(File.NumCreatedFIDs);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001971
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00001972 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00001973 if (FDI != FileDeclIDs.end()) {
1974 Record.push_back(FDI->second->FirstDeclIndex);
1975 Record.push_back(FDI->second->DeclIDs.size());
1976 } else {
1977 Record.push_back(0);
1978 Record.push_back(0);
1979 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001980
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001981 Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00001982
Richard Smithaada85c2016-02-06 02:06:43 +00001983 if (Content->BufferOverridden || Content->IsTransient)
1984 EmitBlob = true;
Douglas Gregor258ae542009-04-27 06:38:32 +00001985 } else {
1986 // The source location entry is a buffer. The blob associated
1987 // with this entry contains the contents of the buffer.
1988
1989 // We add one to the size so that we capture the trailing NULL
1990 // that is required by llvm::MemoryBuffer::getMemBuffer (on
1991 // the reader side).
Duncan P. N. Exon Smithf5848192019-08-26 20:32:05 +00001992 const llvm::MemoryBuffer *Buffer =
1993 Content->getBuffer(PP.getDiagnostics(), PP.getFileManager());
Mehdi Amini99d1b292016-10-01 16:38:28 +00001994 StringRef Name = Buffer->getBufferIdentifier();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00001995 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
Mehdi Amini99d1b292016-10-01 16:38:28 +00001996 StringRef(Name.data(), Name.size() + 1));
Richard Smithaada85c2016-02-06 02:06:43 +00001997 EmitBlob = true;
Douglas Gregor258ae542009-04-27 06:38:32 +00001998
Mehdi Amini99d1b292016-10-01 16:38:28 +00001999 if (Name == "<built-in>")
Douglas Gregor925296b2011-07-19 16:10:42 +00002000 PreloadSLocs.push_back(SLocEntryOffsets.size());
Douglas Gregor258ae542009-04-27 06:38:32 +00002001 }
Richard Smithaada85c2016-02-06 02:06:43 +00002002
2003 if (EmitBlob) {
2004 // Include the implicit terminating null character in the on-disk buffer
2005 // if we're writing it uncompressed.
2006 const llvm::MemoryBuffer *Buffer =
Duncan P. N. Exon Smithf5848192019-08-26 20:32:05 +00002007 Content->getBuffer(PP.getDiagnostics(), PP.getFileManager());
Richard Smithaada85c2016-02-06 02:06:43 +00002008 StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
George Rimarc39f5492017-01-17 15:45:31 +00002009 emitBlob(Stream, Blob, SLocBufferBlobCompressedAbbrv,
2010 SLocBufferBlobAbbrv);
Richard Smithaada85c2016-02-06 02:06:43 +00002011 }
Douglas Gregor258ae542009-04-27 06:38:32 +00002012 } else {
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00002013 // The source location entry is a macro expansion.
Chandler Carruthee4c1d12011-07-26 04:56:51 +00002014 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
Richard Smithb22a1d12016-03-27 20:13:24 +00002015 AddSourceLocation(Expansion.getSpellingLoc(), Record);
2016 AddSourceLocation(Expansion.getExpansionLocStart(), Record);
2017 AddSourceLocation(Expansion.isMacroArgExpansion()
2018 ? SourceLocation()
2019 : Expansion.getExpansionLocEnd(),
2020 Record);
Richard Smithb5f81712018-04-30 05:25:48 +00002021 Record.push_back(Expansion.isExpansionTokenRange());
Douglas Gregor258ae542009-04-27 06:38:32 +00002022
2023 // Compute the token length for this macro expansion.
Douglas Gregor925296b2011-07-19 16:10:42 +00002024 unsigned NextOffset = SourceMgr.getNextLocalOffset();
Douglas Gregor8655e882009-10-16 22:46:09 +00002025 if (I + 1 != N)
Douglas Gregor925296b2011-07-19 16:10:42 +00002026 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
Douglas Gregor258ae542009-04-27 06:38:32 +00002027 Record.push_back(NextOffset - SLoc->getOffset() - 1);
Mehdi Amini5ae4a852015-09-09 20:35:37 +00002028 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
Douglas Gregor258ae542009-04-27 06:38:32 +00002029 }
2030 }
2031
Douglas Gregor8f45df52009-04-16 22:23:12 +00002032 Stream.ExitBlock();
Douglas Gregor258ae542009-04-27 06:38:32 +00002033
2034 if (SLocEntryOffsets.empty())
2035 return;
2036
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002037 // Write the source-location offsets table into the AST block. This
Douglas Gregor258ae542009-04-27 06:38:32 +00002038 // table is used for lazily loading source-location information.
2039 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002040
David Blaikieb44f0bf2017-01-04 22:36:43 +00002041 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00002042 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
Douglas Gregor258ae542009-04-27 06:38:32 +00002043 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
Douglas Gregor925296b2011-07-19 16:10:42 +00002044 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
Dmitry Polukhina7afb212020-04-16 09:24:46 -07002045 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // base offset
Douglas Gregor258ae542009-04-27 06:38:32 +00002046 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
David Blaikieb44f0bf2017-01-04 22:36:43 +00002047 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00002048 {
2049 RecordData::value_type Record[] = {
2050 SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
Dmitry Polukhina7afb212020-04-16 09:24:46 -07002051 SourceMgr.getNextLocalOffset() - 1 /* skip dummy */,
2052 SLocEntryOffsetsBase};
Mehdi Amini57a41912015-09-10 01:46:39 +00002053 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
2054 bytes(SLocEntryOffsets));
2055 }
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002056 // Write the source location entry preloads array, telling the AST
Douglas Gregor258ae542009-04-27 06:38:32 +00002057 // reader which source locations entries it should load eagerly.
Sebastian Redl539c5062010-08-18 23:57:32 +00002058 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
Douglas Gregor925296b2011-07-19 16:10:42 +00002059
2060 // Write the line table. It depends on remapping working, so it must come
2061 // after the source location offsets.
2062 if (SourceMgr.hasLineTable()) {
2063 LineTableInfo &LineTable = SourceMgr.getLineTable();
2064
2065 Record.clear();
Richard Smith63078492015-09-01 07:41:55 +00002066
2067 // Emit the needed file names.
2068 llvm::DenseMap<int, int> FilenameMap;
Hans Wennborg14487362017-12-04 22:28:45 +00002069 FilenameMap[-1] = -1; // For unspecified filenames.
Richard Smith63078492015-09-01 07:41:55 +00002070 for (const auto &L : LineTable) {
2071 if (L.first.ID < 0)
2072 continue;
2073 for (auto &LE : L.second) {
2074 if (FilenameMap.insert(std::make_pair(LE.FilenameID,
Hans Wennborg14487362017-12-04 22:28:45 +00002075 FilenameMap.size() - 1)).second)
Richard Smith63078492015-09-01 07:41:55 +00002076 AddPath(LineTable.getFilename(LE.FilenameID), Record);
2077 }
2078 }
2079 Record.push_back(0);
Douglas Gregor925296b2011-07-19 16:10:42 +00002080
2081 // Emit the line entries
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002082 for (const auto &L : LineTable) {
Douglas Gregor925296b2011-07-19 16:10:42 +00002083 // Only emit entries for local files.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002084 if (L.first.ID < 0)
Douglas Gregor925296b2011-07-19 16:10:42 +00002085 continue;
2086
2087 // Emit the file ID
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002088 Record.push_back(L.first.ID);
Douglas Gregor925296b2011-07-19 16:10:42 +00002089
2090 // Emit the line entries
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002091 Record.push_back(L.second.size());
2092 for (const auto &LE : L.second) {
2093 Record.push_back(LE.FileOffset);
2094 Record.push_back(LE.LineNo);
2095 Record.push_back(FilenameMap[LE.FilenameID]);
2096 Record.push_back((unsigned)LE.FileKind);
2097 Record.push_back(LE.IncludeOffset);
Douglas Gregor925296b2011-07-19 16:10:42 +00002098 }
2099 }
Richard Smith63078492015-09-01 07:41:55 +00002100
Douglas Gregor925296b2011-07-19 16:10:42 +00002101 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
2102 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00002103}
2104
Douglas Gregorc5046832009-04-27 18:38:38 +00002105//===----------------------------------------------------------------------===//
2106// Preprocessor Serialization
2107//===----------------------------------------------------------------------===//
2108
Argyrios Kyrtzidis0aef0f02013-03-15 22:43:10 +00002109static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
2110 const Preprocessor &PP) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002111 if (MacroInfo *MI = MD->getMacroInfo())
2112 if (MI->isBuiltinMacro())
2113 return true;
Argyrios Kyrtzidis0aef0f02013-03-15 22:43:10 +00002114
2115 if (IsModule) {
2116 SourceLocation Loc = MD->getLocation();
2117 if (Loc.isInvalid())
2118 return true;
2119 if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
2120 return true;
2121 }
2122
2123 return false;
2124}
2125
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002126/// Writes the block containing the serialized form of the
Chris Lattnereeffaef2009-04-10 17:15:23 +00002127/// preprocessor.
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00002128void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
Dmitry Polukhina7afb212020-04-16 09:24:46 -07002129 uint64_t MacroOffsetsBase = Stream.GetCurrentBitNo();
2130
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002131 PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
2132 if (PPRec)
Dmitry Polukhina7afb212020-04-16 09:24:46 -07002133 WritePreprocessorDetail(*PPRec, MacroOffsetsBase);
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002134
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002135 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00002136 RecordData ModuleMacroRecord;
Chris Lattner0910e3b2009-04-10 17:16:57 +00002137
Chris Lattner0af3ba12009-04-13 01:29:17 +00002138 // If the preprocessor __COUNTER__ value has been bumped, remember it.
2139 if (PP.getCounterValue() != 0) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002140 RecordData::value_type Record[] = {PP.getCounterValue()};
Sebastian Redl539c5062010-08-18 23:57:32 +00002141 Stream.EmitRecord(PP_COUNTER_VALUE, Record);
Douglas Gregoreda6a892009-04-26 00:07:37 +00002142 }
2143
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00002144 if (PP.isRecordingPreamble() && PP.hasRecordedPreamble()) {
2145 assert(!IsModule);
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00002146 auto SkipInfo = PP.getPreambleSkipInfo();
2147 if (SkipInfo.hasValue()) {
2148 Record.push_back(true);
2149 AddSourceLocation(SkipInfo->HashTokenLoc, Record);
2150 AddSourceLocation(SkipInfo->IfTokenLoc, Record);
2151 Record.push_back(SkipInfo->FoundNonSkipPortion);
2152 Record.push_back(SkipInfo->FoundElse);
2153 AddSourceLocation(SkipInfo->ElseLoc, Record);
2154 } else {
2155 Record.push_back(false);
2156 }
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00002157 for (const auto &Cond : PP.getPreambleConditionalStack()) {
2158 AddSourceLocation(Cond.IfLoc, Record);
2159 Record.push_back(Cond.WasSkipping);
2160 Record.push_back(Cond.FoundNonSkip);
2161 Record.push_back(Cond.FoundElse);
2162 }
2163 Stream.EmitRecord(PP_CONDITIONAL_STACK, Record);
2164 Record.clear();
2165 }
2166
Douglas Gregoreda6a892009-04-26 00:07:37 +00002167 // Enter the preprocessor block.
Douglas Gregor796d76a2010-10-20 22:00:55 +00002168 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
Mike Stump11289f42009-09-09 15:08:12 +00002169
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002170 // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
Richard Smithb5aaf5a2015-09-01 02:35:58 +00002171 // FIXME: Include a location for the use, and say which one was used.
Douglas Gregoreda6a892009-04-26 00:07:37 +00002172 if (PP.SawDateOrTime())
Richard Smithb5aaf5a2015-09-01 02:35:58 +00002173 PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
Douglas Gregor796d76a2010-10-20 22:00:55 +00002174
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002175 // Loop over all the macro directives that are live at the end of the file,
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002176 // emitting each to the PP section.
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002177
Richard Smithee977932015-05-01 21:22:17 +00002178 // Construct the list of identifiers with macro directives that need to be
2179 // serialized.
2180 SmallVector<const IdentifierInfo *, 128> MacroIdentifiers;
2181 for (auto &Id : PP.getIdentifierTable())
2182 if (Id.second->hadMacroDefinition() &&
2183 (!Id.second->isFromAST() ||
2184 Id.second->hasChangedSinceDeserialization()))
2185 MacroIdentifiers.push_back(Id.second);
Douglas Gregor2e5571d2011-02-10 18:20:09 +00002186 // Sort the set of macro definitions that need to be serialized by the
2187 // name of the macro, to provide a stable ordering.
Benjamin Kramercd2bae32019-08-22 17:32:16 +00002188 llvm::sort(MacroIdentifiers, llvm::deref<std::less<>>());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002189
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002190 // Emit the macro directives as a list and associate the offset with the
2191 // identifier they belong to.
Richard Smithee977932015-05-01 21:22:17 +00002192 for (const IdentifierInfo *Name : MacroIdentifiers) {
2193 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name);
Dmitry Polukhina7afb212020-04-16 09:24:46 -07002194 uint64_t StartOffset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2195 assert((StartOffset >> 32) == 0 && "Macro identifiers offset too large");
Richard Smithd7329392015-04-21 21:46:32 +00002196
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002197 // Emit the macro directives in reverse source order.
2198 for (; MD; MD = MD->getPrevious()) {
Richard Smithd7329392015-04-21 21:46:32 +00002199 // Once we hit an ignored macro, we're done: the rest of the chain
2200 // will all be ignored macros.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002201 if (shouldIgnoreMacro(MD, IsModule, PP))
Richard Smithd7329392015-04-21 21:46:32 +00002202 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002203
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002204 AddSourceLocation(MD->getLocation(), Record);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002205 Record.push_back(MD->getKind());
Richard Smithdaa69e02014-07-25 04:40:03 +00002206 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
Richard Smith3981b172015-04-30 02:16:23 +00002207 Record.push_back(getMacroRef(DefMD->getInfo(), Name));
Richard Smith713369b2015-04-23 20:40:50 +00002208 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002209 Record.push_back(VisMD->isPublic());
2210 }
Richard Smithb8b2ed62015-04-23 18:18:26 +00002211 }
Richard Smithd7329392015-04-21 21:46:32 +00002212
Richard Smithb8b2ed62015-04-23 18:18:26 +00002213 // Write out any exported module macros.
Richard Smithee977932015-05-01 21:22:17 +00002214 bool EmittedModuleMacros = false;
Manman Ren33d80292016-05-31 18:19:32 +00002215 // We write out exported module macros for PCH as well.
2216 auto Leafs = PP.getLeafModuleMacros(Name);
2217 SmallVector<ModuleMacro*, 8> Worklist(Leafs.begin(), Leafs.end());
2218 llvm::DenseMap<ModuleMacro*, unsigned> Visits;
2219 while (!Worklist.empty()) {
2220 auto *Macro = Worklist.pop_back_val();
Richard Smithd7329392015-04-21 21:46:32 +00002221
Manman Ren33d80292016-05-31 18:19:32 +00002222 // Emit a record indicating this submodule exports this macro.
2223 ModuleMacroRecord.push_back(
2224 getSubmoduleID(Macro->getOwningModule()));
2225 ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
2226 for (auto *M : Macro->overrides())
2227 ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
Richard Smithd7329392015-04-21 21:46:32 +00002228
Manman Ren33d80292016-05-31 18:19:32 +00002229 Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2230 ModuleMacroRecord.clear();
Richard Smithd7329392015-04-21 21:46:32 +00002231
Manman Ren33d80292016-05-31 18:19:32 +00002232 // Enqueue overridden macros once we've visited all their ancestors.
2233 for (auto *M : Macro->overrides())
2234 if (++Visits[M] == M->getNumOverridingMacros())
2235 Worklist.push_back(M);
Richard Smithee977932015-05-01 21:22:17 +00002236
Manman Ren33d80292016-05-31 18:19:32 +00002237 EmittedModuleMacros = true;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002238 }
Richard Smithd7329392015-04-21 21:46:32 +00002239
Richard Smithee977932015-05-01 21:22:17 +00002240 if (Record.empty() && !EmittedModuleMacros)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002241 continue;
2242
Richard Smithd7329392015-04-21 21:46:32 +00002243 IdentMacroDirectivesOffsetMap[Name] = StartOffset;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002244 Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2245 Record.clear();
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002246 }
Alexander Kornienko1d26c022012-09-25 17:18:14 +00002247
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002248 /// Offsets of each of the macros into the bitstream, indexed by
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002249 /// the local macro ID
2250 ///
2251 /// For each identifier that is associated with a macro, this map
2252 /// provides the offset into the bitstream where that macro is
2253 /// defined.
2254 std::vector<uint32_t> MacroOffsets;
2255
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002256 for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2257 const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2258 MacroInfo *MI = MacroInfosToEmit[I].MI;
2259 MacroID ID = MacroInfosToEmit[I].ID;
Douglas Gregoreb114da2010-10-01 01:03:07 +00002260
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002261 if (ID < FirstMacroID) {
2262 assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2263 continue;
Chris Lattner2199f5b2009-04-10 18:08:30 +00002264 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002265
2266 // Record the local offset of this macro.
2267 unsigned Index = ID - FirstMacroID;
Dmitry Polukhina7afb212020-04-16 09:24:46 -07002268 if (Index >= MacroOffsets.size())
2269 MacroOffsets.resize(Index + 1);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002270
Dmitry Polukhina7afb212020-04-16 09:24:46 -07002271 uint64_t Offset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2272 assert((Offset >> 32) == 0 && "Macro offset too large");
2273 MacroOffsets[Index] = Offset;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002274
2275 AddIdentifierRef(Name, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002276 AddSourceLocation(MI->getDefinitionLoc(), Record);
2277 AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2278 Record.push_back(MI->isUsed());
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00002279 Record.push_back(MI->isUsedForHeaderGuard());
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002280 unsigned Code;
2281 if (MI->isObjectLike()) {
2282 Code = PP_MACRO_OBJECT_LIKE;
2283 } else {
2284 Code = PP_MACRO_FUNCTION_LIKE;
2285
2286 Record.push_back(MI->isC99Varargs());
2287 Record.push_back(MI->isGNUVarargs());
2288 Record.push_back(MI->hasCommaPasting());
Faisal Valiac506d72017-07-17 17:18:43 +00002289 Record.push_back(MI->getNumParams());
2290 for (const IdentifierInfo *Param : MI->params())
2291 AddIdentifierRef(Param, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002292 }
2293
2294 // If we have a detailed preprocessing record, record the macro definition
2295 // ID that corresponds to this macro.
2296 if (PPRec)
2297 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2298
2299 Stream.EmitRecord(Code, Record);
2300 Record.clear();
2301
2302 // Emit the tokens array.
2303 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2304 // Note that we know that the preprocessor does not have any annotation
2305 // tokens in it because they are created by the parser, and thus can't
2306 // be in a macro definition.
2307 const Token &Tok = MI->getReplacementToken(TokNo);
John McCallf413f5e2013-05-03 00:10:13 +00002308 AddToken(Tok, Record);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002309 Stream.EmitRecord(PP_TOKEN, Record);
2310 Record.clear();
2311 }
2312 ++NumMacros;
Chris Lattnerbaa52f42009-04-10 18:00:12 +00002313 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002314
Douglas Gregor92a96f52011-02-08 21:58:10 +00002315 Stream.ExitBlock();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002316
2317 // Write the offsets table for macro IDs.
2318 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002319
David Blaikieb44f0bf2017-01-04 22:36:43 +00002320 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002321 Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2322 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2323 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
Dmitry Polukhina7afb212020-04-16 09:24:46 -07002324 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // base offset
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00002325 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2326
David Blaikieb44f0bf2017-01-04 22:36:43 +00002327 unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00002328 {
2329 RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
Dmitry Polukhina7afb212020-04-16 09:24:46 -07002330 FirstMacroID - NUM_PREDEF_MACRO_IDS,
2331 MacroOffsetsBase};
Mehdi Amini57a41912015-09-10 01:46:39 +00002332 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
2333 }
Douglas Gregor92a96f52011-02-08 21:58:10 +00002334}
2335
Dmitry Polukhina7afb212020-04-16 09:24:46 -07002336void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec,
2337 uint64_t MacroOffsetsBase) {
Argyrios Kyrtzidis7f448362011-09-19 20:40:42 +00002338 if (PPRec.local_begin() == PPRec.local_end())
Douglas Gregor92a96f52011-02-08 21:58:10 +00002339 return;
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002340
Argyrios Kyrtzidis64f63812011-09-19 20:40:25 +00002341 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002342
Douglas Gregor92a96f52011-02-08 21:58:10 +00002343 // Enter the preprocessor block.
2344 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002345
Douglas Gregoraae92242010-03-19 21:51:54 +00002346 // If the preprocessor has a preprocessing record, emit it.
2347 unsigned NumPreprocessingRecords = 0;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002348 using namespace llvm;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002349
2350 // Set up the abbreviation for
Douglas Gregor92a96f52011-02-08 21:58:10 +00002351 unsigned InclusionAbbrev = 0;
2352 {
David Blaikieb44f0bf2017-01-04 22:36:43 +00002353 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor92a96f52011-02-08 21:58:10 +00002354 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
Douglas Gregor92a96f52011-02-08 21:58:10 +00002355 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2356 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2357 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
Argyrios Kyrtzidisf590e092012-10-02 16:10:46 +00002358 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
Douglas Gregor92a96f52011-02-08 21:58:10 +00002359 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00002360 InclusionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor92a96f52011-02-08 21:58:10 +00002361 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002362
2363 unsigned FirstPreprocessorEntityID
2364 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002365 + NUM_PREDEF_PP_ENTITY_IDS;
2366 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002367 RecordData Record;
Argyrios Kyrtzidis7f448362011-09-19 20:40:42 +00002368 for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2369 EEnd = PPRec.local_end();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002370 E != EEnd;
Douglas Gregor0d4b4312011-08-04 17:06:18 +00002371 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
Douglas Gregor92a96f52011-02-08 21:58:10 +00002372 Record.clear();
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002373
Dmitry Polukhina7afb212020-04-16 09:24:46 -07002374 uint64_t Offset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2375 assert((Offset >> 32) == 0 && "Preprocessed entity offset too large");
Richard Smith66a81862015-05-04 02:25:31 +00002376 PreprocessedEntityOffsets.push_back(
Dmitry Polukhina7afb212020-04-16 09:24:46 -07002377 PPEntityOffset((*E)->getSourceRange(), Offset));
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002378
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002379 if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002380 // Record this macro definition's ID.
2381 MacroDefinitions[MD] = NextPreprocessorEntityID;
Richard Smith66a81862015-05-04 02:25:31 +00002382
Douglas Gregor92a96f52011-02-08 21:58:10 +00002383 AddIdentifierRef(MD->getName(), Record);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002384 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2385 continue;
Douglas Gregoraae92242010-03-19 21:51:54 +00002386 }
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002387
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002388 if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
Argyrios Kyrtzidis80f78b92011-09-08 17:18:41 +00002389 Record.push_back(ME->isBuiltinMacro());
2390 if (ME->isBuiltinMacro())
2391 AddIdentifierRef(ME->getName(), Record);
2392 else
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002393 Record.push_back(MacroDefinitions[ME->getDefinition()]);
Chandler Carruthf92ac9e2011-07-15 07:25:21 +00002394 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002395 continue;
2396 }
2397
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002398 if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
Douglas Gregor92a96f52011-02-08 21:58:10 +00002399 Record.push_back(PPD_INCLUSION_DIRECTIVE);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002400 Record.push_back(ID->getFileName().size());
2401 Record.push_back(ID->wasInQuotes());
2402 Record.push_back(static_cast<unsigned>(ID->getKind()));
Argyrios Kyrtzidisf590e092012-10-02 16:10:46 +00002403 Record.push_back(ID->importedModule());
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002404 SmallString<64> Buffer;
Douglas Gregor92a96f52011-02-08 21:58:10 +00002405 Buffer += ID->getFileName();
Argyrios Kyrtzidis8dbcfc32012-03-08 01:08:28 +00002406 // Check that the FileEntry is not null because it was not resolved and
2407 // we create a PCH even with compiler errors.
2408 if (ID->getFile())
2409 Buffer += ID->getFile()->getName();
Mehdi Amini5ae4a852015-09-09 20:35:37 +00002410 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
Douglas Gregor92a96f52011-02-08 21:58:10 +00002411 continue;
2412 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002413
Douglas Gregor92a96f52011-02-08 21:58:10 +00002414 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2415 }
Douglas Gregor8f45df52009-04-16 22:23:12 +00002416 Stream.ExitBlock();
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002417
Douglas Gregoraae92242010-03-19 21:51:54 +00002418 // Write the offsets table for the preprocessing record.
2419 if (NumPreprocessingRecords > 0) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002420 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2421
Douglas Gregoraae92242010-03-19 21:51:54 +00002422 // Write the offsets table for identifier IDs.
2423 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002424
David Blaikieb44f0bf2017-01-04 22:36:43 +00002425 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002426 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
Douglas Gregor2f555fc2011-08-04 18:56:47 +00002427 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
Douglas Gregoraae92242010-03-19 21:51:54 +00002428 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00002429 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00002430
Mehdi Amini57a41912015-09-10 01:46:39 +00002431 RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
2432 FirstPreprocessorEntityID -
2433 NUM_PREDEF_PP_ENTITY_IDS};
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00002434 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00002435 bytes(PreprocessedEntityOffsets));
Douglas Gregoraae92242010-03-19 21:51:54 +00002436 }
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00002437
2438 // Write the skipped region table for the preprocessing record.
2439 ArrayRef<SourceRange> SkippedRanges = PPRec.getSkippedRanges();
2440 if (SkippedRanges.size() > 0) {
2441 std::vector<PPSkippedRange> SerializedSkippedRanges;
2442 SerializedSkippedRanges.reserve(SkippedRanges.size());
2443 for (auto const& Range : SkippedRanges)
2444 SerializedSkippedRanges.emplace_back(Range);
2445
2446 using namespace llvm;
2447 auto Abbrev = std::make_shared<BitCodeAbbrev>();
2448 Abbrev->Add(BitCodeAbbrevOp(PPD_SKIPPED_RANGES));
2449 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2450 unsigned PPESkippedRangeAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2451
2452 Record.clear();
2453 Record.push_back(PPD_SKIPPED_RANGES);
2454 Stream.EmitRecordWithBlob(PPESkippedRangeAbbrev, Record,
2455 bytes(SerializedSkippedRanges));
2456 }
Chris Lattnereeffaef2009-04-10 17:15:23 +00002457}
2458
Richard Smith386bb072015-08-18 23:42:23 +00002459unsigned ASTWriter::getLocalOrImportedSubmoduleID(Module *Mod) {
Richard Smith080056b2015-08-18 21:53:42 +00002460 if (!Mod)
2461 return 0;
2462
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002463 llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
2464 if (Known != SubmoduleIDs.end())
2465 return Known->second;
Richard Smith386bb072015-08-18 23:42:23 +00002466
Richard Smithdc1f0422016-07-20 19:10:16 +00002467 auto *Top = Mod->getTopLevelModule();
2468 if (Top != WritingModule &&
Bruno Cardoso Lopes17da34d2017-02-07 21:54:57 +00002469 (getLangOpts().CompilingPCH ||
2470 !Top->fullModuleNameIs(StringRef(getLangOpts().CurrentModule))))
Richard Smith386bb072015-08-18 23:42:23 +00002471 return 0;
2472
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002473 return SubmoduleIDs[Mod] = NextSubmoduleID++;
2474}
2475
Richard Smith386bb072015-08-18 23:42:23 +00002476unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2477 // FIXME: This can easily happen, if we have a reference to a submodule that
2478 // did not result in us loading a module file for that submodule. For
2479 // instance, a cross-top-level-module 'conflict' declaration will hit this.
2480 unsigned ID = getLocalOrImportedSubmoduleID(Mod);
2481 assert((ID || !Mod) &&
2482 "asked for module ID for non-local, non-imported module");
2483 return ID;
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00002484}
2485
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002486/// Compute the number of modules within the given tree (including the
Douglas Gregor253eefe2011-12-01 00:59:36 +00002487/// given module).
2488static unsigned getNumberOfModules(Module *Mod) {
2489 unsigned ChildModules = 0;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002490 for (auto Sub = Mod->submodule_begin(), SubEnd = Mod->submodule_end();
Douglas Gregor253eefe2011-12-01 00:59:36 +00002491 Sub != SubEnd; ++Sub)
Douglas Gregoreb90e832012-01-04 23:32:19 +00002492 ChildModules += getNumberOfModules(*Sub);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002493
Douglas Gregor253eefe2011-12-01 00:59:36 +00002494 return ChildModules + 1;
2495}
2496
Douglas Gregorde3ef502011-11-30 23:21:26 +00002497void ASTWriter::WriteSubmodules(Module *WritingModule) {
Douglas Gregor69021972011-11-30 17:33:56 +00002498 // Enter the submodule description block.
Richard Smith202210b2014-10-24 20:23:01 +00002499 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002500
Douglas Gregor69021972011-11-30 17:33:56 +00002501 // Write the abbreviations needed for the submodules block.
2502 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002503
David Blaikieb44f0bf2017-01-04 22:36:43 +00002504 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor69021972011-11-30 17:33:56 +00002505 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002506 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
Douglas Gregor69021972011-11-30 17:33:56 +00002507 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
Richard Smithdd8b5332017-09-04 05:37:53 +00002508 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Kind
Douglas Gregor69021972011-11-30 17:33:56 +00002509 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2510 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
Richard Smith9bca2982014-03-08 00:03:56 +00002511 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2512 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
Douglas Gregora686e1b2012-01-27 19:52:33 +00002513 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
Douglas Gregor73441092011-12-05 22:27:44 +00002514 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
Douglas Gregor73441092011-12-05 22:27:44 +00002515 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002516 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
Jordan Rose90b0a1f2018-04-20 17:16:04 +00002517 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ModuleMapIsPriv...
Douglas Gregor69021972011-11-30 17:33:56 +00002518 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002519 unsigned DefinitionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor69021972011-11-30 17:33:56 +00002520
David Blaikieb44f0bf2017-01-04 22:36:43 +00002521 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor524e33e2011-12-08 19:11:24 +00002522 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
Douglas Gregor69021972011-11-30 17:33:56 +00002523 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002524 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor69021972011-11-30 17:33:56 +00002525
David Blaikieb44f0bf2017-01-04 22:36:43 +00002526 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor69021972011-11-30 17:33:56 +00002527 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2528 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002529 unsigned HeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor524e33e2011-12-08 19:11:24 +00002530
David Blaikieb44f0bf2017-01-04 22:36:43 +00002531 Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +00002532 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2533 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002534 unsigned TopHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +00002535
David Blaikieb44f0bf2017-01-04 22:36:43 +00002536 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor524e33e2011-12-08 19:11:24 +00002537 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2538 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002539 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor524e33e2011-12-08 19:11:24 +00002540
David Blaikieb44f0bf2017-01-04 22:36:43 +00002541 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002542 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
Richard Smitha3feee22013-10-28 22:18:19 +00002543 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2544 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
David Blaikieb44f0bf2017-01-04 22:36:43 +00002545 unsigned RequiresAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002546
David Blaikieb44f0bf2017-01-04 22:36:43 +00002547 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor59527662012-10-15 06:28:11 +00002548 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2549 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002550 unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor59527662012-10-15 06:28:11 +00002551
David Blaikieb44f0bf2017-01-04 22:36:43 +00002552 Abbrev = std::make_shared<BitCodeAbbrev>();
Richard Smith306d8922014-10-22 23:50:56 +00002553 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
2554 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002555 unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Richard Smith306d8922014-10-22 23:50:56 +00002556
David Blaikieb44f0bf2017-01-04 22:36:43 +00002557 Abbrev = std::make_shared<BitCodeAbbrev>();
Lawrence Crowlb53e5482013-06-20 21:14:14 +00002558 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2559 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002560 unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Lawrence Crowlb53e5482013-06-20 21:14:14 +00002561
David Blaikieb44f0bf2017-01-04 22:36:43 +00002562 Abbrev = std::make_shared<BitCodeAbbrev>();
Richard Smith202210b2014-10-24 20:23:01 +00002563 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
2564 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002565 unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Richard Smith202210b2014-10-24 20:23:01 +00002566
David Blaikieb44f0bf2017-01-04 22:36:43 +00002567 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002568 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2569 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2570 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002571 unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002572
David Blaikieb44f0bf2017-01-04 22:36:43 +00002573 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002574 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2575 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
David Blaikieb44f0bf2017-01-04 22:36:43 +00002576 unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002577
David Blaikieb44f0bf2017-01-04 22:36:43 +00002578 Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregorfb912652013-03-20 21:10:35 +00002579 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2580 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
2581 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
David Blaikieb44f0bf2017-01-04 22:36:43 +00002582 unsigned ConflictAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregorfb912652013-03-20 21:10:35 +00002583
Douglas Gregorf0b11de2017-09-14 23:38:44 +00002584 Abbrev = std::make_shared<BitCodeAbbrev>();
2585 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXPORT_AS));
2586 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2587 unsigned ExportAsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2588
Douglas Gregor253eefe2011-12-01 00:59:36 +00002589 // Write the submodule metadata block.
Richard Smith145e15a2017-04-24 23:12:30 +00002590 RecordData::value_type Record[] = {
2591 getNumberOfModules(WritingModule),
Richard Smithdd8b5332017-09-04 05:37:53 +00002592 FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS};
Douglas Gregor253eefe2011-12-01 00:59:36 +00002593 Stream.EmitRecord(SUBMODULE_METADATA, Record);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002594
Douglas Gregor69021972011-11-30 17:33:56 +00002595 // Write all of the submodules.
Douglas Gregorde3ef502011-11-30 23:21:26 +00002596 std::queue<Module *> Q;
Douglas Gregor69021972011-11-30 17:33:56 +00002597 Q.push(WritingModule);
Douglas Gregor69021972011-11-30 17:33:56 +00002598 while (!Q.empty()) {
Douglas Gregorde3ef502011-11-30 23:21:26 +00002599 Module *Mod = Q.front();
Douglas Gregor69021972011-11-30 17:33:56 +00002600 Q.pop();
Douglas Gregora89c5ac2011-12-06 01:10:29 +00002601 unsigned ID = getSubmoduleID(Mod);
Mehdi Amini57a41912015-09-10 01:46:39 +00002602
2603 uint64_t ParentID = 0;
Douglas Gregor69021972011-11-30 17:33:56 +00002604 if (Mod->Parent) {
2605 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
Mehdi Amini57a41912015-09-10 01:46:39 +00002606 ParentID = SubmoduleIDs[Mod->Parent];
Douglas Gregor69021972011-11-30 17:33:56 +00002607 }
Mehdi Amini57a41912015-09-10 01:46:39 +00002608
2609 // Emit the definition of the block.
2610 {
David Blaikie9ffe5a32017-01-30 05:00:26 +00002611 RecordData::value_type Record[] = {SUBMODULE_DEFINITION,
2612 ID,
2613 ParentID,
Simon Pilgrimf331a662017-09-04 10:54:39 +00002614 (RecordData::value_type)Mod->Kind,
David Blaikie9ffe5a32017-01-30 05:00:26 +00002615 Mod->IsFramework,
2616 Mod->IsExplicit,
2617 Mod->IsSystem,
2618 Mod->IsExternC,
2619 Mod->InferSubmodules,
2620 Mod->InferExplicitSubmodules,
2621 Mod->InferExportWildcard,
Jordan Rose90b0a1f2018-04-20 17:16:04 +00002622 Mod->ConfigMacrosExhaustive,
2623 Mod->ModuleMapIsPrivate};
Mehdi Amini57a41912015-09-10 01:46:39 +00002624 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2625 }
2626
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002627 // Emit the requirements.
Richard Smith080056b2015-08-18 21:53:42 +00002628 for (const auto &R : Mod->Requirements) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002629 RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.second};
Richard Smith080056b2015-08-18 21:53:42 +00002630 Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.first);
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +00002631 }
2632
Douglas Gregor69021972011-11-30 17:33:56 +00002633 // Emit the umbrella header, if there is one.
Richard Smith2b63d152015-05-16 02:28:53 +00002634 if (auto UmbrellaHeader = Mod->getUmbrellaHeader()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002635 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
Richard Smith2b63d152015-05-16 02:28:53 +00002636 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2637 UmbrellaHeader.NameAsWritten);
2638 } else if (auto UmbrellaDir = Mod->getUmbrellaDir()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002639 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
2640 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
Richard Smith2b63d152015-05-16 02:28:53 +00002641 UmbrellaDir.NameAsWritten);
Douglas Gregor69021972011-11-30 17:33:56 +00002642 }
Richard Smith306d8922014-10-22 23:50:56 +00002643
Douglas Gregor69021972011-11-30 17:33:56 +00002644 // Emit the headers.
Richard Smith202210b2014-10-24 20:23:01 +00002645 struct {
Richard Smith3c1a41a2014-12-02 00:08:08 +00002646 unsigned RecordKind;
Richard Smith202210b2014-10-24 20:23:01 +00002647 unsigned Abbrev;
Richard Smith3c1a41a2014-12-02 00:08:08 +00002648 Module::HeaderKind HeaderKind;
Richard Smith202210b2014-10-24 20:23:01 +00002649 } HeaderLists[] = {
Richard Smith3c1a41a2014-12-02 00:08:08 +00002650 {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
2651 {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
2652 {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
Richard Smith202210b2014-10-24 20:23:01 +00002653 {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
Richard Smith3c1a41a2014-12-02 00:08:08 +00002654 Module::HK_PrivateTextual},
2655 {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
Richard Smith202210b2014-10-24 20:23:01 +00002656 };
2657 for (auto &HL : HeaderLists) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002658 RecordData::value_type Record[] = {HL.RecordKind};
Richard Smith3c1a41a2014-12-02 00:08:08 +00002659 for (auto &H : Mod->Headers[HL.HeaderKind])
2660 Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
2661 }
2662
2663 // Emit the top headers.
2664 {
2665 auto TopHeaders = Mod->getTopHeaders(PP->getFileManager());
Mehdi Amini57a41912015-09-10 01:46:39 +00002666 RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
Richard Smith3c1a41a2014-12-02 00:08:08 +00002667 for (auto *H : TopHeaders)
2668 Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, H->getName());
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +00002669 }
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002670
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002671 // Emit the imports.
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002672 if (!Mod->Imports.empty()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002673 RecordData Record;
Richard Smith080056b2015-08-18 21:53:42 +00002674 for (auto *I : Mod->Imports)
2675 Record.push_back(getSubmoduleID(I));
Douglas Gregor0093b3c2011-12-05 16:33:54 +00002676 Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2677 }
2678
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002679 // Emit the exports.
Douglas Gregor24bb9232011-12-02 18:58:38 +00002680 if (!Mod->Exports.empty()) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002681 RecordData Record;
Richard Smith080056b2015-08-18 21:53:42 +00002682 for (const auto &E : Mod->Exports) {
2683 // FIXME: This may fail; we don't require that all exported modules
2684 // are local or imported.
2685 Record.push_back(getSubmoduleID(E.getPointer()));
2686 Record.push_back(E.getInt());
Douglas Gregor24bb9232011-12-02 18:58:38 +00002687 }
2688 Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2689 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002690
Daniel Jasperba7f2f72013-09-24 09:14:14 +00002691 //FIXME: How do we emit the 'use'd modules? They may not be submodules.
2692 // Might be unnecessary as use declarations are only used to build the
2693 // module itself.
2694
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002695 // Emit the link libraries.
Richard Smith080056b2015-08-18 21:53:42 +00002696 for (const auto &LL : Mod->LinkLibraries) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002697 RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
2698 LL.IsFramework};
Richard Smith080056b2015-08-18 21:53:42 +00002699 Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002700 }
2701
Douglas Gregorfb912652013-03-20 21:10:35 +00002702 // Emit the conflicts.
Richard Smith080056b2015-08-18 21:53:42 +00002703 for (const auto &C : Mod->Conflicts) {
Richard Smith080056b2015-08-18 21:53:42 +00002704 // FIXME: This may fail; we don't require that all conflicting modules
2705 // are local or imported.
Mehdi Amini57a41912015-09-10 01:46:39 +00002706 RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
2707 getSubmoduleID(C.Other)};
Richard Smith080056b2015-08-18 21:53:42 +00002708 Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message);
Douglas Gregorfb912652013-03-20 21:10:35 +00002709 }
2710
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002711 // Emit the configuration macros.
Richard Smith080056b2015-08-18 21:53:42 +00002712 for (const auto &CM : Mod->ConfigMacros) {
Mehdi Amini57a41912015-09-10 01:46:39 +00002713 RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
Richard Smith080056b2015-08-18 21:53:42 +00002714 Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM);
Douglas Gregor35b13ec2013-03-20 00:22:05 +00002715 }
2716
Richard Smithdc1f0422016-07-20 19:10:16 +00002717 // Emit the initializers, if any.
2718 RecordData Inits;
2719 for (Decl *D : Context->getModuleInitializers(Mod))
2720 Inits.push_back(GetDeclRef(D));
2721 if (!Inits.empty())
2722 Stream.EmitRecord(SUBMODULE_INITIALIZERS, Inits);
2723
Douglas Gregorf0b11de2017-09-14 23:38:44 +00002724 // Emit the name of the re-exported module, if any.
2725 if (!Mod->ExportAsModule.empty()) {
2726 RecordData::value_type Record[] = {SUBMODULE_EXPORT_AS};
2727 Stream.EmitRecordWithBlob(ExportAsAbbrev, Record, Mod->ExportAsModule);
2728 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002729
Douglas Gregor69021972011-11-30 17:33:56 +00002730 // Queue up the submodules of this module.
Richard Smith080056b2015-08-18 21:53:42 +00002731 for (auto *M : Mod->submodules())
2732 Q.push(M);
Douglas Gregor69021972011-11-30 17:33:56 +00002733 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002734
Douglas Gregor69021972011-11-30 17:33:56 +00002735 Stream.ExitBlock();
Richard Smith23d8d032015-05-14 00:45:20 +00002736
Richard Smith23d8d032015-05-14 00:45:20 +00002737 assert((NextSubmoduleID - FirstSubmoduleID ==
2738 getNumberOfModules(WritingModule)) &&
2739 "Wrong # of submodules; found a reference to a non-local, "
2740 "non-imported submodule?");
Douglas Gregor69021972011-11-30 17:33:56 +00002741}
2742
Argyrios Kyrtzidis0f06b982013-03-27 17:17:23 +00002743void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
2744 bool isModule) {
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002745 llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
2746 DiagStateIDMap;
2747 unsigned CurrID = 0;
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002748 RecordData Record;
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002749
Richard Smithe37391c2017-05-03 00:28:49 +00002750 auto EncodeDiagStateFlags =
2751 [](const DiagnosticsEngine::DiagState *DS) -> unsigned {
2752 unsigned Result = (unsigned)DS->ExtBehavior;
2753 for (unsigned Val :
Daniel Jasperba9aefc2017-05-03 07:48:27 +00002754 {(unsigned)DS->IgnoreAllWarnings, (unsigned)DS->EnableAllWarnings,
2755 (unsigned)DS->WarningsAsErrors, (unsigned)DS->ErrorsAsFatal,
2756 (unsigned)DS->SuppressSystemWarnings})
Richard Smithe37391c2017-05-03 00:28:49 +00002757 Result = (Result << 1) | Val;
2758 return Result;
2759 };
2760
2761 unsigned Flags = EncodeDiagStateFlags(Diag.DiagStatesByLoc.FirstDiagState);
2762 Record.push_back(Flags);
2763
Richard Smithd230de22017-01-26 01:01:01 +00002764 auto AddDiagState = [&](const DiagnosticsEngine::DiagState *State,
2765 bool IncludeNonPragmaStates) {
Richard Smithe37391c2017-05-03 00:28:49 +00002766 // Ensure that the diagnostic state wasn't modified since it was created.
2767 // We will not correctly round-trip this information otherwise.
2768 assert(Flags == EncodeDiagStateFlags(State) &&
2769 "diag state flags vary in single AST file");
2770
Richard Smithd230de22017-01-26 01:01:01 +00002771 unsigned &DiagStateID = DiagStateIDMap[State];
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002772 Record.push_back(DiagStateID);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00002773
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002774 if (DiagStateID == 0) {
2775 DiagStateID = ++CurrID;
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00002776
2777 // Add a placeholder for the number of mappings.
2778 auto SizeIdx = Record.size();
2779 Record.emplace_back();
Richard Smithd230de22017-01-26 01:01:01 +00002780 for (const auto &I : *State) {
2781 if (I.second.isPragma() || IncludeNonPragmaStates) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00002782 Record.push_back(I.first);
Richard Smithe37391c2017-05-03 00:28:49 +00002783 Record.push_back(I.second.serialize());
Argyrios Kyrtzidisefaa54a2012-10-30 00:27:21 +00002784 }
Argyrios Kyrtzidis243aedb2011-01-14 20:54:07 +00002785 }
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00002786 // Update the placeholder.
2787 Record[SizeIdx] = (Record.size() - SizeIdx) / 2;
Richard Smithd230de22017-01-26 01:01:01 +00002788 }
2789 };
2790
2791 AddDiagState(Diag.DiagStatesByLoc.FirstDiagState, isModule);
Richard Smithd230de22017-01-26 01:01:01 +00002792
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00002793 // Reserve a spot for the number of locations with state transitions.
2794 auto NumLocationsIdx = Record.size();
2795 Record.emplace_back();
2796
2797 // Emit the state transitions.
2798 unsigned NumLocations = 0;
Richard Smithd230de22017-01-26 01:01:01 +00002799 for (auto &FileIDAndFile : Diag.DiagStatesByLoc.Files) {
2800 if (!FileIDAndFile.first.isValid() ||
2801 !FileIDAndFile.second.HasLocalTransitions)
2802 continue;
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00002803 ++NumLocations;
Richard Smith6c2b5a82018-02-09 01:15:13 +00002804
2805 SourceLocation Loc = Diag.SourceMgr->getComposedLoc(FileIDAndFile.first, 0);
2806 assert(!Loc.isInvalid() && "start loc for valid FileID is invalid");
2807 AddSourceLocation(Loc, Record);
2808
Richard Smithd230de22017-01-26 01:01:01 +00002809 Record.push_back(FileIDAndFile.second.StateTransitions.size());
2810 for (auto &StatePoint : FileIDAndFile.second.StateTransitions) {
2811 Record.push_back(StatePoint.Offset);
2812 AddDiagState(StatePoint.State, false);
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002813 }
2814 }
2815
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00002816 // Backpatch the number of locations.
2817 Record[NumLocationsIdx] = NumLocations;
2818
2819 // Emit CurDiagStateLoc. Do it last in order to match source order.
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00002820 //
2821 // This also protects against a hypothetical corner case with simulating
2822 // -Werror settings for implicit modules in the ASTReader, where reading
2823 // CurDiagState out of context could change whether warning pragmas are
2824 // treated as errors.
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00002825 AddSourceLocation(Diag.DiagStatesByLoc.CurDiagStateLoc, Record);
2826 AddDiagState(Diag.DiagStatesByLoc.CurDiagState, false);
2827
Duncan P. N. Exon Smithf2435b92017-04-12 02:31:17 +00002828 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
Argyrios Kyrtzidis452707c2010-11-05 22:10:18 +00002829}
2830
Douglas Gregorc5046832009-04-27 18:38:38 +00002831//===----------------------------------------------------------------------===//
2832// Type Serialization
2833//===----------------------------------------------------------------------===//
Chris Lattnereeffaef2009-04-10 17:15:23 +00002834
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002835/// Write the representation of a type to the AST stream.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002836void ASTWriter::WriteType(QualType T) {
Richard Smith290d8012016-04-06 17:06:00 +00002837 TypeIdx &IdxRef = TypeIdxs[T];
2838 if (IdxRef.getIndex() == 0) // we haven't seen this type before.
2839 IdxRef = TypeIdx(NextTypeID++);
2840 TypeIdx Idx = IdxRef;
Mike Stump11289f42009-09-09 15:08:12 +00002841
Douglas Gregor9b3932c2010-10-05 18:37:06 +00002842 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
Douglas Gregordc72caa2010-10-04 18:21:45 +00002843
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002844 // Emit the type's representation.
John McCalld505e572019-12-13 21:54:44 -05002845 uint64_t Offset = ASTTypeWriter(*this).write(T);
John McCall8ccfcb52009-09-24 19:53:00 +00002846
Richard Smith290d8012016-04-06 17:06:00 +00002847 // Record the offset for this type.
2848 unsigned Index = Idx.getIndex() - FirstTypeID;
2849 if (TypeOffsets.size() == Index)
Dmitry Polukhina7afb212020-04-16 09:24:46 -07002850 TypeOffsets.emplace_back(Offset);
Richard Smith290d8012016-04-06 17:06:00 +00002851 else if (TypeOffsets.size() < Index) {
2852 TypeOffsets.resize(Index + 1);
Dmitry Polukhina7afb212020-04-16 09:24:46 -07002853 TypeOffsets[Index].setBitOffset(Offset);
John McCall8ccfcb52009-09-24 19:53:00 +00002854 } else {
Richard Smith290d8012016-04-06 17:06:00 +00002855 llvm_unreachable("Types emitted in wrong order");
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002856 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002857}
2858
Douglas Gregorc5046832009-04-27 18:38:38 +00002859//===----------------------------------------------------------------------===//
2860// Declaration Serialization
2861//===----------------------------------------------------------------------===//
2862
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002863/// Write the block containing all of the declaration IDs
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002864/// lexically declared within the given DeclContext.
2865///
2866/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002867/// bitstream, or 0 if no block was written.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002868uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002869 DeclContext *DC) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002870 if (DC->decls_empty())
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002871 return 0;
2872
Douglas Gregor8f45df52009-04-16 22:23:12 +00002873 uint64_t Offset = Stream.GetCurrentBitNo();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002874 SmallVector<uint32_t, 128> KindDeclPairs;
2875 for (const auto *D : DC->decls()) {
2876 KindDeclPairs.push_back(D->getKind());
2877 KindDeclPairs.push_back(GetDeclRef(D));
2878 }
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002879
Douglas Gregora57c3ab2009-04-22 22:34:57 +00002880 ++NumLexicalDeclContexts;
Mehdi Amini57a41912015-09-10 01:46:39 +00002881 RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
Richard Smith82f8fcd2015-08-06 22:07:25 +00002882 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
2883 bytes(KindDeclPairs));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00002884 return Offset;
2885}
2886
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002887void ASTWriter::WriteTypeDeclOffsets() {
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002888 using namespace llvm;
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002889
2890 // Write the type offsets array
David Blaikieb44f0bf2017-01-04 22:36:43 +00002891 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00002892 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002893 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
Douglas Gregor5204bde2011-08-02 16:26:37 +00002894 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002895 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
David Blaikieb44f0bf2017-01-04 22:36:43 +00002896 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00002897 {
2898 RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(),
2899 FirstTypeID - NUM_PREDEF_TYPE_IDS};
2900 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
2901 }
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002902
2903 // Write the declaration offsets array
David Blaikieb44f0bf2017-01-04 22:36:43 +00002904 Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00002905 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002906 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
Douglas Gregorf7180622011-08-03 15:48:04 +00002907 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002908 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
David Blaikieb44f0bf2017-01-04 22:36:43 +00002909 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00002910 {
2911 RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(),
2912 FirstDeclID - NUM_PREDEF_DECL_IDS};
2913 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
2914 }
Sebastian Redl1ea025b2010-07-16 16:36:56 +00002915}
2916
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002917void ASTWriter::WriteFileDeclIDsMap() {
2918 using namespace llvm;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002919
David Blaikie409df392020-04-28 18:05:28 -07002920 SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs;
2921 SortedFileDeclIDs.reserve(FileDeclIDs.size());
2922 for (const auto &P : FileDeclIDs)
2923 SortedFileDeclIDs.push_back(std::make_pair(P.first, P.second.get()));
Fangrui Song55fab262018-09-26 22:16:28 +00002924 llvm::sort(SortedFileDeclIDs, llvm::less_first());
Chandler Carruthb306d732015-03-27 00:31:20 +00002925
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002926 // Join the vectors of DeclIDs from all files.
Chandler Carruthb306d732015-03-27 00:31:20 +00002927 SmallVector<DeclID, 256> FileGroupedDeclIDs;
2928 for (auto &FileDeclEntry : SortedFileDeclIDs) {
2929 DeclIDInFileInfo &Info = *FileDeclEntry.second;
2930 Info.FirstDeclIndex = FileGroupedDeclIDs.size();
2931 for (auto &LocDeclEntry : Info.DeclIDs)
2932 FileGroupedDeclIDs.push_back(LocDeclEntry.second);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002933 }
2934
David Blaikieb44f0bf2017-01-04 22:36:43 +00002935 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002936 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002937 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002938 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00002939 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00002940 RecordData::value_type Record[] = {FILE_SORTED_DECLS,
2941 FileGroupedDeclIDs.size()};
Reid Kleckner012665e2015-05-21 00:13:09 +00002942 Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00002943}
2944
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002945void ASTWriter::WriteComments() {
2946 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
Ilya Biryukov45643102018-07-09 11:33:23 +00002947 auto _ = llvm::make_scope_exit([this] { Stream.ExitBlock(); });
2948 if (!PP->getPreprocessorOpts().WriteCommentListToPCH)
2949 return;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002950 RecordData Record;
Jan Korousf31d8df2019-08-13 18:11:44 +00002951 for (const auto &FO : Context->Comments.OrderedComments) {
2952 for (const auto &OC : FO.second) {
2953 const RawComment *I = OC.second;
2954 Record.clear();
2955 AddSourceRange(I->getSourceRange(), Record);
2956 Record.push_back(I->getKind());
2957 Record.push_back(I->isTrailingComment());
2958 Record.push_back(I->isAlmostTrailingComment());
2959 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
2960 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002961 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00002962}
2963
Douglas Gregorc5046832009-04-27 18:38:38 +00002964//===----------------------------------------------------------------------===//
2965// Global Method Pool and Selector Serialization
2966//===----------------------------------------------------------------------===//
2967
Douglas Gregore84a9da2009-04-20 20:36:09 +00002968namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002969
Douglas Gregorc78d3462009-04-24 21:10:55 +00002970// Trait used for the on-disk hash table used in the method pool.
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00002971class ASTMethodPoolTrait {
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002972 ASTWriter &Writer;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002973
2974public:
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002975 using key_type = Selector;
2976 using key_type_ref = key_type;
Mike Stump11289f42009-09-09 15:08:12 +00002977
Sebastian Redl834bb972010-08-04 17:20:04 +00002978 struct data_type {
Sebastian Redl539c5062010-08-18 23:57:32 +00002979 SelectorID ID;
Sebastian Redl834bb972010-08-04 17:20:04 +00002980 ObjCMethodList Instance, Factory;
2981 };
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002982 using data_type_ref = const data_type &;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002983
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002984 using hash_value_type = unsigned;
2985 using offset_type = unsigned;
Justin Bogner25463f12014-04-18 20:27:24 +00002986
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002987 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) {}
Mike Stump11289f42009-09-09 15:08:12 +00002988
Justin Bogner25463f12014-04-18 20:27:24 +00002989 static hash_value_type ComputeHash(Selector Sel) {
Argyrios Kyrtzidis4bd97102010-08-20 16:03:52 +00002990 return serialization::ComputeHash(Sel);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002991 }
Mike Stump11289f42009-09-09 15:08:12 +00002992
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002993 std::pair<unsigned, unsigned>
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002994 EmitKeyDataLength(raw_ostream& Out, Selector Sel,
Douglas Gregorc78d3462009-04-24 21:10:55 +00002995 data_type_ref Methods) {
Justin Bognere1c147c2014-03-28 22:03:19 +00002996 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00002997
Peter Collingbournee3f65292018-05-18 19:46:24 +00002998 endian::Writer LE(Out, little);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002999 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
Justin Bognere1c147c2014-03-28 22:03:19 +00003000 LE.write<uint16_t>(KeyLen);
Sebastian Redl834bb972010-08-04 17:20:04 +00003001 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
3002 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003003 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003004 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00003005 DataLen += 4;
Sebastian Redl834bb972010-08-04 17:20:04 +00003006 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003007 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003008 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00003009 DataLen += 4;
Justin Bognere1c147c2014-03-28 22:03:19 +00003010 LE.write<uint16_t>(DataLen);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003011 return std::make_pair(KeyLen, DataLen);
3012 }
Mike Stump11289f42009-09-09 15:08:12 +00003013
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003014 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003015 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003016
Peter Collingbournee3f65292018-05-18 19:46:24 +00003017 endian::Writer LE(Out, little);
Mike Stump11289f42009-09-09 15:08:12 +00003018 uint64_t Start = Out.tell();
Douglas Gregor95c13f52009-04-25 17:48:32 +00003019 assert((Start >> 32) == 0 && "Selector key offset too large");
3020 Writer.SetSelectorOffset(Sel, Start);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003021 unsigned N = Sel.getNumArgs();
Justin Bognere1c147c2014-03-28 22:03:19 +00003022 LE.write<uint16_t>(N);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003023 if (N == 0)
3024 N = 1;
3025 for (unsigned I = 0; I != N; ++I)
Justin Bognere1c147c2014-03-28 22:03:19 +00003026 LE.write<uint32_t>(
3027 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003028 }
Mike Stump11289f42009-09-09 15:08:12 +00003029
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003030 void EmitData(raw_ostream& Out, key_type_ref,
Douglas Gregor4647cfa2009-04-24 21:49:02 +00003031 data_type_ref Methods, unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003032 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003033
Peter Collingbournee3f65292018-05-18 19:46:24 +00003034 endian::Writer LE(Out, little);
Douglas Gregor4647cfa2009-04-24 21:49:02 +00003035 uint64_t Start = Out.tell(); (void)Start;
Justin Bognere1c147c2014-03-28 22:03:19 +00003036 LE.write<uint32_t>(Methods.ID);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003037 unsigned NumInstanceMethods = 0;
Sebastian Redl834bb972010-08-04 17:20:04 +00003038 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003039 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003040 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00003041 ++NumInstanceMethods;
3042
3043 unsigned NumFactoryMethods = 0;
Sebastian Redl834bb972010-08-04 17:20:04 +00003044 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003045 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003046 if (Method->getMethod())
Douglas Gregorc78d3462009-04-24 21:10:55 +00003047 ++NumFactoryMethods;
3048
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003049 unsigned InstanceBits = Methods.Instance.getBits();
3050 assert(InstanceBits < 4);
Nico Weberff4b35e2014-12-27 22:14:15 +00003051 unsigned InstanceHasMoreThanOneDeclBit =
3052 Methods.Instance.hasMoreThanOneDecl();
3053 unsigned FullInstanceBits = (NumInstanceMethods << 3) |
3054 (InstanceHasMoreThanOneDeclBit << 2) |
3055 InstanceBits;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003056 unsigned FactoryBits = Methods.Factory.getBits();
3057 assert(FactoryBits < 4);
Nico Weberff4b35e2014-12-27 22:14:15 +00003058 unsigned FactoryHasMoreThanOneDeclBit =
3059 Methods.Factory.hasMoreThanOneDecl();
3060 unsigned FullFactoryBits = (NumFactoryMethods << 3) |
3061 (FactoryHasMoreThanOneDeclBit << 2) |
3062 FactoryBits;
3063 LE.write<uint16_t>(FullInstanceBits);
3064 LE.write<uint16_t>(FullFactoryBits);
Sebastian Redl834bb972010-08-04 17:20:04 +00003065 for (const ObjCMethodList *Method = &Methods.Instance; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003066 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003067 if (Method->getMethod())
3068 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
Sebastian Redl834bb972010-08-04 17:20:04 +00003069 for (const ObjCMethodList *Method = &Methods.Factory; Method;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003070 Method = Method->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003071 if (Method->getMethod())
3072 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
Douglas Gregor4647cfa2009-04-24 21:49:02 +00003073
3074 assert(Out.tell() - Start == DataLen && "Data length is wrong");
Douglas Gregorc78d3462009-04-24 21:10:55 +00003075 }
3076};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003077
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003078} // namespace
Douglas Gregorc78d3462009-04-24 21:10:55 +00003079
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003080/// Write ObjC data: selectors and the method pool.
Douglas Gregorc78d3462009-04-24 21:10:55 +00003081///
3082/// The method pool contains both instance and factory methods, stored
Sebastian Redla19a67f2010-08-03 21:58:15 +00003083/// in an on-disk hash table indexed by the selector. The hash table also
3084/// contains an empty entry for every other selector known to Sema.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003085void ASTWriter::WriteSelectors(Sema &SemaRef) {
Douglas Gregorc78d3462009-04-24 21:10:55 +00003086 using namespace llvm;
3087
Sebastian Redla19a67f2010-08-03 21:58:15 +00003088 // Do we have to do anything at all?
Sebastian Redl834bb972010-08-04 17:20:04 +00003089 if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
Sebastian Redla19a67f2010-08-03 21:58:15 +00003090 return;
Sebastian Redld95a56e2010-08-04 18:21:41 +00003091 unsigned NumTableEntries = 0;
Sebastian Redla19a67f2010-08-03 21:58:15 +00003092 // Create and write out the blob that contains selectors and the method pool.
Douglas Gregorc78d3462009-04-24 21:10:55 +00003093 {
Justin Bognerbb094f02014-04-18 19:57:06 +00003094 llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003095 ASTMethodPoolTrait Trait(*this);
Mike Stump11289f42009-09-09 15:08:12 +00003096
Sebastian Redla19a67f2010-08-03 21:58:15 +00003097 // Create the on-disk hash table representation. We walk through every
3098 // selector we've seen and look it up in the method pool.
Sebastian Redld95a56e2010-08-04 18:21:41 +00003099 SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003100 for (auto &SelectorAndID : SelectorIDs) {
3101 Selector S = SelectorAndID.first;
3102 SelectorID ID = SelectorAndID.second;
Sebastian Redla19a67f2010-08-03 21:58:15 +00003103 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003104 ASTMethodPoolTrait::data_type Data = {
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003105 ID,
Sebastian Redl834bb972010-08-04 17:20:04 +00003106 ObjCMethodList(),
3107 ObjCMethodList()
3108 };
3109 if (F != SemaRef.MethodPool.end()) {
3110 Data.Instance = F->second.first;
3111 Data.Factory = F->second.second;
3112 }
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003113 // Only write this selector if it's not in an existing AST or something
Sebastian Redld95a56e2010-08-04 18:21:41 +00003114 // changed.
Chandler Carruthacbbeb92015-03-27 00:47:43 +00003115 if (Chain && ID < FirstSelectorID) {
Sebastian Redld95a56e2010-08-04 18:21:41 +00003116 // Selector already exists. Did it change?
3117 bool changed = false;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003118 for (ObjCMethodList *M = &Data.Instance;
3119 !changed && M && M->getMethod(); M = M->getNext()) {
3120 if (!M->getMethod()->isFromASTFile())
Sebastian Redld95a56e2010-08-04 18:21:41 +00003121 changed = true;
3122 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003123 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->getMethod();
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003124 M = M->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003125 if (!M->getMethod()->isFromASTFile())
Sebastian Redld95a56e2010-08-04 18:21:41 +00003126 changed = true;
3127 }
3128 if (!changed)
3129 continue;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003130 } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
Sebastian Redl6e1a2a02010-08-04 21:22:45 +00003131 // A new method pool entry.
3132 ++NumTableEntries;
Sebastian Redld95a56e2010-08-04 18:21:41 +00003133 }
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003134 Generator.insert(S, Data, Trait);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003135 }
3136
Douglas Gregorc78d3462009-04-24 21:10:55 +00003137 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003138 SmallString<4096> MethodPool;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003139 uint32_t BucketOffset;
3140 {
Justin Bognere1c147c2014-03-28 22:03:19 +00003141 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003142
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003143 ASTMethodPoolTrait Trait(*this);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003144 llvm::raw_svector_ostream Out(MethodPool);
3145 // Make sure that no bucket is at offset 0
Peter Collingbournee3f65292018-05-18 19:46:24 +00003146 endian::write<uint32_t>(Out, 0, little);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003147 BucketOffset = Generator.Emit(Out, Trait);
3148 }
3149
3150 // Create a blob abbreviation
David Blaikieb44f0bf2017-01-04 22:36:43 +00003151 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00003152 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003153 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregor95c13f52009-04-25 17:48:32 +00003154 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003155 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00003156 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregorc78d3462009-04-24 21:10:55 +00003157
Douglas Gregor95c13f52009-04-25 17:48:32 +00003158 // Write the method pool
Mehdi Amini57a41912015-09-10 01:46:39 +00003159 {
3160 RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3161 NumTableEntries};
3162 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3163 }
Douglas Gregor95c13f52009-04-25 17:48:32 +00003164
3165 // Create a blob abbreviation for the selector table offsets.
David Blaikieb44f0bf2017-01-04 22:36:43 +00003166 Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00003167 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
Douglas Gregord4c5ed02010-10-29 22:39:52 +00003168 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
Douglas Gregor8f364fb2011-08-03 23:28:44 +00003169 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
Douglas Gregor95c13f52009-04-25 17:48:32 +00003170 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00003171 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor95c13f52009-04-25 17:48:32 +00003172
3173 // Write the selector offsets table.
Mehdi Amini57a41912015-09-10 01:46:39 +00003174 {
3175 RecordData::value_type Record[] = {
3176 SELECTOR_OFFSETS, SelectorOffsets.size(),
3177 FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3178 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3179 bytes(SelectorOffsets));
3180 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00003181 }
3182}
3183
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003184/// Write the selectors referenced in @selector expression into AST file.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00003185void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003186 using namespace llvm;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003187
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003188 if (SemaRef.ReferencedSelectors.empty())
3189 return;
Sebastian Redlada023c2010-08-04 20:40:17 +00003190
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003191 RecordData Record;
Richard Smithe64e7452016-04-18 21:54:58 +00003192 ASTRecordWriter Writer(*this, Record);
Sebastian Redlada023c2010-08-04 20:40:17 +00003193
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003194 // Note: this writes out all references even for a dependent AST. But it is
Sebastian Redl51c79d82010-08-04 22:21:29 +00003195 // very tricky to fix, and given that @selector shouldn't really appear in
3196 // headers, probably not worth it. It's not a correctness issue.
Chandler Carruth12c8f652015-03-27 00:55:05 +00003197 for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
3198 Selector Sel = SelectorAndLocation.first;
3199 SourceLocation Loc = SelectorAndLocation.second;
Richard Smithe64e7452016-04-18 21:54:58 +00003200 Writer.AddSelectorRef(Sel);
3201 Writer.AddSourceLocation(Loc);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003202 }
Richard Smithe64e7452016-04-18 21:54:58 +00003203 Writer.Emit(REFERENCED_SELECTOR_POOL);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00003204}
3205
Douglas Gregorc5046832009-04-27 18:38:38 +00003206//===----------------------------------------------------------------------===//
3207// Identifier Table Serialization
3208//===----------------------------------------------------------------------===//
3209
Richard Smithb3761912015-02-05 23:08:52 +00003210/// Determine the declaration that should be put into the name lookup table to
3211/// represent the given declaration in this module. This is usually D itself,
3212/// but if D was imported and merged into a local declaration, we want the most
3213/// recent local declaration instead. The chosen declaration will be the most
3214/// recent declaration in any module that imports this one.
3215static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
3216 NamedDecl *D) {
3217 if (!LangOpts.Modules || !D->isFromASTFile())
3218 return D;
3219
3220 if (Decl *Redecl = D->getPreviousDecl()) {
3221 // For Redeclarable decls, a prior declaration might be local.
3222 for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
Richard Smithd49941b2016-04-26 23:40:43 +00003223 // If we find a local decl, we're done.
3224 if (!Redecl->isFromASTFile()) {
3225 // Exception: in very rare cases (for injected-class-names), not all
3226 // redeclarations are in the same semantic context. Skip ones in a
3227 // different context. They don't go in this lookup table at all.
3228 if (!Redecl->getDeclContext()->getRedeclContext()->Equals(
3229 D->getDeclContext()->getRedeclContext()))
3230 continue;
Richard Smithb3761912015-02-05 23:08:52 +00003231 return cast<NamedDecl>(Redecl);
Richard Smithd49941b2016-04-26 23:40:43 +00003232 }
3233
Richard Smithfe620d22015-03-05 23:24:12 +00003234 // If we find a decl from a (chained-)PCH stop since we won't find a
Richard Smithb3761912015-02-05 23:08:52 +00003235 // local one.
Richard Smithd49941b2016-04-26 23:40:43 +00003236 if (Redecl->getOwningModuleID() == 0)
Richard Smithb3761912015-02-05 23:08:52 +00003237 break;
3238 }
3239 } else if (Decl *First = D->getCanonicalDecl()) {
3240 // For Mergeable decls, the first decl might be local.
3241 if (!First->isFromASTFile())
3242 return cast<NamedDecl>(First);
3243 }
3244
3245 // All declarations are imported. Our most recent declaration will also be
3246 // the most recent one in anyone who imports us.
3247 return D;
3248}
3249
Douglas Gregorc78d3462009-04-24 21:10:55 +00003250namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003251
Richard Smithcf97cf62015-04-19 01:34:23 +00003252class ASTIdentifierTableTrait {
3253 ASTWriter &Writer;
3254 Preprocessor &PP;
3255 IdentifierResolver &IdResolver;
Richard Smith9c254182015-07-19 21:41:12 +00003256 bool IsModule;
Richard Smitha534a312015-07-21 23:54:07 +00003257 bool NeedDecls;
Richard Smith33e0f7e2015-07-22 02:08:40 +00003258 ASTWriter::RecordData *InterestingIdentifierOffsets;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003259
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003260 /// Determines whether this is an "interesting" identifier that needs a
Richard Smithcf97cf62015-04-19 01:34:23 +00003261 /// full IdentifierInfo structure written into the hash table. Notably, this
3262 /// doesn't check whether the name has macros defined; use PublicMacroIterator
3263 /// to check that.
Richard Smith9c254182015-07-19 21:41:12 +00003264 bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
Richard Smithd7329392015-04-21 21:46:32 +00003265 if (MacroOffset ||
3266 II->isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +00003267 (IsModule ? II->hasRevertedBuiltin() : II->getObjCOrBuiltinID()) ||
Richard Smithcf97cf62015-04-19 01:34:23 +00003268 II->hasRevertedTokenIDToIdentifier() ||
Bruno Ricci366ba732018-09-21 12:53:22 +00003269 (NeedDecls && II->getFETokenInfo()))
Richard Smithcf97cf62015-04-19 01:34:23 +00003270 return true;
3271
3272 return false;
3273 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003274
Douglas Gregore84a9da2009-04-20 20:36:09 +00003275public:
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003276 using key_type = IdentifierInfo *;
3277 using key_type_ref = key_type;
Mike Stump11289f42009-09-09 15:08:12 +00003278
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003279 using data_type = IdentID;
3280 using data_type_ref = data_type;
Mike Stump11289f42009-09-09 15:08:12 +00003281
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003282 using hash_value_type = unsigned;
3283 using offset_type = unsigned;
Justin Bogner25463f12014-04-18 20:27:24 +00003284
Richard Smithd7329392015-04-21 21:46:32 +00003285 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
Richard Smith33e0f7e2015-07-22 02:08:40 +00003286 IdentifierResolver &IdResolver, bool IsModule,
3287 ASTWriter::RecordData *InterestingIdentifierOffsets)
Richard Smitha534a312015-07-21 23:54:07 +00003288 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
Richard Smith33e0f7e2015-07-22 02:08:40 +00003289 NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3290 InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
Douglas Gregore84a9da2009-04-20 20:36:09 +00003291
Richard Smithd79514e2016-02-05 19:03:40 +00003292 bool needDecls() const { return NeedDecls; }
3293
Justin Bogner25463f12014-04-18 20:27:24 +00003294 static hash_value_type ComputeHash(const IdentifierInfo* II) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003295 return llvm::djbHash(II->getName());
Douglas Gregore84a9da2009-04-20 20:36:09 +00003296 }
Mike Stump11289f42009-09-09 15:08:12 +00003297
Richard Smith33e0f7e2015-07-22 02:08:40 +00003298 bool isInterestingIdentifier(const IdentifierInfo *II) {
3299 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3300 return isInterestingIdentifier(II, MacroOffset);
3301 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003302
Richard Smith9c254182015-07-19 21:41:12 +00003303 bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) {
3304 return isInterestingIdentifier(II, 0);
3305 }
3306
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003307 std::pair<unsigned, unsigned>
Douglas Gregor935bc7a22011-10-27 09:33:13 +00003308 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003309 unsigned KeyLen = II->getLength() + 1;
Douglas Gregor1d583f22009-04-28 21:18:29 +00003310 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
Richard Smithd7329392015-04-21 21:46:32 +00003311 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3312 if (isInterestingIdentifier(II, MacroOffset)) {
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003313 DataLen += 2; // 2 bytes for builtin ID
3314 DataLen += 2; // 2 bytes for flags
Richard Smithd7329392015-04-21 21:46:32 +00003315 if (MacroOffset)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00003316 DataLen += 4; // MacroDirectives offset.
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003317
Richard Smitha534a312015-07-21 23:54:07 +00003318 if (NeedDecls) {
3319 for (IdentifierResolver::iterator D = IdResolver.begin(II),
3320 DEnd = IdResolver.end();
3321 D != DEnd; ++D)
3322 DataLen += 4;
3323 }
Douglas Gregor1d583f22009-04-28 21:18:29 +00003324 }
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003325
Justin Bognere1c147c2014-03-28 22:03:19 +00003326 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003327
Peter Collingbournee3f65292018-05-18 19:46:24 +00003328 endian::Writer LE(Out, little);
Justin Bognere1c147c2014-03-28 22:03:19 +00003329
Richard Smithdf8a8312015-03-13 04:05:01 +00003330 assert((uint16_t)DataLen == DataLen && (uint16_t)KeyLen == KeyLen);
Justin Bognere1c147c2014-03-28 22:03:19 +00003331 LE.write<uint16_t>(DataLen);
Douglas Gregorab4df582009-04-28 20:01:51 +00003332 // We emit the key length after the data length so that every
3333 // string is preceded by a 16-bit length. This matches the PTH
3334 // format for storing identifiers.
Justin Bognere1c147c2014-03-28 22:03:19 +00003335 LE.write<uint16_t>(KeyLen);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003336 return std::make_pair(KeyLen, DataLen);
3337 }
Mike Stump11289f42009-09-09 15:08:12 +00003338
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003339 void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
Douglas Gregore84a9da2009-04-20 20:36:09 +00003340 unsigned KeyLen) {
3341 // Record the location of the key data. This is used when generating
3342 // the mapping from persistent IDs to strings.
3343 Writer.SetIdentifierOffset(II, Out.tell());
Richard Smith33e0f7e2015-07-22 02:08:40 +00003344
3345 // Emit the offset of the key/data length information to the interesting
3346 // identifiers table if necessary.
3347 if (InterestingIdentifierOffsets && isInterestingIdentifier(II))
3348 InterestingIdentifierOffsets->push_back(Out.tell() - 4);
3349
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00003350 Out.write(II->getNameStart(), KeyLen);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003351 }
Mike Stump11289f42009-09-09 15:08:12 +00003352
Douglas Gregor4a69c2e2011-09-01 17:04:32 +00003353 void EmitData(raw_ostream& Out, IdentifierInfo* II,
Sebastian Redl539c5062010-08-18 23:57:32 +00003354 IdentID ID, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003355 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003356
Peter Collingbournee3f65292018-05-18 19:46:24 +00003357 endian::Writer LE(Out, little);
Richard Smithcf97cf62015-04-19 01:34:23 +00003358
Richard Smithd7329392015-04-21 21:46:32 +00003359 auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3360 if (!isInterestingIdentifier(II, MacroOffset)) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003361 LE.write<uint32_t>(ID << 1);
Douglas Gregor1d583f22009-04-28 21:18:29 +00003362 return;
3363 }
Douglas Gregorb9256522009-04-28 21:32:13 +00003364
Justin Bognere1c147c2014-03-28 22:03:19 +00003365 LE.write<uint32_t>((ID << 1) | 0x01);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003366 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3367 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
Justin Bognere1c147c2014-03-28 22:03:19 +00003368 LE.write<uint16_t>(Bits);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003369 Bits = 0;
Richard Smithd7329392015-04-21 21:46:32 +00003370 bool HadMacroDefinition = MacroOffset != 0;
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003371 Bits = (Bits << 1) | unsigned(HadMacroDefinition);
Daniel Dunbar91b640a2009-12-18 20:58:47 +00003372 Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3373 Bits = (Bits << 1) | unsigned(II->isPoisoned());
Richard Smith9c254182015-07-19 21:41:12 +00003374 Bits = (Bits << 1) | unsigned(II->hasRevertedBuiltin());
Argyrios Kyrtzidis3084a612010-08-11 22:55:12 +00003375 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
Daniel Dunbar91b640a2009-12-18 20:58:47 +00003376 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
Justin Bognere1c147c2014-03-28 22:03:19 +00003377 LE.write<uint16_t>(Bits);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003378
Richard Smithd7329392015-04-21 21:46:32 +00003379 if (HadMacroDefinition)
3380 LE.write<uint32_t>(MacroOffset);
Alexander Kornienko1d26c022012-09-25 17:18:14 +00003381
Richard Smitha534a312015-07-21 23:54:07 +00003382 if (NeedDecls) {
3383 // Emit the declaration IDs in reverse order, because the
3384 // IdentifierResolver provides the declarations as they would be
3385 // visible (e.g., the function "stat" would come before the struct
3386 // "stat"), but the ASTReader adds declarations to the end of the list
3387 // (so we need to see the struct "stat" before the function "stat").
3388 // Only emit declarations that aren't from a chained PCH, though.
3389 SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II),
3390 IdResolver.end());
3391 for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(),
3392 DEnd = Decls.rend();
3393 D != DEnd; ++D)
3394 LE.write<uint32_t>(
3395 Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D)));
3396 }
Douglas Gregore84a9da2009-04-20 20:36:09 +00003397 }
3398};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003399
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003400} // namespace
Douglas Gregore84a9da2009-04-20 20:36:09 +00003401
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003402/// Write the identifier table into the AST file.
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003403///
3404/// The identifier table consists of a blob containing string data
3405/// (the actual identifiers themselves) and a separate "offsets" index
3406/// that maps identifier IDs to locations within the blob.
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003407void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
Douglas Gregor935bc7a22011-10-27 09:33:13 +00003408 IdentifierResolver &IdResolver,
3409 bool IsModule) {
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003410 using namespace llvm;
3411
Richard Smith33e0f7e2015-07-22 02:08:40 +00003412 RecordData InterestingIdents;
3413
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003414 // Create and write out the blob that contains the identifier
3415 // strings.
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003416 {
Justin Bognerbb094f02014-04-18 19:57:06 +00003417 llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
Richard Smith33e0f7e2015-07-22 02:08:40 +00003418 ASTIdentifierTableTrait Trait(
3419 *this, PP, IdResolver, IsModule,
3420 (getLangOpts().CPlusPlus && IsModule) ? &InterestingIdents : nullptr);
Mike Stump11289f42009-09-09 15:08:12 +00003421
Douglas Gregore6648fb2009-04-28 20:33:11 +00003422 // Look for any identifiers that were named while processing the
3423 // headers, but are otherwise not needed. We add these to the hash
3424 // table to enable checking of the predefines buffer in the case
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00003425 // where the user adds new macro definitions when building the AST
Douglas Gregore6648fb2009-04-28 20:33:11 +00003426 // file.
Chandler Carruth8440c982015-03-26 23:54:15 +00003427 SmallVector<const IdentifierInfo *, 128> IIs;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003428 for (const auto &ID : PP.getIdentifierTable())
3429 IIs.push_back(ID.second);
Chandler Carruth8440c982015-03-26 23:54:15 +00003430 // Sort the identifiers lexicographically before getting them references so
3431 // that their order is stable.
Benjamin Kramercd2bae32019-08-22 17:32:16 +00003432 llvm::sort(IIs, llvm::deref<std::less<>>());
Chandler Carruth8440c982015-03-26 23:54:15 +00003433 for (const IdentifierInfo *II : IIs)
Richard Smith9c254182015-07-19 21:41:12 +00003434 if (Trait.isInterestingNonMacroIdentifier(II))
3435 getIdentifierRef(II);
Douglas Gregore6648fb2009-04-28 20:33:11 +00003436
Sebastian Redlff4a2952010-07-23 23:49:55 +00003437 // Create the on-disk hash table representation. We only store offsets
3438 // for identifiers that appear here for the first time.
3439 IdentifierOffsets.resize(NextIdentID - FirstIdentID);
Chandler Carruth885e78c2015-03-24 21:18:10 +00003440 for (auto IdentIDPair : IdentifierIDs) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003441 auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
Chandler Carruth885e78c2015-03-24 21:18:10 +00003442 IdentID ID = IdentIDPair.second;
3443 assert(II && "NULL identifier in identifier table");
Vassil Vassilev262f41e2016-03-30 20:16:03 +00003444 // Write out identifiers if either the ID is local or the identifier has
3445 // changed since it was loaded.
3446 if (ID >= FirstIdentID || !Chain || !II->isFromAST()
3447 || II->hasChangedSinceDeserialization() ||
Richard Smithd79514e2016-02-05 19:03:40 +00003448 (Trait.needDecls() &&
3449 II->hasFETokenInfoChangedSinceDeserialization()))
Chandler Carruth885e78c2015-03-24 21:18:10 +00003450 Generator.insert(II, ID, Trait);
Douglas Gregore84a9da2009-04-20 20:36:09 +00003451 }
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003452
Douglas Gregore84a9da2009-04-20 20:36:09 +00003453 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003454 SmallString<4096> IdentifierTable;
Douglas Gregora868bbd2009-04-21 22:25:48 +00003455 uint32_t BucketOffset;
Douglas Gregore84a9da2009-04-20 20:36:09 +00003456 {
Justin Bognere1c147c2014-03-28 22:03:19 +00003457 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003458
Douglas Gregore84a9da2009-04-20 20:36:09 +00003459 llvm::raw_svector_ostream Out(IdentifierTable);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003460 // Make sure that no bucket is at offset 0
Peter Collingbournee3f65292018-05-18 19:46:24 +00003461 endian::write<uint32_t>(Out, 0, little);
Douglas Gregora868bbd2009-04-21 22:25:48 +00003462 BucketOffset = Generator.Emit(Out, Trait);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003463 }
3464
3465 // Create a blob abbreviation
David Blaikieb44f0bf2017-01-04 22:36:43 +00003466 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00003467 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
Douglas Gregora868bbd2009-04-21 22:25:48 +00003468 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
Douglas Gregore84a9da2009-04-20 20:36:09 +00003469 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00003470 unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003471
3472 // Write the identifier table
Mehdi Amini57a41912015-09-10 01:46:39 +00003473 RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
Yaron Keren92e1b622015-03-18 10:17:07 +00003474 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003475 }
3476
3477 // Write the offsets table for identifier IDs.
David Blaikieb44f0bf2017-01-04 22:36:43 +00003478 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Sebastian Redl539c5062010-08-18 23:57:32 +00003479 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
Douglas Gregor0e149972009-04-25 19:10:14 +00003480 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
Douglas Gregor1ab036c2011-08-03 21:49:18 +00003481 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
Douglas Gregor0e149972009-04-25 19:10:14 +00003482 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00003483 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Douglas Gregor0e149972009-04-25 19:10:14 +00003484
Douglas Gregor8d7edce2013-02-08 21:30:59 +00003485#ifndef NDEBUG
3486 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3487 assert(IdentifierOffsets[I] && "Missing identifier offset?");
3488#endif
Mehdi Amini57a41912015-09-10 01:46:39 +00003489
3490 RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
3491 IdentifierOffsets.size(),
3492 FirstIdentID - NUM_PREDEF_IDENT_IDS};
Douglas Gregor0e149972009-04-25 19:10:14 +00003493 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
Reid Kleckner012665e2015-05-21 00:13:09 +00003494 bytes(IdentifierOffsets));
Richard Smith33e0f7e2015-07-22 02:08:40 +00003495
3496 // In C++, write the list of interesting identifiers (those that are
3497 // defined as macros, poisoned, or similar unusual things).
3498 if (!InterestingIdents.empty())
3499 Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00003500}
3501
Douglas Gregorc5046832009-04-27 18:38:38 +00003502//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003503// DeclContext's Name Lookup Table Serialization
3504//===----------------------------------------------------------------------===//
3505
3506namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003507
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003508// Trait used for the on-disk hash table used in the method pool.
3509class ASTDeclContextNameLookupTrait {
3510 ASTWriter &Writer;
Richard Smithd88a7f12015-09-01 20:35:42 +00003511 llvm::SmallVector<DeclID, 64> DeclIDs;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003512
3513public:
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003514 using key_type = DeclarationNameKey;
3515 using key_type_ref = key_type;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003516
Richard Smithd88a7f12015-09-01 20:35:42 +00003517 /// A start and end index into DeclIDs, representing a sequence of decls.
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003518 using data_type = std::pair<unsigned, unsigned>;
3519 using data_type_ref = const data_type &;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003520
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003521 using hash_value_type = unsigned;
3522 using offset_type = unsigned;
Justin Bogner25463f12014-04-18 20:27:24 +00003523
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003524 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) {}
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003525
Richard Smithd88a7f12015-09-01 20:35:42 +00003526 template<typename Coll>
3527 data_type getData(const Coll &Decls) {
3528 unsigned Start = DeclIDs.size();
3529 for (NamedDecl *D : Decls) {
3530 DeclIDs.push_back(
3531 Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3532 }
3533 return std::make_pair(Start, DeclIDs.size());
3534 }
3535
3536 data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
3537 unsigned Start = DeclIDs.size();
3538 for (auto ID : FromReader)
3539 DeclIDs.push_back(ID);
3540 return std::make_pair(Start, DeclIDs.size());
3541 }
3542
3543 static bool EqualKey(key_type_ref a, key_type_ref b) {
3544 return a == b;
3545 }
3546
Richard Smitha06c7e62015-08-26 23:55:49 +00003547 hash_value_type ComputeHash(DeclarationNameKey Name) {
3548 return Name.getHash();
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003549 }
3550
Richard Smithd88a7f12015-09-01 20:35:42 +00003551 void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
3552 assert(Writer.hasChain() &&
3553 "have reference to loaded module file but no chain?");
3554
3555 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003556
Peter Collingbournee3f65292018-05-18 19:46:24 +00003557 endian::write<uint32_t>(Out, Writer.getChain()->getModuleFileID(F), little);
Richard Smithd88a7f12015-09-01 20:35:42 +00003558 }
3559
Richard Smitha06c7e62015-08-26 23:55:49 +00003560 std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
3561 DeclarationNameKey Name,
3562 data_type_ref Lookup) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003563 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003564
Peter Collingbournee3f65292018-05-18 19:46:24 +00003565 endian::Writer LE(Out, little);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003566 unsigned KeyLen = 1;
Richard Smitha06c7e62015-08-26 23:55:49 +00003567 switch (Name.getKind()) {
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003568 case DeclarationName::Identifier:
3569 case DeclarationName::ObjCZeroArgSelector:
3570 case DeclarationName::ObjCOneArgSelector:
3571 case DeclarationName::ObjCMultiArgSelector:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003572 case DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00003573 case DeclarationName::CXXDeductionGuideName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003574 KeyLen += 4;
3575 break;
3576 case DeclarationName::CXXOperatorName:
3577 KeyLen += 1;
3578 break;
Douglas Gregor3b65ed02011-08-02 18:32:54 +00003579 case DeclarationName::CXXConstructorName:
3580 case DeclarationName::CXXDestructorName:
3581 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003582 case DeclarationName::CXXUsingDirective:
3583 break;
3584 }
Justin Bognere1c147c2014-03-28 22:03:19 +00003585 LE.write<uint16_t>(KeyLen);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003586
Richard Smithf02662d2015-07-30 03:17:16 +00003587 // 4 bytes for each DeclID.
Richard Smithd88a7f12015-09-01 20:35:42 +00003588 unsigned DataLen = 4 * (Lookup.second - Lookup.first);
3589 assert(uint16_t(DataLen) == DataLen &&
3590 "too many decls for serialized lookup result");
Justin Bognere1c147c2014-03-28 22:03:19 +00003591 LE.write<uint16_t>(DataLen);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003592
3593 return std::make_pair(KeyLen, DataLen);
3594 }
3595
Richard Smitha06c7e62015-08-26 23:55:49 +00003596 void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003597 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003598
Peter Collingbournee3f65292018-05-18 19:46:24 +00003599 endian::Writer LE(Out, little);
Richard Smitha06c7e62015-08-26 23:55:49 +00003600 LE.write<uint8_t>(Name.getKind());
3601 switch (Name.getKind()) {
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003602 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +00003603 case DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00003604 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00003605 LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier()));
Benjamin Kramer53750b12012-09-19 13:40:40 +00003606 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003607 case DeclarationName::ObjCZeroArgSelector:
3608 case DeclarationName::ObjCOneArgSelector:
3609 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00003610 LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
Benjamin Kramer53750b12012-09-19 13:40:40 +00003611 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003612 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00003613 assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
Benjamin Kramer53750b12012-09-19 13:40:40 +00003614 "Invalid operator?");
Richard Smitha06c7e62015-08-26 23:55:49 +00003615 LE.write<uint8_t>(Name.getOperatorKind());
Benjamin Kramer53750b12012-09-19 13:40:40 +00003616 return;
Douglas Gregor3b65ed02011-08-02 18:32:54 +00003617 case DeclarationName::CXXConstructorName:
3618 case DeclarationName::CXXDestructorName:
3619 case DeclarationName::CXXConversionFunctionName:
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003620 case DeclarationName::CXXUsingDirective:
Benjamin Kramer53750b12012-09-19 13:40:40 +00003621 return;
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003622 }
Benjamin Kramer53750b12012-09-19 13:40:40 +00003623
3624 llvm_unreachable("Invalid name kind?");
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003625 }
3626
Richard Smitha06c7e62015-08-26 23:55:49 +00003627 void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
3628 unsigned DataLen) {
Justin Bognere1c147c2014-03-28 22:03:19 +00003629 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003630
Peter Collingbournee3f65292018-05-18 19:46:24 +00003631 endian::Writer LE(Out, little);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003632 uint64_t Start = Out.tell(); (void)Start;
Richard Smithd88a7f12015-09-01 20:35:42 +00003633 for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
3634 LE.write<uint32_t>(DeclIDs[I]);
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003635 assert(Out.tell() - Start == DataLen && "Data length is wrong");
3636 }
3637};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003638
Eugene Zelenkob7d89102017-11-11 00:08:50 +00003639} // namespace
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00003640
Chandler Carruthe972c362015-03-26 03:11:40 +00003641bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
3642 DeclContext *DC) {
Erich Keanef92f31c2018-08-01 20:48:16 +00003643 return Result.hasExternalDecls() &&
3644 DC->hasNeedToReconcileExternalVisibleStorage();
Chandler Carruthe972c362015-03-26 03:11:40 +00003645}
3646
3647bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
3648 DeclContext *DC) {
3649 for (auto *D : Result.getLookupResult())
3650 if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
3651 return false;
3652
3653 return true;
3654}
3655
Richard Smithd88a7f12015-09-01 20:35:42 +00003656void
Chandler Carruthe972c362015-03-26 03:11:40 +00003657ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
Richard Smithcd45dbc2014-04-19 03:48:30 +00003658 llvm::SmallVectorImpl<char> &LookupTable) {
Erich Keanef92f31c2018-08-01 20:48:16 +00003659 assert(!ConstDC->hasLazyLocalLexicalLookups() &&
3660 !ConstDC->hasLazyExternalLexicalLookups() &&
Richard Smith9e2341d2015-03-23 03:25:59 +00003661 "must call buildLookups first");
Richard Smithcd45dbc2014-04-19 03:48:30 +00003662
Chandler Carruthe972c362015-03-26 03:11:40 +00003663 // FIXME: We need to build the lookups table, which is logically const.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003664 auto *DC = const_cast<DeclContext*>(ConstDC);
Chandler Carruthe972c362015-03-26 03:11:40 +00003665 assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
3666
3667 // Create the on-disk hash table representation.
Richard Smithd88a7f12015-09-01 20:35:42 +00003668 MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait,
3669 ASTDeclContextNameLookupTrait> Generator;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003670 ASTDeclContextNameLookupTrait Trait(*this);
3671
Chandler Carruthe972c362015-03-26 03:11:40 +00003672 // The first step is to collect the declaration names which we need to
3673 // serialize into the name lookup table, and to collect them in a stable
3674 // order.
3675 SmallVector<DeclarationName, 16> Names;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003676
Chandler Carruthe972c362015-03-26 03:11:40 +00003677 // We also build up small sets of the constructor and conversion function
3678 // names which are visible.
3679 llvm::SmallSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003680
Chandler Carruthe972c362015-03-26 03:11:40 +00003681 for (auto &Lookup : *DC->buildLookup()) {
3682 auto &Name = Lookup.first;
3683 auto &Result = Lookup.second;
3684
Douglas Gregor7dd37e52015-11-03 01:20:54 +00003685 // If there are no local declarations in our lookup result, we
3686 // don't need to write an entry for the name at all. If we can't
3687 // write out a lookup set without performing more deserialization,
3688 // just skip this entry.
3689 if (isLookupResultExternal(Result, DC) &&
Chandler Carruthe972c362015-03-26 03:11:40 +00003690 isLookupResultEntirelyExternal(Result, DC))
3691 continue;
3692
3693 // We also skip empty results. If any of the results could be external and
3694 // the currently available results are empty, then all of the results are
3695 // external and we skip it above. So the only way we get here with an empty
3696 // results is when no results could have been external *and* we have
3697 // external results.
3698 //
3699 // FIXME: While we might want to start emitting on-disk entries for negative
3700 // lookups into a decl context as an optimization, today we *have* to skip
3701 // them because there are names with empty lookup results in decl contexts
3702 // which we can't emit in any stable ordering: we lookup constructors and
3703 // conversion functions in the enclosing namespace scope creating empty
3704 // results for them. This in almost certainly a bug in Clang's name lookup,
3705 // but that is likely to be hard or impossible to fix and so we tolerate it
3706 // here by omitting lookups with empty results.
3707 if (Lookup.second.getLookupResult().empty())
3708 continue;
3709
3710 switch (Lookup.first.getNameKind()) {
3711 default:
3712 Names.push_back(Lookup.first);
3713 break;
3714
Richard Smithcd45dbc2014-04-19 03:48:30 +00003715 case DeclarationName::CXXConstructorName:
Chandler Carruthe972c362015-03-26 03:11:40 +00003716 assert(isa<CXXRecordDecl>(DC) &&
3717 "Cannot have a constructor name outside of a class!");
3718 ConstructorNameSet.insert(Name);
3719 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003720
3721 case DeclarationName::CXXConversionFunctionName:
Chandler Carruthe972c362015-03-26 03:11:40 +00003722 assert(isa<CXXRecordDecl>(DC) &&
3723 "Cannot have a conversion function name outside of a class!");
3724 ConversionNameSet.insert(Name);
Rafael Espindolac606b3e2015-03-25 04:43:15 +00003725 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00003726 }
Chandler Carruth75c9f132015-03-25 00:34:51 +00003727 }
Chandler Carruth75c9f132015-03-25 00:34:51 +00003728
Chandler Carruthe972c362015-03-26 03:11:40 +00003729 // Sort the names into a stable order.
Fangrui Song55fab262018-09-26 22:16:28 +00003730 llvm::sort(Names);
Chandler Carruthe972c362015-03-26 03:11:40 +00003731
Chandler Carruthffbf7052015-03-26 22:27:09 +00003732 if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
Chandler Carruthe972c362015-03-26 03:11:40 +00003733 // We need to establish an ordering of constructor and conversion function
Chandler Carruthffbf7052015-03-26 22:27:09 +00003734 // names, and they don't have an intrinsic ordering.
Chandler Carruthe972c362015-03-26 03:11:40 +00003735
Chandler Carruthffbf7052015-03-26 22:27:09 +00003736 // First we try the easy case by forming the current context's constructor
3737 // name and adding that name first. This is a very useful optimization to
3738 // avoid walking the lexical declarations in many cases, and it also
3739 // handles the only case where a constructor name can come from some other
3740 // lexical context -- when that name is an implicit constructor merged from
3741 // another declaration in the redecl chain. Any non-implicit constructor or
3742 // conversion function which doesn't occur in all the lexical contexts
3743 // would be an ODR violation.
3744 auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
3745 Context->getCanonicalType(Context->getRecordType(D)));
3746 if (ConstructorNameSet.erase(ImplicitCtorName))
3747 Names.push_back(ImplicitCtorName);
Chandler Carruthe972c362015-03-26 03:11:40 +00003748
Chandler Carruthffbf7052015-03-26 22:27:09 +00003749 // If we still have constructors or conversion functions, we walk all the
3750 // names in the decl and add the constructors and conversion functions
3751 // which are visible in the order they lexically occur within the context.
3752 if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
3753 for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
3754 if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
3755 auto Name = ChildND->getDeclName();
3756 switch (Name.getNameKind()) {
3757 default:
3758 continue;
3759
3760 case DeclarationName::CXXConstructorName:
3761 if (ConstructorNameSet.erase(Name))
3762 Names.push_back(Name);
3763 break;
3764
3765 case DeclarationName::CXXConversionFunctionName:
3766 if (ConversionNameSet.erase(Name))
3767 Names.push_back(Name);
3768 break;
3769 }
3770
3771 if (ConstructorNameSet.empty() && ConversionNameSet.empty())
3772 break;
Chandler Carruthe972c362015-03-26 03:11:40 +00003773 }
3774
Chandler Carruthe972c362015-03-26 03:11:40 +00003775 assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
3776 "constructors by walking all the "
3777 "lexical members of the context.");
3778 assert(ConversionNameSet.empty() && "Failed to find all of the visible "
3779 "conversion functions by walking all "
3780 "the lexical members of the context.");
Richard Smith961eae52014-03-25 01:14:22 +00003781 }
3782
Chandler Carruthe972c362015-03-26 03:11:40 +00003783 // Next we need to do a lookup with each name into this decl context to fully
3784 // populate any results from external sources. We don't actually use the
3785 // results of these lookups because we only want to use the results after all
3786 // results have been loaded and the pointers into them will be stable.
3787 for (auto &Name : Names)
3788 DC->lookup(Name);
3789
3790 // Now we need to insert the results for each name into the hash table. For
3791 // constructor names and conversion function names, we actually need to merge
3792 // all of the results for them into one list of results each and insert
3793 // those.
3794 SmallVector<NamedDecl *, 8> ConstructorDecls;
3795 SmallVector<NamedDecl *, 8> ConversionDecls;
3796
3797 // Now loop over the names, either inserting them or appending for the two
3798 // special cases.
3799 for (auto &Name : Names) {
3800 DeclContext::lookup_result Result = DC->noload_lookup(Name);
3801
3802 switch (Name.getNameKind()) {
3803 default:
Richard Smithd88a7f12015-09-01 20:35:42 +00003804 Generator.insert(Name, Trait.getData(Result), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00003805 break;
3806
3807 case DeclarationName::CXXConstructorName:
3808 ConstructorDecls.append(Result.begin(), Result.end());
3809 break;
3810
3811 case DeclarationName::CXXConversionFunctionName:
3812 ConversionDecls.append(Result.begin(), Result.end());
3813 break;
3814 }
3815 }
3816
3817 // Handle our two special cases if we ended up having any. We arbitrarily use
3818 // the first declaration's name here because the name itself isn't part of
3819 // the key, only the kind of name is used.
3820 if (!ConstructorDecls.empty())
3821 Generator.insert(ConstructorDecls.front()->getDeclName(),
Richard Smithd88a7f12015-09-01 20:35:42 +00003822 Trait.getData(ConstructorDecls), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00003823 if (!ConversionDecls.empty())
3824 Generator.insert(ConversionDecls.front()->getDeclName(),
Richard Smithd88a7f12015-09-01 20:35:42 +00003825 Trait.getData(ConversionDecls), Trait);
Chandler Carruthe972c362015-03-26 03:11:40 +00003826
Richard Smithd88a7f12015-09-01 20:35:42 +00003827 // Create the on-disk hash table. Also emit the existing imported and
3828 // merged table if there is one.
3829 auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr;
3830 Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr);
Richard Smith961eae52014-03-25 01:14:22 +00003831}
3832
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003833/// Write the block containing all of the declaration IDs
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003834/// visible from the given DeclContext.
3835///
3836/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
Sebastian Redla4071b42010-08-24 00:50:09 +00003837/// bitstream, or 0 if no block was written.
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003838uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
3839 DeclContext *DC) {
Richard Smith5fc18a92015-07-12 23:43:21 +00003840 // If we imported a key declaration of this namespace, write the visible
3841 // lookup results as an update record for it rather than including them
3842 // on this declaration. We will only look at key declarations on reload.
3843 if (isa<NamespaceDecl>(DC) && Chain &&
3844 Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) {
3845 // Only do this once, for the first local declaration of the namespace.
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00003846 for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
Richard Smith5fc18a92015-07-12 23:43:21 +00003847 Prev = Prev->getPreviousDecl())
3848 if (!Prev->isFromASTFile())
3849 return 0;
3850
3851 // Note that we need to emit an update record for the primary context.
3852 UpdatedDeclContexts.insert(DC->getPrimaryContext());
3853
3854 // Make sure all visible decls are written. They will be recorded later. We
3855 // do this using a side data structure so we can sort the names into
3856 // a deterministic order.
3857 StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup();
3858 SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16>
3859 LookupResults;
3860 if (Map) {
3861 LookupResults.reserve(Map->size());
3862 for (auto &Entry : *Map)
3863 LookupResults.push_back(
3864 std::make_pair(Entry.first, Entry.second.getLookupResult()));
3865 }
3866
Fangrui Song55fab262018-09-26 22:16:28 +00003867 llvm::sort(LookupResults, llvm::less_first());
Richard Smith5fc18a92015-07-12 23:43:21 +00003868 for (auto &NameAndResult : LookupResults) {
3869 DeclarationName Name = NameAndResult.first;
3870 DeclContext::lookup_result Result = NameAndResult.second;
3871 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
3872 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
3873 // We have to work around a name lookup bug here where negative lookup
3874 // results for these names get cached in namespace lookup tables (these
3875 // names should never be looked up in a namespace).
3876 assert(Result.empty() && "Cannot have a constructor or conversion "
3877 "function name in a namespace!");
3878 continue;
3879 }
3880
3881 for (NamedDecl *ND : Result)
3882 if (!ND->isFromASTFile())
3883 GetDeclRef(ND);
3884 }
3885
3886 return 0;
3887 }
3888
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003889 if (DC->getPrimaryContext() != DC)
3890 return 0;
3891
Chandler Carruthe972c362015-03-26 03:11:40 +00003892 // Skip contexts which don't support name lookup.
3893 if (!DC->isLookupContext())
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003894 return 0;
3895
3896 // If not in C++, we perform name lookup for the translation unit via the
3897 // IdentifierInfo chains, don't bother to build a visible-declarations table.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003898 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003899 return 0;
3900
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003901 // Serialize the contents of the mapping used for lookup. Note that,
3902 // although we have two very different code paths, the serialized
3903 // representation is the same for both cases: a declaration name,
3904 // followed by a size, followed by references to the visible
3905 // declarations that have that name.
3906 uint64_t Offset = Stream.GetCurrentBitNo();
Richard Smithf634c902012-03-16 06:12:59 +00003907 StoredDeclsMap *Map = DC->buildLookup();
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003908 if (!Map || Map->empty())
3909 return 0;
3910
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003911 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003912 SmallString<4096> LookupTable;
Richard Smithd88a7f12015-09-01 20:35:42 +00003913 GenerateNameLookupTable(DC, LookupTable);
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003914
3915 // Write the lookup table
Mehdi Amini57a41912015-09-10 01:46:39 +00003916 RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003917 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
Yaron Keren92e1b622015-03-18 10:17:07 +00003918 LookupTable);
Argyrios Kyrtzidisba88bfa2010-08-20 16:04:35 +00003919 ++NumVisibleDeclContexts;
3920 return Offset;
3921}
3922
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003923/// Write an UPDATE_VISIBLE block for the given context.
Sebastian Redla4071b42010-08-24 00:50:09 +00003924///
3925/// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
3926/// DeclContext in a dependent AST file. As such, they only exist for the TU
Richard Smithf634c902012-03-16 06:12:59 +00003927/// (in C++), for namespaces, and for classes with forward-declared unscoped
3928/// enumeration members (in C++11).
Sebastian Redla4071b42010-08-24 00:50:09 +00003929void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
Richard Smith961eae52014-03-25 01:14:22 +00003930 StoredDeclsMap *Map = DC->getLookupPtr();
Sebastian Redla4071b42010-08-24 00:50:09 +00003931 if (!Map || Map->empty())
3932 return;
3933
Sebastian Redla4071b42010-08-24 00:50:09 +00003934 // Create the on-disk hash table in a buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003935 SmallString<4096> LookupTable;
Richard Smithd88a7f12015-09-01 20:35:42 +00003936 GenerateNameLookupTable(DC, LookupTable);
Sebastian Redla4071b42010-08-24 00:50:09 +00003937
Richard Smith5fc18a92015-07-12 23:43:21 +00003938 // If we're updating a namespace, select a key declaration as the key for the
3939 // update record; those are the only ones that will be checked on reload.
3940 if (isa<NamespaceDecl>(DC))
3941 DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
3942
Sebastian Redla4071b42010-08-24 00:50:09 +00003943 // Write the lookup table
Mehdi Amini57a41912015-09-10 01:46:39 +00003944 RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))};
Yaron Keren92e1b622015-03-18 10:17:07 +00003945 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
Sebastian Redla4071b42010-08-24 00:50:09 +00003946}
3947
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003948/// Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003949void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
Melanie Blower2ba4e3a2020-04-10 13:34:46 -07003950 RecordData::value_type Record[] = {Opts.getAsOpaqueInt()};
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003951 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
3952}
3953
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003954/// Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003955void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003956 if (!SemaRef.Context.getLangOpts().OpenCL)
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003957 return;
3958
3959 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
3960 RecordData Record;
Yaxun Liu5b746652016-12-18 05:18:55 +00003961 for (const auto &I:Opts.OptMap) {
3962 AddString(I.getKey(), Record);
3963 auto V = I.getValue();
Yaxun Liucc2741c2016-12-18 06:35:06 +00003964 Record.push_back(V.Supported ? 1 : 0);
3965 Record.push_back(V.Enabled ? 1 : 0);
Yaxun Liu5b746652016-12-18 05:18:55 +00003966 Record.push_back(V.Avail);
3967 Record.push_back(V.Core);
3968 }
Peter Collingbourne5df20e02011-02-15 19:46:30 +00003969 Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
3970}
3971
Yaxun Liu5b746652016-12-18 05:18:55 +00003972void ASTWriter::WriteOpenCLExtensionTypes(Sema &SemaRef) {
3973 if (!SemaRef.Context.getLangOpts().OpenCL)
3974 return;
3975
Bruno Ricci2751b692019-04-18 15:13:27 +00003976 // Sort the elements of the map OpenCLTypeExtMap by TypeIDs,
3977 // without copying them.
3978 const llvm::DenseMap<const Type *, std::set<std::string>> &OpenCLTypeExtMap =
3979 SemaRef.OpenCLTypeExtMap;
3980 using ElementTy = std::pair<TypeID, const std::set<std::string> *>;
3981 llvm::SmallVector<ElementTy, 8> StableOpenCLTypeExtMap;
3982 StableOpenCLTypeExtMap.reserve(OpenCLTypeExtMap.size());
3983
3984 for (const auto &I : OpenCLTypeExtMap)
3985 StableOpenCLTypeExtMap.emplace_back(
3986 getTypeID(I.first->getCanonicalTypeInternal()), &I.second);
3987
3988 auto CompareByTypeID = [](const ElementTy &E1, const ElementTy &E2) -> bool {
3989 return E1.first < E2.first;
3990 };
3991 llvm::sort(StableOpenCLTypeExtMap, CompareByTypeID);
3992
Yaxun Liu5b746652016-12-18 05:18:55 +00003993 RecordData Record;
Bruno Ricci2751b692019-04-18 15:13:27 +00003994 for (const ElementTy &E : StableOpenCLTypeExtMap) {
3995 Record.push_back(E.first); // TypeID
3996 const std::set<std::string> *ExtSet = E.second;
3997 Record.push_back(static_cast<unsigned>(ExtSet->size()));
3998 for (const std::string &Ext : *ExtSet)
Yaxun Liu5b746652016-12-18 05:18:55 +00003999 AddString(Ext, Record);
4000 }
Bruno Ricci2751b692019-04-18 15:13:27 +00004001
Yaxun Liu5b746652016-12-18 05:18:55 +00004002 Stream.EmitRecord(OPENCL_EXTENSION_TYPES, Record);
4003}
4004
4005void ASTWriter::WriteOpenCLExtensionDecls(Sema &SemaRef) {
4006 if (!SemaRef.Context.getLangOpts().OpenCL)
4007 return;
4008
Bruno Ricci2751b692019-04-18 15:13:27 +00004009 // Sort the elements of the map OpenCLDeclExtMap by DeclIDs,
4010 // without copying them.
4011 const llvm::DenseMap<const Decl *, std::set<std::string>> &OpenCLDeclExtMap =
4012 SemaRef.OpenCLDeclExtMap;
4013 using ElementTy = std::pair<DeclID, const std::set<std::string> *>;
4014 llvm::SmallVector<ElementTy, 8> StableOpenCLDeclExtMap;
4015 StableOpenCLDeclExtMap.reserve(OpenCLDeclExtMap.size());
4016
4017 for (const auto &I : OpenCLDeclExtMap)
4018 StableOpenCLDeclExtMap.emplace_back(getDeclID(I.first), &I.second);
4019
4020 auto CompareByDeclID = [](const ElementTy &E1, const ElementTy &E2) -> bool {
4021 return E1.first < E2.first;
4022 };
4023 llvm::sort(StableOpenCLDeclExtMap, CompareByDeclID);
4024
Yaxun Liu5b746652016-12-18 05:18:55 +00004025 RecordData Record;
Bruno Ricci2751b692019-04-18 15:13:27 +00004026 for (const ElementTy &E : StableOpenCLDeclExtMap) {
4027 Record.push_back(E.first); // DeclID
4028 const std::set<std::string> *ExtSet = E.second;
4029 Record.push_back(static_cast<unsigned>(ExtSet->size()));
4030 for (const std::string &Ext : *ExtSet)
Yaxun Liu5b746652016-12-18 05:18:55 +00004031 AddString(Ext, Record);
4032 }
Bruno Ricci2751b692019-04-18 15:13:27 +00004033
Yaxun Liu5b746652016-12-18 05:18:55 +00004034 Stream.EmitRecord(OPENCL_EXTENSION_DECLS, Record);
4035}
4036
Justin Lebar67a78a62016-10-08 22:15:58 +00004037void ASTWriter::WriteCUDAPragmas(Sema &SemaRef) {
4038 if (SemaRef.ForceCUDAHostDeviceDepth > 0) {
4039 RecordData::value_type Record[] = {SemaRef.ForceCUDAHostDeviceDepth};
4040 Stream.EmitRecord(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH, Record);
4041 }
4042}
4043
Douglas Gregor404cdde2012-01-27 01:47:08 +00004044void ASTWriter::WriteObjCCategories() {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004045 SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
Douglas Gregor404cdde2012-01-27 01:47:08 +00004046 RecordData Categories;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004047
Douglas Gregor404cdde2012-01-27 01:47:08 +00004048 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
4049 unsigned Size = 0;
4050 unsigned StartIndex = Categories.size();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004051
Douglas Gregor404cdde2012-01-27 01:47:08 +00004052 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004053
Douglas Gregor404cdde2012-01-27 01:47:08 +00004054 // Allocate space for the size.
4055 Categories.push_back(0);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004056
Douglas Gregor404cdde2012-01-27 01:47:08 +00004057 // Add the categories.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00004058 for (ObjCInterfaceDecl::known_categories_iterator
4059 Cat = Class->known_categories_begin(),
4060 CatEnd = Class->known_categories_end();
4061 Cat != CatEnd; ++Cat, ++Size) {
4062 assert(getDeclID(*Cat) != 0 && "Bogus category");
4063 AddDeclRef(*Cat, Categories);
Douglas Gregor404cdde2012-01-27 01:47:08 +00004064 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004065
Douglas Gregor404cdde2012-01-27 01:47:08 +00004066 // Update the size.
4067 Categories[StartIndex] = Size;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004068
Douglas Gregor404cdde2012-01-27 01:47:08 +00004069 // Record this interface -> category map.
4070 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
4071 CategoriesMap.push_back(CatInfo);
4072 }
4073
4074 // Sort the categories map by the definition ID, since the reader will be
4075 // performing binary searches on this information.
4076 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
4077
4078 // Emit the categories map.
4079 using namespace llvm;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004080
David Blaikieb44f0bf2017-01-04 22:36:43 +00004081 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Douglas Gregor404cdde2012-01-27 01:47:08 +00004082 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
4083 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
4084 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004085 unsigned AbbrevID = Stream.EmitAbbrev(std::move(Abbrev));
Mehdi Amini57a41912015-09-10 01:46:39 +00004086
4087 RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
4088 Stream.EmitRecordWithBlob(AbbrevID, Record,
4089 reinterpret_cast<char *>(CategoriesMap.data()),
Douglas Gregor404cdde2012-01-27 01:47:08 +00004090 CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
Mehdi Amini57a41912015-09-10 01:46:39 +00004091
Douglas Gregor404cdde2012-01-27 01:47:08 +00004092 // Emit the category lists.
4093 Stream.EmitRecord(OBJC_CATEGORIES, Categories);
4094}
4095
Richard Smithe40f2ba2013-08-07 21:41:30 +00004096void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
4097 Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
4098
4099 if (LPTMap.empty())
4100 return;
4101
4102 RecordData Record;
Justin Lebar28f09c52016-10-10 16:26:08 +00004103 for (auto &LPTMapEntry : LPTMap) {
Chandler Carruth52cee4d2015-03-26 09:08:15 +00004104 const FunctionDecl *FD = LPTMapEntry.first;
Justin Lebar28f09c52016-10-10 16:26:08 +00004105 LateParsedTemplate &LPT = *LPTMapEntry.second;
Chandler Carruth52cee4d2015-03-26 09:08:15 +00004106 AddDeclRef(FD, Record);
Justin Lebar28f09c52016-10-10 16:26:08 +00004107 AddDeclRef(LPT.D, Record);
4108 Record.push_back(LPT.Toks.size());
Richard Smithe40f2ba2013-08-07 21:41:30 +00004109
Justin Lebar28f09c52016-10-10 16:26:08 +00004110 for (const auto &Tok : LPT.Toks) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004111 AddToken(Tok, Record);
Richard Smithe40f2ba2013-08-07 21:41:30 +00004112 }
4113 }
4114 Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
4115}
4116
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004117/// Write the state of 'pragma clang optimize' at the end of the module.
Dario Domizioli13a0a382014-05-23 12:13:25 +00004118void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
4119 RecordData Record;
4120 SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
4121 AddSourceLocation(PragmaLoc, Record);
4122 Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
4123}
4124
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004125/// Write the state of 'pragma ms_struct' at the end of the module.
Nico Weber779355f2016-03-02 23:22:00 +00004126void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
4127 RecordData Record;
4128 Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF);
4129 Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
4130}
4131
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004132/// Write the state of 'pragma pointers_to_members' at the end of the
Nico Weber42932312016-03-03 00:17:35 +00004133//module.
4134void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
4135 RecordData Record;
4136 Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod);
4137 AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record);
4138 Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
4139}
4140
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004141/// Write the state of 'pragma pack' at the end of the module.
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00004142void ASTWriter::WritePackPragmaOptions(Sema &SemaRef) {
Duncan P. N. Exon Smith03df14c2017-04-15 00:07:57 +00004143 // Don't serialize pragma pack state for modules, since it should only take
4144 // effect on a per-submodule basis.
4145 if (WritingModule)
4146 return;
4147
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00004148 RecordData Record;
4149 Record.push_back(SemaRef.PackStack.CurrentValue);
4150 AddSourceLocation(SemaRef.PackStack.CurrentPragmaLocation, Record);
4151 Record.push_back(SemaRef.PackStack.Stack.size());
4152 for (const auto &StackEntry : SemaRef.PackStack.Stack) {
4153 Record.push_back(StackEntry.Value);
4154 AddSourceLocation(StackEntry.PragmaLocation, Record);
Alex Lorenz45b40142017-07-28 14:41:21 +00004155 AddSourceLocation(StackEntry.PragmaPushLocation, Record);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00004156 AddString(StackEntry.StackSlotLabel, Record);
4157 }
4158 Stream.EmitRecord(PACK_PRAGMA_OPTIONS, Record);
4159}
4160
Melanie Blowerf5360d42020-05-01 10:32:06 -07004161/// Write the state of 'pragma float_control' at the end of the module.
4162void ASTWriter::WriteFloatControlPragmaOptions(Sema &SemaRef) {
4163 // Don't serialize pragma float_control state for modules,
4164 // since it should only take effect on a per-submodule basis.
4165 if (WritingModule)
4166 return;
4167
4168 RecordData Record;
4169 Record.push_back(SemaRef.FpPragmaStack.CurrentValue);
4170 AddSourceLocation(SemaRef.FpPragmaStack.CurrentPragmaLocation, Record);
4171 Record.push_back(SemaRef.FpPragmaStack.Stack.size());
4172 for (const auto &StackEntry : SemaRef.FpPragmaStack.Stack) {
4173 Record.push_back(StackEntry.Value);
4174 AddSourceLocation(StackEntry.PragmaLocation, Record);
4175 AddSourceLocation(StackEntry.PragmaPushLocation, Record);
4176 AddString(StackEntry.StackSlotLabel, Record);
4177 }
4178 Stream.EmitRecord(FLOAT_CONTROL_PRAGMA_OPTIONS, Record);
4179}
4180
Douglas Gregor8f64ca12015-12-08 22:43:32 +00004181void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
4182 ModuleFileExtensionWriter &Writer) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004183 // Enter the extension block.
4184 Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
4185
4186 // Emit the metadata record abbreviation.
David Blaikieb44f0bf2017-01-04 22:36:43 +00004187 auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004188 Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
4189 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4190 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4191 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4192 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4193 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004194 unsigned Abbrev = Stream.EmitAbbrev(std::move(Abv));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004195
4196 // Emit the metadata record.
4197 RecordData Record;
4198 auto Metadata = Writer.getExtension()->getExtensionMetadata();
4199 Record.push_back(EXTENSION_METADATA);
4200 Record.push_back(Metadata.MajorVersion);
4201 Record.push_back(Metadata.MinorVersion);
4202 Record.push_back(Metadata.BlockName.size());
4203 Record.push_back(Metadata.UserInfo.size());
4204 SmallString<64> Buffer;
4205 Buffer += Metadata.BlockName;
4206 Buffer += Metadata.UserInfo;
4207 Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
4208
4209 // Emit the contents of the extension block.
Douglas Gregor8f64ca12015-12-08 22:43:32 +00004210 Writer.writeExtensionContents(SemaRef, Stream);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004211
4212 // Exit the extension block.
4213 Stream.ExitBlock();
4214}
4215
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00004216//===----------------------------------------------------------------------===//
Douglas Gregorc5046832009-04-27 18:38:38 +00004217// General Serialization Routines
4218//===----------------------------------------------------------------------===//
4219
Richard Smithe43e2b32018-08-20 21:47:29 +00004220void ASTRecordWriter::AddAttr(const Attr *A) {
Reid Kleckner11f9f8a2018-08-14 01:55:37 +00004221 auto &Record = *this;
Richard Smithe43e2b32018-08-20 21:47:29 +00004222 if (!A)
4223 return Record.push_back(0);
4224 Record.push_back(A->getKind() + 1); // FIXME: stable encoding, target attrs
Erich Keane6a24e802019-09-13 17:39:31 +00004225
4226 Record.AddIdentifierRef(A->getAttrName());
4227 Record.AddIdentifierRef(A->getScopeName());
Richard Smithe43e2b32018-08-20 21:47:29 +00004228 Record.AddSourceRange(A->getRange());
Erich Keane6a24e802019-09-13 17:39:31 +00004229 Record.AddSourceLocation(A->getScopeLoc());
4230 Record.push_back(A->getParsedKind());
4231 Record.push_back(A->getSyntax());
4232 Record.push_back(A->getAttributeSpellingListIndexRaw());
Reid Kleckner11f9f8a2018-08-14 01:55:37 +00004233
4234#include "clang/Serialization/AttrPCHWrite.inc"
Richard Smithe43e2b32018-08-20 21:47:29 +00004235}
4236
4237/// Emit the list of attributes to the specified record.
4238void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) {
4239 push_back(Attrs.size());
4240 for (const auto *A : Attrs)
4241 AddAttr(A);
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00004242}
4243
John McCallf413f5e2013-05-03 00:10:13 +00004244void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
4245 AddSourceLocation(Tok.getLocation(), Record);
4246 Record.push_back(Tok.getLength());
4247
4248 // FIXME: When reading literal tokens, reconstruct the literal pointer
4249 // if it is needed.
4250 AddIdentifierRef(Tok.getIdentifierInfo(), Record);
4251 // FIXME: Should translate token kind to a stable encoding.
4252 Record.push_back(Tok.getKind());
4253 // FIXME: Should translate token flags to a stable encoding.
4254 Record.push_back(Tok.getFlags());
4255}
4256
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004257void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
Douglas Gregorbc8a78d52009-04-15 21:30:51 +00004258 Record.push_back(Str.size());
4259 Record.insert(Record.end(), Str.begin(), Str.end());
4260}
4261
Richard Smith7ed1bc92014-12-05 22:42:13 +00004262bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
Richard Smith54cc3c22014-12-11 20:50:24 +00004263 assert(Context && "should have context when outputting path");
Richard Smith7ed1bc92014-12-05 22:42:13 +00004264
Richard Smith54cc3c22014-12-11 20:50:24 +00004265 bool Changed =
4266 cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004267
4268 // Remove a prefix to make the path relative, if relevant.
4269 const char *PathBegin = Path.data();
4270 const char *PathPtr =
4271 adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
4272 if (PathPtr != PathBegin) {
4273 Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
4274 Changed = true;
4275 }
4276
4277 return Changed;
4278}
4279
4280void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
4281 SmallString<128> FilePath(Path);
4282 PreparePathForOutput(FilePath);
4283 AddString(FilePath, Record);
4284}
4285
Mehdi Amini57a41912015-09-10 01:46:39 +00004286void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
Richard Smith7ed1bc92014-12-05 22:42:13 +00004287 StringRef Path) {
4288 SmallString<128> FilePath(Path);
4289 PreparePathForOutput(FilePath);
4290 Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
4291}
4292
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004293void ASTWriter::AddVersionTuple(const VersionTuple &Version,
4294 RecordDataImpl &Record) {
4295 Record.push_back(Version.getMajor());
David Blaikie05785d12013-02-20 22:23:23 +00004296 if (Optional<unsigned> Minor = Version.getMinor())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004297 Record.push_back(*Minor + 1);
4298 else
4299 Record.push_back(0);
David Blaikie05785d12013-02-20 22:23:23 +00004300 if (Optional<unsigned> Subminor = Version.getSubminor())
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00004301 Record.push_back(*Subminor + 1);
4302 else
4303 Record.push_back(0);
4304}
4305
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004306/// Note that the identifier II occurs at the given offset
Douglas Gregore84a9da2009-04-20 20:36:09 +00004307/// within the identifier table.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004308void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
Sebastian Redl539c5062010-08-18 23:57:32 +00004309 IdentID ID = IdentifierIDs[II];
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00004310 // Only store offsets new to this AST file. Other identifier names are looked
Sebastian Redlff4a2952010-07-23 23:49:55 +00004311 // up earlier in the chain and thus don't need an offset.
4312 if (ID >= FirstIdentID)
4313 IdentifierOffsets[ID - FirstIdentID] = Offset;
Douglas Gregore84a9da2009-04-20 20:36:09 +00004314}
4315
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004316/// Note that the selector Sel occurs at the given offset
Douglas Gregor95c13f52009-04-25 17:48:32 +00004317/// within the method pool/selector table.
Sebastian Redl55c0ad52010-08-18 23:56:21 +00004318void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
Douglas Gregor95c13f52009-04-25 17:48:32 +00004319 unsigned ID = SelectorIDs[Sel];
4320 assert(ID && "Unknown selector");
Sebastian Redld95a56e2010-08-04 18:21:41 +00004321 // Don't record offsets for selectors that are also available in a different
4322 // file.
4323 if (ID < FirstSelectorID)
4324 return;
4325 SelectorOffsets[ID - FirstSelectorID] = Offset;
Douglas Gregor95c13f52009-04-25 17:48:32 +00004326}
4327
David Blaikie61137e12017-01-05 18:23:18 +00004328ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream,
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +00004329 SmallVectorImpl<char> &Buffer,
4330 InMemoryModuleCache &ModuleCache,
David Blaikie61137e12017-01-05 18:23:18 +00004331 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
4332 bool IncludeTimestamps)
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +00004333 : Stream(Stream), Buffer(Buffer), ModuleCache(ModuleCache),
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004334 IncludeTimestamps(IncludeTimestamps) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004335 for (const auto &Ext : Extensions) {
4336 if (auto Writer = Ext->createExtensionWriter(*this))
4337 ModuleFileExtensionWriters.push_back(std::move(Writer));
4338 }
4339}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004340
David Blaikie409df392020-04-28 18:05:28 -07004341ASTWriter::~ASTWriter() = default;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004342
Richard Smithb3761912015-02-05 23:08:52 +00004343const LangOptions &ASTWriter::getLangOpts() const {
4344 assert(WritingAST && "can't determine lang opts when not writing AST");
4345 return Context->getLangOpts();
4346}
4347
Richard Smithe75ee0f2015-08-17 07:13:32 +00004348time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const {
4349 return IncludeTimestamps ? E->getModificationTime() : 0;
4350}
4351
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004352ASTFileSignature ASTWriter::WriteAST(Sema &SemaRef,
4353 const std::string &OutputFile,
4354 Module *WritingModule, StringRef isysroot,
Duncan P. N. Exon Smith70d759b2019-03-12 18:38:04 +00004355 bool hasErrors,
4356 bool ShouldCacheASTInMemory) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00004357 WritingAST = true;
Adrian Prantladbd2b12015-09-22 23:26:31 +00004358
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00004359 ASTHasCompilerErrors = hasErrors;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004360
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004361 // Emit the file header.
Douglas Gregor8f45df52009-04-16 22:23:12 +00004362 Stream.Emit((unsigned)'C', 8);
4363 Stream.Emit((unsigned)'P', 8);
4364 Stream.Emit((unsigned)'C', 8);
4365 Stream.Emit((unsigned)'H', 8);
Mike Stump11289f42009-09-09 15:08:12 +00004366
Chris Lattner28fa4e62009-04-26 22:26:21 +00004367 WriteBlockInfoBlock();
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004368
Douglas Gregoreda8e122011-08-09 15:13:55 +00004369 Context = &SemaRef.Context;
Douglas Gregora28bcdd2011-12-01 02:07:58 +00004370 PP = &SemaRef.PP;
Douglas Gregora89c5ac2011-12-06 01:10:29 +00004371 this->WritingModule = WritingModule;
Adrian Prantladbd2b12015-09-22 23:26:31 +00004372 ASTFileSignature Signature =
4373 WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
Craig Toppera13603a2014-05-22 05:54:18 +00004374 Context = nullptr;
4375 PP = nullptr;
4376 this->WritingModule = nullptr;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004377 this->BaseDirectory.clear();
Craig Toppera13603a2014-05-22 05:54:18 +00004378
Douglas Gregor2fd3d402011-09-17 00:05:03 +00004379 WritingAST = false;
Duncan P. N. Exon Smith70d759b2019-03-12 18:38:04 +00004380 if (ShouldCacheASTInMemory) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004381 // Construct MemoryBuffer and update buffer manager.
Rumeet Dhindsa57a2eaf2020-03-10 10:59:26 -07004382 ModuleCache.addBuiltPCM(OutputFile,
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004383 llvm::MemoryBuffer::getMemBufferCopy(
4384 StringRef(Buffer.begin(), Buffer.size())));
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004385 }
Adrian Prantladbd2b12015-09-22 23:26:31 +00004386 return Signature;
Sebastian Redl143413f2010-07-12 22:02:52 +00004387}
4388
Douglas Gregora94a1542011-07-27 21:45:57 +00004389template<typename Vector>
4390static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4391 ASTWriter::RecordData &Record) {
Craig Toppera13603a2014-05-22 05:54:18 +00004392 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4393 I != E; ++I) {
Douglas Gregora94a1542011-07-27 21:45:57 +00004394 Writer.AddDeclRef(*I, Record);
4395 }
4396}
4397
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004398ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
4399 const std::string &OutputFile,
4400 Module *WritingModule) {
Sebastian Redl143413f2010-07-12 22:02:52 +00004401 using namespace llvm;
4402
Craig Toppera13603a2014-05-22 05:54:18 +00004403 bool isModule = WritingModule != nullptr;
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004404
Douglas Gregorcf68c582011-12-01 22:20:10 +00004405 // Make sure that the AST reader knows to finalize itself.
4406 if (Chain)
4407 Chain->finalizeForWriting();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004408
Sebastian Redl143413f2010-07-12 22:02:52 +00004409 ASTContext &Context = SemaRef.Context;
4410 Preprocessor &PP = SemaRef.PP;
4411
Douglas Gregordab42432011-08-12 00:15:20 +00004412 // Set up predefined declaration IDs.
Richard Smith5fc18a92015-07-12 23:43:21 +00004413 auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
4414 if (D) {
4415 assert(D->isCanonicalDecl() && "predefined decl is not canonical");
4416 DeclIDs[D] = ID;
Richard Smith5fc18a92015-07-12 23:43:21 +00004417 }
4418 };
4419 RegisterPredefDecl(Context.getTranslationUnitDecl(),
4420 PREDEF_DECL_TRANSLATION_UNIT_ID);
4421 RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
4422 RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
4423 RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
4424 RegisterPredefDecl(Context.ObjCProtocolClassDecl,
4425 PREDEF_DECL_OBJC_PROTOCOL_ID);
4426 RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
4427 RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
4428 RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
4429 PREDEF_DECL_OBJC_INSTANCETYPE_ID);
4430 RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
Richard Smith9b88a4c2015-07-27 05:40:23 +00004431 RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
Charles Davisc7d5c942015-09-17 20:55:33 +00004432 RegisterPredefDecl(Context.BuiltinMSVaListDecl,
4433 PREDEF_DECL_BUILTIN_MS_VA_LIST_ID);
Richard Smithbab6df82020-04-11 22:15:29 -07004434 RegisterPredefDecl(Context.MSGuidTagDecl,
4435 PREDEF_DECL_BUILTIN_MS_GUID_ID);
Richard Smith5fc18a92015-07-12 23:43:21 +00004436 RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
David Majnemerd9b1a4f2015-11-04 03:40:30 +00004437 RegisterPredefDecl(Context.MakeIntegerSeqDecl,
4438 PREDEF_DECL_MAKE_INTEGER_SEQ_ID);
Quentin Colombet043406b2016-02-03 22:41:00 +00004439 RegisterPredefDecl(Context.CFConstantStringTypeDecl,
4440 PREDEF_DECL_CF_CONSTANT_STRING_ID);
Ben Langmuirf5416742016-02-04 00:55:24 +00004441 RegisterPredefDecl(Context.CFConstantStringTagDecl,
4442 PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID);
Eric Fiselier6ad68552016-07-01 01:24:09 +00004443 RegisterPredefDecl(Context.TypePackElementDecl,
4444 PREDEF_DECL_TYPE_PACK_ELEMENT_ID);
Meador Inge5d3fb222012-06-16 03:34:49 +00004445
Chris Lattner0c797362009-09-08 18:19:27 +00004446 // Build a record containing all of the tentative definitions in this file, in
Sebastian Redl35351a92010-01-31 22:27:38 +00004447 // TentativeDefinitions order. Generally, this record will be empty for
Chris Lattner0c797362009-09-08 18:19:27 +00004448 // headers.
Douglas Gregord4df8652009-04-22 22:02:47 +00004449 RecordData TentativeDefinitions;
Douglas Gregora94a1542011-07-27 21:45:57 +00004450 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004451
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00004452 // Build a record containing all of the file scoped decls in this file.
4453 RecordData UnusedFileScopedDecls;
Argyrios Kyrtzidis59852362013-03-14 04:45:00 +00004454 if (!isModule)
4455 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
4456 UnusedFileScopedDecls);
Sebastian Redl08aca90252010-08-05 18:21:25 +00004457
Douglas Gregor851443c2011-08-12 01:39:19 +00004458 // Build a record containing all of the delegating constructors we still need
4459 // to resolve.
Alexis Hunt27a761d2011-05-04 23:29:54 +00004460 RecordData DelegatingCtorDecls;
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004461 if (!isModule)
4462 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
Alexis Hunt27a761d2011-05-04 23:29:54 +00004463
Douglas Gregor851443c2011-08-12 01:39:19 +00004464 // Write the set of weak, undeclared identifiers. We always write the
4465 // entire table, since later PCH files in a PCH chain are only interested in
4466 // the results at the end of the chain.
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004467 RecordData WeakUndeclaredIdentifiers;
Chandler Carruthf85d9822015-03-26 08:32:49 +00004468 for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) {
4469 IdentifierInfo *II = WeakUndeclaredIdentifier.first;
4470 WeakInfo &WI = WeakUndeclaredIdentifier.second;
4471 AddIdentifierRef(II, WeakUndeclaredIdentifiers);
4472 AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
4473 AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
4474 WeakUndeclaredIdentifiers.push_back(WI.getUsed());
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004475 }
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00004476
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004477 // Build a record containing all of the ext_vector declarations.
4478 RecordData ExtVectorDecls;
Douglas Gregorb7098a32011-07-28 00:39:29 +00004479 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004480
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004481 // Build a record containing all of the VTable uses information.
4482 RecordData VTableUses;
Argyrios Kyrtzidisedee67f2010-08-03 17:29:52 +00004483 if (!SemaRef.VTableUses.empty()) {
Argyrios Kyrtzidisedee67f2010-08-03 17:29:52 +00004484 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4485 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4486 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4487 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4488 }
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004489 }
4490
Nico Weber72889432014-09-06 01:25:55 +00004491 // Build a record containing all of the UnusedLocalTypedefNameCandidates.
4492 RecordData UnusedLocalTypedefNameCandidates;
4493 for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4494 AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
4495
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004496 // Build a record containing all of pending implicit instantiations.
Chandler Carruth54080172010-08-25 08:44:16 +00004497 RecordData PendingInstantiations;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004498 for (const auto &I : SemaRef.PendingInstantiations) {
4499 AddDeclRef(I.first, PendingInstantiations);
4500 AddSourceLocation(I.second, PendingInstantiations);
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004501 }
4502 assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4503 "There are local ones at end of translation unit!");
4504
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004505 // Build a record containing some declaration references.
4506 RecordData SemaDeclRefs;
Richard Smith96269c52016-09-29 22:49:46 +00004507 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) {
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004508 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4509 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
Richard Smith96269c52016-09-29 22:49:46 +00004510 AddDeclRef(SemaRef.getStdAlignValT(), SemaDeclRefs);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004511 }
4512
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004513 RecordData CUDASpecialDeclRefs;
4514 if (Context.getcudaConfigureCallDecl()) {
4515 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4516 }
4517
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004518 // Build a record containing all of the known namespaces.
4519 RecordData KnownNamespaces;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004520 for (const auto &I : SemaRef.KnownNamespaces) {
4521 if (!I.second)
4522 AddDeclRef(I.first, KnownNamespaces);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004523 }
Douglas Gregor112b9072012-10-18 05:31:06 +00004524
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004525 // Build a record of all used, undefined objects that require definitions.
4526 RecordData UndefinedButUsed;
Nick Lewyckyf0f56162013-01-31 03:23:57 +00004527
4528 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004529 SemaRef.getUndefinedButUsed(Undefined);
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004530 for (const auto &I : Undefined) {
4531 AddDeclRef(I.first, UndefinedButUsed);
4532 AddSourceLocation(I.second, UndefinedButUsed);
Nick Lewycky8334af82013-01-26 00:35:08 +00004533 }
4534
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00004535 // Build a record containing all delete-expressions that we would like to
4536 // analyze later in AST.
4537 RecordData DeleteExprsToAnalyze;
4538
Richard Smithf5262c62018-06-28 01:57:04 +00004539 if (!isModule) {
4540 for (const auto &DeleteExprsInfo :
4541 SemaRef.getMismatchingDeleteExpressions()) {
4542 AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
4543 DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
4544 for (const auto &DeleteLoc : DeleteExprsInfo.second) {
4545 AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
4546 DeleteExprsToAnalyze.push_back(DeleteLoc.second);
4547 }
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00004548 }
4549 }
4550
Douglas Gregor112b9072012-10-18 05:31:06 +00004551 // Write the control block
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004552 WriteControlBlock(PP, Context, isysroot, OutputFile);
Douglas Gregor112b9072012-10-18 05:31:06 +00004553
Sebastian Redl42a0f6a2010-08-18 23:56:27 +00004554 // Write the remaining AST contents.
Sebastian Redl539c5062010-08-18 23:57:32 +00004555 Stream.EnterSubblock(AST_BLOCK_ID, 5);
Douglas Gregor851443c2011-08-12 01:39:19 +00004556
Argyrios Kyrtzidis39605402012-12-13 21:38:23 +00004557 // This is so that older clang versions, before the introduction
4558 // of the control block, can read and reject the newer PCH format.
Mehdi Amini57a41912015-09-10 01:46:39 +00004559 {
4560 RecordData Record = {VERSION_MAJOR};
4561 Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4562 }
Argyrios Kyrtzidis39605402012-12-13 21:38:23 +00004563
Douglas Gregor851443c2011-08-12 01:39:19 +00004564 // Create a lexical update block containing all of the declarations in the
4565 // translation unit that do not come from other AST files.
4566 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00004567 SmallVector<uint32_t, 128> NewGlobalKindDeclPairs;
4568 for (const auto *D : TU->noload_decls()) {
4569 if (!D->isFromASTFile()) {
4570 NewGlobalKindDeclPairs.push_back(D->getKind());
4571 NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
4572 }
Douglas Gregor851443c2011-08-12 01:39:19 +00004573 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004574
David Blaikieb44f0bf2017-01-04 22:36:43 +00004575 auto Abv = std::make_shared<BitCodeAbbrev>();
Douglas Gregor851443c2011-08-12 01:39:19 +00004576 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4577 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004578 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv));
Mehdi Amini57a41912015-09-10 01:46:39 +00004579 {
4580 RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
4581 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4582 bytes(NewGlobalKindDeclPairs));
4583 }
4584
Douglas Gregor851443c2011-08-12 01:39:19 +00004585 // And a visible updates block for the translation unit.
David Blaikieb44f0bf2017-01-04 22:36:43 +00004586 Abv = std::make_shared<BitCodeAbbrev>();
Douglas Gregor851443c2011-08-12 01:39:19 +00004587 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4588 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
Douglas Gregor851443c2011-08-12 01:39:19 +00004589 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004590 UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv));
Douglas Gregor851443c2011-08-12 01:39:19 +00004591 WriteDeclContextVisibleUpdate(TU);
Richard Smithf19e1272015-03-07 00:04:49 +00004592
4593 // If we have any extern "C" names, write out a visible update for them.
4594 if (Context.ExternCContext)
4595 WriteDeclContextVisibleUpdate(Context.ExternCContext);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004596
Douglas Gregor851443c2011-08-12 01:39:19 +00004597 // If the translation unit has an anonymous namespace, and we don't already
4598 // have an update block for it, write it as an update block.
Richard Smith6ef42932014-03-20 21:02:00 +00004599 // FIXME: Why do we not do this if there's already an update block?
Douglas Gregor851443c2011-08-12 01:39:19 +00004600 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4601 ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
Richard Smith6ef42932014-03-20 21:02:00 +00004602 if (Record.empty())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004603 Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
Douglas Gregor851443c2011-08-12 01:39:19 +00004604 }
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004605
Richard Smith5652c0f2014-03-21 01:48:23 +00004606 // Add update records for all mangling numbers and static local numbers.
4607 // These aren't really update records, but this is a convenient way of
4608 // tagging this rare extra data onto the declarations.
4609 for (const auto &Number : Context.MangleNumbers)
4610 if (!Number.first->isFromASTFile())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004611 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4612 Number.second));
Richard Smith5652c0f2014-03-21 01:48:23 +00004613 for (const auto &Number : Context.StaticLocalNumbers)
4614 if (!Number.first->isFromASTFile())
Aaron Ballman4f45b712014-03-21 15:22:56 +00004615 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4616 Number.second));
Richard Smith5652c0f2014-03-21 01:48:23 +00004617
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004618 // Make sure visible decls, added to DeclContexts previously loaded from
Richard Smithc26d9742016-10-06 20:30:51 +00004619 // an AST file, are registered for serialization. Likewise for template
4620 // specializations added to imported templates.
4621 for (const auto *I : DeclsToEmitEvenIfUnreferenced) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004622 GetDeclRef(I);
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00004623 }
4624
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +00004625 // Make sure all decls associated with an identifier are registered for
Richard Smith79bf9202015-08-24 03:33:22 +00004626 // serialization, if we're storing decls with identifiers.
4627 if (!WritingModule || !getLangOpts().CPlusPlus) {
4628 llvm::SmallVector<const IdentifierInfo*, 256> IIs;
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00004629 for (const auto &ID : PP.getIdentifierTable()) {
4630 const IdentifierInfo *II = ID.second;
Richard Smith79bf9202015-08-24 03:33:22 +00004631 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
4632 IIs.push_back(II);
4633 }
4634 // Sort the identifiers to visit based on their name.
Benjamin Kramercd2bae32019-08-22 17:32:16 +00004635 llvm::sort(IIs, llvm::deref<std::less<>>());
Richard Smith79bf9202015-08-24 03:33:22 +00004636 for (const IdentifierInfo *II : IIs) {
4637 for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4638 DEnd = SemaRef.IdResolver.end();
4639 D != DEnd; ++D) {
4640 GetDeclRef(*D);
4641 }
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +00004642 }
4643 }
4644
Manman Rena0f31a02016-04-29 19:04:05 +00004645 // For method pool in the module, if it contains an entry for a selector,
4646 // the entry should be complete, containing everything introduced by that
4647 // module and all modules it imports. It's possible that the entry is out of
4648 // date, so we need to pull in the new content here.
4649
4650 // It's possible that updateOutOfDateSelector can update SelectorIDs. To be
4651 // safe, we copy all selectors out.
4652 llvm::SmallVector<Selector, 256> AllSelectors;
4653 for (auto &SelectorAndID : SelectorIDs)
4654 AllSelectors.push_back(SelectorAndID.first);
4655 for (auto &Selector : AllSelectors)
4656 SemaRef.updateOutOfDateSelector(Selector);
4657
Douglas Gregor5204bde2011-08-02 16:26:37 +00004658 // Form the record of special types.
4659 RecordData SpecialTypes;
Douglas Gregor5204bde2011-08-02 16:26:37 +00004660 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
Douglas Gregor5204bde2011-08-02 16:26:37 +00004661 AddTypeRef(Context.getFILEType(), SpecialTypes);
4662 AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4663 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4664 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4665 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
Douglas Gregor5204bde2011-08-02 16:26:37 +00004666 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00004667 AddTypeRef(Context.getucontext_tType(), SpecialTypes);
Douglas Gregora28bcdd2011-12-01 02:07:58 +00004668
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004669 if (Chain) {
4670 // Write the mapping information describing our module dependencies and how
4671 // each of those modules were mapped into our own offset/ID space, so that
4672 // the reader can build the appropriate mapping to its own offset/ID space.
4673 // The map consists solely of a blob with the following format:
Boris Kolpackovd30446f2017-08-31 06:26:43 +00004674 // *(module-kind:i8
4675 // module-name-len:i16 module-name:len*i8
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004676 // source-location-offset:i32
4677 // identifier-id:i32
4678 // preprocessed-entity-id:i32
4679 // macro-definition-id:i32
Douglas Gregor253eefe2011-12-01 00:59:36 +00004680 // submodule-id:i32
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004681 // selector-id:i32
4682 // declaration-id:i32
4683 // c++-base-specifiers-id:i32
4684 // type-id:i32)
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004685 //
Boris Kolpackovd30446f2017-08-31 06:26:43 +00004686 // module-kind is the ModuleKind enum value. If it is MK_PrebuiltModule or
4687 // MK_ExplicitModule, then the module-name is the module name. Otherwise,
4688 // it is the module file name.
David Blaikieb44f0bf2017-01-04 22:36:43 +00004689 auto Abbrev = std::make_shared<BitCodeAbbrev>();
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004690 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4691 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
David Blaikieb44f0bf2017-01-04 22:36:43 +00004692 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004693 SmallString<2048> Buffer;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004694 {
4695 llvm::raw_svector_ostream Out(Buffer);
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00004696 for (ModuleFile &M : Chain->ModuleMgr) {
Justin Bognere1c147c2014-03-28 22:03:19 +00004697 using namespace llvm::support;
Eugene Zelenkob7d89102017-11-11 00:08:50 +00004698
Peter Collingbournee3f65292018-05-18 19:46:24 +00004699 endian::Writer LE(Out, little);
Boris Kolpackovd30446f2017-08-31 06:26:43 +00004700 LE.write<uint8_t>(static_cast<uint8_t>(M.Kind));
4701 StringRef Name =
4702 M.Kind == MK_PrebuiltModule || M.Kind == MK_ExplicitModule
4703 ? M.ModuleName
4704 : M.FileName;
4705 LE.write<uint16_t>(Name.size());
4706 Out.write(Name.data(), Name.size());
Ben Langmuirfe971d92014-08-16 04:54:18 +00004707
Ben Langmuir785180e2014-10-20 16:27:30 +00004708 // Note: if a base ID was uint max, it would not be possible to load
4709 // another module after it or have more than one entity inside it.
4710 uint32_t None = std::numeric_limits<uint32_t>::max();
4711
4712 auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) {
4713 assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
4714 if (ShouldWrite)
4715 LE.write<uint32_t>(BaseID);
4716 else
4717 LE.write<uint32_t>(None);
4718 };
4719
Ben Langmuirfe971d92014-08-16 04:54:18 +00004720 // These values should be unique within a chain, since they will be read
4721 // as keys into ContinuousRangeMaps.
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00004722 writeBaseIDOrNone(M.SLocEntryBaseOffset, M.LocalNumSLocEntries);
4723 writeBaseIDOrNone(M.BaseIdentifierID, M.LocalNumIdentifiers);
4724 writeBaseIDOrNone(M.BaseMacroID, M.LocalNumMacros);
4725 writeBaseIDOrNone(M.BasePreprocessedEntityID,
4726 M.NumPreprocessedEntities);
4727 writeBaseIDOrNone(M.BaseSubmoduleID, M.LocalNumSubmodules);
4728 writeBaseIDOrNone(M.BaseSelectorID, M.LocalNumSelectors);
4729 writeBaseIDOrNone(M.BaseDeclID, M.LocalNumDecls);
4730 writeBaseIDOrNone(M.BaseTypeIndex, M.LocalNumTypes);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004731 }
4732 }
Mehdi Amini57a41912015-09-10 01:46:39 +00004733 RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00004734 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4735 Buffer.data(), Buffer.size());
4736 }
Richard Smithb9eab6d2014-03-20 19:44:17 +00004737
Yaxun (Sam) Liub670ab72020-02-26 10:57:39 -05004738 // Build a record containing all of the DeclsToCheckForDeferredDiags.
4739 RecordData DeclsToCheckForDeferredDiags;
4740 for (auto *D : SemaRef.DeclsToCheckForDeferredDiags)
4741 AddDeclRef(D, DeclsToCheckForDeferredDiags);
4742
Richard Smithb9eab6d2014-03-20 19:44:17 +00004743 RecordData DeclUpdatesOffsetsRecord;
4744
Richard Smith59442b42014-03-20 20:07:19 +00004745 // Keep writing types, declarations, and declaration update records
4746 // until we've emitted all of them.
Richard Smith01b2cb42014-07-26 06:37:51 +00004747 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
4748 WriteTypeAbbrevs();
4749 WriteDeclAbbrevs();
Richard Smith59442b42014-03-20 20:07:19 +00004750 do {
4751 WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
4752 while (!DeclTypesToEmit.empty()) {
4753 DeclOrType DOT = DeclTypesToEmit.front();
4754 DeclTypesToEmit.pop();
4755 if (DOT.isType())
4756 WriteType(DOT.getType());
4757 else
4758 WriteDecl(Context, DOT.getDecl());
4759 }
4760 } while (!DeclUpdates.empty());
Richard Smithb9eab6d2014-03-20 19:44:17 +00004761 Stream.ExitBlock();
4762
Richard Smithb9eab6d2014-03-20 19:44:17 +00004763 DoneWritingDeclsAndTypes = true;
4764
4765 // These things can only be done once we've written out decls and types.
4766 WriteTypeDeclOffsets();
Richard Smith5652c0f2014-03-21 01:48:23 +00004767 if (!DeclUpdatesOffsetsRecord.empty())
4768 Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
Richard Smithb9eab6d2014-03-20 19:44:17 +00004769 WriteFileDeclIDsMap();
Richard Smith7ed1bc92014-12-05 22:42:13 +00004770 WriteSourceManagerBlock(Context.getSourceManager(), PP);
Richard Smithb9eab6d2014-03-20 19:44:17 +00004771 WriteComments();
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004772 WritePreprocessor(PP, isModule);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004773 WriteHeaderSearch(PP.getHeaderSearchInfo());
Sebastian Redla19a67f2010-08-03 21:58:15 +00004774 WriteSelectors(SemaRef);
Fariborz Jahanianc51609a2010-07-23 19:11:11 +00004775 WriteReferencedSelectorsPool(SemaRef);
Richard Smith9c254182015-07-19 21:41:12 +00004776 WriteLateParsedTemplates(SemaRef);
Argyrios Kyrtzidisffb35582013-03-14 04:44:56 +00004777 WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
Melanie Blower8812b0c2020-04-16 08:45:26 -07004778 WriteFPPragmaOptions(SemaRef.getCurFPFeatures());
Peter Collingbourne5df20e02011-02-15 19:46:30 +00004779 WriteOpenCLExtensions(SemaRef);
Yaxun Liu5b746652016-12-18 05:18:55 +00004780 WriteOpenCLExtensionTypes(SemaRef);
Justin Lebar67a78a62016-10-08 22:15:58 +00004781 WriteCUDAPragmas(SemaRef);
Douglas Gregor652d82a2009-04-18 05:55:16 +00004782
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004783 // If we're emitting a module, write out the submodule information.
Douglas Gregora89c5ac2011-12-06 01:10:29 +00004784 if (WritingModule)
4785 WriteSubmodules(WritingModule);
4786
Andrew Savonichev52d674d2018-10-29 11:14:01 +00004787 // We need to have information about submodules to correctly deserialize
4788 // decls from OpenCLExtensionDecls block
4789 WriteOpenCLExtensionDecls(SemaRef);
4790
Douglas Gregor5204bde2011-08-02 16:26:37 +00004791 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
4792
Douglas Gregord4df8652009-04-22 22:02:47 +00004793 // Write the record containing external, unnamed definitions.
Ben Langmuir332aafe2014-01-31 01:06:56 +00004794 if (!EagerlyDeserializedDecls.empty())
4795 Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
Douglas Gregord4df8652009-04-22 22:02:47 +00004796
David Blaikief63556d2017-04-12 20:58:33 +00004797 if (!ModularCodegenDecls.empty())
David Blaikie9ffe5a32017-01-30 05:00:26 +00004798 Stream.EmitRecord(MODULAR_CODEGEN_DECLS, ModularCodegenDecls);
4799
Douglas Gregord4df8652009-04-22 22:02:47 +00004800 // Write the record containing tentative definitions.
4801 if (!TentativeDefinitions.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004802 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
Douglas Gregoracfc76c2009-04-22 22:18:58 +00004803
Argyrios Kyrtzidis35672e72010-08-13 18:42:17 +00004804 // Write the record containing unused file scoped decls.
4805 if (!UnusedFileScopedDecls.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004806 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00004807
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004808 // Write the record containing weak undeclared identifiers.
4809 if (!WeakUndeclaredIdentifiers.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004810 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
Argyrios Kyrtzidisee1afa32010-08-05 09:48:08 +00004811 WeakUndeclaredIdentifiers);
4812
Douglas Gregor61cac2b2009-04-27 20:06:05 +00004813 // Write the record containing ext_vector type names.
4814 if (!ExtVectorDecls.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004815 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
Mike Stump11289f42009-09-09 15:08:12 +00004816
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004817 // Write the record containing VTable uses information.
4818 if (!VTableUses.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004819 Stream.EmitRecord(VTABLE_USES, VTableUses);
Argyrios Kyrtzidisaf2eac22010-07-06 15:37:04 +00004820
Nico Weber72889432014-09-06 01:25:55 +00004821 // Write the record containing potentially unused local typedefs.
4822 if (!UnusedLocalTypedefNameCandidates.empty())
4823 Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
4824 UnusedLocalTypedefNameCandidates);
4825
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004826 // Write the record containing pending implicit instantiations.
Chandler Carruth54080172010-08-25 08:44:16 +00004827 if (!PendingInstantiations.empty())
4828 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
Argyrios Kyrtzidis7f76d112010-08-05 09:48:16 +00004829
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004830 // Write the record containing declaration references of Sema.
4831 if (!SemaDeclRefs.empty())
Sebastian Redl539c5062010-08-18 23:57:32 +00004832 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00004833
Yaxun (Sam) Liub670ab72020-02-26 10:57:39 -05004834 // Write the record containing decls to be checked for deferred diags.
4835 if (!DeclsToCheckForDeferredDiags.empty())
4836 Stream.EmitRecord(DECLS_TO_CHECK_FOR_DEFERRED_DIAGS,
4837 DeclsToCheckForDeferredDiags);
4838
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004839 // Write the record containing CUDA-specific declaration references.
4840 if (!CUDASpecialDeclRefs.empty())
4841 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00004842
Alexis Hunt27a761d2011-05-04 23:29:54 +00004843 // Write the delegating constructors.
4844 if (!DelegatingCtorDecls.empty())
4845 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
Peter Collingbourne9e2c81f2011-02-09 21:04:32 +00004846
Douglas Gregorc2fa1692011-06-28 16:20:02 +00004847 // Write the known namespaces.
4848 if (!KnownNamespaces.empty())
4849 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
Nick Lewycky8334af82013-01-26 00:35:08 +00004850
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00004851 // Write the undefined internal functions and variables, and inline functions.
4852 if (!UndefinedButUsed.empty())
4853 Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00004854
4855 if (!DeleteExprsToAnalyze.empty())
4856 Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
4857
Douglas Gregor851443c2011-08-12 01:39:19 +00004858 // Write the visible updates to DeclContexts.
Richard Smithcd45dbc2014-04-19 03:48:30 +00004859 for (auto *DC : UpdatedDeclContexts)
4860 WriteDeclContextVisibleUpdate(DC);
Douglas Gregor851443c2011-08-12 01:39:19 +00004861
Douglas Gregor959bb062011-12-03 01:15:29 +00004862 if (!WritingModule) {
4863 // Write the submodules that were imported, if any.
Aaron Ballman4f45b712014-03-21 15:22:56 +00004864 struct ModuleInfo {
4865 uint64_t ID;
4866 Module *M;
4867 ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
4868 };
Richard Smith56be7542014-03-21 00:33:59 +00004869 llvm::SmallVector<ModuleInfo, 64> Imports;
Aaron Ballmanbbc31212014-03-14 20:59:21 +00004870 for (const auto *I : Context.local_imports()) {
Douglas Gregor959bb062011-12-03 01:15:29 +00004871 assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
Aaron Ballman4f45b712014-03-21 15:22:56 +00004872 Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
4873 I->getImportedModule()));
Douglas Gregor959bb062011-12-03 01:15:29 +00004874 }
Richard Smith56be7542014-03-21 00:33:59 +00004875
4876 if (!Imports.empty()) {
4877 auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
4878 return A.ID < B.ID;
4879 };
Ben Langmuir5f95c8f2014-09-08 20:36:26 +00004880 auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
4881 return A.ID == B.ID;
4882 };
Richard Smith56be7542014-03-21 00:33:59 +00004883
4884 // Sort and deduplicate module IDs.
Fangrui Song55fab262018-09-26 22:16:28 +00004885 llvm::sort(Imports, Cmp);
Ben Langmuir5f95c8f2014-09-08 20:36:26 +00004886 Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
Richard Smith56be7542014-03-21 00:33:59 +00004887 Imports.end());
4888
4889 RecordData ImportedModules;
4890 for (const auto &Import : Imports) {
4891 ImportedModules.push_back(Import.ID);
4892 // FIXME: If the module has macros imported then later has declarations
4893 // imported, this location won't be the right one as a location for the
4894 // declaration imports.
Richard Smith10434f32015-05-02 02:08:26 +00004895 AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
Richard Smith56be7542014-03-21 00:33:59 +00004896 }
4897
Douglas Gregor959bb062011-12-03 01:15:29 +00004898 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
4899 }
Douglas Gregor0a839132011-12-03 00:59:55 +00004900 }
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00004901
Douglas Gregor404cdde2012-01-27 01:47:08 +00004902 WriteObjCCategories();
Nico Weber779355f2016-03-02 23:22:00 +00004903 if(!WritingModule) {
Dario Domizioli13a0a382014-05-23 12:13:25 +00004904 WriteOptimizePragmaOptions(SemaRef);
Nico Weber779355f2016-03-02 23:22:00 +00004905 WriteMSStructPragmaOptions(SemaRef);
Nico Weber42932312016-03-03 00:17:35 +00004906 WriteMSPointersToMembersPragmaOptions(SemaRef);
Nico Weber779355f2016-03-02 23:22:00 +00004907 }
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00004908 WritePackPragmaOptions(SemaRef);
Melanie Blowerf5360d42020-05-01 10:32:06 -07004909 WriteFloatControlPragmaOptions(SemaRef);
Richard Smithe40f2ba2013-08-07 21:41:30 +00004910
Douglas Gregor08f01292009-04-17 22:13:46 +00004911 // Some simple statistics
Mehdi Amini57a41912015-09-10 01:46:39 +00004912 RecordData::value_type Record[] = {
4913 NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts};
Sebastian Redl539c5062010-08-18 23:57:32 +00004914 Stream.EmitRecord(STATISTICS, Record);
Douglas Gregor8f45df52009-04-16 22:23:12 +00004915 Stream.ExitBlock();
Adrian Prantladbd2b12015-09-22 23:26:31 +00004916
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004917 // Write the module file extension blocks.
4918 for (const auto &ExtWriter : ModuleFileExtensionWriters)
Douglas Gregor8f64ca12015-12-08 22:43:32 +00004919 WriteModuleFileExtension(SemaRef, *ExtWriter);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004920
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004921 return writeUnhashedControlBlock(PP, Context);
Douglas Gregoref84c4b2009-04-09 22:27:44 +00004922}
4923
Richard Smithb9eab6d2014-03-20 19:44:17 +00004924void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00004925 if (DeclUpdates.empty())
4926 return;
4927
Richard Smith59442b42014-03-20 20:07:19 +00004928 DeclUpdateMap LocalUpdates;
4929 LocalUpdates.swap(DeclUpdates);
4930
Richard Smith6ef42932014-03-20 21:02:00 +00004931 for (auto &DeclUpdate : LocalUpdates) {
4932 const Decl *D = DeclUpdate.first;
Argyrios Kyrtzidis3ba70b82010-10-24 17:26:46 +00004933
Richard Smithd28ac5b2014-03-22 23:33:22 +00004934 bool HasUpdatedBody = false;
Richard Smith69c82bf2016-04-01 22:52:03 +00004935 RecordData RecordData;
4936 ASTRecordWriter Record(*this, RecordData);
Richard Smith6ef42932014-03-20 21:02:00 +00004937 for (auto &Update : DeclUpdate.second) {
4938 DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
4939
Richard Smith69c82bf2016-04-01 22:52:03 +00004940 // An updated body is emitted last, so that the reader doesn't need
4941 // to skip over the lazy body to reach statements for other records.
4942 if (Kind == UPD_CXX_ADDED_FUNCTION_DEFINITION)
4943 HasUpdatedBody = true;
4944 else
4945 Record.push_back(Kind);
4946
Richard Smith6ef42932014-03-20 21:02:00 +00004947 switch (Kind) {
4948 case UPD_CXX_ADDED_IMPLICIT_MEMBER:
4949 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4950 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
Richard Smithcd45dbc2014-04-19 03:48:30 +00004951 assert(Update.getDecl() && "no decl to add?");
Richard Smith6ef42932014-03-20 21:02:00 +00004952 Record.push_back(GetDeclRef(Update.getDecl()));
4953 break;
4954
Richard Smith4d235792014-08-07 18:53:08 +00004955 case UPD_CXX_ADDED_FUNCTION_DEFINITION:
Richard Smithd28ac5b2014-03-22 23:33:22 +00004956 break;
4957
Richard Smith891fc7f2017-12-05 01:31:47 +00004958 case UPD_CXX_POINT_OF_INSTANTIATION:
4959 // FIXME: Do we need to also save the template specialization kind here?
Richard Smith69c82bf2016-04-01 22:52:03 +00004960 Record.AddSourceLocation(Update.getLoc());
Richard Smith891fc7f2017-12-05 01:31:47 +00004961 break;
4962
4963 case UPD_CXX_ADDED_VAR_DEFINITION: {
4964 const VarDecl *VD = cast<VarDecl>(D);
Richard Smithf5017592017-11-02 01:06:00 +00004965 Record.push_back(VD->isInline());
4966 Record.push_back(VD->isInlineSpecified());
Richard Smith05a21352017-06-22 22:18:46 +00004967 if (VD->getInit()) {
4968 Record.push_back(!VD->isInitKnownICE() ? 1
4969 : (VD->isInitICE() ? 3 : 2));
4970 Record.AddStmt(const_cast<Expr*>(VD->getInit()));
4971 } else {
4972 Record.push_back(0);
4973 }
Richard Smith4d235792014-08-07 18:53:08 +00004974 break;
Richard Smith05a21352017-06-22 22:18:46 +00004975 }
Richard Smith4d235792014-08-07 18:53:08 +00004976
John McCall32791cc2016-01-06 22:34:54 +00004977 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT:
Richard Smith290d8012016-04-06 17:06:00 +00004978 Record.AddStmt(const_cast<Expr *>(
4979 cast<ParmVarDecl>(Update.getDecl())->getDefaultArg()));
John McCall32791cc2016-01-06 22:34:54 +00004980 break;
4981
Richard Smith4b054b22016-08-24 21:25:37 +00004982 case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER:
4983 Record.AddStmt(
4984 cast<FieldDecl>(Update.getDecl())->getInClassInitializer());
4985 break;
4986
Richard Smithcd45dbc2014-04-19 03:48:30 +00004987 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
4988 auto *RD = cast<CXXRecordDecl>(D);
Chandler Carruth8a3d24d2015-03-26 04:27:10 +00004989 UpdatedDeclContexts.insert(RD->getPrimaryContext());
Akira Hatanakafcbe17c2018-03-28 21:13:14 +00004990 Record.push_back(RD->isParamDestroyedInCallee());
Akira Hatanakae6313ac2018-04-09 22:48:22 +00004991 Record.push_back(RD->getArgPassingRestrictions());
Richard Smith69c82bf2016-04-01 22:52:03 +00004992 Record.AddCXXDefinitionData(RD);
Richard Smith72e50fe2016-04-14 00:50:18 +00004993 Record.AddOffset(WriteDeclContextLexicalBlock(
Richard Smithcd45dbc2014-04-19 03:48:30 +00004994 *Context, const_cast<CXXRecordDecl *>(RD)));
4995
4996 // This state is sometimes updated by template instantiation, when we
4997 // switch from the specialization referring to the template declaration
4998 // to it referring to the template definition.
4999 if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
5000 Record.push_back(MSInfo->getTemplateSpecializationKind());
Richard Smith69c82bf2016-04-01 22:52:03 +00005001 Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
Richard Smithcd45dbc2014-04-19 03:48:30 +00005002 } else {
5003 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
5004 Record.push_back(Spec->getTemplateSpecializationKind());
Richard Smith69c82bf2016-04-01 22:52:03 +00005005 Record.AddSourceLocation(Spec->getPointOfInstantiation());
Richard Smithdf352052014-05-22 20:59:29 +00005006
5007 // The instantiation might have been resolved to a partial
5008 // specialization. If so, record which one.
5009 auto From = Spec->getInstantiatedFrom();
5010 if (auto PartialSpec =
5011 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
5012 Record.push_back(true);
Richard Smith69c82bf2016-04-01 22:52:03 +00005013 Record.AddDeclRef(PartialSpec);
5014 Record.AddTemplateArgumentList(
5015 &Spec->getTemplateInstantiationArgs());
Richard Smithdf352052014-05-22 20:59:29 +00005016 } else {
5017 Record.push_back(false);
5018 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00005019 }
5020 Record.push_back(RD->getTagKind());
Richard Smith69c82bf2016-04-01 22:52:03 +00005021 Record.AddSourceLocation(RD->getLocation());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005022 Record.AddSourceLocation(RD->getBeginLoc());
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00005023 Record.AddSourceRange(RD->getBraceRange());
Richard Smithcd45dbc2014-04-19 03:48:30 +00005024
5025 // Instantiation may change attributes; write them all out afresh.
5026 Record.push_back(D->hasAttrs());
Richard Smith69c82bf2016-04-01 22:52:03 +00005027 if (D->hasAttrs())
5028 Record.AddAttributes(D->getAttrs());
Richard Smithcd45dbc2014-04-19 03:48:30 +00005029
5030 // FIXME: Ensure we don't get here for explicit instantiations.
5031 break;
5032 }
5033
Richard Smithf8134002015-03-10 01:41:22 +00005034 case UPD_CXX_RESOLVED_DTOR_DELETE:
Richard Smith69c82bf2016-04-01 22:52:03 +00005035 Record.AddDeclRef(Update.getDecl());
Richard Smith5b349582017-10-13 01:55:36 +00005036 Record.AddStmt(cast<CXXDestructorDecl>(D)->getOperatorDeleteThisArg());
Richard Smithf8134002015-03-10 01:41:22 +00005037 break;
5038
John McCalld505e572019-12-13 21:54:44 -05005039 case UPD_CXX_RESOLVED_EXCEPTION_SPEC: {
5040 auto prototype =
5041 cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>();
5042 Record.writeExceptionSpecInfo(prototype->getExceptionSpecInfo());
Richard Smith564417a2014-03-20 21:47:22 +00005043 break;
John McCalld505e572019-12-13 21:54:44 -05005044 }
Richard Smith564417a2014-03-20 21:47:22 +00005045
Richard Smith6ef42932014-03-20 21:02:00 +00005046 case UPD_CXX_DEDUCED_RETURN_TYPE:
5047 Record.push_back(GetOrCreateTypeID(Update.getType()));
5048 break;
5049
5050 case UPD_DECL_MARKED_USED:
5051 break;
Richard Smith5652c0f2014-03-21 01:48:23 +00005052
5053 case UPD_MANGLING_NUMBER:
5054 case UPD_STATIC_LOCAL_NUMBER:
5055 Record.push_back(Update.getNumber());
5056 break;
Richard Smith65ebb4a2015-03-26 04:09:53 +00005057
Alexey Bataev97720002014-11-11 04:05:39 +00005058 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
Richard Smith69c82bf2016-04-01 22:52:03 +00005059 Record.AddSourceRange(
5060 D->getAttr<OMPThreadPrivateDeclAttr>()->getRange());
Alexey Bataev97720002014-11-11 04:05:39 +00005061 break;
Richard Smith65ebb4a2015-03-26 04:09:53 +00005062
Alexey Bataev27ef9512019-03-20 20:14:22 +00005063 case UPD_DECL_MARKED_OPENMP_ALLOCATE: {
5064 auto *A = D->getAttr<OMPAllocateDeclAttr>();
5065 Record.push_back(A->getAllocatorType());
5066 Record.AddStmt(A->getAllocator());
5067 Record.AddSourceRange(A->getRange());
Alexey Bataev25ed0c02019-03-07 17:54:44 +00005068 break;
Alexey Bataev27ef9512019-03-20 20:14:22 +00005069 }
Alexey Bataev25ed0c02019-03-07 17:54:44 +00005070
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00005071 case UPD_DECL_MARKED_OPENMP_DECLARETARGET:
Alexey Bataevd01b7492018-08-15 19:45:12 +00005072 Record.push_back(D->getAttr<OMPDeclareTargetDeclAttr>()->getMapType());
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00005073 Record.AddSourceRange(
5074 D->getAttr<OMPDeclareTargetDeclAttr>()->getRange());
5075 break;
5076
Richard Smith65ebb4a2015-03-26 04:09:53 +00005077 case UPD_DECL_EXPORTED:
Richard Smith4caa4492015-05-15 02:34:32 +00005078 Record.push_back(getSubmoduleID(Update.getModule()));
Richard Smith65ebb4a2015-03-26 04:09:53 +00005079 break;
Alex Denisovfde64952015-06-26 05:28:36 +00005080
5081 case UPD_ADDED_ATTR_TO_RECORD:
Richard Smith69c82bf2016-04-01 22:52:03 +00005082 Record.AddAttributes(llvm::makeArrayRef(Update.getAttr()));
Alex Denisovfde64952015-06-26 05:28:36 +00005083 break;
Richard Smith6ef42932014-03-20 21:02:00 +00005084 }
5085 }
5086
Richard Smithd28ac5b2014-03-22 23:33:22 +00005087 if (HasUpdatedBody) {
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005088 const auto *Def = cast<FunctionDecl>(D);
Richard Smith4d235792014-08-07 18:53:08 +00005089 Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
Richard Smithd28ac5b2014-03-22 23:33:22 +00005090 Record.push_back(Def->isInlined());
Richard Smith69c82bf2016-04-01 22:52:03 +00005091 Record.AddSourceLocation(Def->getInnerLocStart());
Richard Smith290d8012016-04-06 17:06:00 +00005092 Record.AddFunctionDefinition(Def);
Richard Smithd28ac5b2014-03-22 23:33:22 +00005093 }
5094
Richard Smithcd45dbc2014-04-19 03:48:30 +00005095 OffsetsRecord.push_back(GetDeclRef(D));
Richard Smith69c82bf2016-04-01 22:52:03 +00005096 OffsetsRecord.push_back(Record.Emit(DECL_UPDATES));
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005097 }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005098}
5099
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005100void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
Richard Smithb22a1d12016-03-27 20:13:24 +00005101 uint32_t Raw = Loc.getRawEncoding();
5102 Record.push_back((Raw << 1) | (Raw >> 31));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005103}
5104
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005105void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
Chris Lattnerca025db2010-05-07 21:43:38 +00005106 AddSourceLocation(Range.getBegin(), Record);
5107 AddSourceLocation(Range.getEnd(), Record);
5108}
5109
Richard Smithf144b542016-04-08 21:54:32 +00005110void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) {
5111 AddAPInt(Value.bitcastToAPInt());
Douglas Gregore0a3a512009-04-14 21:55:33 +00005112}
5113
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00005114static void WriteFixedPointSemantics(ASTRecordWriter &Record,
5115 FixedPointSemantics FPSema) {
5116 Record.push_back(FPSema.getWidth());
5117 Record.push_back(FPSema.getScale());
5118 Record.push_back(FPSema.isSigned() | FPSema.isSaturated() << 1 |
5119 FPSema.hasUnsignedPadding() << 2);
5120}
5121
5122void ASTRecordWriter::AddAPValue(const APValue &Value) {
5123 APValue::ValueKind Kind = Value.getKind();
5124 push_back(static_cast<uint64_t>(Kind));
5125 switch (Kind) {
5126 case APValue::None:
5127 case APValue::Indeterminate:
5128 return;
5129 case APValue::Int:
5130 AddAPSInt(Value.getInt());
5131 return;
5132 case APValue::Float:
5133 push_back(static_cast<uint64_t>(
5134 llvm::APFloatBase::SemanticsToEnum(Value.getFloat().getSemantics())));
5135 AddAPFloat(Value.getFloat());
5136 return;
5137 case APValue::FixedPoint: {
5138 WriteFixedPointSemantics(*this, Value.getFixedPoint().getSemantics());
5139 AddAPSInt(Value.getFixedPoint().getValue());
5140 return;
5141 }
5142 case APValue::ComplexInt: {
5143 AddAPSInt(Value.getComplexIntReal());
5144 AddAPSInt(Value.getComplexIntImag());
5145 return;
5146 }
5147 case APValue::ComplexFloat: {
5148 push_back(static_cast<uint64_t>(llvm::APFloatBase::SemanticsToEnum(
5149 Value.getComplexFloatReal().getSemantics())));
5150 AddAPFloat(Value.getComplexFloatReal());
5151 push_back(static_cast<uint64_t>(llvm::APFloatBase::SemanticsToEnum(
5152 Value.getComplexFloatImag().getSemantics())));
5153 AddAPFloat(Value.getComplexFloatImag());
5154 return;
5155 }
5156 case APValue::LValue:
5157 case APValue::Vector:
5158 case APValue::Array:
5159 case APValue::Struct:
5160 case APValue::Union:
5161 case APValue::MemberPointer:
5162 case APValue::AddrLabelDiff:
5163 // TODO : Handle all these APValue::ValueKind.
5164 return;
5165 }
5166 llvm_unreachable("Invalid APValue::ValueKind");
5167}
5168
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005169void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
Douglas Gregor4621c6a2009-04-22 18:49:13 +00005170 Record.push_back(getIdentifierRef(II));
5171}
5172
Sebastian Redl539c5062010-08-18 23:57:32 +00005173IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
Craig Toppera13603a2014-05-22 05:54:18 +00005174 if (!II)
Douglas Gregor4621c6a2009-04-22 18:49:13 +00005175 return 0;
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00005176
Sebastian Redl539c5062010-08-18 23:57:32 +00005177 IdentID &ID = IdentifierIDs[II];
Douglas Gregor3ed42cb2009-04-11 00:14:32 +00005178 if (ID == 0)
Sebastian Redlff4a2952010-07-23 23:49:55 +00005179 ID = NextIdentID++;
Douglas Gregor4621c6a2009-04-22 18:49:13 +00005180 return ID;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005181}
5182
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005183MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005184 // Don't emit builtin macros like __LINE__ to the AST file unless they
5185 // have been redefined by the header (in which case they are not
5186 // isBuiltinMacro).
Craig Toppera13603a2014-05-22 05:54:18 +00005187 if (!MI || MI->isBuiltinMacro())
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005188 return 0;
5189
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005190 MacroID &ID = MacroIDs[MI];
5191 if (ID == 0) {
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005192 ID = NextMacroID++;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005193 MacroInfoToEmitData Info = { Name, MI, ID };
5194 MacroInfosToEmit.push_back(Info);
5195 }
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005196 return ID;
5197}
5198
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005199MacroID ASTWriter::getMacroID(MacroInfo *MI) {
Craig Toppera13603a2014-05-22 05:54:18 +00005200 if (!MI || MI->isBuiltinMacro())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005201 return 0;
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005202
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005203 assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
5204 return MacroIDs[MI];
5205}
5206
Dmitry Polukhina7afb212020-04-16 09:24:46 -07005207uint32_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
Richard Smithd7329392015-04-21 21:46:32 +00005208 return IdentMacroDirectivesOffsetMap.lookup(Name);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005209}
5210
Richard Smithe64e7452016-04-18 21:54:58 +00005211void ASTRecordWriter::AddSelectorRef(const Selector SelRef) {
5212 Record->push_back(Writer->getSelectorRef(SelRef));
Sebastian Redl834bb972010-08-04 17:20:04 +00005213}
5214
Sebastian Redl539c5062010-08-18 23:57:32 +00005215SelectorID ASTWriter::getSelectorRef(Selector Sel) {
Craig Toppera13603a2014-05-22 05:54:18 +00005216 if (Sel.getAsOpaquePtr() == nullptr) {
Sebastian Redl834bb972010-08-04 17:20:04 +00005217 return 0;
Steve Naroff2ddea052009-04-23 10:39:46 +00005218 }
5219
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005220 SelectorID SID = SelectorIDs[Sel];
Sebastian Redld95a56e2010-08-04 18:21:41 +00005221 if (SID == 0 && Chain) {
5222 // This might trigger a ReadSelector callback, which will set the ID for
5223 // this selector.
5224 Chain->LoadSelector(Sel);
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005225 SID = SelectorIDs[Sel];
Sebastian Redld95a56e2010-08-04 18:21:41 +00005226 }
Steve Naroff2ddea052009-04-23 10:39:46 +00005227 if (SID == 0) {
Sebastian Redld95a56e2010-08-04 18:21:41 +00005228 SID = NextSelectorID++;
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005229 SelectorIDs[Sel] = SID;
Steve Naroff2ddea052009-04-23 10:39:46 +00005230 }
Sebastian Redl834bb972010-08-04 17:20:04 +00005231 return SID;
Steve Naroff2ddea052009-04-23 10:39:46 +00005232}
5233
Richard Smithe64e7452016-04-18 21:54:58 +00005234void ASTRecordWriter::AddCXXTemporary(const CXXTemporary *Temp) {
5235 AddDeclRef(Temp->getDestructor());
Chris Lattnercba86142010-05-10 00:25:06 +00005236}
5237
Richard Smith290d8012016-04-06 17:06:00 +00005238void ASTRecordWriter::AddTemplateArgumentLocInfo(
5239 TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg) {
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00005240 switch (Kind) {
John McCall0ad16662009-10-29 08:12:44 +00005241 case TemplateArgument::Expression:
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00005242 AddStmt(Arg.getAsExpr());
John McCall0ad16662009-10-29 08:12:44 +00005243 break;
5244 case TemplateArgument::Type:
Richard Smith290d8012016-04-06 17:06:00 +00005245 AddTypeSourceInfo(Arg.getAsTypeSourceInfo());
John McCall0ad16662009-10-29 08:12:44 +00005246 break;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005247 case TemplateArgument::Template:
Richard Smith290d8012016-04-06 17:06:00 +00005248 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5249 AddSourceLocation(Arg.getTemplateNameLoc());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005250 break;
5251 case TemplateArgument::TemplateExpansion:
Richard Smith290d8012016-04-06 17:06:00 +00005252 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5253 AddSourceLocation(Arg.getTemplateNameLoc());
5254 AddSourceLocation(Arg.getTemplateEllipsisLoc());
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005255 break;
John McCall0ad16662009-10-29 08:12:44 +00005256 case TemplateArgument::Null:
5257 case TemplateArgument::Integral:
5258 case TemplateArgument::Declaration:
Eli Friedmanb826a002012-09-26 02:36:12 +00005259 case TemplateArgument::NullPtr:
John McCall0ad16662009-10-29 08:12:44 +00005260 case TemplateArgument::Pack:
Eli Friedmanb826a002012-09-26 02:36:12 +00005261 // FIXME: Is this right?
John McCall0ad16662009-10-29 08:12:44 +00005262 break;
5263 }
5264}
5265
Richard Smith290d8012016-04-06 17:06:00 +00005266void ASTRecordWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg) {
5267 AddTemplateArgument(Arg.getArgument());
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00005268
5269 if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
5270 bool InfoHasSameExpr
5271 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
Richard Smith290d8012016-04-06 17:06:00 +00005272 Record->push_back(InfoHasSameExpr);
Argyrios Kyrtzidisddf5f212010-06-28 09:31:42 +00005273 if (InfoHasSameExpr)
5274 return; // Avoid storing the same expr twice.
5275 }
Richard Smith290d8012016-04-06 17:06:00 +00005276 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo());
Argyrios Kyrtzidisae85e242010-06-22 09:54:59 +00005277}
5278
Richard Smith290d8012016-04-06 17:06:00 +00005279void ASTRecordWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo) {
Craig Toppera13603a2014-05-22 05:54:18 +00005280 if (!TInfo) {
Richard Smith290d8012016-04-06 17:06:00 +00005281 AddTypeRef(QualType());
John McCall8f115c62009-10-16 21:56:05 +00005282 return;
5283 }
5284
Richard Smithc23d7342018-06-29 20:46:25 +00005285 AddTypeRef(TInfo->getType());
Richard Smith290d8012016-04-06 17:06:00 +00005286 AddTypeLoc(TInfo->getTypeLoc());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005287}
5288
Richard Smith290d8012016-04-06 17:06:00 +00005289void ASTRecordWriter::AddTypeLoc(TypeLoc TL) {
Richard Smith290d8012016-04-06 17:06:00 +00005290 TypeLocWriter TLW(*this);
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005291 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
Kovarththanan Rajaratnama9c81a82010-03-14 07:06:50 +00005292 TLW.Visit(TL);
John McCall8f115c62009-10-16 21:56:05 +00005293}
5294
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005295void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
Argyrios Kyrtzidis9ab44ea2010-08-20 16:04:14 +00005296 Record.push_back(GetOrCreateTypeID(T));
5297}
5298
Richard Smith2095ffe2015-03-16 20:11:03 +00005299TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
Richard Smith1fa5d642013-05-11 05:45:24 +00005300 assert(Context);
Richard Smith2095ffe2015-03-16 20:11:03 +00005301 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5302 if (T.isNull())
5303 return TypeIdx();
5304 assert(!T.getLocalFastQualifiers());
5305
5306 TypeIdx &Idx = TypeIdxs[T];
5307 if (Idx.getIndex() == 0) {
5308 if (DoneWritingDeclsAndTypes) {
5309 assert(0 && "New type seen after serializing all the types to emit!");
5310 return TypeIdx();
5311 }
5312
5313 // We haven't seen this type before. Assign it a new ID and put it
5314 // into the queue of types to emit.
5315 Idx = TypeIdx(NextTypeID++);
5316 DeclTypesToEmit.push(T);
5317 }
5318 return Idx;
5319 });
Argyrios Kyrtzidis082e4612010-08-20 16:04:20 +00005320}
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005321
Argyrios Kyrtzidis07347322010-08-20 16:04:27 +00005322TypeID ASTWriter::getTypeID(QualType T) const {
Richard Smith1fa5d642013-05-11 05:45:24 +00005323 assert(Context);
Richard Smith2095ffe2015-03-16 20:11:03 +00005324 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5325 if (T.isNull())
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005326 return TypeIdx();
Richard Smith2095ffe2015-03-16 20:11:03 +00005327 assert(!T.getLocalFastQualifiers());
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005328
Richard Smith2095ffe2015-03-16 20:11:03 +00005329 TypeIdxMap::const_iterator I = TypeIdxs.find(T);
5330 assert(I != TypeIdxs.end() && "Type not emitted!");
5331 return I->second;
5332 });
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005333}
5334
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005335void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005336 Record.push_back(GetDeclRef(D));
5337}
5338
Sebastian Redl539c5062010-08-18 23:57:32 +00005339DeclID ASTWriter::GetDeclRef(const Decl *D) {
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005340 assert(WritingAST && "Cannot request a declaration ID before AST writing");
Craig Toppera13603a2014-05-22 05:54:18 +00005341
5342 if (!D) {
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005343 return 0;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005344 }
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005345
Douglas Gregorb3163e52012-01-05 22:33:30 +00005346 // If D comes from an AST file, its declaration ID is already known and
5347 // fixed.
5348 if (D->isFromASTFile())
5349 return D->getGlobalID();
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005350
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005351 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
Sebastian Redl539c5062010-08-18 23:57:32 +00005352 DeclID &ID = DeclIDs[D];
Mike Stump11289f42009-09-09 15:08:12 +00005353 if (ID == 0) {
Argyrios Kyrtzidis442dd802012-07-02 19:19:01 +00005354 if (DoneWritingDeclsAndTypes) {
5355 assert(0 && "New decl seen after serializing all the decls to emit!");
5356 return 0;
5357 }
5358
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005359 // We haven't seen this declaration before. Give it a new ID and
5360 // enqueue it in the list of declarations to emit.
Sebastian Redlff4a2952010-07-23 23:49:55 +00005361 ID = NextDeclID++;
Douglas Gregor12bfa382009-10-17 00:13:19 +00005362 DeclTypesToEmit.push(const_cast<Decl *>(D));
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005363 }
5364
Sebastian Redl66c5eef2010-07-27 00:17:23 +00005365 return ID;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00005366}
5367
Sebastian Redl539c5062010-08-18 23:57:32 +00005368DeclID ASTWriter::getDeclID(const Decl *D) {
Craig Toppera13603a2014-05-22 05:54:18 +00005369 if (!D)
Douglas Gregore84a9da2009-04-20 20:36:09 +00005370 return 0;
5371
Douglas Gregorb3163e52012-01-05 22:33:30 +00005372 // If D comes from an AST file, its declaration ID is already known and
5373 // fixed.
5374 if (D->isFromASTFile())
5375 return D->getGlobalID();
5376
Douglas Gregore84a9da2009-04-20 20:36:09 +00005377 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
5378 return DeclIDs[D];
5379}
5380
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005381void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005382 assert(ID);
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005383 assert(D);
5384
5385 SourceLocation Loc = D->getLocation();
5386 if (Loc.isInvalid())
5387 return;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005388
5389 // We only keep track of the file-level declarations of each file.
5390 if (!D->getLexicalDeclContext()->isFileContext())
5391 return;
Argyrios Kyrtzidise1bc99e2012-02-24 19:45:46 +00005392 // FIXME: ParmVarDecls that are part of a function type of a parameter of
5393 // a function/objc method, should not have TU as lexical context.
Argyrios Kyrtzidis71b74eb2018-01-26 19:26:12 +00005394 // TemplateTemplateParmDecls that are part of an alias template, should not
5395 // have TU as lexical context.
5396 if (isa<ParmVarDecl>(D) || isa<TemplateTemplateParmDecl>(D))
Argyrios Kyrtzidisffe055a82012-02-24 01:12:38 +00005397 return;
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005398
5399 SourceManager &SM = Context->getSourceManager();
Argyrios Kyrtzidisdf53da82011-10-28 23:57:43 +00005400 SourceLocation FileLoc = SM.getFileLoc(Loc);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005401 assert(SM.isLocalSourceLocation(FileLoc));
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005402 FileID FID;
5403 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00005404 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005405 if (FID.isInvalid())
5406 return;
Argyrios Kyrtzidis4db774a2012-10-02 21:09:17 +00005407 assert(SM.getSLocEntry(FID).isFile());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005408
David Blaikie409df392020-04-28 18:05:28 -07005409 std::unique_ptr<DeclIDInFileInfo> &Info = FileDeclIDs[FID];
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005410 if (!Info)
David Blaikie409df392020-04-28 18:05:28 -07005411 Info = std::make_unique<DeclIDInFileInfo>();
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005412
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005413 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005414 LocDeclIDsTy &Decls = Info->DeclIDs;
5415
Argyrios Kyrtzidis7362e9b2011-10-28 23:57:47 +00005416 if (Decls.empty() || Decls.back().first <= Offset) {
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005417 Decls.push_back(LocDecl);
5418 return;
5419 }
5420
Benjamin Kramer45025c02013-08-24 13:22:59 +00005421 LocDeclIDsTy::iterator I =
Fangrui Song7264a472019-07-03 08:13:17 +00005422 llvm::upper_bound(Decls, LocDecl, llvm::less_first());
Argyrios Kyrtzidis5fc727a2011-10-28 22:54:21 +00005423
5424 Decls.insert(I, LocDecl);
5425}
5426
Richard Smithd08aeb62014-08-28 01:33:39 +00005427unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
5428 assert(needsAnonymousDeclarationNumber(D) &&
5429 "expected an anonymous declaration");
5430
5431 // Number the anonymous declarations within this context, if we've not
5432 // already done so.
5433 auto It = AnonymousDeclarationNumbers.find(D);
5434 if (It == AnonymousDeclarationNumbers.end()) {
Richard Smith2b560572015-02-07 03:11:11 +00005435 auto *DC = D->getLexicalDeclContext();
5436 numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
5437 AnonymousDeclarationNumbers[ND] = Number;
5438 });
Richard Smithd08aeb62014-08-28 01:33:39 +00005439
5440 It = AnonymousDeclarationNumbers.find(D);
5441 assert(It != AnonymousDeclarationNumbers.end() &&
5442 "declaration not found within its lexical context");
5443 }
5444
5445 return It->second;
5446}
5447
Richard Smith290d8012016-04-06 17:06:00 +00005448void ASTRecordWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
5449 DeclarationName Name) {
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005450 switch (Name.getNameKind()) {
5451 case DeclarationName::CXXConstructorName:
5452 case DeclarationName::CXXDestructorName:
5453 case DeclarationName::CXXConversionFunctionName:
Richard Smith290d8012016-04-06 17:06:00 +00005454 AddTypeSourceInfo(DNLoc.NamedType.TInfo);
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005455 break;
5456
5457 case DeclarationName::CXXOperatorName:
Richard Smith290d8012016-04-06 17:06:00 +00005458 AddSourceLocation(SourceLocation::getFromRawEncoding(
5459 DNLoc.CXXOperatorName.BeginOpNameLoc));
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005460 AddSourceLocation(
Richard Smith290d8012016-04-06 17:06:00 +00005461 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc));
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005462 break;
5463
5464 case DeclarationName::CXXLiteralOperatorName:
Richard Smith290d8012016-04-06 17:06:00 +00005465 AddSourceLocation(SourceLocation::getFromRawEncoding(
5466 DNLoc.CXXLiteralOperatorName.OpNameLoc));
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005467 break;
5468
5469 case DeclarationName::Identifier:
5470 case DeclarationName::ObjCZeroArgSelector:
5471 case DeclarationName::ObjCOneArgSelector:
5472 case DeclarationName::ObjCMultiArgSelector:
5473 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00005474 case DeclarationName::CXXDeductionGuideName:
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005475 break;
5476 }
5477}
5478
Richard Smith290d8012016-04-06 17:06:00 +00005479void ASTRecordWriter::AddDeclarationNameInfo(
5480 const DeclarationNameInfo &NameInfo) {
5481 AddDeclarationName(NameInfo.getName());
5482 AddSourceLocation(NameInfo.getLoc());
5483 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName());
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005484}
5485
Richard Smith290d8012016-04-06 17:06:00 +00005486void ASTRecordWriter::AddQualifierInfo(const QualifierInfo &Info) {
5487 AddNestedNameSpecifierLoc(Info.QualifierLoc);
5488 Record->push_back(Info.NumTemplParamLists);
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005489 for (unsigned i = 0, e = Info.NumTemplParamLists; i != e; ++i)
Richard Smith290d8012016-04-06 17:06:00 +00005490 AddTemplateParameterList(Info.TemplParamLists[i]);
Argyrios Kyrtzidis434383d2010-10-15 18:21:24 +00005491}
5492
Richard Smith290d8012016-04-06 17:06:00 +00005493void ASTRecordWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005494 // Nested name specifiers usually aren't too long. I think that 8 would
Chris Lattner57540c52011-04-15 05:22:18 +00005495 // typically accommodate the vast majority.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005496 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005497
5498 // Push each of the nested-name-specifiers's onto a stack for
5499 // serialization in reverse order.
5500 while (NNS) {
5501 NestedNames.push_back(NNS);
5502 NNS = NNS.getPrefix();
5503 }
5504
Richard Smith290d8012016-04-06 17:06:00 +00005505 Record->push_back(NestedNames.size());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005506 while(!NestedNames.empty()) {
5507 NNS = NestedNames.pop_back_val();
5508 NestedNameSpecifier::SpecifierKind Kind
5509 = NNS.getNestedNameSpecifier()->getKind();
Richard Smith290d8012016-04-06 17:06:00 +00005510 Record->push_back(Kind);
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005511 switch (Kind) {
5512 case NestedNameSpecifier::Identifier:
Richard Smith290d8012016-04-06 17:06:00 +00005513 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier());
5514 AddSourceRange(NNS.getLocalSourceRange());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005515 break;
5516
5517 case NestedNameSpecifier::Namespace:
Richard Smith290d8012016-04-06 17:06:00 +00005518 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace());
5519 AddSourceRange(NNS.getLocalSourceRange());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005520 break;
5521
5522 case NestedNameSpecifier::NamespaceAlias:
Richard Smith290d8012016-04-06 17:06:00 +00005523 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias());
5524 AddSourceRange(NNS.getLocalSourceRange());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005525 break;
5526
5527 case NestedNameSpecifier::TypeSpec:
5528 case NestedNameSpecifier::TypeSpecWithTemplate:
Richard Smith290d8012016-04-06 17:06:00 +00005529 Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
Richard Smithc23d7342018-06-29 20:46:25 +00005530 AddTypeRef(NNS.getTypeLoc().getType());
Richard Smith290d8012016-04-06 17:06:00 +00005531 AddTypeLoc(NNS.getTypeLoc());
5532 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005533 break;
5534
5535 case NestedNameSpecifier::Global:
Richard Smith290d8012016-04-06 17:06:00 +00005536 AddSourceLocation(NNS.getLocalSourceRange().getEnd());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005537 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00005538
5539 case NestedNameSpecifier::Super:
Richard Smith290d8012016-04-06 17:06:00 +00005540 AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl());
5541 AddSourceRange(NNS.getLocalSourceRange());
Nikola Smiljanic67860242014-09-26 00:28:20 +00005542 break;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00005543 }
5544 }
5545}
5546
Richard Smithe64e7452016-04-18 21:54:58 +00005547void ASTRecordWriter::AddTemplateParameterList(
5548 const TemplateParameterList *TemplateParams) {
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005549 assert(TemplateParams && "No TemplateParams!");
Richard Smithe64e7452016-04-18 21:54:58 +00005550 AddSourceLocation(TemplateParams->getTemplateLoc());
5551 AddSourceLocation(TemplateParams->getLAngleLoc());
5552 AddSourceLocation(TemplateParams->getRAngleLoc());
Saar Raz0330fba2019-10-15 18:44:06 +00005553
Richard Smithe64e7452016-04-18 21:54:58 +00005554 Record->push_back(TemplateParams->size());
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005555 for (const auto &P : *TemplateParams)
Richard Smithe64e7452016-04-18 21:54:58 +00005556 AddDeclRef(P);
Saar Raz0330fba2019-10-15 18:44:06 +00005557 if (const Expr *RequiresClause = TemplateParams->getRequiresClause()) {
5558 Record->push_back(true);
5559 AddStmt(const_cast<Expr*>(RequiresClause));
5560 } else {
5561 Record->push_back(false);
5562 }
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005563}
5564
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005565/// Emit a template argument list.
Richard Smith290d8012016-04-06 17:06:00 +00005566void ASTRecordWriter::AddTemplateArgumentList(
5567 const TemplateArgumentList *TemplateArgs) {
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005568 assert(TemplateArgs && "No TemplateArgs!");
Richard Smith290d8012016-04-06 17:06:00 +00005569 Record->push_back(TemplateArgs->size());
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005570 for (int i = 0, e = TemplateArgs->size(); i != e; ++i)
Richard Smith290d8012016-04-06 17:06:00 +00005571 AddTemplateArgument(TemplateArgs->get(i));
Argyrios Kyrtzidis818c5db2010-06-23 13:48:30 +00005572}
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005573
Richard Smith290d8012016-04-06 17:06:00 +00005574void ASTRecordWriter::AddASTTemplateArgumentListInfo(
5575 const ASTTemplateArgumentListInfo *ASTTemplArgList) {
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005576 assert(ASTTemplArgList && "No ASTTemplArgList!");
Richard Smith290d8012016-04-06 17:06:00 +00005577 AddSourceLocation(ASTTemplArgList->LAngleLoc);
5578 AddSourceLocation(ASTTemplArgList->RAngleLoc);
5579 Record->push_back(ASTTemplArgList->NumTemplateArgs);
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005580 const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005581 for (int i = 0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
Richard Smith290d8012016-04-06 17:06:00 +00005582 AddTemplateArgumentLoc(TemplArgs[i]);
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00005583}
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005584
Richard Smithe64e7452016-04-18 21:54:58 +00005585void ASTRecordWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set) {
5586 Record->push_back(Set.size());
Argyrios Kyrtzidis0f05fb92012-11-28 03:56:16 +00005587 for (ASTUnresolvedSet::const_iterator
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005588 I = Set.begin(), E = Set.end(); I != E; ++I) {
Richard Smithe64e7452016-04-18 21:54:58 +00005589 AddDeclRef(I.getDecl());
5590 Record->push_back(I.getAccess());
Argyrios Kyrtzidis2c2167a2010-07-02 11:55:32 +00005591 }
5592}
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005593
Richard Smith290d8012016-04-06 17:06:00 +00005594// FIXME: Move this out of the main ASTRecordWriter interface.
5595void ASTRecordWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
5596 Record->push_back(Base.isVirtual());
5597 Record->push_back(Base.isBaseOfClass());
5598 Record->push_back(Base.getAccessSpecifierAsWritten());
5599 Record->push_back(Base.getInheritConstructors());
5600 AddTypeSourceInfo(Base.getTypeSourceInfo());
5601 AddSourceRange(Base.getSourceRange());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005602 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
Richard Smith290d8012016-04-06 17:06:00 +00005603 : SourceLocation());
Argyrios Kyrtzidis3701fcd2010-07-02 23:30:27 +00005604}
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00005605
Richard Smith645d2cf2016-04-14 00:29:55 +00005606static uint64_t EmitCXXBaseSpecifiers(ASTWriter &W,
5607 ArrayRef<CXXBaseSpecifier> Bases) {
5608 ASTWriter::RecordData Record;
5609 ASTRecordWriter Writer(W, Record);
5610 Writer.push_back(Bases.size());
Dmitry Polukhin790b5402016-04-06 10:01:46 +00005611
Richard Smith645d2cf2016-04-14 00:29:55 +00005612 for (auto &Base : Bases)
5613 Writer.AddCXXBaseSpecifier(Base);
Richard Smith290d8012016-04-06 17:06:00 +00005614
Richard Smith645d2cf2016-04-14 00:29:55 +00005615 return Writer.Emit(serialization::DECL_CXX_BASE_SPECIFIERS);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005616}
5617
Richard Smith290d8012016-04-06 17:06:00 +00005618// FIXME: Move this out of the main ASTRecordWriter interface.
Richard Smith645d2cf2016-04-14 00:29:55 +00005619void ASTRecordWriter::AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases) {
5620 AddOffset(EmitCXXBaseSpecifiers(*Writer, Bases));
5621}
5622
Richard Smithaa165cf2016-04-13 21:57:08 +00005623static uint64_t
5624EmitCXXCtorInitializers(ASTWriter &W,
5625 ArrayRef<CXXCtorInitializer *> CtorInits) {
5626 ASTWriter::RecordData Record;
5627 ASTRecordWriter Writer(W, Record);
5628 Writer.push_back(CtorInits.size());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005629
Richard Smithaa165cf2016-04-13 21:57:08 +00005630 for (auto *Init : CtorInits) {
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005631 if (Init->isBaseInitializer()) {
Richard Smithaa165cf2016-04-13 21:57:08 +00005632 Writer.push_back(CTOR_INITIALIZER_BASE);
5633 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
5634 Writer.push_back(Init->isBaseVirtual());
Alexis Hunt37a477f2011-05-04 01:19:08 +00005635 } else if (Init->isDelegatingInitializer()) {
Richard Smithaa165cf2016-04-13 21:57:08 +00005636 Writer.push_back(CTOR_INITIALIZER_DELEGATING);
5637 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
Alexis Hunt37a477f2011-05-04 01:19:08 +00005638 } else if (Init->isMemberInitializer()){
Richard Smithaa165cf2016-04-13 21:57:08 +00005639 Writer.push_back(CTOR_INITIALIZER_MEMBER);
5640 Writer.AddDeclRef(Init->getMember());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005641 } else {
Richard Smithaa165cf2016-04-13 21:57:08 +00005642 Writer.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
5643 Writer.AddDeclRef(Init->getIndirectMember());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005644 }
Francois Pichetd583da02010-12-04 09:14:42 +00005645
Richard Smithaa165cf2016-04-13 21:57:08 +00005646 Writer.AddSourceLocation(Init->getMemberLocation());
5647 Writer.AddStmt(Init->getInit());
5648 Writer.AddSourceLocation(Init->getLParenLoc());
5649 Writer.AddSourceLocation(Init->getRParenLoc());
5650 Writer.push_back(Init->isWritten());
Richard Smith30e304e2016-12-14 00:03:17 +00005651 if (Init->isWritten())
Richard Smithaa165cf2016-04-13 21:57:08 +00005652 Writer.push_back(Init->getSourceOrder());
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005653 }
Richard Smithaa165cf2016-04-13 21:57:08 +00005654
5655 return Writer.Emit(serialization::DECL_CXX_CTOR_INITIALIZERS);
Argyrios Kyrtzidis5b6a03f2010-08-09 10:54:12 +00005656}
5657
Richard Smithaa165cf2016-04-13 21:57:08 +00005658// FIXME: Move this out of the main ASTRecordWriter interface.
5659void ASTRecordWriter::AddCXXCtorInitializers(
5660 ArrayRef<CXXCtorInitializer *> CtorInits) {
5661 AddOffset(EmitCXXCtorInitializers(*Writer, CtorInits));
Richard Smithc2bb8182015-03-24 06:36:48 +00005662}
5663
Richard Smith290d8012016-04-06 17:06:00 +00005664void ASTRecordWriter::AddCXXDefinitionData(const CXXRecordDecl *D) {
Richard Smith053f6c62014-05-16 23:01:30 +00005665 auto &Data = D->data();
Richard Smith290d8012016-04-06 17:06:00 +00005666 Record->push_back(Data.IsLambda);
Richard Smith91aeacc2019-10-11 00:29:04 +00005667
5668 #define FIELD(Name, Width, Merge) \
5669 Record->push_back(Data.Name);
5670 #include "clang/AST/CXXRecordDeclDefinitionBits.def"
Richard Trieufd1acbb2017-04-11 21:31:00 +00005671
5672 // getODRHash will compute the ODRHash if it has not been previously computed.
5673 Record->push_back(D->getODRHash());
Hans Wennborg7ea9a6e2020-02-27 14:33:43 +01005674 bool ModulesDebugInfo = Writer->Context->getLangOpts().ModulesDebugInfo &&
5675 Writer->WritingModule && !D->isDependentType();
David Blaikief63556d2017-04-12 20:58:33 +00005676 Record->push_back(ModulesDebugInfo);
5677 if (ModulesDebugInfo)
David Blaikie1ac9c982017-04-11 21:13:37 +00005678 Writer->ModularCodegenDecls.push_back(Writer->GetDeclRef(D));
5679
Richard Smith561fb152012-02-25 07:33:38 +00005680 // IsLambda bit is already saved.
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005681
Richard Smith290d8012016-04-06 17:06:00 +00005682 Record->push_back(Data.NumBases);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005683 if (Data.NumBases > 0)
Richard Smith645d2cf2016-04-14 00:29:55 +00005684 AddCXXBaseSpecifiers(Data.bases());
5685
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005686 // FIXME: Make VBases lazily computed when needed to avoid storing them.
Richard Smith290d8012016-04-06 17:06:00 +00005687 Record->push_back(Data.NumVBases);
Douglas Gregord4c5ed02010-10-29 22:39:52 +00005688 if (Data.NumVBases > 0)
Richard Smith645d2cf2016-04-14 00:29:55 +00005689 AddCXXBaseSpecifiers(Data.vbases());
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005690
Richard Smith290d8012016-04-06 17:06:00 +00005691 AddUnresolvedSet(Data.Conversions.get(*Writer->Context));
Richard Smith91aeacc2019-10-11 00:29:04 +00005692 Record->push_back(Data.ComputedVisibleConversions);
5693 if (Data.ComputedVisibleConversions)
5694 AddUnresolvedSet(Data.VisibleConversions.get(*Writer->Context));
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005695 // Data.Definition is the owning decl, no need to write it.
Richard Smith290d8012016-04-06 17:06:00 +00005696 AddDeclRef(D->getFirstFriend());
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005697
Douglas Gregor99ae8062012-02-14 17:54:36 +00005698 // Add lambda-specific data.
5699 if (Data.IsLambda) {
Richard Smith053f6c62014-05-16 23:01:30 +00005700 auto &Lambda = D->getLambdaData();
Richard Smith290d8012016-04-06 17:06:00 +00005701 Record->push_back(Lambda.Dependent);
5702 Record->push_back(Lambda.IsGenericLambda);
5703 Record->push_back(Lambda.CaptureDefault);
5704 Record->push_back(Lambda.NumCaptures);
5705 Record->push_back(Lambda.NumExplicitCaptures);
Michael Liao243ebfb2019-10-19 00:15:19 +00005706 Record->push_back(Lambda.HasKnownInternalLinkage);
Richard Smith290d8012016-04-06 17:06:00 +00005707 Record->push_back(Lambda.ManglingNumber);
Richard Smith0bae6242016-08-25 00:34:00 +00005708 AddDeclRef(D->getLambdaContextDecl());
Richard Smith290d8012016-04-06 17:06:00 +00005709 AddTypeSourceInfo(Lambda.MethodTyInfo);
Douglas Gregor99ae8062012-02-14 17:54:36 +00005710 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
Benjamin Kramerf3ca26982014-05-10 16:31:55 +00005711 const LambdaCapture &Capture = Lambda.Captures[I];
Richard Smith290d8012016-04-06 17:06:00 +00005712 AddSourceLocation(Capture.getLocation());
5713 Record->push_back(Capture.isImplicit());
5714 Record->push_back(Capture.getCaptureKind());
Richard Smithba71c082013-05-16 06:20:58 +00005715 switch (Capture.getCaptureKind()) {
Faisal Validc6b5962016-03-21 09:25:37 +00005716 case LCK_StarThis:
Richard Smithba71c082013-05-16 06:20:58 +00005717 case LCK_This:
Alexey Bataev39c81e22014-08-28 04:28:19 +00005718 case LCK_VLAType:
Richard Smithba71c082013-05-16 06:20:58 +00005719 break;
5720 case LCK_ByCopy:
Richard Smithbb13c9a2013-09-28 04:02:39 +00005721 case LCK_ByRef:
Richard Smithba71c082013-05-16 06:20:58 +00005722 VarDecl *Var =
Craig Toppera13603a2014-05-22 05:54:18 +00005723 Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
Richard Smith290d8012016-04-06 17:06:00 +00005724 AddDeclRef(Var);
Richard Smithba71c082013-05-16 06:20:58 +00005725 AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
Richard Smith290d8012016-04-06 17:06:00 +00005726 : SourceLocation());
Richard Smithba71c082013-05-16 06:20:58 +00005727 break;
5728 }
Douglas Gregor99ae8062012-02-14 17:54:36 +00005729 }
5730 }
Argyrios Kyrtzidiseb39d9a2010-10-24 17:26:40 +00005731}
5732
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005733void ASTWriter::ReaderInitialized(ASTReader *Reader) {
Sebastian Redl07a89a82010-07-30 00:29:29 +00005734 assert(Reader && "Cannot remove chain");
Douglas Gregordf0c1512011-08-18 04:12:04 +00005735 assert((!Chain || Chain == Reader) && "Cannot replace chain");
Sebastian Redl07a89a82010-07-30 00:29:29 +00005736 assert(FirstDeclID == NextDeclID &&
5737 FirstTypeID == NextTypeID &&
5738 FirstIdentID == NextIdentID &&
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005739 FirstMacroID == NextMacroID &&
Douglas Gregor253eefe2011-12-01 00:59:36 +00005740 FirstSubmoduleID == NextSubmoduleID &&
Sebastian Redld95a56e2010-08-04 18:21:41 +00005741 FirstSelectorID == NextSelectorID &&
Sebastian Redl07a89a82010-07-30 00:29:29 +00005742 "Setting chain after writing has started.");
Douglas Gregor925296b2011-07-19 16:10:42 +00005743
Sebastian Redl07a89a82010-07-30 00:29:29 +00005744 Chain = Reader;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005745
Richard Smith7f330cd2015-03-18 01:42:29 +00005746 // Note, this will get called multiple times, once one the reader starts up
5747 // and again each time it's done reading a PCH or module.
Douglas Gregordf0c1512011-08-18 04:12:04 +00005748 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
5749 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
5750 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005751 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
Douglas Gregor253eefe2011-12-01 00:59:36 +00005752 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
Douglas Gregordf0c1512011-08-18 04:12:04 +00005753 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005754 NextDeclID = FirstDeclID;
5755 NextTypeID = FirstTypeID;
5756 NextIdentID = FirstIdentID;
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005757 NextMacroID = FirstMacroID;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00005758 NextSelectorID = FirstSelectorID;
Douglas Gregor253eefe2011-12-01 00:59:36 +00005759 NextSubmoduleID = FirstSubmoduleID;
Sebastian Redl07a89a82010-07-30 00:29:29 +00005760}
5761
Sebastian Redl539c5062010-08-18 23:57:32 +00005762void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005763 // Always keep the highest ID. See \p TypeRead() for more information.
5764 IdentID &StoredID = IdentifierIDs[II];
5765 if (ID > StoredID)
5766 StoredID = ID;
Sebastian Redlff4a2952010-07-23 23:49:55 +00005767}
5768
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005769void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005770 // Always keep the highest ID. See \p TypeRead() for more information.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00005771 MacroID &StoredID = MacroIDs[MI];
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005772 if (ID > StoredID)
5773 StoredID = ID;
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005774}
5775
Argyrios Kyrtzidisbb5c7eae2010-08-20 16:03:59 +00005776void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005777 // Always take the highest-numbered type index. This copes with an interesting
5778 // case for chained AST writing where we schedule writing the type and then,
Michael J. Spencer4c0ffa82010-10-21 03:16:25 +00005779 // later, deserialize the type from another AST. In this case, we want to
Douglas Gregor9b3932c2010-10-05 18:37:06 +00005780 // keep the higher-numbered entry so that we can properly write it out to
5781 // the AST file.
5782 TypeIdx &StoredIdx = TypeIdxs[T];
5783 if (Idx.getIndex() >= StoredIdx.getIndex())
5784 StoredIdx = Idx;
Sebastian Redl85b2a6a2010-07-14 23:45:08 +00005785}
5786
Sebastian Redl539c5062010-08-18 23:57:32 +00005787void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
Douglas Gregor8d7edce2013-02-08 21:30:59 +00005788 // Always keep the highest ID. See \p TypeRead() for more information.
5789 SelectorID &StoredID = SelectorIDs[S];
5790 if (ID > StoredID)
5791 StoredID = ID;
Sebastian Redl834bb972010-08-04 17:20:04 +00005792}
Douglas Gregor91096292010-10-02 19:29:26 +00005793
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00005794void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
Richard Smith66a81862015-05-04 02:25:31 +00005795 MacroDefinitionRecord *MD) {
Argyrios Kyrtzidis03c40c52011-09-15 18:02:56 +00005796 assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
Douglas Gregor91096292010-10-02 19:29:26 +00005797 MacroDefinitions[MD] = ID;
5798}
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005799
Douglas Gregore37a85a2011-12-02 17:30:13 +00005800void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
5801 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
5802 SubmoduleIDs[Mod] = ID;
5803}
5804
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005805void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005806 if (Chain && Chain->isProcessingUpdateRecords()) return;
John McCallf937c022011-10-07 06:10:15 +00005807 assert(D->isCompleteDefinition());
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005808 assert(!WritingAST && "Already writing the AST!");
Eugene Zelenkoddaa4b42015-12-08 18:00:11 +00005809 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005810 // We are interested when a PCH decl is modified.
Douglas Gregorb3722e22011-09-09 23:01:35 +00005811 if (RD->isFromASTFile()) {
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005812 // A forward reference was mutated into a definition. Rewrite it.
5813 // FIXME: This happens during template instantiation, should we
5814 // have created a new definition decl instead ?
Richard Smithcd45dbc2014-04-19 03:48:30 +00005815 assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
5816 "completed a tag from another module but not by instantiation?");
5817 DeclUpdates[RD].push_back(
5818 DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION));
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005819 }
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00005820 }
5821}
Douglas Gregorcb28f9d2012-10-09 23:05:51 +00005822
Richard Smithf983f7f2015-10-13 00:23:25 +00005823static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) {
5824 if (D->isFromASTFile())
5825 return true;
5826
Richard Smithf983f7f2015-10-13 00:23:25 +00005827 // The predefined __va_list_tag struct is imported if we imported any decls.
5828 // FIXME: This is a gross hack.
5829 return D == D->getASTContext().getVaListTagDecl();
5830}
5831
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005832void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005833 if (Chain && Chain->isProcessingUpdateRecords()) return;
5834 assert(DC->isLookupContext() &&
Vassil Vassilev71eafde2016-04-06 20:56:03 +00005835 "Should not add lookup results to non-lookup contexts!");
5836
Vassil Vassilev632eac32016-03-16 11:17:04 +00005837 // TU is handled elsewhere.
5838 if (isa<TranslationUnitDecl>(DC))
5839 return;
5840
5841 // Namespaces are handled elsewhere, except for template instantiations of
5842 // FunctionTemplateDecls in namespaces. We are interested in cases where the
5843 // local instantiations are added to an imported context. Only happens when
5844 // adding ADL lookup candidates, for example templated friends.
5845 if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None &&
5846 !isa<FunctionTemplateDecl>(D))
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005847 return;
5848
Richard Smithf983f7f2015-10-13 00:23:25 +00005849 // We're only interested in cases where a local declaration is added to an
5850 // imported context.
5851 if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC)))
5852 return;
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005853
Richard Smith0f4e2c42015-08-06 04:23:48 +00005854 assert(DC == DC->getPrimaryContext() && "added to non-primary context");
Douglas Gregor9f782892013-01-21 15:25:38 +00005855 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
Richard Smithe9a8bc32014-09-30 00:45:29 +00005856 assert(!WritingAST && "Already writing the AST!");
Richard Smithf983f7f2015-10-13 00:23:25 +00005857 if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) {
5858 // We're adding a visible declaration to a predefined decl context. Ensure
5859 // that we write out all of its lookup results so we don't get a nasty
5860 // surprise when we try to emit its lookup table.
5861 for (auto *Child : DC->decls())
Richard Smithc26d9742016-10-06 20:30:51 +00005862 DeclsToEmitEvenIfUnreferenced.push_back(Child);
Richard Smithf983f7f2015-10-13 00:23:25 +00005863 }
Richard Smithc26d9742016-10-06 20:30:51 +00005864 DeclsToEmitEvenIfUnreferenced.push_back(D);
Argyrios Kyrtzidis01c2df42010-10-28 07:38:51 +00005865}
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005866
5867void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005868 if (Chain && Chain->isProcessingUpdateRecords()) return;
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005869 assert(D->isImplicit());
Richard Smithf983f7f2015-10-13 00:23:25 +00005870
5871 // We're only interested in cases where a local declaration is added to an
5872 // imported context.
5873 if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD))
5874 return;
5875
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005876 if (!isa<CXXMethodDecl>(D))
Richard Smithf983f7f2015-10-13 00:23:25 +00005877 return;
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005878
5879 // A decl coming from PCH was modified.
John McCallf937c022011-10-07 06:10:15 +00005880 assert(RD->isCompleteDefinition());
Richard Smithe9a8bc32014-09-30 00:45:29 +00005881 assert(!WritingAST && "Already writing the AST!");
Aaron Ballman4f45b712014-03-21 15:22:56 +00005882 DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
Argyrios Kyrtzidise16a5302010-10-24 17:26:54 +00005883}
Argyrios Kyrtzidis402dbbb2010-10-28 07:38:42 +00005884
Richard Smith564417a2014-03-20 21:47:22 +00005885void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005886 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smith9e2341d2015-03-23 03:25:59 +00005887 assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
5888 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00005889 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005890 // If we don't already know the exception specification for this redecl
5891 // chain, add an update record for it.
5892 if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
5893 ->getType()
5894 ->castAs<FunctionProtoType>()
5895 ->getExceptionSpecType()))
5896 DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
5897 });
Richard Smith564417a2014-03-20 21:47:22 +00005898}
5899
Richard Smith1fa5d642013-05-11 05:45:24 +00005900void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005901 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smith1fa5d642013-05-11 05:45:24 +00005902 assert(!WritingAST && "Already writing the AST!");
Richard Smith9e2341d2015-03-23 03:25:59 +00005903 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00005904 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005905 DeclUpdates[D].push_back(
5906 DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
5907 });
Richard Smith1fa5d642013-05-11 05:45:24 +00005908}
5909
Richard Smithf8134002015-03-10 01:41:22 +00005910void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
Richard Smith5b349582017-10-13 01:55:36 +00005911 const FunctionDecl *Delete,
5912 Expr *ThisArg) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005913 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smithf8134002015-03-10 01:41:22 +00005914 assert(!WritingAST && "Already writing the AST!");
5915 assert(Delete && "Not given an operator delete");
Richard Smith9e2341d2015-03-23 03:25:59 +00005916 if (!Chain) return;
Richard Smith5fc18a92015-07-12 23:43:21 +00005917 Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
Richard Smith9e2341d2015-03-23 03:25:59 +00005918 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete));
5919 });
Richard Smithf8134002015-03-10 01:41:22 +00005920}
5921
Sebastian Redlab238a72011-04-24 16:28:06 +00005922void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005923 if (Chain && Chain->isProcessingUpdateRecords()) return;
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005924 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005925 if (!D->isFromASTFile())
Sebastian Redlab238a72011-04-24 16:28:06 +00005926 return; // Declaration not imported from PCH.
5927
Richard Smith4d235792014-08-07 18:53:08 +00005928 // Implicit function decl from a PCH was defined.
5929 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
Sebastian Redlab238a72011-04-24 16:28:06 +00005930}
5931
Richard Smith891fc7f2017-12-05 01:31:47 +00005932void ASTWriter::VariableDefinitionInstantiated(const VarDecl *D) {
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_CXX_ADDED_VAR_DEFINITION));
5939}
5940
Richard Smithd28ac5b2014-03-22 23:33:22 +00005941void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005942 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smithd28ac5b2014-03-22 23:33:22 +00005943 assert(!WritingAST && "Already writing the AST!");
5944 if (!D->isFromASTFile())
5945 return;
5946
Richard Smith9e2341d2015-03-23 03:25:59 +00005947 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
Richard Smithd28ac5b2014-03-22 23:33:22 +00005948}
5949
Richard Smith891fc7f2017-12-05 01:31:47 +00005950void ASTWriter::InstantiationRequested(const ValueDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005951 if (Chain && Chain->isProcessingUpdateRecords()) return;
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005952 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005953 if (!D->isFromASTFile())
Sebastian Redl2ac2c722011-04-29 08:19:30 +00005954 return;
5955
5956 // Since the actual instantiation is delayed, this really means that we need
5957 // to update the instantiation location.
Richard Smith891fc7f2017-12-05 01:31:47 +00005958 SourceLocation POI;
5959 if (auto *VD = dyn_cast<VarDecl>(D))
5960 POI = VD->getPointOfInstantiation();
5961 else
5962 POI = cast<FunctionDecl>(D)->getPointOfInstantiation();
5963 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_POINT_OF_INSTANTIATION, POI));
Sebastian Redl2ac2c722011-04-29 08:19:30 +00005964}
5965
John McCall32791cc2016-01-06 22:34:54 +00005966void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005967 if (Chain && Chain->isProcessingUpdateRecords()) return;
John McCall32791cc2016-01-06 22:34:54 +00005968 assert(!WritingAST && "Already writing the AST!");
5969 if (!D->isFromASTFile())
5970 return;
5971
5972 DeclUpdates[D].push_back(
5973 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D));
5974}
5975
Richard Smith4b054b22016-08-24 21:25:37 +00005976void ASTWriter::DefaultMemberInitializerInstantiated(const FieldDecl *D) {
5977 assert(!WritingAST && "Already writing the AST!");
5978 if (!D->isFromASTFile())
5979 return;
5980
5981 DeclUpdates[D].push_back(
5982 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER, D));
5983}
5984
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00005985void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
5986 const ObjCInterfaceDecl *IFD) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005987 if (Chain && Chain->isProcessingUpdateRecords()) return;
Douglas Gregor2fd3d402011-09-17 00:05:03 +00005988 assert(!WritingAST && "Already writing the AST!");
Douglas Gregorb3722e22011-09-09 23:01:35 +00005989 if (!IFD->isFromASTFile())
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00005990 return; // Declaration not imported from PCH.
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00005991
Douglas Gregor404cdde2012-01-27 01:47:08 +00005992 assert(IFD->getDefinition() && "Category on a class without a definition?");
5993 ObjCClassesWithCategories.insert(
5994 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
Argyrios Kyrtzidis7d847c92011-09-01 00:58:55 +00005995}
Argyrios Kyrtzidisb97a4022011-11-12 21:07:46 +00005996
Eli Friedman276dd182013-09-05 00:02:25 +00005997void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00005998 if (Chain && Chain->isProcessingUpdateRecords()) return;
Eli Friedman276dd182013-09-05 00:02:25 +00005999 assert(!WritingAST && "Already writing the AST!");
Vassil Vassilev928c8252016-04-28 14:13:28 +00006000
6001 // If there is *any* declaration of the entity that's not from an AST file,
6002 // we can skip writing the update record. We make sure that isUsed() triggers
6003 // completion of the redeclaration chain of the entity.
6004 for (auto Prev = D->getMostRecentDecl(); Prev; Prev = Prev->getPreviousDecl())
6005 if (IsLocalDecl(Prev))
6006 return;
Eli Friedman276dd182013-09-05 00:02:25 +00006007
Aaron Ballman4f45b712014-03-21 15:22:56 +00006008 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
Eli Friedman276dd182013-09-05 00:02:25 +00006009}
Alexey Bataev97720002014-11-11 04:05:39 +00006010
6011void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006012 if (Chain && Chain->isProcessingUpdateRecords()) return;
Alexey Bataev97720002014-11-11 04:05:39 +00006013 assert(!WritingAST && "Already writing the AST!");
6014 if (!D->isFromASTFile())
6015 return;
6016
6017 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE));
6018}
Richard Smith65ebb4a2015-03-26 04:09:53 +00006019
Alexey Bataev25ed0c02019-03-07 17:54:44 +00006020void ASTWriter::DeclarationMarkedOpenMPAllocate(const Decl *D, const Attr *A) {
6021 if (Chain && Chain->isProcessingUpdateRecords()) return;
6022 assert(!WritingAST && "Already writing the AST!");
6023 if (!D->isFromASTFile())
6024 return;
6025
6026 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_ALLOCATE, A));
6027}
6028
Dmitry Polukhind69b5052016-05-09 14:59:13 +00006029void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
6030 const Attr *Attr) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006031 if (Chain && Chain->isProcessingUpdateRecords()) return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00006032 assert(!WritingAST && "Already writing the AST!");
6033 if (!D->isFromASTFile())
6034 return;
6035
Dmitry Polukhind69b5052016-05-09 14:59:13 +00006036 DeclUpdates[D].push_back(
6037 DeclUpdate(UPD_DECL_MARKED_OPENMP_DECLARETARGET, Attr));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00006038}
6039
Richard Smith4caa4492015-05-15 02:34:32 +00006040void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006041 if (Chain && Chain->isProcessingUpdateRecords()) return;
Richard Smith65ebb4a2015-03-26 04:09:53 +00006042 assert(!WritingAST && "Already writing the AST!");
6043 assert(D->isHidden() && "expected a hidden declaration");
Richard Smith4caa4492015-05-15 02:34:32 +00006044 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M));
Richard Smith65ebb4a2015-03-26 04:09:53 +00006045}
Alex Denisovfde64952015-06-26 05:28:36 +00006046
6047void ASTWriter::AddedAttributeToRecord(const Attr *Attr,
6048 const RecordDecl *Record) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00006049 if (Chain && Chain->isProcessingUpdateRecords()) return;
Alex Denisovfde64952015-06-26 05:28:36 +00006050 assert(!WritingAST && "Already writing the AST!");
6051 if (!Record->isFromASTFile())
6052 return;
6053 DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr));
6054}
Richard Smithc26d9742016-10-06 20:30:51 +00006055
6056void ASTWriter::AddedCXXTemplateSpecialization(
6057 const ClassTemplateDecl *TD, const ClassTemplateSpecializationDecl *D) {
6058 assert(!WritingAST && "Already writing the AST!");
6059
6060 if (!TD->getFirstDecl()->isFromASTFile())
6061 return;
6062 if (Chain && Chain->isProcessingUpdateRecords())
6063 return;
6064
6065 DeclsToEmitEvenIfUnreferenced.push_back(D);
6066}
6067
6068void ASTWriter::AddedCXXTemplateSpecialization(
6069 const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) {
6070 assert(!WritingAST && "Already writing the AST!");
6071
6072 if (!TD->getFirstDecl()->isFromASTFile())
6073 return;
6074 if (Chain && Chain->isProcessingUpdateRecords())
6075 return;
6076
6077 DeclsToEmitEvenIfUnreferenced.push_back(D);
6078}
6079
6080void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
6081 const FunctionDecl *D) {
6082 assert(!WritingAST && "Already writing the AST!");
6083
6084 if (!TD->getFirstDecl()->isFromASTFile())
6085 return;
6086 if (Chain && Chain->isProcessingUpdateRecords())
6087 return;
6088
6089 DeclsToEmitEvenIfUnreferenced.push_back(D);
6090}
Kelvin Libe286f52018-09-15 13:54:15 +00006091
6092//===----------------------------------------------------------------------===//
6093//// OMPClause Serialization
6094////===----------------------------------------------------------------------===//
6095
John McCall2ac702a2019-12-14 03:17:03 -05006096namespace {
6097
6098class OMPClauseWriter : public OMPClauseVisitor<OMPClauseWriter> {
6099 ASTRecordWriter &Record;
6100
6101public:
6102 OMPClauseWriter(ASTRecordWriter &Record) : Record(Record) {}
Johannes Doerfert419a5592020-03-30 19:58:40 -05006103#define OMP_CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *S);
6104#include "llvm/Frontend/OpenMP/OMPKinds.def"
John McCall2ac702a2019-12-14 03:17:03 -05006105 void writeClause(OMPClause *C);
6106 void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C);
6107 void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C);
6108};
6109
6110}
6111
6112void ASTRecordWriter::writeOMPClause(OMPClause *C) {
6113 OMPClauseWriter(*this).writeClause(C);
6114}
6115
Kelvin Libe286f52018-09-15 13:54:15 +00006116void OMPClauseWriter::writeClause(OMPClause *C) {
Johannes Doerfert419a5592020-03-30 19:58:40 -05006117 Record.push_back(unsigned(C->getClauseKind()));
Kelvin Libe286f52018-09-15 13:54:15 +00006118 Visit(C);
6119 Record.AddSourceLocation(C->getBeginLoc());
6120 Record.AddSourceLocation(C->getEndLoc());
6121}
6122
6123void OMPClauseWriter::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
Johannes Doerferteb3e81f2019-11-04 22:00:49 -06006124 Record.push_back(uint64_t(C->getCaptureRegion()));
Kelvin Libe286f52018-09-15 13:54:15 +00006125 Record.AddStmt(C->getPreInitStmt());
6126}
6127
6128void OMPClauseWriter::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
6129 VisitOMPClauseWithPreInit(C);
6130 Record.AddStmt(C->getPostUpdateExpr());
6131}
6132
6133void OMPClauseWriter::VisitOMPIfClause(OMPIfClause *C) {
6134 VisitOMPClauseWithPreInit(C);
Johannes Doerferteb3e81f2019-11-04 22:00:49 -06006135 Record.push_back(uint64_t(C->getNameModifier()));
Kelvin Libe286f52018-09-15 13:54:15 +00006136 Record.AddSourceLocation(C->getNameModifierLoc());
6137 Record.AddSourceLocation(C->getColonLoc());
6138 Record.AddStmt(C->getCondition());
6139 Record.AddSourceLocation(C->getLParenLoc());
6140}
6141
6142void OMPClauseWriter::VisitOMPFinalClause(OMPFinalClause *C) {
Alexey Bataev3a842ec2019-10-15 19:37:05 +00006143 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +00006144 Record.AddStmt(C->getCondition());
6145 Record.AddSourceLocation(C->getLParenLoc());
6146}
6147
6148void OMPClauseWriter::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
6149 VisitOMPClauseWithPreInit(C);
6150 Record.AddStmt(C->getNumThreads());
6151 Record.AddSourceLocation(C->getLParenLoc());
6152}
6153
6154void OMPClauseWriter::VisitOMPSafelenClause(OMPSafelenClause *C) {
6155 Record.AddStmt(C->getSafelen());
6156 Record.AddSourceLocation(C->getLParenLoc());
6157}
6158
6159void OMPClauseWriter::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
6160 Record.AddStmt(C->getSimdlen());
6161 Record.AddSourceLocation(C->getLParenLoc());
6162}
6163
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00006164void OMPClauseWriter::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
6165 Record.AddStmt(C->getAllocator());
6166 Record.AddSourceLocation(C->getLParenLoc());
6167}
6168
Kelvin Libe286f52018-09-15 13:54:15 +00006169void OMPClauseWriter::VisitOMPCollapseClause(OMPCollapseClause *C) {
6170 Record.AddStmt(C->getNumForLoops());
6171 Record.AddSourceLocation(C->getLParenLoc());
6172}
6173
Alexey Bataev0f0564b2020-03-17 09:17:42 -04006174void OMPClauseWriter::VisitOMPDetachClause(OMPDetachClause *C) {
6175 Record.AddStmt(C->getEventHandler());
6176 Record.AddSourceLocation(C->getLParenLoc());
6177}
6178
Kelvin Libe286f52018-09-15 13:54:15 +00006179void OMPClauseWriter::VisitOMPDefaultClause(OMPDefaultClause *C) {
Atmn Patel577c9b02020-02-14 21:45:49 -06006180 Record.push_back(unsigned(C->getDefaultKind()));
Kelvin Libe286f52018-09-15 13:54:15 +00006181 Record.AddSourceLocation(C->getLParenLoc());
6182 Record.AddSourceLocation(C->getDefaultKindKwLoc());
6183}
6184
6185void OMPClauseWriter::VisitOMPProcBindClause(OMPProcBindClause *C) {
Johannes Doerfert6c5d1f402019-12-25 18:15:36 -06006186 Record.push_back(unsigned(C->getProcBindKind()));
Kelvin Libe286f52018-09-15 13:54:15 +00006187 Record.AddSourceLocation(C->getLParenLoc());
6188 Record.AddSourceLocation(C->getProcBindKindKwLoc());
6189}
6190
6191void OMPClauseWriter::VisitOMPScheduleClause(OMPScheduleClause *C) {
6192 VisitOMPClauseWithPreInit(C);
6193 Record.push_back(C->getScheduleKind());
6194 Record.push_back(C->getFirstScheduleModifier());
6195 Record.push_back(C->getSecondScheduleModifier());
6196 Record.AddStmt(C->getChunkSize());
6197 Record.AddSourceLocation(C->getLParenLoc());
6198 Record.AddSourceLocation(C->getFirstScheduleModifierLoc());
6199 Record.AddSourceLocation(C->getSecondScheduleModifierLoc());
6200 Record.AddSourceLocation(C->getScheduleKindLoc());
6201 Record.AddSourceLocation(C->getCommaLoc());
6202}
6203
6204void OMPClauseWriter::VisitOMPOrderedClause(OMPOrderedClause *C) {
6205 Record.push_back(C->getLoopNumIterations().size());
6206 Record.AddStmt(C->getNumForLoops());
6207 for (Expr *NumIter : C->getLoopNumIterations())
6208 Record.AddStmt(NumIter);
6209 for (unsigned I = 0, E = C->getLoopNumIterations().size(); I <E; ++I)
Mike Rice0ed46662018-09-20 17:19:41 +00006210 Record.AddStmt(C->getLoopCounter(I));
Kelvin Libe286f52018-09-15 13:54:15 +00006211 Record.AddSourceLocation(C->getLParenLoc());
6212}
6213
6214void OMPClauseWriter::VisitOMPNowaitClause(OMPNowaitClause *) {}
6215
6216void OMPClauseWriter::VisitOMPUntiedClause(OMPUntiedClause *) {}
6217
6218void OMPClauseWriter::VisitOMPMergeableClause(OMPMergeableClause *) {}
6219
6220void OMPClauseWriter::VisitOMPReadClause(OMPReadClause *) {}
6221
6222void OMPClauseWriter::VisitOMPWriteClause(OMPWriteClause *) {}
6223
Alexey Bataev82f7c202020-03-03 13:22:35 -05006224void OMPClauseWriter::VisitOMPUpdateClause(OMPUpdateClause *C) {
6225 Record.push_back(C->isExtended() ? 1 : 0);
6226 if (C->isExtended()) {
6227 Record.AddSourceLocation(C->getLParenLoc());
6228 Record.AddSourceLocation(C->getArgumentLoc());
6229 Record.writeEnum(C->getDependencyKind());
6230 }
6231}
Kelvin Libe286f52018-09-15 13:54:15 +00006232
6233void OMPClauseWriter::VisitOMPCaptureClause(OMPCaptureClause *) {}
6234
6235void OMPClauseWriter::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
6236
Alexey Bataevea9166b2020-02-06 16:30:23 -05006237void OMPClauseWriter::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
6238
Alexey Bataev04a830f2020-02-10 14:30:39 -05006239void OMPClauseWriter::VisitOMPAcquireClause(OMPAcquireClause *) {}
6240
Alexey Bataev95598342020-02-10 15:49:05 -05006241void OMPClauseWriter::VisitOMPReleaseClause(OMPReleaseClause *) {}
6242
Alexey Bataev9a8defc2020-02-11 11:10:43 -05006243void OMPClauseWriter::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
6244
Kelvin Libe286f52018-09-15 13:54:15 +00006245void OMPClauseWriter::VisitOMPThreadsClause(OMPThreadsClause *) {}
6246
6247void OMPClauseWriter::VisitOMPSIMDClause(OMPSIMDClause *) {}
6248
6249void OMPClauseWriter::VisitOMPNogroupClause(OMPNogroupClause *) {}
6250
Alexey Bataev375437a2020-03-02 14:21:20 -05006251void OMPClauseWriter::VisitOMPDestroyClause(OMPDestroyClause *) {}
6252
Kelvin Libe286f52018-09-15 13:54:15 +00006253void OMPClauseWriter::VisitOMPPrivateClause(OMPPrivateClause *C) {
6254 Record.push_back(C->varlist_size());
6255 Record.AddSourceLocation(C->getLParenLoc());
6256 for (auto *VE : C->varlists()) {
6257 Record.AddStmt(VE);
6258 }
6259 for (auto *VE : C->private_copies()) {
6260 Record.AddStmt(VE);
6261 }
6262}
6263
6264void OMPClauseWriter::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
6265 Record.push_back(C->varlist_size());
6266 VisitOMPClauseWithPreInit(C);
6267 Record.AddSourceLocation(C->getLParenLoc());
6268 for (auto *VE : C->varlists()) {
6269 Record.AddStmt(VE);
6270 }
6271 for (auto *VE : C->private_copies()) {
6272 Record.AddStmt(VE);
6273 }
6274 for (auto *VE : C->inits()) {
6275 Record.AddStmt(VE);
6276 }
6277}
6278
6279void OMPClauseWriter::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
6280 Record.push_back(C->varlist_size());
6281 VisitOMPClauseWithPostUpdate(C);
6282 Record.AddSourceLocation(C->getLParenLoc());
Alexey Bataev93dc40d2019-12-20 11:04:57 -05006283 Record.writeEnum(C->getKind());
6284 Record.AddSourceLocation(C->getKindLoc());
6285 Record.AddSourceLocation(C->getColonLoc());
Kelvin Libe286f52018-09-15 13:54:15 +00006286 for (auto *VE : C->varlists())
6287 Record.AddStmt(VE);
6288 for (auto *E : C->private_copies())
6289 Record.AddStmt(E);
6290 for (auto *E : C->source_exprs())
6291 Record.AddStmt(E);
6292 for (auto *E : C->destination_exprs())
6293 Record.AddStmt(E);
6294 for (auto *E : C->assignment_ops())
6295 Record.AddStmt(E);
6296}
6297
6298void OMPClauseWriter::VisitOMPSharedClause(OMPSharedClause *C) {
6299 Record.push_back(C->varlist_size());
6300 Record.AddSourceLocation(C->getLParenLoc());
6301 for (auto *VE : C->varlists())
6302 Record.AddStmt(VE);
6303}
6304
6305void OMPClauseWriter::VisitOMPReductionClause(OMPReductionClause *C) {
6306 Record.push_back(C->varlist_size());
6307 VisitOMPClauseWithPostUpdate(C);
6308 Record.AddSourceLocation(C->getLParenLoc());
Alexey Bataev1236eb62020-03-23 17:30:38 -04006309 Record.AddSourceLocation(C->getModifierLoc());
Kelvin Libe286f52018-09-15 13:54:15 +00006310 Record.AddSourceLocation(C->getColonLoc());
Alexey Bataev1236eb62020-03-23 17:30:38 -04006311 Record.writeEnum(C->getModifier());
Kelvin Libe286f52018-09-15 13:54:15 +00006312 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
6313 Record.AddDeclarationNameInfo(C->getNameInfo());
6314 for (auto *VE : C->varlists())
6315 Record.AddStmt(VE);
6316 for (auto *VE : C->privates())
6317 Record.AddStmt(VE);
6318 for (auto *E : C->lhs_exprs())
6319 Record.AddStmt(E);
6320 for (auto *E : C->rhs_exprs())
6321 Record.AddStmt(E);
6322 for (auto *E : C->reduction_ops())
6323 Record.AddStmt(E);
6324}
6325
6326void OMPClauseWriter::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
6327 Record.push_back(C->varlist_size());
6328 VisitOMPClauseWithPostUpdate(C);
6329 Record.AddSourceLocation(C->getLParenLoc());
6330 Record.AddSourceLocation(C->getColonLoc());
6331 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
6332 Record.AddDeclarationNameInfo(C->getNameInfo());
6333 for (auto *VE : C->varlists())
6334 Record.AddStmt(VE);
6335 for (auto *VE : C->privates())
6336 Record.AddStmt(VE);
6337 for (auto *E : C->lhs_exprs())
6338 Record.AddStmt(E);
6339 for (auto *E : C->rhs_exprs())
6340 Record.AddStmt(E);
6341 for (auto *E : C->reduction_ops())
6342 Record.AddStmt(E);
6343}
6344
6345void OMPClauseWriter::VisitOMPInReductionClause(OMPInReductionClause *C) {
6346 Record.push_back(C->varlist_size());
6347 VisitOMPClauseWithPostUpdate(C);
6348 Record.AddSourceLocation(C->getLParenLoc());
6349 Record.AddSourceLocation(C->getColonLoc());
6350 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
6351 Record.AddDeclarationNameInfo(C->getNameInfo());
6352 for (auto *VE : C->varlists())
6353 Record.AddStmt(VE);
6354 for (auto *VE : C->privates())
6355 Record.AddStmt(VE);
6356 for (auto *E : C->lhs_exprs())
6357 Record.AddStmt(E);
6358 for (auto *E : C->rhs_exprs())
6359 Record.AddStmt(E);
6360 for (auto *E : C->reduction_ops())
6361 Record.AddStmt(E);
6362 for (auto *E : C->taskgroup_descriptors())
6363 Record.AddStmt(E);
6364}
6365
6366void OMPClauseWriter::VisitOMPLinearClause(OMPLinearClause *C) {
6367 Record.push_back(C->varlist_size());
6368 VisitOMPClauseWithPostUpdate(C);
6369 Record.AddSourceLocation(C->getLParenLoc());
6370 Record.AddSourceLocation(C->getColonLoc());
6371 Record.push_back(C->getModifier());
6372 Record.AddSourceLocation(C->getModifierLoc());
6373 for (auto *VE : C->varlists()) {
6374 Record.AddStmt(VE);
6375 }
6376 for (auto *VE : C->privates()) {
6377 Record.AddStmt(VE);
6378 }
6379 for (auto *VE : C->inits()) {
6380 Record.AddStmt(VE);
6381 }
6382 for (auto *VE : C->updates()) {
6383 Record.AddStmt(VE);
6384 }
6385 for (auto *VE : C->finals()) {
6386 Record.AddStmt(VE);
6387 }
6388 Record.AddStmt(C->getStep());
6389 Record.AddStmt(C->getCalcStep());
Alexey Bataev195ae902019-08-08 13:42:45 +00006390 for (auto *VE : C->used_expressions())
6391 Record.AddStmt(VE);
Kelvin Libe286f52018-09-15 13:54:15 +00006392}
6393
6394void OMPClauseWriter::VisitOMPAlignedClause(OMPAlignedClause *C) {
6395 Record.push_back(C->varlist_size());
6396 Record.AddSourceLocation(C->getLParenLoc());
6397 Record.AddSourceLocation(C->getColonLoc());
6398 for (auto *VE : C->varlists())
6399 Record.AddStmt(VE);
6400 Record.AddStmt(C->getAlignment());
6401}
6402
6403void OMPClauseWriter::VisitOMPCopyinClause(OMPCopyinClause *C) {
6404 Record.push_back(C->varlist_size());
6405 Record.AddSourceLocation(C->getLParenLoc());
6406 for (auto *VE : C->varlists())
6407 Record.AddStmt(VE);
6408 for (auto *E : C->source_exprs())
6409 Record.AddStmt(E);
6410 for (auto *E : C->destination_exprs())
6411 Record.AddStmt(E);
6412 for (auto *E : C->assignment_ops())
6413 Record.AddStmt(E);
6414}
6415
6416void OMPClauseWriter::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
6417 Record.push_back(C->varlist_size());
6418 Record.AddSourceLocation(C->getLParenLoc());
6419 for (auto *VE : C->varlists())
6420 Record.AddStmt(VE);
6421 for (auto *E : C->source_exprs())
6422 Record.AddStmt(E);
6423 for (auto *E : C->destination_exprs())
6424 Record.AddStmt(E);
6425 for (auto *E : C->assignment_ops())
6426 Record.AddStmt(E);
6427}
6428
6429void OMPClauseWriter::VisitOMPFlushClause(OMPFlushClause *C) {
6430 Record.push_back(C->varlist_size());
6431 Record.AddSourceLocation(C->getLParenLoc());
6432 for (auto *VE : C->varlists())
6433 Record.AddStmt(VE);
6434}
6435
Alexey Bataevc112e942020-02-28 09:52:15 -05006436void OMPClauseWriter::VisitOMPDepobjClause(OMPDepobjClause *C) {
6437 Record.AddStmt(C->getDepobj());
6438 Record.AddSourceLocation(C->getLParenLoc());
6439}
6440
Kelvin Libe286f52018-09-15 13:54:15 +00006441void OMPClauseWriter::VisitOMPDependClause(OMPDependClause *C) {
6442 Record.push_back(C->varlist_size());
6443 Record.push_back(C->getNumLoops());
6444 Record.AddSourceLocation(C->getLParenLoc());
Alexey Bataev13a15042020-04-01 15:06:38 -04006445 Record.AddStmt(C->getModifier());
Kelvin Libe286f52018-09-15 13:54:15 +00006446 Record.push_back(C->getDependencyKind());
6447 Record.AddSourceLocation(C->getDependencyLoc());
6448 Record.AddSourceLocation(C->getColonLoc());
6449 for (auto *VE : C->varlists())
6450 Record.AddStmt(VE);
6451 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
6452 Record.AddStmt(C->getLoopData(I));
6453}
6454
6455void OMPClauseWriter::VisitOMPDeviceClause(OMPDeviceClause *C) {
6456 VisitOMPClauseWithPreInit(C);
Alexey Bataev2f8894a2020-03-18 15:01:15 -04006457 Record.writeEnum(C->getModifier());
Kelvin Libe286f52018-09-15 13:54:15 +00006458 Record.AddStmt(C->getDevice());
Alexey Bataev2f8894a2020-03-18 15:01:15 -04006459 Record.AddSourceLocation(C->getModifierLoc());
Kelvin Libe286f52018-09-15 13:54:15 +00006460 Record.AddSourceLocation(C->getLParenLoc());
6461}
6462
6463void OMPClauseWriter::VisitOMPMapClause(OMPMapClause *C) {
6464 Record.push_back(C->varlist_size());
6465 Record.push_back(C->getUniqueDeclarationsNum());
6466 Record.push_back(C->getTotalComponentListNum());
6467 Record.push_back(C->getTotalComponentsNum());
6468 Record.AddSourceLocation(C->getLParenLoc());
Reid Klecknerba1ffd22020-04-03 12:35:30 -07006469 for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
Kelvin Lief579432018-12-18 22:18:41 +00006470 Record.push_back(C->getMapTypeModifier(I));
6471 Record.AddSourceLocation(C->getMapTypeModifierLoc(I));
6472 }
Michael Kruse4304e9d2019-02-19 16:38:20 +00006473 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
6474 Record.AddDeclarationNameInfo(C->getMapperIdInfo());
Kelvin Libe286f52018-09-15 13:54:15 +00006475 Record.push_back(C->getMapType());
6476 Record.AddSourceLocation(C->getMapLoc());
6477 Record.AddSourceLocation(C->getColonLoc());
6478 for (auto *E : C->varlists())
6479 Record.AddStmt(E);
Michael Kruse4304e9d2019-02-19 16:38:20 +00006480 for (auto *E : C->mapperlists())
6481 Record.AddStmt(E);
Kelvin Libe286f52018-09-15 13:54:15 +00006482 for (auto *D : C->all_decls())
6483 Record.AddDeclRef(D);
6484 for (auto N : C->all_num_lists())
6485 Record.push_back(N);
6486 for (auto N : C->all_lists_sizes())
6487 Record.push_back(N);
6488 for (auto &M : C->all_components()) {
6489 Record.AddStmt(M.getAssociatedExpression());
6490 Record.AddDeclRef(M.getAssociatedDeclaration());
6491 }
6492}
6493
Alexey Bataeve04483e2019-03-27 14:14:31 +00006494void OMPClauseWriter::VisitOMPAllocateClause(OMPAllocateClause *C) {
6495 Record.push_back(C->varlist_size());
6496 Record.AddSourceLocation(C->getLParenLoc());
6497 Record.AddSourceLocation(C->getColonLoc());
6498 Record.AddStmt(C->getAllocator());
6499 for (auto *VE : C->varlists())
6500 Record.AddStmt(VE);
6501}
6502
Kelvin Libe286f52018-09-15 13:54:15 +00006503void OMPClauseWriter::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
6504 VisitOMPClauseWithPreInit(C);
6505 Record.AddStmt(C->getNumTeams());
6506 Record.AddSourceLocation(C->getLParenLoc());
6507}
6508
6509void OMPClauseWriter::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
6510 VisitOMPClauseWithPreInit(C);
6511 Record.AddStmt(C->getThreadLimit());
6512 Record.AddSourceLocation(C->getLParenLoc());
6513}
6514
6515void OMPClauseWriter::VisitOMPPriorityClause(OMPPriorityClause *C) {
Alexey Bataev31ba4762019-10-16 18:09:37 +00006516 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +00006517 Record.AddStmt(C->getPriority());
6518 Record.AddSourceLocation(C->getLParenLoc());
6519}
6520
6521void OMPClauseWriter::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
Alexey Bataevb9c55e22019-10-14 19:29:52 +00006522 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +00006523 Record.AddStmt(C->getGrainsize());
6524 Record.AddSourceLocation(C->getLParenLoc());
6525}
6526
6527void OMPClauseWriter::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
Alexey Bataevd88c7de2019-10-14 20:44:34 +00006528 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +00006529 Record.AddStmt(C->getNumTasks());
6530 Record.AddSourceLocation(C->getLParenLoc());
6531}
6532
6533void OMPClauseWriter::VisitOMPHintClause(OMPHintClause *C) {
6534 Record.AddStmt(C->getHint());
6535 Record.AddSourceLocation(C->getLParenLoc());
6536}
6537
6538void OMPClauseWriter::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
6539 VisitOMPClauseWithPreInit(C);
6540 Record.push_back(C->getDistScheduleKind());
6541 Record.AddStmt(C->getChunkSize());
6542 Record.AddSourceLocation(C->getLParenLoc());
6543 Record.AddSourceLocation(C->getDistScheduleKindLoc());
6544 Record.AddSourceLocation(C->getCommaLoc());
6545}
6546
6547void OMPClauseWriter::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
6548 Record.push_back(C->getDefaultmapKind());
6549 Record.push_back(C->getDefaultmapModifier());
6550 Record.AddSourceLocation(C->getLParenLoc());
6551 Record.AddSourceLocation(C->getDefaultmapModifierLoc());
6552 Record.AddSourceLocation(C->getDefaultmapKindLoc());
6553}
6554
6555void OMPClauseWriter::VisitOMPToClause(OMPToClause *C) {
6556 Record.push_back(C->varlist_size());
6557 Record.push_back(C->getUniqueDeclarationsNum());
6558 Record.push_back(C->getTotalComponentListNum());
6559 Record.push_back(C->getTotalComponentsNum());
6560 Record.AddSourceLocation(C->getLParenLoc());
Michael Kruse01f670d2019-02-22 22:29:42 +00006561 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
6562 Record.AddDeclarationNameInfo(C->getMapperIdInfo());
Kelvin Libe286f52018-09-15 13:54:15 +00006563 for (auto *E : C->varlists())
6564 Record.AddStmt(E);
Michael Kruse01f670d2019-02-22 22:29:42 +00006565 for (auto *E : C->mapperlists())
6566 Record.AddStmt(E);
Kelvin Libe286f52018-09-15 13:54:15 +00006567 for (auto *D : C->all_decls())
6568 Record.AddDeclRef(D);
6569 for (auto N : C->all_num_lists())
6570 Record.push_back(N);
6571 for (auto N : C->all_lists_sizes())
6572 Record.push_back(N);
6573 for (auto &M : C->all_components()) {
6574 Record.AddStmt(M.getAssociatedExpression());
6575 Record.AddDeclRef(M.getAssociatedDeclaration());
6576 }
6577}
6578
6579void OMPClauseWriter::VisitOMPFromClause(OMPFromClause *C) {
6580 Record.push_back(C->varlist_size());
6581 Record.push_back(C->getUniqueDeclarationsNum());
6582 Record.push_back(C->getTotalComponentListNum());
6583 Record.push_back(C->getTotalComponentsNum());
6584 Record.AddSourceLocation(C->getLParenLoc());
Michael Kruse0336c752019-02-25 20:34:15 +00006585 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
6586 Record.AddDeclarationNameInfo(C->getMapperIdInfo());
Kelvin Libe286f52018-09-15 13:54:15 +00006587 for (auto *E : C->varlists())
6588 Record.AddStmt(E);
Michael Kruse0336c752019-02-25 20:34:15 +00006589 for (auto *E : C->mapperlists())
6590 Record.AddStmt(E);
Kelvin Libe286f52018-09-15 13:54:15 +00006591 for (auto *D : C->all_decls())
6592 Record.AddDeclRef(D);
6593 for (auto N : C->all_num_lists())
6594 Record.push_back(N);
6595 for (auto N : C->all_lists_sizes())
6596 Record.push_back(N);
6597 for (auto &M : C->all_components()) {
6598 Record.AddStmt(M.getAssociatedExpression());
6599 Record.AddDeclRef(M.getAssociatedDeclaration());
6600 }
6601}
6602
6603void OMPClauseWriter::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
6604 Record.push_back(C->varlist_size());
6605 Record.push_back(C->getUniqueDeclarationsNum());
6606 Record.push_back(C->getTotalComponentListNum());
6607 Record.push_back(C->getTotalComponentsNum());
6608 Record.AddSourceLocation(C->getLParenLoc());
6609 for (auto *E : C->varlists())
6610 Record.AddStmt(E);
6611 for (auto *VE : C->private_copies())
6612 Record.AddStmt(VE);
6613 for (auto *VE : C->inits())
6614 Record.AddStmt(VE);
6615 for (auto *D : C->all_decls())
6616 Record.AddDeclRef(D);
6617 for (auto N : C->all_num_lists())
6618 Record.push_back(N);
6619 for (auto N : C->all_lists_sizes())
6620 Record.push_back(N);
6621 for (auto &M : C->all_components()) {
6622 Record.AddStmt(M.getAssociatedExpression());
6623 Record.AddDeclRef(M.getAssociatedDeclaration());
6624 }
6625}
6626
6627void OMPClauseWriter::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
6628 Record.push_back(C->varlist_size());
6629 Record.push_back(C->getUniqueDeclarationsNum());
6630 Record.push_back(C->getTotalComponentListNum());
6631 Record.push_back(C->getTotalComponentsNum());
6632 Record.AddSourceLocation(C->getLParenLoc());
6633 for (auto *E : C->varlists())
6634 Record.AddStmt(E);
6635 for (auto *D : C->all_decls())
6636 Record.AddDeclRef(D);
6637 for (auto N : C->all_num_lists())
6638 Record.push_back(N);
6639 for (auto N : C->all_lists_sizes())
6640 Record.push_back(N);
6641 for (auto &M : C->all_components()) {
6642 Record.AddStmt(M.getAssociatedExpression());
6643 Record.AddDeclRef(M.getAssociatedDeclaration());
6644 }
6645}
Kelvin Li1408f912018-09-26 04:28:39 +00006646
6647void OMPClauseWriter::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
Patrick Lyster4a370b92018-10-01 13:47:43 +00006648
6649void OMPClauseWriter::VisitOMPUnifiedSharedMemoryClause(
6650 OMPUnifiedSharedMemoryClause *) {}
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00006651
6652void OMPClauseWriter::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
Patrick Lyster3fe9e392018-10-11 14:41:10 +00006653
6654void
6655OMPClauseWriter::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
6656}
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00006657
6658void OMPClauseWriter::VisitOMPAtomicDefaultMemOrderClause(
6659 OMPAtomicDefaultMemOrderClause *C) {
6660 Record.push_back(C->getAtomicDefaultMemOrderKind());
6661 Record.AddSourceLocation(C->getLParenLoc());
6662 Record.AddSourceLocation(C->getAtomicDefaultMemOrderKindKwLoc());
6663}
Alexey Bataevb6e70842019-12-16 15:54:17 -05006664
6665void OMPClauseWriter::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
6666 Record.push_back(C->varlist_size());
6667 Record.AddSourceLocation(C->getLParenLoc());
6668 for (auto *VE : C->varlists())
6669 Record.AddStmt(VE);
Alexey Bataev0860db92019-12-19 10:01:10 -05006670 for (auto *E : C->private_refs())
6671 Record.AddStmt(E);
Alexey Bataevb6e70842019-12-16 15:54:17 -05006672}
Alexey Bataevcb8e6912020-01-31 16:09:26 -05006673
Alexey Bataev06dea732020-03-20 09:41:22 -04006674void OMPClauseWriter::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
6675 Record.push_back(C->varlist_size());
6676 Record.AddSourceLocation(C->getLParenLoc());
6677 for (auto *VE : C->varlists())
6678 Record.AddStmt(VE);
6679}
6680
Alexey Bataev63828a32020-03-23 10:41:08 -04006681void OMPClauseWriter::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
6682 Record.push_back(C->varlist_size());
6683 Record.AddSourceLocation(C->getLParenLoc());
6684 for (auto *VE : C->varlists())
6685 Record.AddStmt(VE);
6686}
6687
Alexey Bataevcb8e6912020-01-31 16:09:26 -05006688void OMPClauseWriter::VisitOMPOrderClause(OMPOrderClause *C) {
6689 Record.writeEnum(C->getKind());
6690 Record.AddSourceLocation(C->getLParenLoc());
6691 Record.AddSourceLocation(C->getKindKwLoc());
6692}
6693
Alexey Bataevb5be1c52020-04-21 13:21:00 -04006694void OMPClauseWriter::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
6695 Record.push_back(C->getNumberOfAllocators());
6696 Record.AddSourceLocation(C->getLParenLoc());
6697 for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) {
6698 OMPUsesAllocatorsClause::Data Data = C->getAllocatorData(I);
6699 Record.AddStmt(Data.Allocator);
6700 Record.AddStmt(Data.AllocatorTraits);
6701 Record.AddSourceLocation(Data.LParenLoc);
6702 Record.AddSourceLocation(Data.RParenLoc);
6703 }
6704}
6705
Johannes Doerfert55eca282020-03-13 23:42:05 -05006706void ASTRecordWriter::writeOMPTraitInfo(const OMPTraitInfo *TI) {
6707 writeUInt32(TI->Sets.size());
6708 for (const auto &Set : TI->Sets) {
Johannes Doerfert1228d422019-12-19 20:42:12 -06006709 writeEnum(Set.Kind);
6710 writeUInt32(Set.Selectors.size());
6711 for (const auto &Selector : Set.Selectors) {
6712 writeEnum(Selector.Kind);
6713 writeBool(Selector.ScoreOrCondition);
6714 if (Selector.ScoreOrCondition)
6715 writeExprRef(Selector.ScoreOrCondition);
6716 writeUInt32(Selector.Properties.size());
6717 for (const auto &Property : Selector.Properties)
6718 writeEnum(Property.Kind);
6719 }
6720 }
6721}