1 //===- ASTWriter.cpp - AST File Writer ------------------------------------===//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file defines the ASTWriter class, which writes AST files.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "ASTCommon.h"
14 #include "ASTReaderInternals.h"
15 #include "MultiOnDiskHashTable.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTUnresolvedSet.h"
18 #include "clang/AST/AbstractTypeWriter.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclBase.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclContextInternals.h"
24 #include "clang/AST/DeclFriend.h"
25 #include "clang/AST/DeclObjC.h"
26 #include "clang/AST/DeclTemplate.h"
27 #include "clang/AST/DeclarationName.h"
28 #include "clang/AST/Expr.h"
29 #include "clang/AST/ExprCXX.h"
30 #include "clang/AST/LambdaCapture.h"
31 #include "clang/AST/NestedNameSpecifier.h"
32 #include "clang/AST/OpenMPClause.h"
33 #include "clang/AST/RawCommentList.h"
34 #include "clang/AST/TemplateName.h"
35 #include "clang/AST/Type.h"
36 #include "clang/AST/TypeLocVisitor.h"
37 #include "clang/Basic/Diagnostic.h"
38 #include "clang/Basic/DiagnosticOptions.h"
39 #include "clang/Basic/FileManager.h"
40 #include "clang/Basic/FileSystemOptions.h"
41 #include "clang/Basic/IdentifierTable.h"
42 #include "clang/Basic/LLVM.h"
43 #include "clang/Basic/Lambda.h"
44 #include "clang/Basic/LangOptions.h"
45 #include "clang/Basic/Module.h"
46 #include "clang/Basic/ObjCRuntime.h"
47 #include "clang/Basic/OpenCLOptions.h"
48 #include "clang/Basic/SourceLocation.h"
49 #include "clang/Basic/SourceManager.h"
50 #include "clang/Basic/SourceManagerInternals.h"
51 #include "clang/Basic/Specifiers.h"
52 #include "clang/Basic/TargetInfo.h"
53 #include "clang/Basic/TargetOptions.h"
54 #include "clang/Basic/Version.h"
55 #include "clang/Lex/HeaderSearch.h"
56 #include "clang/Lex/HeaderSearchOptions.h"
57 #include "clang/Lex/MacroInfo.h"
58 #include "clang/Lex/ModuleMap.h"
59 #include "clang/Lex/PreprocessingRecord.h"
60 #include "clang/Lex/Preprocessor.h"
61 #include "clang/Lex/PreprocessorOptions.h"
62 #include "clang/Lex/Token.h"
63 #include "clang/Sema/IdentifierResolver.h"
64 #include "clang/Sema/ObjCMethodList.h"
65 #include "clang/Sema/Sema.h"
66 #include "clang/Sema/Weak.h"
67 #include "clang/Serialization/ASTBitCodes.h"
68 #include "clang/Serialization/ASTReader.h"
69 #include "clang/Serialization/ASTRecordWriter.h"
70 #include "clang/Serialization/InMemoryModuleCache.h"
71 #include "clang/Serialization/ModuleFile.h"
72 #include "clang/Serialization/ModuleFileExtension.h"
73 #include "clang/Serialization/SerializationDiagnostic.h"
74 #include "llvm/ADT/APFloat.h"
75 #include "llvm/ADT/APInt.h"
76 #include "llvm/ADT/APSInt.h"
77 #include "llvm/ADT/ArrayRef.h"
78 #include "llvm/ADT/DenseMap.h"
79 #include "llvm/ADT/Hashing.h"
80 #include "llvm/ADT/Optional.h"
81 #include "llvm/ADT/PointerIntPair.h"
82 #include "llvm/ADT/STLExtras.h"
83 #include "llvm/ADT/ScopeExit.h"
84 #include "llvm/ADT/SmallPtrSet.h"
85 #include "llvm/ADT/SmallString.h"
86 #include "llvm/ADT/SmallVector.h"
87 #include "llvm/ADT/StringMap.h"
88 #include "llvm/ADT/StringRef.h"
89 #include "llvm/Bitstream/BitCodes.h"
90 #include "llvm/Bitstream/BitstreamWriter.h"
91 #include "llvm/Support/Casting.h"
92 #include "llvm/Support/Compression.h"
93 #include "llvm/Support/DJB.h"
94 #include "llvm/Support/Endian.h"
95 #include "llvm/Support/EndianStream.h"
96 #include "llvm/Support/Error.h"
97 #include "llvm/Support/ErrorHandling.h"
98 #include "llvm/Support/LEB128.h"
99 #include "llvm/Support/MemoryBuffer.h"
100 #include "llvm/Support/OnDiskHashTable.h"
101 #include "llvm/Support/Path.h"
102 #include "llvm/Support/SHA1.h"
103 #include "llvm/Support/VersionTuple.h"
104 #include "llvm/Support/raw_ostream.h"
105 #include <algorithm>
106 #include <cassert>
107 #include <cstdint>
108 #include <cstdlib>
109 #include <cstring>
110 #include <ctime>
111 #include <deque>
112 #include <limits>
113 #include <memory>
114 #include <queue>
115 #include <tuple>
116 #include <utility>
117 #include <vector>
118 
119 using namespace clang;
120 using namespace clang::serialization;
121 
122 template <typename T, typename Allocator>
bytes(const std::vector<T,Allocator> & v)123 static StringRef bytes(const std::vector<T, Allocator> &v) {
124   if (v.empty()) return StringRef();
125   return StringRef(reinterpret_cast<const char*>(&v[0]),
126                          sizeof(T) * v.size());
127 }
128 
129 template <typename T>
bytes(const SmallVectorImpl<T> & v)130 static StringRef bytes(const SmallVectorImpl<T> &v) {
131   return StringRef(reinterpret_cast<const char*>(v.data()),
132                          sizeof(T) * v.size());
133 }
134 
bytes(const std::vector<bool> & V)135 static std::string bytes(const std::vector<bool> &V) {
136   std::string Str;
137   Str.reserve(V.size() / 8);
138   for (unsigned I = 0, E = V.size(); I < E;) {
139     char Byte = 0;
140     for (unsigned Bit = 0; Bit < 8 && I < E; ++Bit, ++I)
141       Byte |= V[I] << Bit;
142     Str += Byte;
143   }
144   return Str;
145 }
146 
147 //===----------------------------------------------------------------------===//
148 // Type serialization
149 //===----------------------------------------------------------------------===//
150 
getTypeCodeForTypeClass(Type::TypeClass id)151 static TypeCode getTypeCodeForTypeClass(Type::TypeClass id) {
152   switch (id) {
153 #define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
154   case Type::CLASS_ID: return TYPE_##CODE_ID;
155 #include "clang/Serialization/TypeBitCodes.def"
156   case Type::Builtin:
157     llvm_unreachable("shouldn't be serializing a builtin type this way");
158   }
159   llvm_unreachable("bad type kind");
160 }
161 
162 namespace {
163 
164 class ASTTypeWriter {
165   ASTWriter &Writer;
166   ASTWriter::RecordData Record;
167   ASTRecordWriter BasicWriter;
168 
169 public:
ASTTypeWriter(ASTWriter & Writer)170   ASTTypeWriter(ASTWriter &Writer)
171     : Writer(Writer), BasicWriter(Writer, Record) {}
172 
write(QualType T)173   uint64_t write(QualType T) {
174     if (T.hasLocalNonFastQualifiers()) {
175       Qualifiers Qs = T.getLocalQualifiers();
176       BasicWriter.writeQualType(T.getLocalUnqualifiedType());
177       BasicWriter.writeQualifiers(Qs);
178       return BasicWriter.Emit(TYPE_EXT_QUAL, Writer.getTypeExtQualAbbrev());
179     }
180 
181     const Type *typePtr = T.getTypePtr();
182     serialization::AbstractTypeWriter<ASTRecordWriter> atw(BasicWriter);
183     atw.write(typePtr);
184     return BasicWriter.Emit(getTypeCodeForTypeClass(typePtr->getTypeClass()),
185                             /*abbrev*/ 0);
186   }
187 };
188 
189 class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
190   ASTRecordWriter &Record;
191 
192 public:
TypeLocWriter(ASTRecordWriter & Record)193   TypeLocWriter(ASTRecordWriter &Record) : Record(Record) {}
194 
195 #define ABSTRACT_TYPELOC(CLASS, PARENT)
196 #define TYPELOC(CLASS, PARENT) \
197     void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
198 #include "clang/AST/TypeLocNodes.def"
199 
200   void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
201   void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
202 };
203 
204 } // namespace
205 
VisitQualifiedTypeLoc(QualifiedTypeLoc TL)206 void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
207   // nothing to do
208 }
209 
VisitBuiltinTypeLoc(BuiltinTypeLoc TL)210 void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
211   Record.AddSourceLocation(TL.getBuiltinLoc());
212   if (TL.needsExtraLocalData()) {
213     Record.push_back(TL.getWrittenTypeSpec());
214     Record.push_back(static_cast<uint64_t>(TL.getWrittenSignSpec()));
215     Record.push_back(static_cast<uint64_t>(TL.getWrittenWidthSpec()));
216     Record.push_back(TL.hasModeAttr());
217   }
218 }
219 
VisitComplexTypeLoc(ComplexTypeLoc TL)220 void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
221   Record.AddSourceLocation(TL.getNameLoc());
222 }
223 
VisitPointerTypeLoc(PointerTypeLoc TL)224 void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
225   Record.AddSourceLocation(TL.getStarLoc());
226 }
227 
VisitDecayedTypeLoc(DecayedTypeLoc TL)228 void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
229   // nothing to do
230 }
231 
VisitAdjustedTypeLoc(AdjustedTypeLoc TL)232 void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
233   // nothing to do
234 }
235 
VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL)236 void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
237   Record.AddSourceLocation(TL.getCaretLoc());
238 }
239 
VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL)240 void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
241   Record.AddSourceLocation(TL.getAmpLoc());
242 }
243 
VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL)244 void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
245   Record.AddSourceLocation(TL.getAmpAmpLoc());
246 }
247 
VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL)248 void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
249   Record.AddSourceLocation(TL.getStarLoc());
250   Record.AddTypeSourceInfo(TL.getClassTInfo());
251 }
252 
VisitArrayTypeLoc(ArrayTypeLoc TL)253 void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
254   Record.AddSourceLocation(TL.getLBracketLoc());
255   Record.AddSourceLocation(TL.getRBracketLoc());
256   Record.push_back(TL.getSizeExpr() ? 1 : 0);
257   if (TL.getSizeExpr())
258     Record.AddStmt(TL.getSizeExpr());
259 }
260 
VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL)261 void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
262   VisitArrayTypeLoc(TL);
263 }
264 
VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL)265 void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
266   VisitArrayTypeLoc(TL);
267 }
268 
VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL)269 void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
270   VisitArrayTypeLoc(TL);
271 }
272 
VisitDependentSizedArrayTypeLoc(DependentSizedArrayTypeLoc TL)273 void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
274                                             DependentSizedArrayTypeLoc TL) {
275   VisitArrayTypeLoc(TL);
276 }
277 
VisitDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc TL)278 void TypeLocWriter::VisitDependentAddressSpaceTypeLoc(
279     DependentAddressSpaceTypeLoc TL) {
280   Record.AddSourceLocation(TL.getAttrNameLoc());
281   SourceRange range = TL.getAttrOperandParensRange();
282   Record.AddSourceLocation(range.getBegin());
283   Record.AddSourceLocation(range.getEnd());
284   Record.AddStmt(TL.getAttrExprOperand());
285 }
286 
VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL)287 void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
288                                         DependentSizedExtVectorTypeLoc TL) {
289   Record.AddSourceLocation(TL.getNameLoc());
290 }
291 
VisitVectorTypeLoc(VectorTypeLoc TL)292 void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
293   Record.AddSourceLocation(TL.getNameLoc());
294 }
295 
VisitDependentVectorTypeLoc(DependentVectorTypeLoc TL)296 void TypeLocWriter::VisitDependentVectorTypeLoc(
297     DependentVectorTypeLoc TL) {
298   Record.AddSourceLocation(TL.getNameLoc());
299 }
300 
VisitExtVectorTypeLoc(ExtVectorTypeLoc TL)301 void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
302   Record.AddSourceLocation(TL.getNameLoc());
303 }
304 
VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL)305 void TypeLocWriter::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
306   Record.AddSourceLocation(TL.getAttrNameLoc());
307   SourceRange range = TL.getAttrOperandParensRange();
308   Record.AddSourceLocation(range.getBegin());
309   Record.AddSourceLocation(range.getEnd());
310   Record.AddStmt(TL.getAttrRowOperand());
311   Record.AddStmt(TL.getAttrColumnOperand());
312 }
313 
VisitDependentSizedMatrixTypeLoc(DependentSizedMatrixTypeLoc TL)314 void TypeLocWriter::VisitDependentSizedMatrixTypeLoc(
315     DependentSizedMatrixTypeLoc TL) {
316   Record.AddSourceLocation(TL.getAttrNameLoc());
317   SourceRange range = TL.getAttrOperandParensRange();
318   Record.AddSourceLocation(range.getBegin());
319   Record.AddSourceLocation(range.getEnd());
320   Record.AddStmt(TL.getAttrRowOperand());
321   Record.AddStmt(TL.getAttrColumnOperand());
322 }
323 
VisitFunctionTypeLoc(FunctionTypeLoc TL)324 void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
325   Record.AddSourceLocation(TL.getLocalRangeBegin());
326   Record.AddSourceLocation(TL.getLParenLoc());
327   Record.AddSourceLocation(TL.getRParenLoc());
328   Record.AddSourceRange(TL.getExceptionSpecRange());
329   Record.AddSourceLocation(TL.getLocalRangeEnd());
330   for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
331     Record.AddDeclRef(TL.getParam(i));
332 }
333 
VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL)334 void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
335   VisitFunctionTypeLoc(TL);
336 }
337 
VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL)338 void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
339   VisitFunctionTypeLoc(TL);
340 }
341 
VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL)342 void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
343   Record.AddSourceLocation(TL.getNameLoc());
344 }
345 
VisitTypedefTypeLoc(TypedefTypeLoc TL)346 void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
347   Record.AddSourceLocation(TL.getNameLoc());
348 }
349 
VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL)350 void TypeLocWriter::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
351   if (TL.getNumProtocols()) {
352     Record.AddSourceLocation(TL.getProtocolLAngleLoc());
353     Record.AddSourceLocation(TL.getProtocolRAngleLoc());
354   }
355   for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
356     Record.AddSourceLocation(TL.getProtocolLoc(i));
357 }
358 
VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL)359 void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
360   Record.AddSourceLocation(TL.getTypeofLoc());
361   Record.AddSourceLocation(TL.getLParenLoc());
362   Record.AddSourceLocation(TL.getRParenLoc());
363 }
364 
VisitTypeOfTypeLoc(TypeOfTypeLoc TL)365 void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
366   Record.AddSourceLocation(TL.getTypeofLoc());
367   Record.AddSourceLocation(TL.getLParenLoc());
368   Record.AddSourceLocation(TL.getRParenLoc());
369   Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
370 }
371 
VisitDecltypeTypeLoc(DecltypeTypeLoc TL)372 void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
373   Record.AddSourceLocation(TL.getNameLoc());
374 }
375 
VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL)376 void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
377   Record.AddSourceLocation(TL.getKWLoc());
378   Record.AddSourceLocation(TL.getLParenLoc());
379   Record.AddSourceLocation(TL.getRParenLoc());
380   Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
381 }
382 
VisitAutoTypeLoc(AutoTypeLoc TL)383 void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
384   Record.AddSourceLocation(TL.getNameLoc());
385   Record.push_back(TL.isConstrained());
386   if (TL.isConstrained()) {
387     Record.AddNestedNameSpecifierLoc(TL.getNestedNameSpecifierLoc());
388     Record.AddSourceLocation(TL.getTemplateKWLoc());
389     Record.AddSourceLocation(TL.getConceptNameLoc());
390     Record.AddDeclRef(TL.getFoundDecl());
391     Record.AddSourceLocation(TL.getLAngleLoc());
392     Record.AddSourceLocation(TL.getRAngleLoc());
393     for (unsigned I = 0; I < TL.getNumArgs(); ++I)
394       Record.AddTemplateArgumentLocInfo(TL.getTypePtr()->getArg(I).getKind(),
395                                         TL.getArgLocInfo(I));
396   }
397 }
398 
VisitDeducedTemplateSpecializationTypeLoc(DeducedTemplateSpecializationTypeLoc TL)399 void TypeLocWriter::VisitDeducedTemplateSpecializationTypeLoc(
400     DeducedTemplateSpecializationTypeLoc TL) {
401   Record.AddSourceLocation(TL.getTemplateNameLoc());
402 }
403 
VisitRecordTypeLoc(RecordTypeLoc TL)404 void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
405   Record.AddSourceLocation(TL.getNameLoc());
406 }
407 
VisitEnumTypeLoc(EnumTypeLoc TL)408 void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
409   Record.AddSourceLocation(TL.getNameLoc());
410 }
411 
VisitAttributedTypeLoc(AttributedTypeLoc TL)412 void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
413   Record.AddAttr(TL.getAttr());
414 }
415 
VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL)416 void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
417   Record.AddSourceLocation(TL.getNameLoc());
418 }
419 
VisitSubstTemplateTypeParmTypeLoc(SubstTemplateTypeParmTypeLoc TL)420 void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
421                                             SubstTemplateTypeParmTypeLoc TL) {
422   Record.AddSourceLocation(TL.getNameLoc());
423 }
424 
VisitSubstTemplateTypeParmPackTypeLoc(SubstTemplateTypeParmPackTypeLoc TL)425 void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
426                                           SubstTemplateTypeParmPackTypeLoc TL) {
427   Record.AddSourceLocation(TL.getNameLoc());
428 }
429 
VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL)430 void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
431                                            TemplateSpecializationTypeLoc TL) {
432   Record.AddSourceLocation(TL.getTemplateKeywordLoc());
433   Record.AddSourceLocation(TL.getTemplateNameLoc());
434   Record.AddSourceLocation(TL.getLAngleLoc());
435   Record.AddSourceLocation(TL.getRAngleLoc());
436   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
437     Record.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
438                                       TL.getArgLoc(i).getLocInfo());
439 }
440 
VisitParenTypeLoc(ParenTypeLoc TL)441 void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
442   Record.AddSourceLocation(TL.getLParenLoc());
443   Record.AddSourceLocation(TL.getRParenLoc());
444 }
445 
VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL)446 void TypeLocWriter::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
447   Record.AddSourceLocation(TL.getExpansionLoc());
448 }
449 
VisitElaboratedTypeLoc(ElaboratedTypeLoc TL)450 void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
451   Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
452   Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
453 }
454 
VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL)455 void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
456   Record.AddSourceLocation(TL.getNameLoc());
457 }
458 
VisitDependentNameTypeLoc(DependentNameTypeLoc TL)459 void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
460   Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
461   Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
462   Record.AddSourceLocation(TL.getNameLoc());
463 }
464 
VisitDependentTemplateSpecializationTypeLoc(DependentTemplateSpecializationTypeLoc TL)465 void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
466        DependentTemplateSpecializationTypeLoc TL) {
467   Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
468   Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
469   Record.AddSourceLocation(TL.getTemplateKeywordLoc());
470   Record.AddSourceLocation(TL.getTemplateNameLoc());
471   Record.AddSourceLocation(TL.getLAngleLoc());
472   Record.AddSourceLocation(TL.getRAngleLoc());
473   for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
474     Record.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
475                                       TL.getArgLoc(I).getLocInfo());
476 }
477 
VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL)478 void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
479   Record.AddSourceLocation(TL.getEllipsisLoc());
480 }
481 
VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL)482 void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
483   Record.AddSourceLocation(TL.getNameLoc());
484 }
485 
VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL)486 void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
487   Record.push_back(TL.hasBaseTypeAsWritten());
488   Record.AddSourceLocation(TL.getTypeArgsLAngleLoc());
489   Record.AddSourceLocation(TL.getTypeArgsRAngleLoc());
490   for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
491     Record.AddTypeSourceInfo(TL.getTypeArgTInfo(i));
492   Record.AddSourceLocation(TL.getProtocolLAngleLoc());
493   Record.AddSourceLocation(TL.getProtocolRAngleLoc());
494   for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
495     Record.AddSourceLocation(TL.getProtocolLoc(i));
496 }
497 
VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL)498 void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
499   Record.AddSourceLocation(TL.getStarLoc());
500 }
501 
VisitAtomicTypeLoc(AtomicTypeLoc TL)502 void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
503   Record.AddSourceLocation(TL.getKWLoc());
504   Record.AddSourceLocation(TL.getLParenLoc());
505   Record.AddSourceLocation(TL.getRParenLoc());
506 }
507 
VisitPipeTypeLoc(PipeTypeLoc TL)508 void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
509   Record.AddSourceLocation(TL.getKWLoc());
510 }
511 
VisitExtIntTypeLoc(clang::ExtIntTypeLoc TL)512 void TypeLocWriter::VisitExtIntTypeLoc(clang::ExtIntTypeLoc TL) {
513   Record.AddSourceLocation(TL.getNameLoc());
514 }
VisitDependentExtIntTypeLoc(clang::DependentExtIntTypeLoc TL)515 void TypeLocWriter::VisitDependentExtIntTypeLoc(
516     clang::DependentExtIntTypeLoc TL) {
517   Record.AddSourceLocation(TL.getNameLoc());
518 }
519 
WriteTypeAbbrevs()520 void ASTWriter::WriteTypeAbbrevs() {
521   using namespace llvm;
522 
523   std::shared_ptr<BitCodeAbbrev> Abv;
524 
525   // Abbreviation for TYPE_EXT_QUAL
526   Abv = std::make_shared<BitCodeAbbrev>();
527   Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
528   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // Type
529   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3));   // Quals
530   TypeExtQualAbbrev = Stream.EmitAbbrev(std::move(Abv));
531 
532   // Abbreviation for TYPE_FUNCTION_PROTO
533   Abv = std::make_shared<BitCodeAbbrev>();
534   Abv->Add(BitCodeAbbrevOp(serialization::TYPE_FUNCTION_PROTO));
535   // FunctionType
536   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // ReturnType
537   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NoReturn
538   Abv->Add(BitCodeAbbrevOp(0));                         // HasRegParm
539   Abv->Add(BitCodeAbbrevOp(0));                         // RegParm
540   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // CC
541   Abv->Add(BitCodeAbbrevOp(0));                         // ProducesResult
542   Abv->Add(BitCodeAbbrevOp(0));                         // NoCallerSavedRegs
543   Abv->Add(BitCodeAbbrevOp(0));                         // NoCfCheck
544   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // CmseNSCall
545   // FunctionProtoType
546   Abv->Add(BitCodeAbbrevOp(0));                         // IsVariadic
547   Abv->Add(BitCodeAbbrevOp(0));                         // HasTrailingReturn
548   Abv->Add(BitCodeAbbrevOp(0));                         // TypeQuals
549   Abv->Add(BitCodeAbbrevOp(0));                         // RefQualifier
550   Abv->Add(BitCodeAbbrevOp(EST_None));                  // ExceptionSpec
551   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // NumParams
552   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
553   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));   // Params
554   TypeFunctionProtoAbbrev = Stream.EmitAbbrev(std::move(Abv));
555 }
556 
557 //===----------------------------------------------------------------------===//
558 // ASTWriter Implementation
559 //===----------------------------------------------------------------------===//
560 
EmitBlockID(unsigned ID,const char * Name,llvm::BitstreamWriter & Stream,ASTWriter::RecordDataImpl & Record)561 static void EmitBlockID(unsigned ID, const char *Name,
562                         llvm::BitstreamWriter &Stream,
563                         ASTWriter::RecordDataImpl &Record) {
564   Record.clear();
565   Record.push_back(ID);
566   Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
567 
568   // Emit the block name if present.
569   if (!Name || Name[0] == 0)
570     return;
571   Record.clear();
572   while (*Name)
573     Record.push_back(*Name++);
574   Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
575 }
576 
EmitRecordID(unsigned ID,const char * Name,llvm::BitstreamWriter & Stream,ASTWriter::RecordDataImpl & Record)577 static void EmitRecordID(unsigned ID, const char *Name,
578                          llvm::BitstreamWriter &Stream,
579                          ASTWriter::RecordDataImpl &Record) {
580   Record.clear();
581   Record.push_back(ID);
582   while (*Name)
583     Record.push_back(*Name++);
584   Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
585 }
586 
AddStmtsExprs(llvm::BitstreamWriter & Stream,ASTWriter::RecordDataImpl & Record)587 static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
588                           ASTWriter::RecordDataImpl &Record) {
589 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
590   RECORD(STMT_STOP);
591   RECORD(STMT_NULL_PTR);
592   RECORD(STMT_REF_PTR);
593   RECORD(STMT_NULL);
594   RECORD(STMT_COMPOUND);
595   RECORD(STMT_CASE);
596   RECORD(STMT_DEFAULT);
597   RECORD(STMT_LABEL);
598   RECORD(STMT_ATTRIBUTED);
599   RECORD(STMT_IF);
600   RECORD(STMT_SWITCH);
601   RECORD(STMT_WHILE);
602   RECORD(STMT_DO);
603   RECORD(STMT_FOR);
604   RECORD(STMT_GOTO);
605   RECORD(STMT_INDIRECT_GOTO);
606   RECORD(STMT_CONTINUE);
607   RECORD(STMT_BREAK);
608   RECORD(STMT_RETURN);
609   RECORD(STMT_DECL);
610   RECORD(STMT_GCCASM);
611   RECORD(STMT_MSASM);
612   RECORD(EXPR_PREDEFINED);
613   RECORD(EXPR_DECL_REF);
614   RECORD(EXPR_INTEGER_LITERAL);
615   RECORD(EXPR_FIXEDPOINT_LITERAL);
616   RECORD(EXPR_FLOATING_LITERAL);
617   RECORD(EXPR_IMAGINARY_LITERAL);
618   RECORD(EXPR_STRING_LITERAL);
619   RECORD(EXPR_CHARACTER_LITERAL);
620   RECORD(EXPR_PAREN);
621   RECORD(EXPR_PAREN_LIST);
622   RECORD(EXPR_UNARY_OPERATOR);
623   RECORD(EXPR_SIZEOF_ALIGN_OF);
624   RECORD(EXPR_ARRAY_SUBSCRIPT);
625   RECORD(EXPR_CALL);
626   RECORD(EXPR_MEMBER);
627   RECORD(EXPR_BINARY_OPERATOR);
628   RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
629   RECORD(EXPR_CONDITIONAL_OPERATOR);
630   RECORD(EXPR_IMPLICIT_CAST);
631   RECORD(EXPR_CSTYLE_CAST);
632   RECORD(EXPR_COMPOUND_LITERAL);
633   RECORD(EXPR_EXT_VECTOR_ELEMENT);
634   RECORD(EXPR_INIT_LIST);
635   RECORD(EXPR_DESIGNATED_INIT);
636   RECORD(EXPR_DESIGNATED_INIT_UPDATE);
637   RECORD(EXPR_IMPLICIT_VALUE_INIT);
638   RECORD(EXPR_NO_INIT);
639   RECORD(EXPR_VA_ARG);
640   RECORD(EXPR_ADDR_LABEL);
641   RECORD(EXPR_STMT);
642   RECORD(EXPR_CHOOSE);
643   RECORD(EXPR_GNU_NULL);
644   RECORD(EXPR_SHUFFLE_VECTOR);
645   RECORD(EXPR_BLOCK);
646   RECORD(EXPR_GENERIC_SELECTION);
647   RECORD(EXPR_OBJC_STRING_LITERAL);
648   RECORD(EXPR_OBJC_BOXED_EXPRESSION);
649   RECORD(EXPR_OBJC_ARRAY_LITERAL);
650   RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
651   RECORD(EXPR_OBJC_ENCODE);
652   RECORD(EXPR_OBJC_SELECTOR_EXPR);
653   RECORD(EXPR_OBJC_PROTOCOL_EXPR);
654   RECORD(EXPR_OBJC_IVAR_REF_EXPR);
655   RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
656   RECORD(EXPR_OBJC_KVC_REF_EXPR);
657   RECORD(EXPR_OBJC_MESSAGE_EXPR);
658   RECORD(STMT_OBJC_FOR_COLLECTION);
659   RECORD(STMT_OBJC_CATCH);
660   RECORD(STMT_OBJC_FINALLY);
661   RECORD(STMT_OBJC_AT_TRY);
662   RECORD(STMT_OBJC_AT_SYNCHRONIZED);
663   RECORD(STMT_OBJC_AT_THROW);
664   RECORD(EXPR_OBJC_BOOL_LITERAL);
665   RECORD(STMT_CXX_CATCH);
666   RECORD(STMT_CXX_TRY);
667   RECORD(STMT_CXX_FOR_RANGE);
668   RECORD(EXPR_CXX_OPERATOR_CALL);
669   RECORD(EXPR_CXX_MEMBER_CALL);
670   RECORD(EXPR_CXX_REWRITTEN_BINARY_OPERATOR);
671   RECORD(EXPR_CXX_CONSTRUCT);
672   RECORD(EXPR_CXX_TEMPORARY_OBJECT);
673   RECORD(EXPR_CXX_STATIC_CAST);
674   RECORD(EXPR_CXX_DYNAMIC_CAST);
675   RECORD(EXPR_CXX_REINTERPRET_CAST);
676   RECORD(EXPR_CXX_CONST_CAST);
677   RECORD(EXPR_CXX_ADDRSPACE_CAST);
678   RECORD(EXPR_CXX_FUNCTIONAL_CAST);
679   RECORD(EXPR_USER_DEFINED_LITERAL);
680   RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
681   RECORD(EXPR_CXX_BOOL_LITERAL);
682   RECORD(EXPR_CXX_NULL_PTR_LITERAL);
683   RECORD(EXPR_CXX_TYPEID_EXPR);
684   RECORD(EXPR_CXX_TYPEID_TYPE);
685   RECORD(EXPR_CXX_THIS);
686   RECORD(EXPR_CXX_THROW);
687   RECORD(EXPR_CXX_DEFAULT_ARG);
688   RECORD(EXPR_CXX_DEFAULT_INIT);
689   RECORD(EXPR_CXX_BIND_TEMPORARY);
690   RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
691   RECORD(EXPR_CXX_NEW);
692   RECORD(EXPR_CXX_DELETE);
693   RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
694   RECORD(EXPR_EXPR_WITH_CLEANUPS);
695   RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
696   RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
697   RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
698   RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
699   RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
700   RECORD(EXPR_CXX_EXPRESSION_TRAIT);
701   RECORD(EXPR_CXX_NOEXCEPT);
702   RECORD(EXPR_OPAQUE_VALUE);
703   RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR);
704   RECORD(EXPR_TYPE_TRAIT);
705   RECORD(EXPR_ARRAY_TYPE_TRAIT);
706   RECORD(EXPR_PACK_EXPANSION);
707   RECORD(EXPR_SIZEOF_PACK);
708   RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM);
709   RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
710   RECORD(EXPR_FUNCTION_PARM_PACK);
711   RECORD(EXPR_MATERIALIZE_TEMPORARY);
712   RECORD(EXPR_CUDA_KERNEL_CALL);
713   RECORD(EXPR_CXX_UUIDOF_EXPR);
714   RECORD(EXPR_CXX_UUIDOF_TYPE);
715   RECORD(EXPR_LAMBDA);
716 #undef RECORD
717 }
718 
WriteBlockInfoBlock()719 void ASTWriter::WriteBlockInfoBlock() {
720   RecordData Record;
721   Stream.EnterBlockInfoBlock();
722 
723 #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
724 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
725 
726   // Control Block.
727   BLOCK(CONTROL_BLOCK);
728   RECORD(METADATA);
729   RECORD(MODULE_NAME);
730   RECORD(MODULE_DIRECTORY);
731   RECORD(MODULE_MAP_FILE);
732   RECORD(IMPORTS);
733   RECORD(ORIGINAL_FILE);
734   RECORD(ORIGINAL_PCH_DIR);
735   RECORD(ORIGINAL_FILE_ID);
736   RECORD(INPUT_FILE_OFFSETS);
737 
738   BLOCK(OPTIONS_BLOCK);
739   RECORD(LANGUAGE_OPTIONS);
740   RECORD(TARGET_OPTIONS);
741   RECORD(FILE_SYSTEM_OPTIONS);
742   RECORD(HEADER_SEARCH_OPTIONS);
743   RECORD(PREPROCESSOR_OPTIONS);
744 
745   BLOCK(INPUT_FILES_BLOCK);
746   RECORD(INPUT_FILE);
747   RECORD(INPUT_FILE_HASH);
748 
749   // AST Top-Level Block.
750   BLOCK(AST_BLOCK);
751   RECORD(TYPE_OFFSET);
752   RECORD(DECL_OFFSET);
753   RECORD(IDENTIFIER_OFFSET);
754   RECORD(IDENTIFIER_TABLE);
755   RECORD(EAGERLY_DESERIALIZED_DECLS);
756   RECORD(MODULAR_CODEGEN_DECLS);
757   RECORD(SPECIAL_TYPES);
758   RECORD(STATISTICS);
759   RECORD(TENTATIVE_DEFINITIONS);
760   RECORD(SELECTOR_OFFSETS);
761   RECORD(METHOD_POOL);
762   RECORD(PP_COUNTER_VALUE);
763   RECORD(SOURCE_LOCATION_OFFSETS);
764   RECORD(SOURCE_LOCATION_PRELOADS);
765   RECORD(EXT_VECTOR_DECLS);
766   RECORD(UNUSED_FILESCOPED_DECLS);
767   RECORD(PPD_ENTITIES_OFFSETS);
768   RECORD(VTABLE_USES);
769   RECORD(PPD_SKIPPED_RANGES);
770   RECORD(REFERENCED_SELECTOR_POOL);
771   RECORD(TU_UPDATE_LEXICAL);
772   RECORD(SEMA_DECL_REFS);
773   RECORD(WEAK_UNDECLARED_IDENTIFIERS);
774   RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
775   RECORD(UPDATE_VISIBLE);
776   RECORD(DECL_UPDATE_OFFSETS);
777   RECORD(DECL_UPDATES);
778   RECORD(CUDA_SPECIAL_DECL_REFS);
779   RECORD(HEADER_SEARCH_TABLE);
780   RECORD(FP_PRAGMA_OPTIONS);
781   RECORD(OPENCL_EXTENSIONS);
782   RECORD(OPENCL_EXTENSION_TYPES);
783   RECORD(OPENCL_EXTENSION_DECLS);
784   RECORD(DELEGATING_CTORS);
785   RECORD(KNOWN_NAMESPACES);
786   RECORD(MODULE_OFFSET_MAP);
787   RECORD(SOURCE_MANAGER_LINE_TABLE);
788   RECORD(OBJC_CATEGORIES_MAP);
789   RECORD(FILE_SORTED_DECLS);
790   RECORD(IMPORTED_MODULES);
791   RECORD(OBJC_CATEGORIES);
792   RECORD(MACRO_OFFSET);
793   RECORD(INTERESTING_IDENTIFIERS);
794   RECORD(UNDEFINED_BUT_USED);
795   RECORD(LATE_PARSED_TEMPLATE);
796   RECORD(OPTIMIZE_PRAGMA_OPTIONS);
797   RECORD(MSSTRUCT_PRAGMA_OPTIONS);
798   RECORD(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS);
799   RECORD(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES);
800   RECORD(DELETE_EXPRS_TO_ANALYZE);
801   RECORD(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH);
802   RECORD(PP_CONDITIONAL_STACK);
803   RECORD(DECLS_TO_CHECK_FOR_DEFERRED_DIAGS);
804 
805   // SourceManager Block.
806   BLOCK(SOURCE_MANAGER_BLOCK);
807   RECORD(SM_SLOC_FILE_ENTRY);
808   RECORD(SM_SLOC_BUFFER_ENTRY);
809   RECORD(SM_SLOC_BUFFER_BLOB);
810   RECORD(SM_SLOC_BUFFER_BLOB_COMPRESSED);
811   RECORD(SM_SLOC_EXPANSION_ENTRY);
812 
813   // Preprocessor Block.
814   BLOCK(PREPROCESSOR_BLOCK);
815   RECORD(PP_MACRO_DIRECTIVE_HISTORY);
816   RECORD(PP_MACRO_FUNCTION_LIKE);
817   RECORD(PP_MACRO_OBJECT_LIKE);
818   RECORD(PP_MODULE_MACRO);
819   RECORD(PP_TOKEN);
820 
821   // Submodule Block.
822   BLOCK(SUBMODULE_BLOCK);
823   RECORD(SUBMODULE_METADATA);
824   RECORD(SUBMODULE_DEFINITION);
825   RECORD(SUBMODULE_UMBRELLA_HEADER);
826   RECORD(SUBMODULE_HEADER);
827   RECORD(SUBMODULE_TOPHEADER);
828   RECORD(SUBMODULE_UMBRELLA_DIR);
829   RECORD(SUBMODULE_IMPORTS);
830   RECORD(SUBMODULE_EXPORTS);
831   RECORD(SUBMODULE_REQUIRES);
832   RECORD(SUBMODULE_EXCLUDED_HEADER);
833   RECORD(SUBMODULE_LINK_LIBRARY);
834   RECORD(SUBMODULE_CONFIG_MACRO);
835   RECORD(SUBMODULE_CONFLICT);
836   RECORD(SUBMODULE_PRIVATE_HEADER);
837   RECORD(SUBMODULE_TEXTUAL_HEADER);
838   RECORD(SUBMODULE_PRIVATE_TEXTUAL_HEADER);
839   RECORD(SUBMODULE_INITIALIZERS);
840   RECORD(SUBMODULE_EXPORT_AS);
841 
842   // Comments Block.
843   BLOCK(COMMENTS_BLOCK);
844   RECORD(COMMENTS_RAW_COMMENT);
845 
846   // Decls and Types block.
847   BLOCK(DECLTYPES_BLOCK);
848   RECORD(TYPE_EXT_QUAL);
849   RECORD(TYPE_COMPLEX);
850   RECORD(TYPE_POINTER);
851   RECORD(TYPE_BLOCK_POINTER);
852   RECORD(TYPE_LVALUE_REFERENCE);
853   RECORD(TYPE_RVALUE_REFERENCE);
854   RECORD(TYPE_MEMBER_POINTER);
855   RECORD(TYPE_CONSTANT_ARRAY);
856   RECORD(TYPE_INCOMPLETE_ARRAY);
857   RECORD(TYPE_VARIABLE_ARRAY);
858   RECORD(TYPE_VECTOR);
859   RECORD(TYPE_EXT_VECTOR);
860   RECORD(TYPE_FUNCTION_NO_PROTO);
861   RECORD(TYPE_FUNCTION_PROTO);
862   RECORD(TYPE_TYPEDEF);
863   RECORD(TYPE_TYPEOF_EXPR);
864   RECORD(TYPE_TYPEOF);
865   RECORD(TYPE_RECORD);
866   RECORD(TYPE_ENUM);
867   RECORD(TYPE_OBJC_INTERFACE);
868   RECORD(TYPE_OBJC_OBJECT_POINTER);
869   RECORD(TYPE_DECLTYPE);
870   RECORD(TYPE_ELABORATED);
871   RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
872   RECORD(TYPE_UNRESOLVED_USING);
873   RECORD(TYPE_INJECTED_CLASS_NAME);
874   RECORD(TYPE_OBJC_OBJECT);
875   RECORD(TYPE_TEMPLATE_TYPE_PARM);
876   RECORD(TYPE_TEMPLATE_SPECIALIZATION);
877   RECORD(TYPE_DEPENDENT_NAME);
878   RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
879   RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
880   RECORD(TYPE_PAREN);
881   RECORD(TYPE_MACRO_QUALIFIED);
882   RECORD(TYPE_PACK_EXPANSION);
883   RECORD(TYPE_ATTRIBUTED);
884   RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
885   RECORD(TYPE_AUTO);
886   RECORD(TYPE_UNARY_TRANSFORM);
887   RECORD(TYPE_ATOMIC);
888   RECORD(TYPE_DECAYED);
889   RECORD(TYPE_ADJUSTED);
890   RECORD(TYPE_OBJC_TYPE_PARAM);
891   RECORD(LOCAL_REDECLARATIONS);
892   RECORD(DECL_TYPEDEF);
893   RECORD(DECL_TYPEALIAS);
894   RECORD(DECL_ENUM);
895   RECORD(DECL_RECORD);
896   RECORD(DECL_ENUM_CONSTANT);
897   RECORD(DECL_FUNCTION);
898   RECORD(DECL_OBJC_METHOD);
899   RECORD(DECL_OBJC_INTERFACE);
900   RECORD(DECL_OBJC_PROTOCOL);
901   RECORD(DECL_OBJC_IVAR);
902   RECORD(DECL_OBJC_AT_DEFS_FIELD);
903   RECORD(DECL_OBJC_CATEGORY);
904   RECORD(DECL_OBJC_CATEGORY_IMPL);
905   RECORD(DECL_OBJC_IMPLEMENTATION);
906   RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
907   RECORD(DECL_OBJC_PROPERTY);
908   RECORD(DECL_OBJC_PROPERTY_IMPL);
909   RECORD(DECL_FIELD);
910   RECORD(DECL_MS_PROPERTY);
911   RECORD(DECL_VAR);
912   RECORD(DECL_IMPLICIT_PARAM);
913   RECORD(DECL_PARM_VAR);
914   RECORD(DECL_FILE_SCOPE_ASM);
915   RECORD(DECL_BLOCK);
916   RECORD(DECL_CONTEXT_LEXICAL);
917   RECORD(DECL_CONTEXT_VISIBLE);
918   RECORD(DECL_NAMESPACE);
919   RECORD(DECL_NAMESPACE_ALIAS);
920   RECORD(DECL_USING);
921   RECORD(DECL_USING_SHADOW);
922   RECORD(DECL_USING_DIRECTIVE);
923   RECORD(DECL_UNRESOLVED_USING_VALUE);
924   RECORD(DECL_UNRESOLVED_USING_TYPENAME);
925   RECORD(DECL_LINKAGE_SPEC);
926   RECORD(DECL_CXX_RECORD);
927   RECORD(DECL_CXX_METHOD);
928   RECORD(DECL_CXX_CONSTRUCTOR);
929   RECORD(DECL_CXX_DESTRUCTOR);
930   RECORD(DECL_CXX_CONVERSION);
931   RECORD(DECL_ACCESS_SPEC);
932   RECORD(DECL_FRIEND);
933   RECORD(DECL_FRIEND_TEMPLATE);
934   RECORD(DECL_CLASS_TEMPLATE);
935   RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
936   RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
937   RECORD(DECL_VAR_TEMPLATE);
938   RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
939   RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
940   RECORD(DECL_FUNCTION_TEMPLATE);
941   RECORD(DECL_TEMPLATE_TYPE_PARM);
942   RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
943   RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
944   RECORD(DECL_CONCEPT);
945   RECORD(DECL_REQUIRES_EXPR_BODY);
946   RECORD(DECL_TYPE_ALIAS_TEMPLATE);
947   RECORD(DECL_STATIC_ASSERT);
948   RECORD(DECL_CXX_BASE_SPECIFIERS);
949   RECORD(DECL_CXX_CTOR_INITIALIZERS);
950   RECORD(DECL_INDIRECTFIELD);
951   RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
952   RECORD(DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK);
953   RECORD(DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION);
954   RECORD(DECL_IMPORT);
955   RECORD(DECL_OMP_THREADPRIVATE);
956   RECORD(DECL_EMPTY);
957   RECORD(DECL_OBJC_TYPE_PARAM);
958   RECORD(DECL_OMP_CAPTUREDEXPR);
959   RECORD(DECL_PRAGMA_COMMENT);
960   RECORD(DECL_PRAGMA_DETECT_MISMATCH);
961   RECORD(DECL_OMP_DECLARE_REDUCTION);
962   RECORD(DECL_OMP_ALLOCATE);
963 
964   // Statements and Exprs can occur in the Decls and Types block.
965   AddStmtsExprs(Stream, Record);
966 
967   BLOCK(PREPROCESSOR_DETAIL_BLOCK);
968   RECORD(PPD_MACRO_EXPANSION);
969   RECORD(PPD_MACRO_DEFINITION);
970   RECORD(PPD_INCLUSION_DIRECTIVE);
971 
972   // Decls and Types block.
973   BLOCK(EXTENSION_BLOCK);
974   RECORD(EXTENSION_METADATA);
975 
976   BLOCK(UNHASHED_CONTROL_BLOCK);
977   RECORD(SIGNATURE);
978   RECORD(AST_BLOCK_HASH);
979   RECORD(DIAGNOSTIC_OPTIONS);
980   RECORD(DIAG_PRAGMA_MAPPINGS);
981 
982 #undef RECORD
983 #undef BLOCK
984   Stream.ExitBlock();
985 }
986 
987 /// Prepares a path for being written to an AST file by converting it
988 /// to an absolute path and removing nested './'s.
989 ///
990 /// \return \c true if the path was changed.
cleanPathForOutput(FileManager & FileMgr,SmallVectorImpl<char> & Path)991 static bool cleanPathForOutput(FileManager &FileMgr,
992                                SmallVectorImpl<char> &Path) {
993   bool Changed = FileMgr.makeAbsolutePath(Path);
994   return Changed | llvm::sys::path::remove_dots(Path);
995 }
996 
997 /// Adjusts the given filename to only write out the portion of the
998 /// filename that is not part of the system root directory.
999 ///
1000 /// \param Filename the file name to adjust.
1001 ///
1002 /// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
1003 /// the returned filename will be adjusted by this root directory.
1004 ///
1005 /// \returns either the original filename (if it needs no adjustment) or the
1006 /// adjusted filename (which points into the @p Filename parameter).
1007 static const char *
adjustFilenameForRelocatableAST(const char * Filename,StringRef BaseDir)1008 adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
1009   assert(Filename && "No file name to adjust?");
1010 
1011   if (BaseDir.empty())
1012     return Filename;
1013 
1014   // Verify that the filename and the system root have the same prefix.
1015   unsigned Pos = 0;
1016   for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
1017     if (Filename[Pos] != BaseDir[Pos])
1018       return Filename; // Prefixes don't match.
1019 
1020   // We hit the end of the filename before we hit the end of the system root.
1021   if (!Filename[Pos])
1022     return Filename;
1023 
1024   // If there's not a path separator at the end of the base directory nor
1025   // immediately after it, then this isn't within the base directory.
1026   if (!llvm::sys::path::is_separator(Filename[Pos])) {
1027     if (!llvm::sys::path::is_separator(BaseDir.back()))
1028       return Filename;
1029   } else {
1030     // If the file name has a '/' at the current position, skip over the '/'.
1031     // We distinguish relative paths from absolute paths by the
1032     // absence of '/' at the beginning of relative paths.
1033     //
1034     // FIXME: This is wrong. We distinguish them by asking if the path is
1035     // absolute, which isn't the same thing. And there might be multiple '/'s
1036     // in a row. Use a better mechanism to indicate whether we have emitted an
1037     // absolute or relative path.
1038     ++Pos;
1039   }
1040 
1041   return Filename + Pos;
1042 }
1043 
1044 std::pair<ASTFileSignature, ASTFileSignature>
createSignature(StringRef AllBytes,StringRef ASTBlockBytes)1045 ASTWriter::createSignature(StringRef AllBytes, StringRef ASTBlockBytes) {
1046   llvm::SHA1 Hasher;
1047   Hasher.update(ASTBlockBytes);
1048   auto Hash = Hasher.result();
1049   ASTFileSignature ASTBlockHash = ASTFileSignature::create(Hash);
1050 
1051   // Add the remaining bytes (i.e. bytes before the unhashed control block that
1052   // are not part of the AST block).
1053   Hasher.update(
1054       AllBytes.take_front(ASTBlockBytes.bytes_end() - AllBytes.bytes_begin()));
1055   Hasher.update(
1056       AllBytes.take_back(AllBytes.bytes_end() - ASTBlockBytes.bytes_end()));
1057   Hash = Hasher.result();
1058   ASTFileSignature Signature = ASTFileSignature::create(Hash);
1059 
1060   return std::make_pair(ASTBlockHash, Signature);
1061 }
1062 
writeUnhashedControlBlock(Preprocessor & PP,ASTContext & Context)1063 ASTFileSignature ASTWriter::writeUnhashedControlBlock(Preprocessor &PP,
1064                                                       ASTContext &Context) {
1065   using namespace llvm;
1066 
1067   // Flush first to prepare the PCM hash (signature).
1068   Stream.FlushToWord();
1069   auto StartOfUnhashedControl = Stream.GetCurrentBitNo() >> 3;
1070 
1071   // Enter the block and prepare to write records.
1072   RecordData Record;
1073   Stream.EnterSubblock(UNHASHED_CONTROL_BLOCK_ID, 5);
1074 
1075   // For implicit modules, write the hash of the PCM as its signature.
1076   ASTFileSignature Signature;
1077   if (WritingModule &&
1078       PP.getHeaderSearchInfo().getHeaderSearchOpts().ModulesHashContent) {
1079     ASTFileSignature ASTBlockHash;
1080     auto ASTBlockStartByte = ASTBlockRange.first >> 3;
1081     auto ASTBlockByteLength = (ASTBlockRange.second >> 3) - ASTBlockStartByte;
1082     std::tie(ASTBlockHash, Signature) = createSignature(
1083         StringRef(Buffer.begin(), StartOfUnhashedControl),
1084         StringRef(Buffer.begin() + ASTBlockStartByte, ASTBlockByteLength));
1085 
1086     Record.append(ASTBlockHash.begin(), ASTBlockHash.end());
1087     Stream.EmitRecord(AST_BLOCK_HASH, Record);
1088     Record.clear();
1089     Record.append(Signature.begin(), Signature.end());
1090     Stream.EmitRecord(SIGNATURE, Record);
1091     Record.clear();
1092   }
1093 
1094   // Diagnostic options.
1095   const auto &Diags = Context.getDiagnostics();
1096   const DiagnosticOptions &DiagOpts = Diags.getDiagnosticOptions();
1097 #define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1098 #define ENUM_DIAGOPT(Name, Type, Bits, Default)                                \
1099   Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1100 #include "clang/Basic/DiagnosticOptions.def"
1101   Record.push_back(DiagOpts.Warnings.size());
1102   for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1103     AddString(DiagOpts.Warnings[I], Record);
1104   Record.push_back(DiagOpts.Remarks.size());
1105   for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1106     AddString(DiagOpts.Remarks[I], Record);
1107   // Note: we don't serialize the log or serialization file names, because they
1108   // are generally transient files and will almost always be overridden.
1109   Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1110   Record.clear();
1111 
1112   // Write out the diagnostic/pragma mappings.
1113   WritePragmaDiagnosticMappings(Diags, /* isModule = */ WritingModule);
1114 
1115   // Header search entry usage.
1116   auto HSEntryUsage = PP.getHeaderSearchInfo().computeUserEntryUsage();
1117   auto Abbrev = std::make_shared<BitCodeAbbrev>();
1118   Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_ENTRY_USAGE));
1119   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Number of bits.
1120   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));      // Bit vector.
1121   unsigned HSUsageAbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1122   {
1123     RecordData::value_type Record[] = {HEADER_SEARCH_ENTRY_USAGE,
1124                                        HSEntryUsage.size()};
1125     Stream.EmitRecordWithBlob(HSUsageAbbrevCode, Record, bytes(HSEntryUsage));
1126   }
1127 
1128   // Leave the options block.
1129   Stream.ExitBlock();
1130   return Signature;
1131 }
1132 
1133 /// Write the control block.
WriteControlBlock(Preprocessor & PP,ASTContext & Context,StringRef isysroot,const std::string & OutputFile)1134 void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context,
1135                                   StringRef isysroot,
1136                                   const std::string &OutputFile) {
1137   using namespace llvm;
1138 
1139   Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
1140   RecordData Record;
1141 
1142   // Metadata
1143   auto MetadataAbbrev = std::make_shared<BitCodeAbbrev>();
1144   MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1145   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1146   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1147   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1148   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1149   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
1150   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
1151   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1152   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1153   unsigned MetadataAbbrevCode = Stream.EmitAbbrev(std::move(MetadataAbbrev));
1154   assert((!WritingModule || isysroot.empty()) &&
1155          "writing module as a relocatable PCH?");
1156   {
1157     RecordData::value_type Record[] = {
1158         METADATA,
1159         VERSION_MAJOR,
1160         VERSION_MINOR,
1161         CLANG_VERSION_MAJOR,
1162         CLANG_VERSION_MINOR,
1163         !isysroot.empty(),
1164         IncludeTimestamps,
1165         ASTHasCompilerErrors};
1166     Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1167                               getClangFullRepositoryVersion());
1168   }
1169 
1170   if (WritingModule) {
1171     // Module name
1172     auto Abbrev = std::make_shared<BitCodeAbbrev>();
1173     Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1174     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1175     unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1176     RecordData::value_type Record[] = {MODULE_NAME};
1177     Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1178   }
1179 
1180   if (WritingModule && WritingModule->Directory) {
1181     SmallString<128> BaseDir(WritingModule->Directory->getName());
1182     cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
1183 
1184     // If the home of the module is the current working directory, then we
1185     // want to pick up the cwd of the build process loading the module, not
1186     // our cwd, when we load this module.
1187     if (!PP.getHeaderSearchInfo()
1188              .getHeaderSearchOpts()
1189              .ModuleMapFileHomeIsCwd ||
1190         WritingModule->Directory->getName() != StringRef(".")) {
1191       // Module directory.
1192       auto Abbrev = std::make_shared<BitCodeAbbrev>();
1193       Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1194       Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
1195       unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1196 
1197       RecordData::value_type Record[] = {MODULE_DIRECTORY};
1198       Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
1199     }
1200 
1201     // Write out all other paths relative to the base directory if possible.
1202     BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1203   } else if (!isysroot.empty()) {
1204     // Write out paths relative to the sysroot if possible.
1205     BaseDirectory = std::string(isysroot);
1206   }
1207 
1208   // Module map file
1209   if (WritingModule && WritingModule->Kind == Module::ModuleMapModule) {
1210     Record.clear();
1211 
1212     auto &Map = PP.getHeaderSearchInfo().getModuleMap();
1213     AddPath(WritingModule->PresumedModuleMapFile.empty()
1214                 ? Map.getModuleMapFileForUniquing(WritingModule)->getName()
1215                 : StringRef(WritingModule->PresumedModuleMapFile),
1216             Record);
1217 
1218     // Additional module map files.
1219     if (auto *AdditionalModMaps =
1220             Map.getAdditionalModuleMapFiles(WritingModule)) {
1221       Record.push_back(AdditionalModMaps->size());
1222       for (const FileEntry *F : *AdditionalModMaps)
1223         AddPath(F->getName(), Record);
1224     } else {
1225       Record.push_back(0);
1226     }
1227 
1228     Stream.EmitRecord(MODULE_MAP_FILE, Record);
1229   }
1230 
1231   // Imports
1232   if (Chain) {
1233     serialization::ModuleManager &Mgr = Chain->getModuleManager();
1234     Record.clear();
1235 
1236     for (ModuleFile &M : Mgr) {
1237       // Skip modules that weren't directly imported.
1238       if (!M.isDirectlyImported())
1239         continue;
1240 
1241       Record.push_back((unsigned)M.Kind); // FIXME: Stable encoding
1242       AddSourceLocation(M.ImportLoc, Record);
1243 
1244       // If we have calculated signature, there is no need to store
1245       // the size or timestamp.
1246       Record.push_back(M.Signature ? 0 : M.File->getSize());
1247       Record.push_back(M.Signature ? 0 : getTimestampForOutput(M.File));
1248 
1249       for (auto I : M.Signature)
1250         Record.push_back(I);
1251 
1252       AddString(M.ModuleName, Record);
1253       AddPath(M.FileName, Record);
1254     }
1255     Stream.EmitRecord(IMPORTS, Record);
1256   }
1257 
1258   // Write the options block.
1259   Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
1260 
1261   // Language options.
1262   Record.clear();
1263   const LangOptions &LangOpts = Context.getLangOpts();
1264 #define LANGOPT(Name, Bits, Default, Description) \
1265   Record.push_back(LangOpts.Name);
1266 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1267   Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
1268 #include "clang/Basic/LangOptions.def"
1269 #define SANITIZER(NAME, ID)                                                    \
1270   Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
1271 #include "clang/Basic/Sanitizers.def"
1272 
1273   Record.push_back(LangOpts.ModuleFeatures.size());
1274   for (StringRef Feature : LangOpts.ModuleFeatures)
1275     AddString(Feature, Record);
1276 
1277   Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1278   AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
1279 
1280   AddString(LangOpts.CurrentModule, Record);
1281 
1282   // Comment options.
1283   Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
1284   for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1285     AddString(I, Record);
1286   }
1287   Record.push_back(LangOpts.CommentOpts.ParseAllComments);
1288 
1289   // OpenMP offloading options.
1290   Record.push_back(LangOpts.OMPTargetTriples.size());
1291   for (auto &T : LangOpts.OMPTargetTriples)
1292     AddString(T.getTriple(), Record);
1293 
1294   AddString(LangOpts.OMPHostIRFile, Record);
1295 
1296   Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1297 
1298   // Target options.
1299   Record.clear();
1300   const TargetInfo &Target = Context.getTargetInfo();
1301   const TargetOptions &TargetOpts = Target.getTargetOpts();
1302   AddString(TargetOpts.Triple, Record);
1303   AddString(TargetOpts.CPU, Record);
1304   AddString(TargetOpts.TuneCPU, Record);
1305   AddString(TargetOpts.ABI, Record);
1306   Record.push_back(TargetOpts.FeaturesAsWritten.size());
1307   for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1308     AddString(TargetOpts.FeaturesAsWritten[I], Record);
1309   }
1310   Record.push_back(TargetOpts.Features.size());
1311   for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1312     AddString(TargetOpts.Features[I], Record);
1313   }
1314   Stream.EmitRecord(TARGET_OPTIONS, Record);
1315 
1316   // File system options.
1317   Record.clear();
1318   const FileSystemOptions &FSOpts =
1319       Context.getSourceManager().getFileManager().getFileSystemOpts();
1320   AddString(FSOpts.WorkingDir, Record);
1321   Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1322 
1323   // Header search options.
1324   Record.clear();
1325   const HeaderSearchOptions &HSOpts
1326     = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1327   AddString(HSOpts.Sysroot, Record);
1328 
1329   // Include entries.
1330   Record.push_back(HSOpts.UserEntries.size());
1331   for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1332     const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1333     AddString(Entry.Path, Record);
1334     Record.push_back(static_cast<unsigned>(Entry.Group));
1335     Record.push_back(Entry.IsFramework);
1336     Record.push_back(Entry.IgnoreSysRoot);
1337   }
1338 
1339   // System header prefixes.
1340   Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1341   for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1342     AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1343     Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1344   }
1345 
1346   AddString(HSOpts.ResourceDir, Record);
1347   AddString(HSOpts.ModuleCachePath, Record);
1348   AddString(HSOpts.ModuleUserBuildPath, Record);
1349   Record.push_back(HSOpts.DisableModuleHash);
1350   Record.push_back(HSOpts.ImplicitModuleMaps);
1351   Record.push_back(HSOpts.ModuleMapFileHomeIsCwd);
1352   Record.push_back(HSOpts.EnablePrebuiltImplicitModules);
1353   Record.push_back(HSOpts.UseBuiltinIncludes);
1354   Record.push_back(HSOpts.UseStandardSystemIncludes);
1355   Record.push_back(HSOpts.UseStandardCXXIncludes);
1356   Record.push_back(HSOpts.UseLibcxx);
1357   // Write out the specific module cache path that contains the module files.
1358   AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
1359   Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1360 
1361   // Preprocessor options.
1362   Record.clear();
1363   const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1364 
1365   // Macro definitions.
1366   Record.push_back(PPOpts.Macros.size());
1367   for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1368     AddString(PPOpts.Macros[I].first, Record);
1369     Record.push_back(PPOpts.Macros[I].second);
1370   }
1371 
1372   // Includes
1373   Record.push_back(PPOpts.Includes.size());
1374   for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1375     AddString(PPOpts.Includes[I], Record);
1376 
1377   // Macro includes
1378   Record.push_back(PPOpts.MacroIncludes.size());
1379   for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1380     AddString(PPOpts.MacroIncludes[I], Record);
1381 
1382   Record.push_back(PPOpts.UsePredefines);
1383   // Detailed record is important since it is used for the module cache hash.
1384   Record.push_back(PPOpts.DetailedRecord);
1385   AddString(PPOpts.ImplicitPCHInclude, Record);
1386   Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1387   Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1388 
1389   // Leave the options block.
1390   Stream.ExitBlock();
1391 
1392   // Original file name and file ID
1393   SourceManager &SM = Context.getSourceManager();
1394   if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1395     auto FileAbbrev = std::make_shared<BitCodeAbbrev>();
1396     FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1397     FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
1398     FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1399     unsigned FileAbbrevCode = Stream.EmitAbbrev(std::move(FileAbbrev));
1400 
1401     Record.clear();
1402     Record.push_back(ORIGINAL_FILE);
1403     Record.push_back(SM.getMainFileID().getOpaqueValue());
1404     EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
1405   }
1406 
1407   Record.clear();
1408   Record.push_back(SM.getMainFileID().getOpaqueValue());
1409   Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1410 
1411   // Original PCH directory
1412   if (!OutputFile.empty() && OutputFile != "-") {
1413     auto Abbrev = std::make_shared<BitCodeAbbrev>();
1414     Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1415     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1416     unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1417 
1418     SmallString<128> OutputPath(OutputFile);
1419 
1420     SM.getFileManager().makeAbsolutePath(OutputPath);
1421     StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1422 
1423     RecordData::value_type Record[] = {ORIGINAL_PCH_DIR};
1424     Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1425   }
1426 
1427   WriteInputFiles(Context.SourceMgr,
1428                   PP.getHeaderSearchInfo().getHeaderSearchOpts(),
1429                   PP.getLangOpts().Modules);
1430   Stream.ExitBlock();
1431 }
1432 
1433 namespace  {
1434 
1435 /// An input file.
1436 struct InputFileEntry {
1437   const FileEntry *File;
1438   bool IsSystemFile;
1439   bool IsTransient;
1440   bool BufferOverridden;
1441   bool IsTopLevelModuleMap;
1442   uint32_t ContentHash[2];
1443 };
1444 
1445 } // namespace
1446 
WriteInputFiles(SourceManager & SourceMgr,HeaderSearchOptions & HSOpts,bool Modules)1447 void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1448                                 HeaderSearchOptions &HSOpts,
1449                                 bool Modules) {
1450   using namespace llvm;
1451 
1452   Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
1453 
1454   // Create input-file abbreviation.
1455   auto IFAbbrev = std::make_shared<BitCodeAbbrev>();
1456   IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
1457   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
1458   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1459   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1460   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
1461   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
1462   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Module map
1463   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1464   unsigned IFAbbrevCode = Stream.EmitAbbrev(std::move(IFAbbrev));
1465 
1466   // Create input file hash abbreviation.
1467   auto IFHAbbrev = std::make_shared<BitCodeAbbrev>();
1468   IFHAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_HASH));
1469   IFHAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1470   IFHAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1471   unsigned IFHAbbrevCode = Stream.EmitAbbrev(std::move(IFHAbbrev));
1472 
1473   // Get all ContentCache objects for files, sorted by whether the file is a
1474   // system one or not. System files go at the back, users files at the front.
1475   std::deque<InputFileEntry> SortedFiles;
1476   for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1477     // Get this source location entry.
1478     const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1479     assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
1480 
1481     // We only care about file entries that were not overridden.
1482     if (!SLoc->isFile())
1483       continue;
1484     const SrcMgr::FileInfo &File = SLoc->getFile();
1485     const SrcMgr::ContentCache *Cache = &File.getContentCache();
1486     if (!Cache->OrigEntry)
1487       continue;
1488 
1489     InputFileEntry Entry;
1490     Entry.File = Cache->OrigEntry;
1491     Entry.IsSystemFile = isSystem(File.getFileCharacteristic());
1492     Entry.IsTransient = Cache->IsTransient;
1493     Entry.BufferOverridden = Cache->BufferOverridden;
1494     Entry.IsTopLevelModuleMap = isModuleMap(File.getFileCharacteristic()) &&
1495                                 File.getIncludeLoc().isInvalid();
1496 
1497     auto ContentHash = hash_code(-1);
1498     if (PP->getHeaderSearchInfo()
1499             .getHeaderSearchOpts()
1500             .ValidateASTInputFilesContent) {
1501       auto MemBuff = Cache->getBufferIfLoaded();
1502       if (MemBuff)
1503         ContentHash = hash_value(MemBuff->getBuffer());
1504       else
1505         // FIXME: The path should be taken from the FileEntryRef.
1506         PP->Diag(SourceLocation(), diag::err_module_unable_to_hash_content)
1507             << Entry.File->getName();
1508     }
1509     auto CH = llvm::APInt(64, ContentHash);
1510     Entry.ContentHash[0] =
1511         static_cast<uint32_t>(CH.getLoBits(32).getZExtValue());
1512     Entry.ContentHash[1] =
1513         static_cast<uint32_t>(CH.getHiBits(32).getZExtValue());
1514 
1515     if (Entry.IsSystemFile)
1516       SortedFiles.push_back(Entry);
1517     else
1518       SortedFiles.push_front(Entry);
1519   }
1520 
1521   unsigned UserFilesNum = 0;
1522   // Write out all of the input files.
1523   std::vector<uint64_t> InputFileOffsets;
1524   for (const auto &Entry : SortedFiles) {
1525     uint32_t &InputFileID = InputFileIDs[Entry.File];
1526     if (InputFileID != 0)
1527       continue; // already recorded this file.
1528 
1529     // Record this entry's offset.
1530     InputFileOffsets.push_back(Stream.GetCurrentBitNo());
1531 
1532     InputFileID = InputFileOffsets.size();
1533 
1534     if (!Entry.IsSystemFile)
1535       ++UserFilesNum;
1536 
1537     // Emit size/modification time for this file.
1538     // And whether this file was overridden.
1539     {
1540       RecordData::value_type Record[] = {
1541           INPUT_FILE,
1542           InputFileOffsets.size(),
1543           (uint64_t)Entry.File->getSize(),
1544           (uint64_t)getTimestampForOutput(Entry.File),
1545           Entry.BufferOverridden,
1546           Entry.IsTransient,
1547           Entry.IsTopLevelModuleMap};
1548 
1549       // FIXME: The path should be taken from the FileEntryRef.
1550       EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
1551     }
1552 
1553     // Emit content hash for this file.
1554     {
1555       RecordData::value_type Record[] = {INPUT_FILE_HASH, Entry.ContentHash[0],
1556                                          Entry.ContentHash[1]};
1557       Stream.EmitRecordWithAbbrev(IFHAbbrevCode, Record);
1558     }
1559   }
1560 
1561   Stream.ExitBlock();
1562 
1563   // Create input file offsets abbreviation.
1564   auto OffsetsAbbrev = std::make_shared<BitCodeAbbrev>();
1565   OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1566   OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
1567   OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1568                                                                 //   input files
1569   OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));   // Array
1570   unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(std::move(OffsetsAbbrev));
1571 
1572   // Write input file offsets.
1573   RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
1574                                      InputFileOffsets.size(), UserFilesNum};
1575   Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
1576 }
1577 
1578 //===----------------------------------------------------------------------===//
1579 // Source Manager Serialization
1580 //===----------------------------------------------------------------------===//
1581 
1582 /// Create an abbreviation for the SLocEntry that refers to a
1583 /// file.
CreateSLocFileAbbrev(llvm::BitstreamWriter & Stream)1584 static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1585   using namespace llvm;
1586 
1587   auto Abbrev = std::make_shared<BitCodeAbbrev>();
1588   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1589   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1590   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1591   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
1592   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1593   // FileEntry fields.
1594   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
1595   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
1596   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1597   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
1598   return Stream.EmitAbbrev(std::move(Abbrev));
1599 }
1600 
1601 /// Create an abbreviation for the SLocEntry that refers to a
1602 /// buffer.
CreateSLocBufferAbbrev(llvm::BitstreamWriter & Stream)1603 static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1604   using namespace llvm;
1605 
1606   auto Abbrev = std::make_shared<BitCodeAbbrev>();
1607   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
1608   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1609   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1610   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
1611   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1612   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
1613   return Stream.EmitAbbrev(std::move(Abbrev));
1614 }
1615 
1616 /// Create an abbreviation for the SLocEntry that refers to a
1617 /// buffer's blob.
CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter & Stream,bool Compressed)1618 static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
1619                                            bool Compressed) {
1620   using namespace llvm;
1621 
1622   auto Abbrev = std::make_shared<BitCodeAbbrev>();
1623   Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED
1624                                          : SM_SLOC_BUFFER_BLOB));
1625   if (Compressed)
1626     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
1627   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
1628   return Stream.EmitAbbrev(std::move(Abbrev));
1629 }
1630 
1631 /// Create an abbreviation for the SLocEntry that refers to a macro
1632 /// expansion.
CreateSLocExpansionAbbrev(llvm::BitstreamWriter & Stream)1633 static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
1634   using namespace llvm;
1635 
1636   auto Abbrev = std::make_shared<BitCodeAbbrev>();
1637   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
1638   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1639   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1640   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1641   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
1642   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Is token range
1643   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
1644   return Stream.EmitAbbrev(std::move(Abbrev));
1645 }
1646 
1647 /// Emit key length and data length as ULEB-encoded data, and return them as a
1648 /// pair.
1649 static std::pair<unsigned, unsigned>
emitULEBKeyDataLength(unsigned KeyLen,unsigned DataLen,raw_ostream & Out)1650 emitULEBKeyDataLength(unsigned KeyLen, unsigned DataLen, raw_ostream &Out) {
1651   llvm::encodeULEB128(KeyLen, Out);
1652   llvm::encodeULEB128(DataLen, Out);
1653   return std::make_pair(KeyLen, DataLen);
1654 }
1655 
1656 namespace {
1657 
1658   // Trait used for the on-disk hash table of header search information.
1659   class HeaderFileInfoTrait {
1660     ASTWriter &Writer;
1661 
1662     // Keep track of the framework names we've used during serialization.
1663     SmallString<128> FrameworkStringData;
1664     llvm::StringMap<unsigned> FrameworkNameOffset;
1665 
1666   public:
HeaderFileInfoTrait(ASTWriter & Writer)1667     HeaderFileInfoTrait(ASTWriter &Writer) : Writer(Writer) {}
1668 
1669     struct key_type {
1670       StringRef Filename;
1671       off_t Size;
1672       time_t ModTime;
1673     };
1674     using key_type_ref = const key_type &;
1675 
1676     using UnresolvedModule =
1677         llvm::PointerIntPair<Module *, 2, ModuleMap::ModuleHeaderRole>;
1678 
1679     struct data_type {
1680       const HeaderFileInfo &HFI;
1681       ArrayRef<ModuleMap::KnownHeader> KnownHeaders;
1682       UnresolvedModule Unresolved;
1683     };
1684     using data_type_ref = const data_type &;
1685 
1686     using hash_value_type = unsigned;
1687     using offset_type = unsigned;
1688 
ComputeHash(key_type_ref key)1689     hash_value_type ComputeHash(key_type_ref key) {
1690       // The hash is based only on size/time of the file, so that the reader can
1691       // match even when symlinking or excess path elements ("foo/../", "../")
1692       // change the form of the name. However, complete path is still the key.
1693       return llvm::hash_combine(key.Size, key.ModTime);
1694     }
1695 
1696     std::pair<unsigned, unsigned>
EmitKeyDataLength(raw_ostream & Out,key_type_ref key,data_type_ref Data)1697     EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
1698       unsigned KeyLen = key.Filename.size() + 1 + 8 + 8;
1699       unsigned DataLen = 1 + 2 + 4 + 4;
1700       for (auto ModInfo : Data.KnownHeaders)
1701         if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
1702           DataLen += 4;
1703       if (Data.Unresolved.getPointer())
1704         DataLen += 4;
1705       return emitULEBKeyDataLength(KeyLen, DataLen, Out);
1706     }
1707 
EmitKey(raw_ostream & Out,key_type_ref key,unsigned KeyLen)1708     void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
1709       using namespace llvm::support;
1710 
1711       endian::Writer LE(Out, little);
1712       LE.write<uint64_t>(key.Size);
1713       KeyLen -= 8;
1714       LE.write<uint64_t>(key.ModTime);
1715       KeyLen -= 8;
1716       Out.write(key.Filename.data(), KeyLen);
1717     }
1718 
EmitData(raw_ostream & Out,key_type_ref key,data_type_ref Data,unsigned DataLen)1719     void EmitData(raw_ostream &Out, key_type_ref key,
1720                   data_type_ref Data, unsigned DataLen) {
1721       using namespace llvm::support;
1722 
1723       endian::Writer LE(Out, little);
1724       uint64_t Start = Out.tell(); (void)Start;
1725 
1726       unsigned char Flags = (Data.HFI.isImport << 5)
1727                           | (Data.HFI.isPragmaOnce << 4)
1728                           | (Data.HFI.DirInfo << 1)
1729                           | Data.HFI.IndexHeaderMapHeader;
1730       LE.write<uint8_t>(Flags);
1731       LE.write<uint16_t>(Data.HFI.NumIncludes);
1732 
1733       if (!Data.HFI.ControllingMacro)
1734         LE.write<uint32_t>(Data.HFI.ControllingMacroID);
1735       else
1736         LE.write<uint32_t>(Writer.getIdentifierRef(Data.HFI.ControllingMacro));
1737 
1738       unsigned Offset = 0;
1739       if (!Data.HFI.Framework.empty()) {
1740         // If this header refers into a framework, save the framework name.
1741         llvm::StringMap<unsigned>::iterator Pos
1742           = FrameworkNameOffset.find(Data.HFI.Framework);
1743         if (Pos == FrameworkNameOffset.end()) {
1744           Offset = FrameworkStringData.size() + 1;
1745           FrameworkStringData.append(Data.HFI.Framework);
1746           FrameworkStringData.push_back(0);
1747 
1748           FrameworkNameOffset[Data.HFI.Framework] = Offset;
1749         } else
1750           Offset = Pos->second;
1751       }
1752       LE.write<uint32_t>(Offset);
1753 
1754       auto EmitModule = [&](Module *M, ModuleMap::ModuleHeaderRole Role) {
1755         if (uint32_t ModID = Writer.getLocalOrImportedSubmoduleID(M)) {
1756           uint32_t Value = (ModID << 2) | (unsigned)Role;
1757           assert((Value >> 2) == ModID && "overflow in header module info");
1758           LE.write<uint32_t>(Value);
1759         }
1760       };
1761 
1762       // FIXME: If the header is excluded, we should write out some
1763       // record of that fact.
1764       for (auto ModInfo : Data.KnownHeaders)
1765         EmitModule(ModInfo.getModule(), ModInfo.getRole());
1766       if (Data.Unresolved.getPointer())
1767         EmitModule(Data.Unresolved.getPointer(), Data.Unresolved.getInt());
1768 
1769       assert(Out.tell() - Start == DataLen && "Wrong data length");
1770     }
1771 
strings_begin() const1772     const char *strings_begin() const { return FrameworkStringData.begin(); }
strings_end() const1773     const char *strings_end() const { return FrameworkStringData.end(); }
1774   };
1775 
1776 } // namespace
1777 
1778 /// Write the header search block for the list of files that
1779 ///
1780 /// \param HS The header search structure to save.
WriteHeaderSearch(const HeaderSearch & HS)1781 void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
1782   HeaderFileInfoTrait GeneratorTrait(*this);
1783   llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
1784   SmallVector<const char *, 4> SavedStrings;
1785   unsigned NumHeaderSearchEntries = 0;
1786 
1787   // Find all unresolved headers for the current module. We generally will
1788   // have resolved them before we get here, but not necessarily: we might be
1789   // compiling a preprocessed module, where there is no requirement for the
1790   // original files to exist any more.
1791   const HeaderFileInfo Empty; // So we can take a reference.
1792   if (WritingModule) {
1793     llvm::SmallVector<Module *, 16> Worklist(1, WritingModule);
1794     while (!Worklist.empty()) {
1795       Module *M = Worklist.pop_back_val();
1796       // We don't care about headers in unimportable submodules.
1797       if (M->isUnimportable())
1798         continue;
1799 
1800       // Map to disk files where possible, to pick up any missing stat
1801       // information. This also means we don't need to check the unresolved
1802       // headers list when emitting resolved headers in the first loop below.
1803       // FIXME: It'd be preferable to avoid doing this if we were given
1804       // sufficient stat information in the module map.
1805       HS.getModuleMap().resolveHeaderDirectives(M);
1806 
1807       // If the file didn't exist, we can still create a module if we were given
1808       // enough information in the module map.
1809       for (auto U : M->MissingHeaders) {
1810         // Check that we were given enough information to build a module
1811         // without this file existing on disk.
1812         if (!U.Size || (!U.ModTime && IncludeTimestamps)) {
1813           PP->Diag(U.FileNameLoc, diag::err_module_no_size_mtime_for_header)
1814             << WritingModule->getFullModuleName() << U.Size.hasValue()
1815             << U.FileName;
1816           continue;
1817         }
1818 
1819         // Form the effective relative pathname for the file.
1820         SmallString<128> Filename(M->Directory->getName());
1821         llvm::sys::path::append(Filename, U.FileName);
1822         PreparePathForOutput(Filename);
1823 
1824         StringRef FilenameDup = strdup(Filename.c_str());
1825         SavedStrings.push_back(FilenameDup.data());
1826 
1827         HeaderFileInfoTrait::key_type Key = {
1828           FilenameDup, *U.Size, IncludeTimestamps ? *U.ModTime : 0
1829         };
1830         HeaderFileInfoTrait::data_type Data = {
1831           Empty, {}, {M, ModuleMap::headerKindToRole(U.Kind)}
1832         };
1833         // FIXME: Deal with cases where there are multiple unresolved header
1834         // directives in different submodules for the same header.
1835         Generator.insert(Key, Data, GeneratorTrait);
1836         ++NumHeaderSearchEntries;
1837       }
1838 
1839       Worklist.append(M->submodule_begin(), M->submodule_end());
1840     }
1841   }
1842 
1843   SmallVector<const FileEntry *, 16> FilesByUID;
1844   HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
1845 
1846   if (FilesByUID.size() > HS.header_file_size())
1847     FilesByUID.resize(HS.header_file_size());
1848 
1849   for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1850     const FileEntry *File = FilesByUID[UID];
1851     if (!File)
1852       continue;
1853 
1854     // Get the file info. This will load info from the external source if
1855     // necessary. Skip emitting this file if we have no information on it
1856     // as a header file (in which case HFI will be null) or if it hasn't
1857     // changed since it was loaded. Also skip it if it's for a modular header
1858     // from a different module; in that case, we rely on the module(s)
1859     // containing the header to provide this information.
1860     const HeaderFileInfo *HFI =
1861         HS.getExistingFileInfo(File, /*WantExternal*/!Chain);
1862     if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
1863       continue;
1864 
1865     // Massage the file path into an appropriate form.
1866     StringRef Filename = File->getName();
1867     SmallString<128> FilenameTmp(Filename);
1868     if (PreparePathForOutput(FilenameTmp)) {
1869       // If we performed any translation on the file name at all, we need to
1870       // save this string, since the generator will refer to it later.
1871       Filename = StringRef(strdup(FilenameTmp.c_str()));
1872       SavedStrings.push_back(Filename.data());
1873     }
1874 
1875     HeaderFileInfoTrait::key_type Key = {
1876       Filename, File->getSize(), getTimestampForOutput(File)
1877     };
1878     HeaderFileInfoTrait::data_type Data = {
1879       *HFI, HS.getModuleMap().findResolvedModulesForHeader(File), {}
1880     };
1881     Generator.insert(Key, Data, GeneratorTrait);
1882     ++NumHeaderSearchEntries;
1883   }
1884 
1885   // Create the on-disk hash table in a buffer.
1886   SmallString<4096> TableData;
1887   uint32_t BucketOffset;
1888   {
1889     using namespace llvm::support;
1890 
1891     llvm::raw_svector_ostream Out(TableData);
1892     // Make sure that no bucket is at offset 0
1893     endian::write<uint32_t>(Out, 0, little);
1894     BucketOffset = Generator.Emit(Out, GeneratorTrait);
1895   }
1896 
1897   // Create a blob abbreviation
1898   using namespace llvm;
1899 
1900   auto Abbrev = std::make_shared<BitCodeAbbrev>();
1901   Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1902   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1903   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1904   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1905   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1906   unsigned TableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
1907 
1908   // Write the header search table
1909   RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
1910                                      NumHeaderSearchEntries, TableData.size()};
1911   TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
1912   Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
1913 
1914   // Free all of the strings we had to duplicate.
1915   for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
1916     free(const_cast<char *>(SavedStrings[I]));
1917 }
1918 
emitBlob(llvm::BitstreamWriter & Stream,StringRef Blob,unsigned SLocBufferBlobCompressedAbbrv,unsigned SLocBufferBlobAbbrv)1919 static void emitBlob(llvm::BitstreamWriter &Stream, StringRef Blob,
1920                      unsigned SLocBufferBlobCompressedAbbrv,
1921                      unsigned SLocBufferBlobAbbrv) {
1922   using RecordDataType = ASTWriter::RecordData::value_type;
1923 
1924   // Compress the buffer if possible. We expect that almost all PCM
1925   // consumers will not want its contents.
1926   SmallString<0> CompressedBuffer;
1927   if (llvm::zlib::isAvailable()) {
1928     llvm::Error E = llvm::zlib::compress(Blob.drop_back(1), CompressedBuffer);
1929     if (!E) {
1930       RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED,
1931                                  Blob.size() - 1};
1932       Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
1933                                 CompressedBuffer);
1934       return;
1935     }
1936     llvm::consumeError(std::move(E));
1937   }
1938 
1939   RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB};
1940   Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob);
1941 }
1942 
1943 /// Writes the block containing the serialized form of the
1944 /// source manager.
1945 ///
1946 /// TODO: We should probably use an on-disk hash table (stored in a
1947 /// blob), indexed based on the file name, so that we only create
1948 /// entries for files that we actually need. In the common case (no
1949 /// errors), we probably won't have to create file entries for any of
1950 /// the files in the AST.
WriteSourceManagerBlock(SourceManager & SourceMgr,const Preprocessor & PP)1951 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
1952                                         const Preprocessor &PP) {
1953   RecordData Record;
1954 
1955   // Enter the source manager block.
1956   Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
1957   const uint64_t SourceManagerBlockOffset = Stream.GetCurrentBitNo();
1958 
1959   // Abbreviations for the various kinds of source-location entries.
1960   unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
1961   unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
1962   unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
1963   unsigned SLocBufferBlobCompressedAbbrv =
1964       CreateSLocBufferBlobAbbrev(Stream, true);
1965   unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
1966 
1967   // Write out the source location entry table. We skip the first
1968   // entry, which is always the same dummy entry.
1969   std::vector<uint32_t> SLocEntryOffsets;
1970   uint64_t SLocEntryOffsetsBase = Stream.GetCurrentBitNo();
1971   RecordData PreloadSLocs;
1972   SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
1973   for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
1974        I != N; ++I) {
1975     // Get this source location entry.
1976     const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1977     FileID FID = FileID::get(I);
1978     assert(&SourceMgr.getSLocEntry(FID) == SLoc);
1979 
1980     // Record the offset of this source-location entry.
1981     uint64_t Offset = Stream.GetCurrentBitNo() - SLocEntryOffsetsBase;
1982     assert((Offset >> 32) == 0 && "SLocEntry offset too large");
1983     SLocEntryOffsets.push_back(Offset);
1984 
1985     // Figure out which record code to use.
1986     unsigned Code;
1987     if (SLoc->isFile()) {
1988       const SrcMgr::ContentCache *Cache = &SLoc->getFile().getContentCache();
1989       if (Cache->OrigEntry) {
1990         Code = SM_SLOC_FILE_ENTRY;
1991       } else
1992         Code = SM_SLOC_BUFFER_ENTRY;
1993     } else
1994       Code = SM_SLOC_EXPANSION_ENTRY;
1995     Record.clear();
1996     Record.push_back(Code);
1997 
1998     // Starting offset of this entry within this module, so skip the dummy.
1999     Record.push_back(SLoc->getOffset() - 2);
2000     if (SLoc->isFile()) {
2001       const SrcMgr::FileInfo &File = SLoc->getFile();
2002       AddSourceLocation(File.getIncludeLoc(), Record);
2003       Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
2004       Record.push_back(File.hasLineDirectives());
2005 
2006       const SrcMgr::ContentCache *Content = &File.getContentCache();
2007       bool EmitBlob = false;
2008       if (Content->OrigEntry) {
2009         assert(Content->OrigEntry == Content->ContentsEntry &&
2010                "Writing to AST an overridden file is not supported");
2011 
2012         // The source location entry is a file. Emit input file ID.
2013         assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
2014         Record.push_back(InputFileIDs[Content->OrigEntry]);
2015 
2016         Record.push_back(File.NumCreatedFIDs);
2017 
2018         FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
2019         if (FDI != FileDeclIDs.end()) {
2020           Record.push_back(FDI->second->FirstDeclIndex);
2021           Record.push_back(FDI->second->DeclIDs.size());
2022         } else {
2023           Record.push_back(0);
2024           Record.push_back(0);
2025         }
2026 
2027         Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
2028 
2029         if (Content->BufferOverridden || Content->IsTransient)
2030           EmitBlob = true;
2031       } else {
2032         // The source location entry is a buffer. The blob associated
2033         // with this entry contains the contents of the buffer.
2034 
2035         // We add one to the size so that we capture the trailing NULL
2036         // that is required by llvm::MemoryBuffer::getMemBuffer (on
2037         // the reader side).
2038         llvm::Optional<llvm::MemoryBufferRef> Buffer =
2039             Content->getBufferOrNone(PP.getDiagnostics(), PP.getFileManager());
2040         StringRef Name = Buffer ? Buffer->getBufferIdentifier() : "";
2041         Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
2042                                   StringRef(Name.data(), Name.size() + 1));
2043         EmitBlob = true;
2044 
2045         if (Name == "<built-in>")
2046           PreloadSLocs.push_back(SLocEntryOffsets.size());
2047       }
2048 
2049       if (EmitBlob) {
2050         // Include the implicit terminating null character in the on-disk buffer
2051         // if we're writing it uncompressed.
2052         llvm::Optional<llvm::MemoryBufferRef> Buffer =
2053             Content->getBufferOrNone(PP.getDiagnostics(), PP.getFileManager());
2054         if (!Buffer)
2055           Buffer = llvm::MemoryBufferRef("<<<INVALID BUFFER>>>", "");
2056         StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
2057         emitBlob(Stream, Blob, SLocBufferBlobCompressedAbbrv,
2058                  SLocBufferBlobAbbrv);
2059       }
2060     } else {
2061       // The source location entry is a macro expansion.
2062       const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
2063       AddSourceLocation(Expansion.getSpellingLoc(), Record);
2064       AddSourceLocation(Expansion.getExpansionLocStart(), Record);
2065       AddSourceLocation(Expansion.isMacroArgExpansion()
2066                             ? SourceLocation()
2067                             : Expansion.getExpansionLocEnd(),
2068                         Record);
2069       Record.push_back(Expansion.isExpansionTokenRange());
2070 
2071       // Compute the token length for this macro expansion.
2072       SourceLocation::UIntTy NextOffset = SourceMgr.getNextLocalOffset();
2073       if (I + 1 != N)
2074         NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
2075       Record.push_back(NextOffset - SLoc->getOffset() - 1);
2076       Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
2077     }
2078   }
2079 
2080   Stream.ExitBlock();
2081 
2082   if (SLocEntryOffsets.empty())
2083     return;
2084 
2085   // Write the source-location offsets table into the AST block. This
2086   // table is used for lazily loading source-location information.
2087   using namespace llvm;
2088 
2089   auto Abbrev = std::make_shared<BitCodeAbbrev>();
2090   Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
2091   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
2092   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
2093   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // base offset
2094   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
2095   unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2096   {
2097     RecordData::value_type Record[] = {
2098         SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
2099         SourceMgr.getNextLocalOffset() - 1 /* skip dummy */,
2100         SLocEntryOffsetsBase - SourceManagerBlockOffset};
2101     Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
2102                               bytes(SLocEntryOffsets));
2103   }
2104   // Write the source location entry preloads array, telling the AST
2105   // reader which source locations entries it should load eagerly.
2106   Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
2107 
2108   // Write the line table. It depends on remapping working, so it must come
2109   // after the source location offsets.
2110   if (SourceMgr.hasLineTable()) {
2111     LineTableInfo &LineTable = SourceMgr.getLineTable();
2112 
2113     Record.clear();
2114 
2115     // Emit the needed file names.
2116     llvm::DenseMap<int, int> FilenameMap;
2117     FilenameMap[-1] = -1; // For unspecified filenames.
2118     for (const auto &L : LineTable) {
2119       if (L.first.ID < 0)
2120         continue;
2121       for (auto &LE : L.second) {
2122         if (FilenameMap.insert(std::make_pair(LE.FilenameID,
2123                                               FilenameMap.size() - 1)).second)
2124           AddPath(LineTable.getFilename(LE.FilenameID), Record);
2125       }
2126     }
2127     Record.push_back(0);
2128 
2129     // Emit the line entries
2130     for (const auto &L : LineTable) {
2131       // Only emit entries for local files.
2132       if (L.first.ID < 0)
2133         continue;
2134 
2135       // Emit the file ID
2136       Record.push_back(L.first.ID);
2137 
2138       // Emit the line entries
2139       Record.push_back(L.second.size());
2140       for (const auto &LE : L.second) {
2141         Record.push_back(LE.FileOffset);
2142         Record.push_back(LE.LineNo);
2143         Record.push_back(FilenameMap[LE.FilenameID]);
2144         Record.push_back((unsigned)LE.FileKind);
2145         Record.push_back(LE.IncludeOffset);
2146       }
2147     }
2148 
2149     Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
2150   }
2151 }
2152 
2153 //===----------------------------------------------------------------------===//
2154 // Preprocessor Serialization
2155 //===----------------------------------------------------------------------===//
2156 
shouldIgnoreMacro(MacroDirective * MD,bool IsModule,const Preprocessor & PP)2157 static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
2158                               const Preprocessor &PP) {
2159   if (MacroInfo *MI = MD->getMacroInfo())
2160     if (MI->isBuiltinMacro())
2161       return true;
2162 
2163   if (IsModule) {
2164     SourceLocation Loc = MD->getLocation();
2165     if (Loc.isInvalid())
2166       return true;
2167     if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
2168       return true;
2169   }
2170 
2171   return false;
2172 }
2173 
2174 /// Writes the block containing the serialized form of the
2175 /// preprocessor.
WritePreprocessor(const Preprocessor & PP,bool IsModule)2176 void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
2177   uint64_t MacroOffsetsBase = Stream.GetCurrentBitNo();
2178 
2179   PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
2180   if (PPRec)
2181     WritePreprocessorDetail(*PPRec, MacroOffsetsBase);
2182 
2183   RecordData Record;
2184   RecordData ModuleMacroRecord;
2185 
2186   // If the preprocessor __COUNTER__ value has been bumped, remember it.
2187   if (PP.getCounterValue() != 0) {
2188     RecordData::value_type Record[] = {PP.getCounterValue()};
2189     Stream.EmitRecord(PP_COUNTER_VALUE, Record);
2190   }
2191 
2192   if (PP.isRecordingPreamble() && PP.hasRecordedPreamble()) {
2193     assert(!IsModule);
2194     auto SkipInfo = PP.getPreambleSkipInfo();
2195     if (SkipInfo.hasValue()) {
2196       Record.push_back(true);
2197       AddSourceLocation(SkipInfo->HashTokenLoc, Record);
2198       AddSourceLocation(SkipInfo->IfTokenLoc, Record);
2199       Record.push_back(SkipInfo->FoundNonSkipPortion);
2200       Record.push_back(SkipInfo->FoundElse);
2201       AddSourceLocation(SkipInfo->ElseLoc, Record);
2202     } else {
2203       Record.push_back(false);
2204     }
2205     for (const auto &Cond : PP.getPreambleConditionalStack()) {
2206       AddSourceLocation(Cond.IfLoc, Record);
2207       Record.push_back(Cond.WasSkipping);
2208       Record.push_back(Cond.FoundNonSkip);
2209       Record.push_back(Cond.FoundElse);
2210     }
2211     Stream.EmitRecord(PP_CONDITIONAL_STACK, Record);
2212     Record.clear();
2213   }
2214 
2215   // Enter the preprocessor block.
2216   Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
2217 
2218   // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
2219   // FIXME: Include a location for the use, and say which one was used.
2220   if (PP.SawDateOrTime())
2221     PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
2222 
2223   // Loop over all the macro directives that are live at the end of the file,
2224   // emitting each to the PP section.
2225 
2226   // Construct the list of identifiers with macro directives that need to be
2227   // serialized.
2228   SmallVector<const IdentifierInfo *, 128> MacroIdentifiers;
2229   for (auto &Id : PP.getIdentifierTable())
2230     if (Id.second->hadMacroDefinition() &&
2231         (!Id.second->isFromAST() ||
2232          Id.second->hasChangedSinceDeserialization()))
2233       MacroIdentifiers.push_back(Id.second);
2234   // Sort the set of macro definitions that need to be serialized by the
2235   // name of the macro, to provide a stable ordering.
2236   llvm::sort(MacroIdentifiers, llvm::deref<std::less<>>());
2237 
2238   // Emit the macro directives as a list and associate the offset with the
2239   // identifier they belong to.
2240   for (const IdentifierInfo *Name : MacroIdentifiers) {
2241     MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name);
2242     uint64_t StartOffset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2243     assert((StartOffset >> 32) == 0 && "Macro identifiers offset too large");
2244 
2245     // Emit the macro directives in reverse source order.
2246     for (; MD; MD = MD->getPrevious()) {
2247       // Once we hit an ignored macro, we're done: the rest of the chain
2248       // will all be ignored macros.
2249       if (shouldIgnoreMacro(MD, IsModule, PP))
2250         break;
2251 
2252       AddSourceLocation(MD->getLocation(), Record);
2253       Record.push_back(MD->getKind());
2254       if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
2255         Record.push_back(getMacroRef(DefMD->getInfo(), Name));
2256       } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
2257         Record.push_back(VisMD->isPublic());
2258       }
2259     }
2260 
2261     // Write out any exported module macros.
2262     bool EmittedModuleMacros = false;
2263     // We write out exported module macros for PCH as well.
2264     auto Leafs = PP.getLeafModuleMacros(Name);
2265     SmallVector<ModuleMacro*, 8> Worklist(Leafs.begin(), Leafs.end());
2266     llvm::DenseMap<ModuleMacro*, unsigned> Visits;
2267     while (!Worklist.empty()) {
2268       auto *Macro = Worklist.pop_back_val();
2269 
2270       // Emit a record indicating this submodule exports this macro.
2271       ModuleMacroRecord.push_back(
2272           getSubmoduleID(Macro->getOwningModule()));
2273       ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
2274       for (auto *M : Macro->overrides())
2275         ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
2276 
2277       Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2278       ModuleMacroRecord.clear();
2279 
2280       // Enqueue overridden macros once we've visited all their ancestors.
2281       for (auto *M : Macro->overrides())
2282         if (++Visits[M] == M->getNumOverridingMacros())
2283           Worklist.push_back(M);
2284 
2285       EmittedModuleMacros = true;
2286     }
2287 
2288     if (Record.empty() && !EmittedModuleMacros)
2289       continue;
2290 
2291     IdentMacroDirectivesOffsetMap[Name] = StartOffset;
2292     Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2293     Record.clear();
2294   }
2295 
2296   /// Offsets of each of the macros into the bitstream, indexed by
2297   /// the local macro ID
2298   ///
2299   /// For each identifier that is associated with a macro, this map
2300   /// provides the offset into the bitstream where that macro is
2301   /// defined.
2302   std::vector<uint32_t> MacroOffsets;
2303 
2304   for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2305     const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2306     MacroInfo *MI = MacroInfosToEmit[I].MI;
2307     MacroID ID = MacroInfosToEmit[I].ID;
2308 
2309     if (ID < FirstMacroID) {
2310       assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2311       continue;
2312     }
2313 
2314     // Record the local offset of this macro.
2315     unsigned Index = ID - FirstMacroID;
2316     if (Index >= MacroOffsets.size())
2317       MacroOffsets.resize(Index + 1);
2318 
2319     uint64_t Offset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2320     assert((Offset >> 32) == 0 && "Macro offset too large");
2321     MacroOffsets[Index] = Offset;
2322 
2323     AddIdentifierRef(Name, Record);
2324     AddSourceLocation(MI->getDefinitionLoc(), Record);
2325     AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2326     Record.push_back(MI->isUsed());
2327     Record.push_back(MI->isUsedForHeaderGuard());
2328     unsigned Code;
2329     if (MI->isObjectLike()) {
2330       Code = PP_MACRO_OBJECT_LIKE;
2331     } else {
2332       Code = PP_MACRO_FUNCTION_LIKE;
2333 
2334       Record.push_back(MI->isC99Varargs());
2335       Record.push_back(MI->isGNUVarargs());
2336       Record.push_back(MI->hasCommaPasting());
2337       Record.push_back(MI->getNumParams());
2338       for (const IdentifierInfo *Param : MI->params())
2339         AddIdentifierRef(Param, Record);
2340     }
2341 
2342     // If we have a detailed preprocessing record, record the macro definition
2343     // ID that corresponds to this macro.
2344     if (PPRec)
2345       Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2346 
2347     Stream.EmitRecord(Code, Record);
2348     Record.clear();
2349 
2350     // Emit the tokens array.
2351     for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2352       // Note that we know that the preprocessor does not have any annotation
2353       // tokens in it because they are created by the parser, and thus can't
2354       // be in a macro definition.
2355       const Token &Tok = MI->getReplacementToken(TokNo);
2356       AddToken(Tok, Record);
2357       Stream.EmitRecord(PP_TOKEN, Record);
2358       Record.clear();
2359     }
2360     ++NumMacros;
2361   }
2362 
2363   Stream.ExitBlock();
2364 
2365   // Write the offsets table for macro IDs.
2366   using namespace llvm;
2367 
2368   auto Abbrev = std::make_shared<BitCodeAbbrev>();
2369   Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2370   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2371   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2372   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32));   // base offset
2373   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2374 
2375   unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2376   {
2377     RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
2378                                        FirstMacroID - NUM_PREDEF_MACRO_IDS,
2379                                        MacroOffsetsBase - ASTBlockStartOffset};
2380     Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
2381   }
2382 }
2383 
WritePreprocessorDetail(PreprocessingRecord & PPRec,uint64_t MacroOffsetsBase)2384 void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec,
2385                                         uint64_t MacroOffsetsBase) {
2386   if (PPRec.local_begin() == PPRec.local_end())
2387     return;
2388 
2389   SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
2390 
2391   // Enter the preprocessor block.
2392   Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
2393 
2394   // If the preprocessor has a preprocessing record, emit it.
2395   unsigned NumPreprocessingRecords = 0;
2396   using namespace llvm;
2397 
2398   // Set up the abbreviation for
2399   unsigned InclusionAbbrev = 0;
2400   {
2401     auto Abbrev = std::make_shared<BitCodeAbbrev>();
2402     Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
2403     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2404     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2405     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
2406     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
2407     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2408     InclusionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2409   }
2410 
2411   unsigned FirstPreprocessorEntityID
2412     = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
2413     + NUM_PREDEF_PP_ENTITY_IDS;
2414   unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
2415   RecordData Record;
2416   for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2417                                   EEnd = PPRec.local_end();
2418        E != EEnd;
2419        (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
2420     Record.clear();
2421 
2422     uint64_t Offset = Stream.GetCurrentBitNo() - MacroOffsetsBase;
2423     assert((Offset >> 32) == 0 && "Preprocessed entity offset too large");
2424     PreprocessedEntityOffsets.push_back(
2425         PPEntityOffset((*E)->getSourceRange(), Offset));
2426 
2427     if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
2428       // Record this macro definition's ID.
2429       MacroDefinitions[MD] = NextPreprocessorEntityID;
2430 
2431       AddIdentifierRef(MD->getName(), Record);
2432       Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2433       continue;
2434     }
2435 
2436     if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
2437       Record.push_back(ME->isBuiltinMacro());
2438       if (ME->isBuiltinMacro())
2439         AddIdentifierRef(ME->getName(), Record);
2440       else
2441         Record.push_back(MacroDefinitions[ME->getDefinition()]);
2442       Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
2443       continue;
2444     }
2445 
2446     if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
2447       Record.push_back(PPD_INCLUSION_DIRECTIVE);
2448       Record.push_back(ID->getFileName().size());
2449       Record.push_back(ID->wasInQuotes());
2450       Record.push_back(static_cast<unsigned>(ID->getKind()));
2451       Record.push_back(ID->importedModule());
2452       SmallString<64> Buffer;
2453       Buffer += ID->getFileName();
2454       // Check that the FileEntry is not null because it was not resolved and
2455       // we create a PCH even with compiler errors.
2456       if (ID->getFile())
2457         Buffer += ID->getFile()->getName();
2458       Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
2459       continue;
2460     }
2461 
2462     llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2463   }
2464   Stream.ExitBlock();
2465 
2466   // Write the offsets table for the preprocessing record.
2467   if (NumPreprocessingRecords > 0) {
2468     assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2469 
2470     // Write the offsets table for identifier IDs.
2471     using namespace llvm;
2472 
2473     auto Abbrev = std::make_shared<BitCodeAbbrev>();
2474     Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
2475     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
2476     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2477     unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2478 
2479     RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
2480                                        FirstPreprocessorEntityID -
2481                                            NUM_PREDEF_PP_ENTITY_IDS};
2482     Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
2483                               bytes(PreprocessedEntityOffsets));
2484   }
2485 
2486   // Write the skipped region table for the preprocessing record.
2487   ArrayRef<SourceRange> SkippedRanges = PPRec.getSkippedRanges();
2488   if (SkippedRanges.size() > 0) {
2489     std::vector<PPSkippedRange> SerializedSkippedRanges;
2490     SerializedSkippedRanges.reserve(SkippedRanges.size());
2491     for (auto const& Range : SkippedRanges)
2492       SerializedSkippedRanges.emplace_back(Range);
2493 
2494     using namespace llvm;
2495     auto Abbrev = std::make_shared<BitCodeAbbrev>();
2496     Abbrev->Add(BitCodeAbbrevOp(PPD_SKIPPED_RANGES));
2497     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2498     unsigned PPESkippedRangeAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2499 
2500     Record.clear();
2501     Record.push_back(PPD_SKIPPED_RANGES);
2502     Stream.EmitRecordWithBlob(PPESkippedRangeAbbrev, Record,
2503                               bytes(SerializedSkippedRanges));
2504   }
2505 }
2506 
getLocalOrImportedSubmoduleID(const Module * Mod)2507 unsigned ASTWriter::getLocalOrImportedSubmoduleID(const Module *Mod) {
2508   if (!Mod)
2509     return 0;
2510 
2511   auto Known = SubmoduleIDs.find(Mod);
2512   if (Known != SubmoduleIDs.end())
2513     return Known->second;
2514 
2515   auto *Top = Mod->getTopLevelModule();
2516   if (Top != WritingModule &&
2517       (getLangOpts().CompilingPCH ||
2518        !Top->fullModuleNameIs(StringRef(getLangOpts().CurrentModule))))
2519     return 0;
2520 
2521   return SubmoduleIDs[Mod] = NextSubmoduleID++;
2522 }
2523 
getSubmoduleID(Module * Mod)2524 unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2525   // FIXME: This can easily happen, if we have a reference to a submodule that
2526   // did not result in us loading a module file for that submodule. For
2527   // instance, a cross-top-level-module 'conflict' declaration will hit this.
2528   unsigned ID = getLocalOrImportedSubmoduleID(Mod);
2529   assert((ID || !Mod) &&
2530          "asked for module ID for non-local, non-imported module");
2531   return ID;
2532 }
2533 
2534 /// Compute the number of modules within the given tree (including the
2535 /// given module).
getNumberOfModules(Module * Mod)2536 static unsigned getNumberOfModules(Module *Mod) {
2537   unsigned ChildModules = 0;
2538   for (auto Sub = Mod->submodule_begin(), SubEnd = Mod->submodule_end();
2539        Sub != SubEnd; ++Sub)
2540     ChildModules += getNumberOfModules(*Sub);
2541 
2542   return ChildModules + 1;
2543 }
2544 
WriteSubmodules(Module * WritingModule)2545 void ASTWriter::WriteSubmodules(Module *WritingModule) {
2546   // Enter the submodule description block.
2547   Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
2548 
2549   // Write the abbreviations needed for the submodules block.
2550   using namespace llvm;
2551 
2552   auto Abbrev = std::make_shared<BitCodeAbbrev>();
2553   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
2554   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
2555   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
2556   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Kind
2557   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2558   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
2559   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2560   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
2561   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
2562   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
2563   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
2564   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
2565   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ModuleMapIsPriv...
2566   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2567   unsigned DefinitionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2568 
2569   Abbrev = std::make_shared<BitCodeAbbrev>();
2570   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
2571   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2572   unsigned UmbrellaAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2573 
2574   Abbrev = std::make_shared<BitCodeAbbrev>();
2575   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2576   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2577   unsigned HeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2578 
2579   Abbrev = std::make_shared<BitCodeAbbrev>();
2580   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2581   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2582   unsigned TopHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2583 
2584   Abbrev = std::make_shared<BitCodeAbbrev>();
2585   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2586   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2587   unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2588 
2589   Abbrev = std::make_shared<BitCodeAbbrev>();
2590   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
2591   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2592   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));     // Feature
2593   unsigned RequiresAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2594 
2595   Abbrev = std::make_shared<BitCodeAbbrev>();
2596   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2597   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2598   unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2599 
2600   Abbrev = std::make_shared<BitCodeAbbrev>();
2601   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
2602   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2603   unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2604 
2605   Abbrev = std::make_shared<BitCodeAbbrev>();
2606   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2607   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2608   unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2609 
2610   Abbrev = std::make_shared<BitCodeAbbrev>();
2611   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
2612   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2613   unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2614 
2615   Abbrev = std::make_shared<BitCodeAbbrev>();
2616   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2617   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2618   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));     // Name
2619   unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2620 
2621   Abbrev = std::make_shared<BitCodeAbbrev>();
2622   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2623   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));    // Macro name
2624   unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2625 
2626   Abbrev = std::make_shared<BitCodeAbbrev>();
2627   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2628   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));  // Other module
2629   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));    // Message
2630   unsigned ConflictAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2631 
2632   Abbrev = std::make_shared<BitCodeAbbrev>();
2633   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXPORT_AS));
2634   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));    // Macro name
2635   unsigned ExportAsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2636 
2637   // Write the submodule metadata block.
2638   RecordData::value_type Record[] = {
2639       getNumberOfModules(WritingModule),
2640       FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS};
2641   Stream.EmitRecord(SUBMODULE_METADATA, Record);
2642 
2643   // Write all of the submodules.
2644   std::queue<Module *> Q;
2645   Q.push(WritingModule);
2646   while (!Q.empty()) {
2647     Module *Mod = Q.front();
2648     Q.pop();
2649     unsigned ID = getSubmoduleID(Mod);
2650 
2651     uint64_t ParentID = 0;
2652     if (Mod->Parent) {
2653       assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
2654       ParentID = SubmoduleIDs[Mod->Parent];
2655     }
2656 
2657     // Emit the definition of the block.
2658     {
2659       RecordData::value_type Record[] = {SUBMODULE_DEFINITION,
2660                                          ID,
2661                                          ParentID,
2662                                          (RecordData::value_type)Mod->Kind,
2663                                          Mod->IsFramework,
2664                                          Mod->IsExplicit,
2665                                          Mod->IsSystem,
2666                                          Mod->IsExternC,
2667                                          Mod->InferSubmodules,
2668                                          Mod->InferExplicitSubmodules,
2669                                          Mod->InferExportWildcard,
2670                                          Mod->ConfigMacrosExhaustive,
2671                                          Mod->ModuleMapIsPrivate};
2672       Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2673     }
2674 
2675     // Emit the requirements.
2676     for (const auto &R : Mod->Requirements) {
2677       RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.second};
2678       Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.first);
2679     }
2680 
2681     // Emit the umbrella header, if there is one.
2682     if (auto UmbrellaHeader = Mod->getUmbrellaHeader()) {
2683       RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
2684       Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2685                                 UmbrellaHeader.NameAsWritten);
2686     } else if (auto UmbrellaDir = Mod->getUmbrellaDir()) {
2687       RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
2688       Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
2689                                 UmbrellaDir.NameAsWritten);
2690     }
2691 
2692     // Emit the headers.
2693     struct {
2694       unsigned RecordKind;
2695       unsigned Abbrev;
2696       Module::HeaderKind HeaderKind;
2697     } HeaderLists[] = {
2698       {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
2699       {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
2700       {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
2701       {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
2702         Module::HK_PrivateTextual},
2703       {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
2704     };
2705     for (auto &HL : HeaderLists) {
2706       RecordData::value_type Record[] = {HL.RecordKind};
2707       for (auto &H : Mod->Headers[HL.HeaderKind])
2708         Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
2709     }
2710 
2711     // Emit the top headers.
2712     {
2713       auto TopHeaders = Mod->getTopHeaders(PP->getFileManager());
2714       RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
2715       for (auto *H : TopHeaders)
2716         Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, H->getName());
2717     }
2718 
2719     // Emit the imports.
2720     if (!Mod->Imports.empty()) {
2721       RecordData Record;
2722       for (auto *I : Mod->Imports)
2723         Record.push_back(getSubmoduleID(I));
2724       Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2725     }
2726 
2727     // Emit the exports.
2728     if (!Mod->Exports.empty()) {
2729       RecordData Record;
2730       for (const auto &E : Mod->Exports) {
2731         // FIXME: This may fail; we don't require that all exported modules
2732         // are local or imported.
2733         Record.push_back(getSubmoduleID(E.getPointer()));
2734         Record.push_back(E.getInt());
2735       }
2736       Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2737     }
2738 
2739     //FIXME: How do we emit the 'use'd modules?  They may not be submodules.
2740     // Might be unnecessary as use declarations are only used to build the
2741     // module itself.
2742 
2743     // Emit the link libraries.
2744     for (const auto &LL : Mod->LinkLibraries) {
2745       RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
2746                                          LL.IsFramework};
2747       Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library);
2748     }
2749 
2750     // Emit the conflicts.
2751     for (const auto &C : Mod->Conflicts) {
2752       // FIXME: This may fail; we don't require that all conflicting modules
2753       // are local or imported.
2754       RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
2755                                          getSubmoduleID(C.Other)};
2756       Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message);
2757     }
2758 
2759     // Emit the configuration macros.
2760     for (const auto &CM : Mod->ConfigMacros) {
2761       RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
2762       Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM);
2763     }
2764 
2765     // Emit the initializers, if any.
2766     RecordData Inits;
2767     for (Decl *D : Context->getModuleInitializers(Mod))
2768       Inits.push_back(GetDeclRef(D));
2769     if (!Inits.empty())
2770       Stream.EmitRecord(SUBMODULE_INITIALIZERS, Inits);
2771 
2772     // Emit the name of the re-exported module, if any.
2773     if (!Mod->ExportAsModule.empty()) {
2774       RecordData::value_type Record[] = {SUBMODULE_EXPORT_AS};
2775       Stream.EmitRecordWithBlob(ExportAsAbbrev, Record, Mod->ExportAsModule);
2776     }
2777 
2778     // Queue up the submodules of this module.
2779     for (auto *M : Mod->submodules())
2780       Q.push(M);
2781   }
2782 
2783   Stream.ExitBlock();
2784 
2785   assert((NextSubmoduleID - FirstSubmoduleID ==
2786           getNumberOfModules(WritingModule)) &&
2787          "Wrong # of submodules; found a reference to a non-local, "
2788          "non-imported submodule?");
2789 }
2790 
WritePragmaDiagnosticMappings(const DiagnosticsEngine & Diag,bool isModule)2791 void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
2792                                               bool isModule) {
2793   llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
2794       DiagStateIDMap;
2795   unsigned CurrID = 0;
2796   RecordData Record;
2797 
2798   auto EncodeDiagStateFlags =
2799       [](const DiagnosticsEngine::DiagState *DS) -> unsigned {
2800     unsigned Result = (unsigned)DS->ExtBehavior;
2801     for (unsigned Val :
2802          {(unsigned)DS->IgnoreAllWarnings, (unsigned)DS->EnableAllWarnings,
2803           (unsigned)DS->WarningsAsErrors, (unsigned)DS->ErrorsAsFatal,
2804           (unsigned)DS->SuppressSystemWarnings})
2805       Result = (Result << 1) | Val;
2806     return Result;
2807   };
2808 
2809   unsigned Flags = EncodeDiagStateFlags(Diag.DiagStatesByLoc.FirstDiagState);
2810   Record.push_back(Flags);
2811 
2812   auto AddDiagState = [&](const DiagnosticsEngine::DiagState *State,
2813                           bool IncludeNonPragmaStates) {
2814     // Ensure that the diagnostic state wasn't modified since it was created.
2815     // We will not correctly round-trip this information otherwise.
2816     assert(Flags == EncodeDiagStateFlags(State) &&
2817            "diag state flags vary in single AST file");
2818 
2819     unsigned &DiagStateID = DiagStateIDMap[State];
2820     Record.push_back(DiagStateID);
2821 
2822     if (DiagStateID == 0) {
2823       DiagStateID = ++CurrID;
2824 
2825       // Add a placeholder for the number of mappings.
2826       auto SizeIdx = Record.size();
2827       Record.emplace_back();
2828       for (const auto &I : *State) {
2829         if (I.second.isPragma() || IncludeNonPragmaStates) {
2830           Record.push_back(I.first);
2831           Record.push_back(I.second.serialize());
2832         }
2833       }
2834       // Update the placeholder.
2835       Record[SizeIdx] = (Record.size() - SizeIdx) / 2;
2836     }
2837   };
2838 
2839   AddDiagState(Diag.DiagStatesByLoc.FirstDiagState, isModule);
2840 
2841   // Reserve a spot for the number of locations with state transitions.
2842   auto NumLocationsIdx = Record.size();
2843   Record.emplace_back();
2844 
2845   // Emit the state transitions.
2846   unsigned NumLocations = 0;
2847   for (auto &FileIDAndFile : Diag.DiagStatesByLoc.Files) {
2848     if (!FileIDAndFile.first.isValid() ||
2849         !FileIDAndFile.second.HasLocalTransitions)
2850       continue;
2851     ++NumLocations;
2852 
2853     SourceLocation Loc = Diag.SourceMgr->getComposedLoc(FileIDAndFile.first, 0);
2854     assert(!Loc.isInvalid() && "start loc for valid FileID is invalid");
2855     AddSourceLocation(Loc, Record);
2856 
2857     Record.push_back(FileIDAndFile.second.StateTransitions.size());
2858     for (auto &StatePoint : FileIDAndFile.second.StateTransitions) {
2859       Record.push_back(StatePoint.Offset);
2860       AddDiagState(StatePoint.State, false);
2861     }
2862   }
2863 
2864   // Backpatch the number of locations.
2865   Record[NumLocationsIdx] = NumLocations;
2866 
2867   // Emit CurDiagStateLoc.  Do it last in order to match source order.
2868   //
2869   // This also protects against a hypothetical corner case with simulating
2870   // -Werror settings for implicit modules in the ASTReader, where reading
2871   // CurDiagState out of context could change whether warning pragmas are
2872   // treated as errors.
2873   AddSourceLocation(Diag.DiagStatesByLoc.CurDiagStateLoc, Record);
2874   AddDiagState(Diag.DiagStatesByLoc.CurDiagState, false);
2875 
2876   Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
2877 }
2878 
2879 //===----------------------------------------------------------------------===//
2880 // Type Serialization
2881 //===----------------------------------------------------------------------===//
2882 
2883 /// Write the representation of a type to the AST stream.
WriteType(QualType T)2884 void ASTWriter::WriteType(QualType T) {
2885   TypeIdx &IdxRef = TypeIdxs[T];
2886   if (IdxRef.getIndex() == 0) // we haven't seen this type before.
2887     IdxRef = TypeIdx(NextTypeID++);
2888   TypeIdx Idx = IdxRef;
2889 
2890   assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
2891 
2892   // Emit the type's representation.
2893   uint64_t Offset = ASTTypeWriter(*this).write(T) - DeclTypesBlockStartOffset;
2894 
2895   // Record the offset for this type.
2896   unsigned Index = Idx.getIndex() - FirstTypeID;
2897   if (TypeOffsets.size() == Index)
2898     TypeOffsets.emplace_back(Offset);
2899   else if (TypeOffsets.size() < Index) {
2900     TypeOffsets.resize(Index + 1);
2901     TypeOffsets[Index].setBitOffset(Offset);
2902   } else {
2903     llvm_unreachable("Types emitted in wrong order");
2904   }
2905 }
2906 
2907 //===----------------------------------------------------------------------===//
2908 // Declaration Serialization
2909 //===----------------------------------------------------------------------===//
2910 
2911 /// Write the block containing all of the declaration IDs
2912 /// lexically declared within the given DeclContext.
2913 ///
2914 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
2915 /// bitstream, or 0 if no block was written.
WriteDeclContextLexicalBlock(ASTContext & Context,DeclContext * DC)2916 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
2917                                                  DeclContext *DC) {
2918   if (DC->decls_empty())
2919     return 0;
2920 
2921   uint64_t Offset = Stream.GetCurrentBitNo();
2922   SmallVector<uint32_t, 128> KindDeclPairs;
2923   for (const auto *D : DC->decls()) {
2924     KindDeclPairs.push_back(D->getKind());
2925     KindDeclPairs.push_back(GetDeclRef(D));
2926   }
2927 
2928   ++NumLexicalDeclContexts;
2929   RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
2930   Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
2931                             bytes(KindDeclPairs));
2932   return Offset;
2933 }
2934 
WriteTypeDeclOffsets()2935 void ASTWriter::WriteTypeDeclOffsets() {
2936   using namespace llvm;
2937 
2938   // Write the type offsets array
2939   auto Abbrev = std::make_shared<BitCodeAbbrev>();
2940   Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
2941   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
2942   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
2943   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
2944   unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2945   {
2946     RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(),
2947                                        FirstTypeID - NUM_PREDEF_TYPE_IDS};
2948     Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
2949   }
2950 
2951   // Write the declaration offsets array
2952   Abbrev = std::make_shared<BitCodeAbbrev>();
2953   Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
2954   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
2955   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
2956   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
2957   unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2958   {
2959     RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(),
2960                                        FirstDeclID - NUM_PREDEF_DECL_IDS};
2961     Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
2962   }
2963 }
2964 
WriteFileDeclIDsMap()2965 void ASTWriter::WriteFileDeclIDsMap() {
2966   using namespace llvm;
2967 
2968   SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs;
2969   SortedFileDeclIDs.reserve(FileDeclIDs.size());
2970   for (const auto &P : FileDeclIDs)
2971     SortedFileDeclIDs.push_back(std::make_pair(P.first, P.second.get()));
2972   llvm::sort(SortedFileDeclIDs, llvm::less_first());
2973 
2974   // Join the vectors of DeclIDs from all files.
2975   SmallVector<DeclID, 256> FileGroupedDeclIDs;
2976   for (auto &FileDeclEntry : SortedFileDeclIDs) {
2977     DeclIDInFileInfo &Info = *FileDeclEntry.second;
2978     Info.FirstDeclIndex = FileGroupedDeclIDs.size();
2979     for (auto &LocDeclEntry : Info.DeclIDs)
2980       FileGroupedDeclIDs.push_back(LocDeclEntry.second);
2981   }
2982 
2983   auto Abbrev = std::make_shared<BitCodeAbbrev>();
2984   Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
2985   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2986   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2987   unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
2988   RecordData::value_type Record[] = {FILE_SORTED_DECLS,
2989                                      FileGroupedDeclIDs.size()};
2990   Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
2991 }
2992 
WriteComments()2993 void ASTWriter::WriteComments() {
2994   Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
2995   auto _ = llvm::make_scope_exit([this] { Stream.ExitBlock(); });
2996   if (!PP->getPreprocessorOpts().WriteCommentListToPCH)
2997     return;
2998   RecordData Record;
2999   for (const auto &FO : Context->Comments.OrderedComments) {
3000     for (const auto &OC : FO.second) {
3001       const RawComment *I = OC.second;
3002       Record.clear();
3003       AddSourceRange(I->getSourceRange(), Record);
3004       Record.push_back(I->getKind());
3005       Record.push_back(I->isTrailingComment());
3006       Record.push_back(I->isAlmostTrailingComment());
3007       Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
3008     }
3009   }
3010 }
3011 
3012 //===----------------------------------------------------------------------===//
3013 // Global Method Pool and Selector Serialization
3014 //===----------------------------------------------------------------------===//
3015 
3016 namespace {
3017 
3018 // Trait used for the on-disk hash table used in the method pool.
3019 class ASTMethodPoolTrait {
3020   ASTWriter &Writer;
3021 
3022 public:
3023   using key_type = Selector;
3024   using key_type_ref = key_type;
3025 
3026   struct data_type {
3027     SelectorID ID;
3028     ObjCMethodList Instance, Factory;
3029   };
3030   using data_type_ref = const data_type &;
3031 
3032   using hash_value_type = unsigned;
3033   using offset_type = unsigned;
3034 
ASTMethodPoolTrait(ASTWriter & Writer)3035   explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) {}
3036 
ComputeHash(Selector Sel)3037   static hash_value_type ComputeHash(Selector Sel) {
3038     return serialization::ComputeHash(Sel);
3039   }
3040 
3041   std::pair<unsigned, unsigned>
EmitKeyDataLength(raw_ostream & Out,Selector Sel,data_type_ref Methods)3042     EmitKeyDataLength(raw_ostream& Out, Selector Sel,
3043                       data_type_ref Methods) {
3044     unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
3045     unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
3046     for (const ObjCMethodList *Method = &Methods.Instance; Method;
3047          Method = Method->getNext())
3048       if (Method->getMethod())
3049         DataLen += 4;
3050     for (const ObjCMethodList *Method = &Methods.Factory; Method;
3051          Method = Method->getNext())
3052       if (Method->getMethod())
3053         DataLen += 4;
3054     return emitULEBKeyDataLength(KeyLen, DataLen, Out);
3055   }
3056 
EmitKey(raw_ostream & Out,Selector Sel,unsigned)3057   void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
3058     using namespace llvm::support;
3059 
3060     endian::Writer LE(Out, little);
3061     uint64_t Start = Out.tell();
3062     assert((Start >> 32) == 0 && "Selector key offset too large");
3063     Writer.SetSelectorOffset(Sel, Start);
3064     unsigned N = Sel.getNumArgs();
3065     LE.write<uint16_t>(N);
3066     if (N == 0)
3067       N = 1;
3068     for (unsigned I = 0; I != N; ++I)
3069       LE.write<uint32_t>(
3070           Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
3071   }
3072 
EmitData(raw_ostream & Out,key_type_ref,data_type_ref Methods,unsigned DataLen)3073   void EmitData(raw_ostream& Out, key_type_ref,
3074                 data_type_ref Methods, unsigned DataLen) {
3075     using namespace llvm::support;
3076 
3077     endian::Writer LE(Out, little);
3078     uint64_t Start = Out.tell(); (void)Start;
3079     LE.write<uint32_t>(Methods.ID);
3080     unsigned NumInstanceMethods = 0;
3081     for (const ObjCMethodList *Method = &Methods.Instance; Method;
3082          Method = Method->getNext())
3083       if (Method->getMethod())
3084         ++NumInstanceMethods;
3085 
3086     unsigned NumFactoryMethods = 0;
3087     for (const ObjCMethodList *Method = &Methods.Factory; Method;
3088          Method = Method->getNext())
3089       if (Method->getMethod())
3090         ++NumFactoryMethods;
3091 
3092     unsigned InstanceBits = Methods.Instance.getBits();
3093     assert(InstanceBits < 4);
3094     unsigned InstanceHasMoreThanOneDeclBit =
3095         Methods.Instance.hasMoreThanOneDecl();
3096     unsigned FullInstanceBits = (NumInstanceMethods << 3) |
3097                                 (InstanceHasMoreThanOneDeclBit << 2) |
3098                                 InstanceBits;
3099     unsigned FactoryBits = Methods.Factory.getBits();
3100     assert(FactoryBits < 4);
3101     unsigned FactoryHasMoreThanOneDeclBit =
3102         Methods.Factory.hasMoreThanOneDecl();
3103     unsigned FullFactoryBits = (NumFactoryMethods << 3) |
3104                                (FactoryHasMoreThanOneDeclBit << 2) |
3105                                FactoryBits;
3106     LE.write<uint16_t>(FullInstanceBits);
3107     LE.write<uint16_t>(FullFactoryBits);
3108     for (const ObjCMethodList *Method = &Methods.Instance; Method;
3109          Method = Method->getNext())
3110       if (Method->getMethod())
3111         LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
3112     for (const ObjCMethodList *Method = &Methods.Factory; Method;
3113          Method = Method->getNext())
3114       if (Method->getMethod())
3115         LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
3116 
3117     assert(Out.tell() - Start == DataLen && "Data length is wrong");
3118   }
3119 };
3120 
3121 } // namespace
3122 
3123 /// Write ObjC data: selectors and the method pool.
3124 ///
3125 /// The method pool contains both instance and factory methods, stored
3126 /// in an on-disk hash table indexed by the selector. The hash table also
3127 /// contains an empty entry for every other selector known to Sema.
WriteSelectors(Sema & SemaRef)3128 void ASTWriter::WriteSelectors(Sema &SemaRef) {
3129   using namespace llvm;
3130 
3131   // Do we have to do anything at all?
3132   if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
3133     return;
3134   unsigned NumTableEntries = 0;
3135   // Create and write out the blob that contains selectors and the method pool.
3136   {
3137     llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
3138     ASTMethodPoolTrait Trait(*this);
3139 
3140     // Create the on-disk hash table representation. We walk through every
3141     // selector we've seen and look it up in the method pool.
3142     SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
3143     for (auto &SelectorAndID : SelectorIDs) {
3144       Selector S = SelectorAndID.first;
3145       SelectorID ID = SelectorAndID.second;
3146       Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
3147       ASTMethodPoolTrait::data_type Data = {
3148         ID,
3149         ObjCMethodList(),
3150         ObjCMethodList()
3151       };
3152       if (F != SemaRef.MethodPool.end()) {
3153         Data.Instance = F->second.first;
3154         Data.Factory = F->second.second;
3155       }
3156       // Only write this selector if it's not in an existing AST or something
3157       // changed.
3158       if (Chain && ID < FirstSelectorID) {
3159         // Selector already exists. Did it change?
3160         bool changed = false;
3161         for (ObjCMethodList *M = &Data.Instance;
3162              !changed && M && M->getMethod(); M = M->getNext()) {
3163           if (!M->getMethod()->isFromASTFile())
3164             changed = true;
3165         }
3166         for (ObjCMethodList *M = &Data.Factory; !changed && M && M->getMethod();
3167              M = M->getNext()) {
3168           if (!M->getMethod()->isFromASTFile())
3169             changed = true;
3170         }
3171         if (!changed)
3172           continue;
3173       } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
3174         // A new method pool entry.
3175         ++NumTableEntries;
3176       }
3177       Generator.insert(S, Data, Trait);
3178     }
3179 
3180     // Create the on-disk hash table in a buffer.
3181     SmallString<4096> MethodPool;
3182     uint32_t BucketOffset;
3183     {
3184       using namespace llvm::support;
3185 
3186       ASTMethodPoolTrait Trait(*this);
3187       llvm::raw_svector_ostream Out(MethodPool);
3188       // Make sure that no bucket is at offset 0
3189       endian::write<uint32_t>(Out, 0, little);
3190       BucketOffset = Generator.Emit(Out, Trait);
3191     }
3192 
3193     // Create a blob abbreviation
3194     auto Abbrev = std::make_shared<BitCodeAbbrev>();
3195     Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
3196     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3197     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3198     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3199     unsigned MethodPoolAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3200 
3201     // Write the method pool
3202     {
3203       RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3204                                          NumTableEntries};
3205       Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3206     }
3207 
3208     // Create a blob abbreviation for the selector table offsets.
3209     Abbrev = std::make_shared<BitCodeAbbrev>();
3210     Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
3211     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
3212     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3213     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3214     unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3215 
3216     // Write the selector offsets table.
3217     {
3218       RecordData::value_type Record[] = {
3219           SELECTOR_OFFSETS, SelectorOffsets.size(),
3220           FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3221       Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3222                                 bytes(SelectorOffsets));
3223     }
3224   }
3225 }
3226 
3227 /// Write the selectors referenced in @selector expression into AST file.
WriteReferencedSelectorsPool(Sema & SemaRef)3228 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
3229   using namespace llvm;
3230 
3231   if (SemaRef.ReferencedSelectors.empty())
3232     return;
3233 
3234   RecordData Record;
3235   ASTRecordWriter Writer(*this, Record);
3236 
3237   // Note: this writes out all references even for a dependent AST. But it is
3238   // very tricky to fix, and given that @selector shouldn't really appear in
3239   // headers, probably not worth it. It's not a correctness issue.
3240   for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
3241     Selector Sel = SelectorAndLocation.first;
3242     SourceLocation Loc = SelectorAndLocation.second;
3243     Writer.AddSelectorRef(Sel);
3244     Writer.AddSourceLocation(Loc);
3245   }
3246   Writer.Emit(REFERENCED_SELECTOR_POOL);
3247 }
3248 
3249 //===----------------------------------------------------------------------===//
3250 // Identifier Table Serialization
3251 //===----------------------------------------------------------------------===//
3252 
3253 /// Determine the declaration that should be put into the name lookup table to
3254 /// represent the given declaration in this module. This is usually D itself,
3255 /// but if D was imported and merged into a local declaration, we want the most
3256 /// recent local declaration instead. The chosen declaration will be the most
3257 /// recent declaration in any module that imports this one.
getDeclForLocalLookup(const LangOptions & LangOpts,NamedDecl * D)3258 static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
3259                                         NamedDecl *D) {
3260   if (!LangOpts.Modules || !D->isFromASTFile())
3261     return D;
3262 
3263   if (Decl *Redecl = D->getPreviousDecl()) {
3264     // For Redeclarable decls, a prior declaration might be local.
3265     for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
3266       // If we find a local decl, we're done.
3267       if (!Redecl->isFromASTFile()) {
3268         // Exception: in very rare cases (for injected-class-names), not all
3269         // redeclarations are in the same semantic context. Skip ones in a
3270         // different context. They don't go in this lookup table at all.
3271         if (!Redecl->getDeclContext()->getRedeclContext()->Equals(
3272                 D->getDeclContext()->getRedeclContext()))
3273           continue;
3274         return cast<NamedDecl>(Redecl);
3275       }
3276 
3277       // If we find a decl from a (chained-)PCH stop since we won't find a
3278       // local one.
3279       if (Redecl->getOwningModuleID() == 0)
3280         break;
3281     }
3282   } else if (Decl *First = D->getCanonicalDecl()) {
3283     // For Mergeable decls, the first decl might be local.
3284     if (!First->isFromASTFile())
3285       return cast<NamedDecl>(First);
3286   }
3287 
3288   // All declarations are imported. Our most recent declaration will also be
3289   // the most recent one in anyone who imports us.
3290   return D;
3291 }
3292 
3293 namespace {
3294 
3295 class ASTIdentifierTableTrait {
3296   ASTWriter &Writer;
3297   Preprocessor &PP;
3298   IdentifierResolver &IdResolver;
3299   bool IsModule;
3300   bool NeedDecls;
3301   ASTWriter::RecordData *InterestingIdentifierOffsets;
3302 
3303   /// Determines whether this is an "interesting" identifier that needs a
3304   /// full IdentifierInfo structure written into the hash table. Notably, this
3305   /// doesn't check whether the name has macros defined; use PublicMacroIterator
3306   /// to check that.
isInterestingIdentifier(const IdentifierInfo * II,uint64_t MacroOffset)3307   bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
3308     if (MacroOffset || II->isPoisoned() ||
3309         (!IsModule && II->getObjCOrBuiltinID()) ||
3310         II->hasRevertedTokenIDToIdentifier() ||
3311         (NeedDecls && II->getFETokenInfo()))
3312       return true;
3313 
3314     return false;
3315   }
3316 
3317 public:
3318   using key_type = IdentifierInfo *;
3319   using key_type_ref = key_type;
3320 
3321   using data_type = IdentID;
3322   using data_type_ref = data_type;
3323 
3324   using hash_value_type = unsigned;
3325   using offset_type = unsigned;
3326 
ASTIdentifierTableTrait(ASTWriter & Writer,Preprocessor & PP,IdentifierResolver & IdResolver,bool IsModule,ASTWriter::RecordData * InterestingIdentifierOffsets)3327   ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
3328                           IdentifierResolver &IdResolver, bool IsModule,
3329                           ASTWriter::RecordData *InterestingIdentifierOffsets)
3330       : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
3331         NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3332         InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
3333 
needDecls() const3334   bool needDecls() const { return NeedDecls; }
3335 
ComputeHash(const IdentifierInfo * II)3336   static hash_value_type ComputeHash(const IdentifierInfo* II) {
3337     return llvm::djbHash(II->getName());
3338   }
3339 
isInterestingIdentifier(const IdentifierInfo * II)3340   bool isInterestingIdentifier(const IdentifierInfo *II) {
3341     auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3342     return isInterestingIdentifier(II, MacroOffset);
3343   }
3344 
isInterestingNonMacroIdentifier(const IdentifierInfo * II)3345   bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) {
3346     return isInterestingIdentifier(II, 0);
3347   }
3348 
3349   std::pair<unsigned, unsigned>
EmitKeyDataLength(raw_ostream & Out,IdentifierInfo * II,IdentID ID)3350   EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
3351     // Record the location of the identifier data. This is used when generating
3352     // the mapping from persistent IDs to strings.
3353     Writer.SetIdentifierOffset(II, Out.tell());
3354 
3355     // Emit the offset of the key/data length information to the interesting
3356     // identifiers table if necessary.
3357     if (InterestingIdentifierOffsets && isInterestingIdentifier(II))
3358       InterestingIdentifierOffsets->push_back(Out.tell());
3359 
3360     unsigned KeyLen = II->getLength() + 1;
3361     unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
3362     auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3363     if (isInterestingIdentifier(II, MacroOffset)) {
3364       DataLen += 2; // 2 bytes for builtin ID
3365       DataLen += 2; // 2 bytes for flags
3366       if (MacroOffset)
3367         DataLen += 4; // MacroDirectives offset.
3368 
3369       if (NeedDecls) {
3370         for (IdentifierResolver::iterator D = IdResolver.begin(II),
3371                                        DEnd = IdResolver.end();
3372              D != DEnd; ++D)
3373           DataLen += 4;
3374       }
3375     }
3376     return emitULEBKeyDataLength(KeyLen, DataLen, Out);
3377   }
3378 
EmitKey(raw_ostream & Out,const IdentifierInfo * II,unsigned KeyLen)3379   void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
3380                unsigned KeyLen) {
3381     Out.write(II->getNameStart(), KeyLen);
3382   }
3383 
EmitData(raw_ostream & Out,IdentifierInfo * II,IdentID ID,unsigned)3384   void EmitData(raw_ostream& Out, IdentifierInfo* II,
3385                 IdentID ID, unsigned) {
3386     using namespace llvm::support;
3387 
3388     endian::Writer LE(Out, little);
3389 
3390     auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3391     if (!isInterestingIdentifier(II, MacroOffset)) {
3392       LE.write<uint32_t>(ID << 1);
3393       return;
3394     }
3395 
3396     LE.write<uint32_t>((ID << 1) | 0x01);
3397     uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3398     assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
3399     LE.write<uint16_t>(Bits);
3400     Bits = 0;
3401     bool HadMacroDefinition = MacroOffset != 0;
3402     Bits = (Bits << 1) | unsigned(HadMacroDefinition);
3403     Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3404     Bits = (Bits << 1) | unsigned(II->isPoisoned());
3405     Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
3406     Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
3407     LE.write<uint16_t>(Bits);
3408 
3409     if (HadMacroDefinition)
3410       LE.write<uint32_t>(MacroOffset);
3411 
3412     if (NeedDecls) {
3413       // Emit the declaration IDs in reverse order, because the
3414       // IdentifierResolver provides the declarations as they would be
3415       // visible (e.g., the function "stat" would come before the struct
3416       // "stat"), but the ASTReader adds declarations to the end of the list
3417       // (so we need to see the struct "stat" before the function "stat").
3418       // Only emit declarations that aren't from a chained PCH, though.
3419       SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II),
3420                                          IdResolver.end());
3421       for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(),
3422                                                           DEnd = Decls.rend();
3423            D != DEnd; ++D)
3424         LE.write<uint32_t>(
3425             Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D)));
3426     }
3427   }
3428 };
3429 
3430 } // namespace
3431 
3432 /// Write the identifier table into the AST file.
3433 ///
3434 /// The identifier table consists of a blob containing string data
3435 /// (the actual identifiers themselves) and a separate "offsets" index
3436 /// that maps identifier IDs to locations within the blob.
WriteIdentifierTable(Preprocessor & PP,IdentifierResolver & IdResolver,bool IsModule)3437 void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3438                                      IdentifierResolver &IdResolver,
3439                                      bool IsModule) {
3440   using namespace llvm;
3441 
3442   RecordData InterestingIdents;
3443 
3444   // Create and write out the blob that contains the identifier
3445   // strings.
3446   {
3447     llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
3448     ASTIdentifierTableTrait Trait(
3449         *this, PP, IdResolver, IsModule,
3450         (getLangOpts().CPlusPlus && IsModule) ? &InterestingIdents : nullptr);
3451 
3452     // Look for any identifiers that were named while processing the
3453     // headers, but are otherwise not needed. We add these to the hash
3454     // table to enable checking of the predefines buffer in the case
3455     // where the user adds new macro definitions when building the AST
3456     // file.
3457     SmallVector<const IdentifierInfo *, 128> IIs;
3458     for (const auto &ID : PP.getIdentifierTable())
3459       IIs.push_back(ID.second);
3460     // Sort the identifiers lexicographically before getting them references so
3461     // that their order is stable.
3462     llvm::sort(IIs, llvm::deref<std::less<>>());
3463     for (const IdentifierInfo *II : IIs)
3464       if (Trait.isInterestingNonMacroIdentifier(II))
3465         getIdentifierRef(II);
3466 
3467     // Create the on-disk hash table representation. We only store offsets
3468     // for identifiers that appear here for the first time.
3469     IdentifierOffsets.resize(NextIdentID - FirstIdentID);
3470     for (auto IdentIDPair : IdentifierIDs) {
3471       auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
3472       IdentID ID = IdentIDPair.second;
3473       assert(II && "NULL identifier in identifier table");
3474       // Write out identifiers if either the ID is local or the identifier has
3475       // changed since it was loaded.
3476       if (ID >= FirstIdentID || !Chain || !II->isFromAST()
3477           || II->hasChangedSinceDeserialization() ||
3478           (Trait.needDecls() &&
3479            II->hasFETokenInfoChangedSinceDeserialization()))
3480         Generator.insert(II, ID, Trait);
3481     }
3482 
3483     // Create the on-disk hash table in a buffer.
3484     SmallString<4096> IdentifierTable;
3485     uint32_t BucketOffset;
3486     {
3487       using namespace llvm::support;
3488 
3489       llvm::raw_svector_ostream Out(IdentifierTable);
3490       // Make sure that no bucket is at offset 0
3491       endian::write<uint32_t>(Out, 0, little);
3492       BucketOffset = Generator.Emit(Out, Trait);
3493     }
3494 
3495     // Create a blob abbreviation
3496     auto Abbrev = std::make_shared<BitCodeAbbrev>();
3497     Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
3498     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3499     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3500     unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3501 
3502     // Write the identifier table
3503     RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
3504     Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
3505   }
3506 
3507   // Write the offsets table for identifier IDs.
3508   auto Abbrev = std::make_shared<BitCodeAbbrev>();
3509   Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
3510   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
3511   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3512   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3513   unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3514 
3515 #ifndef NDEBUG
3516   for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3517     assert(IdentifierOffsets[I] && "Missing identifier offset?");
3518 #endif
3519 
3520   RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
3521                                      IdentifierOffsets.size(),
3522                                      FirstIdentID - NUM_PREDEF_IDENT_IDS};
3523   Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
3524                             bytes(IdentifierOffsets));
3525 
3526   // In C++, write the list of interesting identifiers (those that are
3527   // defined as macros, poisoned, or similar unusual things).
3528   if (!InterestingIdents.empty())
3529     Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
3530 }
3531 
3532 //===----------------------------------------------------------------------===//
3533 // DeclContext's Name Lookup Table Serialization
3534 //===----------------------------------------------------------------------===//
3535 
3536 namespace {
3537 
3538 // Trait used for the on-disk hash table used in the method pool.
3539 class ASTDeclContextNameLookupTrait {
3540   ASTWriter &Writer;
3541   llvm::SmallVector<DeclID, 64> DeclIDs;
3542 
3543 public:
3544   using key_type = DeclarationNameKey;
3545   using key_type_ref = key_type;
3546 
3547   /// A start and end index into DeclIDs, representing a sequence of decls.
3548   using data_type = std::pair<unsigned, unsigned>;
3549   using data_type_ref = const data_type &;
3550 
3551   using hash_value_type = unsigned;
3552   using offset_type = unsigned;
3553 
ASTDeclContextNameLookupTrait(ASTWriter & Writer)3554   explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) {}
3555 
3556   template<typename Coll>
getData(const Coll & Decls)3557   data_type getData(const Coll &Decls) {
3558     unsigned Start = DeclIDs.size();
3559     for (NamedDecl *D : Decls) {
3560       DeclIDs.push_back(
3561           Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3562     }
3563     return std::make_pair(Start, DeclIDs.size());
3564   }
3565 
ImportData(const reader::ASTDeclContextNameLookupTrait::data_type & FromReader)3566   data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
3567     unsigned Start = DeclIDs.size();
3568     for (auto ID : FromReader)
3569       DeclIDs.push_back(ID);
3570     return std::make_pair(Start, DeclIDs.size());
3571   }
3572 
EqualKey(key_type_ref a,key_type_ref b)3573   static bool EqualKey(key_type_ref a, key_type_ref b) {
3574     return a == b;
3575   }
3576 
ComputeHash(DeclarationNameKey Name)3577   hash_value_type ComputeHash(DeclarationNameKey Name) {
3578     return Name.getHash();
3579   }
3580 
EmitFileRef(raw_ostream & Out,ModuleFile * F) const3581   void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
3582     assert(Writer.hasChain() &&
3583            "have reference to loaded module file but no chain?");
3584 
3585     using namespace llvm::support;
3586 
3587     endian::write<uint32_t>(Out, Writer.getChain()->getModuleFileID(F), little);
3588   }
3589 
EmitKeyDataLength(raw_ostream & Out,DeclarationNameKey Name,data_type_ref Lookup)3590   std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
3591                                                   DeclarationNameKey Name,
3592                                                   data_type_ref Lookup) {
3593     unsigned KeyLen = 1;
3594     switch (Name.getKind()) {
3595     case DeclarationName::Identifier:
3596     case DeclarationName::ObjCZeroArgSelector:
3597     case DeclarationName::ObjCOneArgSelector:
3598     case DeclarationName::ObjCMultiArgSelector:
3599     case DeclarationName::CXXLiteralOperatorName:
3600     case DeclarationName::CXXDeductionGuideName:
3601       KeyLen += 4;
3602       break;
3603     case DeclarationName::CXXOperatorName:
3604       KeyLen += 1;
3605       break;
3606     case DeclarationName::CXXConstructorName:
3607     case DeclarationName::CXXDestructorName:
3608     case DeclarationName::CXXConversionFunctionName:
3609     case DeclarationName::CXXUsingDirective:
3610       break;
3611     }
3612 
3613     // 4 bytes for each DeclID.
3614     unsigned DataLen = 4 * (Lookup.second - Lookup.first);
3615 
3616     return emitULEBKeyDataLength(KeyLen, DataLen, Out);
3617   }
3618 
EmitKey(raw_ostream & Out,DeclarationNameKey Name,unsigned)3619   void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
3620     using namespace llvm::support;
3621 
3622     endian::Writer LE(Out, little);
3623     LE.write<uint8_t>(Name.getKind());
3624     switch (Name.getKind()) {
3625     case DeclarationName::Identifier:
3626     case DeclarationName::CXXLiteralOperatorName:
3627     case DeclarationName::CXXDeductionGuideName:
3628       LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier()));
3629       return;
3630     case DeclarationName::ObjCZeroArgSelector:
3631     case DeclarationName::ObjCOneArgSelector:
3632     case DeclarationName::ObjCMultiArgSelector:
3633       LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
3634       return;
3635     case DeclarationName::CXXOperatorName:
3636       assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
3637              "Invalid operator?");
3638       LE.write<uint8_t>(Name.getOperatorKind());
3639       return;
3640     case DeclarationName::CXXConstructorName:
3641     case DeclarationName::CXXDestructorName:
3642     case DeclarationName::CXXConversionFunctionName:
3643     case DeclarationName::CXXUsingDirective:
3644       return;
3645     }
3646 
3647     llvm_unreachable("Invalid name kind?");
3648   }
3649 
EmitData(raw_ostream & Out,key_type_ref,data_type Lookup,unsigned DataLen)3650   void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
3651                 unsigned DataLen) {
3652     using namespace llvm::support;
3653 
3654     endian::Writer LE(Out, little);
3655     uint64_t Start = Out.tell(); (void)Start;
3656     for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
3657       LE.write<uint32_t>(DeclIDs[I]);
3658     assert(Out.tell() - Start == DataLen && "Data length is wrong");
3659   }
3660 };
3661 
3662 } // namespace
3663 
isLookupResultExternal(StoredDeclsList & Result,DeclContext * DC)3664 bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
3665                                        DeclContext *DC) {
3666   return Result.hasExternalDecls() &&
3667          DC->hasNeedToReconcileExternalVisibleStorage();
3668 }
3669 
isLookupResultEntirelyExternal(StoredDeclsList & Result,DeclContext * DC)3670 bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
3671                                                DeclContext *DC) {
3672   for (auto *D : Result.getLookupResult())
3673     if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
3674       return false;
3675 
3676   return true;
3677 }
3678 
3679 void
GenerateNameLookupTable(const DeclContext * ConstDC,llvm::SmallVectorImpl<char> & LookupTable)3680 ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
3681                                    llvm::SmallVectorImpl<char> &LookupTable) {
3682   assert(!ConstDC->hasLazyLocalLexicalLookups() &&
3683          !ConstDC->hasLazyExternalLexicalLookups() &&
3684          "must call buildLookups first");
3685 
3686   // FIXME: We need to build the lookups table, which is logically const.
3687   auto *DC = const_cast<DeclContext*>(ConstDC);
3688   assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
3689 
3690   // Create the on-disk hash table representation.
3691   MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait,
3692                                 ASTDeclContextNameLookupTrait> Generator;
3693   ASTDeclContextNameLookupTrait Trait(*this);
3694 
3695   // The first step is to collect the declaration names which we need to
3696   // serialize into the name lookup table, and to collect them in a stable
3697   // order.
3698   SmallVector<DeclarationName, 16> Names;
3699 
3700   // We also build up small sets of the constructor and conversion function
3701   // names which are visible.
3702   llvm::SmallPtrSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
3703 
3704   for (auto &Lookup : *DC->buildLookup()) {
3705     auto &Name = Lookup.first;
3706     auto &Result = Lookup.second;
3707 
3708     // If there are no local declarations in our lookup result, we
3709     // don't need to write an entry for the name at all. If we can't
3710     // write out a lookup set without performing more deserialization,
3711     // just skip this entry.
3712     if (isLookupResultExternal(Result, DC) &&
3713         isLookupResultEntirelyExternal(Result, DC))
3714       continue;
3715 
3716     // We also skip empty results. If any of the results could be external and
3717     // the currently available results are empty, then all of the results are
3718     // external and we skip it above. So the only way we get here with an empty
3719     // results is when no results could have been external *and* we have
3720     // external results.
3721     //
3722     // FIXME: While we might want to start emitting on-disk entries for negative
3723     // lookups into a decl context as an optimization, today we *have* to skip
3724     // them because there are names with empty lookup results in decl contexts
3725     // which we can't emit in any stable ordering: we lookup constructors and
3726     // conversion functions in the enclosing namespace scope creating empty
3727     // results for them. This in almost certainly a bug in Clang's name lookup,
3728     // but that is likely to be hard or impossible to fix and so we tolerate it
3729     // here by omitting lookups with empty results.
3730     if (Lookup.second.getLookupResult().empty())
3731       continue;
3732 
3733     switch (Lookup.first.getNameKind()) {
3734     default:
3735       Names.push_back(Lookup.first);
3736       break;
3737 
3738     case DeclarationName::CXXConstructorName:
3739       assert(isa<CXXRecordDecl>(DC) &&
3740              "Cannot have a constructor name outside of a class!");
3741       ConstructorNameSet.insert(Name);
3742       break;
3743 
3744     case DeclarationName::CXXConversionFunctionName:
3745       assert(isa<CXXRecordDecl>(DC) &&
3746              "Cannot have a conversion function name outside of a class!");
3747       ConversionNameSet.insert(Name);
3748       break;
3749     }
3750   }
3751 
3752   // Sort the names into a stable order.
3753   llvm::sort(Names);
3754 
3755   if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
3756     // We need to establish an ordering of constructor and conversion function
3757     // names, and they don't have an intrinsic ordering.
3758 
3759     // First we try the easy case by forming the current context's constructor
3760     // name and adding that name first. This is a very useful optimization to
3761     // avoid walking the lexical declarations in many cases, and it also
3762     // handles the only case where a constructor name can come from some other
3763     // lexical context -- when that name is an implicit constructor merged from
3764     // another declaration in the redecl chain. Any non-implicit constructor or
3765     // conversion function which doesn't occur in all the lexical contexts
3766     // would be an ODR violation.
3767     auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
3768         Context->getCanonicalType(Context->getRecordType(D)));
3769     if (ConstructorNameSet.erase(ImplicitCtorName))
3770       Names.push_back(ImplicitCtorName);
3771 
3772     // If we still have constructors or conversion functions, we walk all the
3773     // names in the decl and add the constructors and conversion functions
3774     // which are visible in the order they lexically occur within the context.
3775     if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
3776       for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
3777         if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
3778           auto Name = ChildND->getDeclName();
3779           switch (Name.getNameKind()) {
3780           default:
3781             continue;
3782 
3783           case DeclarationName::CXXConstructorName:
3784             if (ConstructorNameSet.erase(Name))
3785               Names.push_back(Name);
3786             break;
3787 
3788           case DeclarationName::CXXConversionFunctionName:
3789             if (ConversionNameSet.erase(Name))
3790               Names.push_back(Name);
3791             break;
3792           }
3793 
3794           if (ConstructorNameSet.empty() && ConversionNameSet.empty())
3795             break;
3796         }
3797 
3798     assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
3799                                          "constructors by walking all the "
3800                                          "lexical members of the context.");
3801     assert(ConversionNameSet.empty() && "Failed to find all of the visible "
3802                                         "conversion functions by walking all "
3803                                         "the lexical members of the context.");
3804   }
3805 
3806   // Next we need to do a lookup with each name into this decl context to fully
3807   // populate any results from external sources. We don't actually use the
3808   // results of these lookups because we only want to use the results after all
3809   // results have been loaded and the pointers into them will be stable.
3810   for (auto &Name : Names)
3811     DC->lookup(Name);
3812 
3813   // Now we need to insert the results for each name into the hash table. For
3814   // constructor names and conversion function names, we actually need to merge
3815   // all of the results for them into one list of results each and insert
3816   // those.
3817   SmallVector<NamedDecl *, 8> ConstructorDecls;
3818   SmallVector<NamedDecl *, 8> ConversionDecls;
3819 
3820   // Now loop over the names, either inserting them or appending for the two
3821   // special cases.
3822   for (auto &Name : Names) {
3823     DeclContext::lookup_result Result = DC->noload_lookup(Name);
3824 
3825     switch (Name.getNameKind()) {
3826     default:
3827       Generator.insert(Name, Trait.getData(Result), Trait);
3828       break;
3829 
3830     case DeclarationName::CXXConstructorName:
3831       ConstructorDecls.append(Result.begin(), Result.end());
3832       break;
3833 
3834     case DeclarationName::CXXConversionFunctionName:
3835       ConversionDecls.append(Result.begin(), Result.end());
3836       break;
3837     }
3838   }
3839 
3840   // Handle our two special cases if we ended up having any. We arbitrarily use
3841   // the first declaration's name here because the name itself isn't part of
3842   // the key, only the kind of name is used.
3843   if (!ConstructorDecls.empty())
3844     Generator.insert(ConstructorDecls.front()->getDeclName(),
3845                      Trait.getData(ConstructorDecls), Trait);
3846   if (!ConversionDecls.empty())
3847     Generator.insert(ConversionDecls.front()->getDeclName(),
3848                      Trait.getData(ConversionDecls), Trait);
3849 
3850   // Create the on-disk hash table. Also emit the existing imported and
3851   // merged table if there is one.
3852   auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr;
3853   Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr);
3854 }
3855 
3856 /// Write the block containing all of the declaration IDs
3857 /// visible from the given DeclContext.
3858 ///
3859 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
3860 /// bitstream, or 0 if no block was written.
WriteDeclContextVisibleBlock(ASTContext & Context,DeclContext * DC)3861 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
3862                                                  DeclContext *DC) {
3863   // If we imported a key declaration of this namespace, write the visible
3864   // lookup results as an update record for it rather than including them
3865   // on this declaration. We will only look at key declarations on reload.
3866   if (isa<NamespaceDecl>(DC) && Chain &&
3867       Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) {
3868     // Only do this once, for the first local declaration of the namespace.
3869     for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
3870          Prev = Prev->getPreviousDecl())
3871       if (!Prev->isFromASTFile())
3872         return 0;
3873 
3874     // Note that we need to emit an update record for the primary context.
3875     UpdatedDeclContexts.insert(DC->getPrimaryContext());
3876 
3877     // Make sure all visible decls are written. They will be recorded later. We
3878     // do this using a side data structure so we can sort the names into
3879     // a deterministic order.
3880     StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup();
3881     SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16>
3882         LookupResults;
3883     if (Map) {
3884       LookupResults.reserve(Map->size());
3885       for (auto &Entry : *Map)
3886         LookupResults.push_back(
3887             std::make_pair(Entry.first, Entry.second.getLookupResult()));
3888     }
3889 
3890     llvm::sort(LookupResults, llvm::less_first());
3891     for (auto &NameAndResult : LookupResults) {
3892       DeclarationName Name = NameAndResult.first;
3893       DeclContext::lookup_result Result = NameAndResult.second;
3894       if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
3895           Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
3896         // We have to work around a name lookup bug here where negative lookup
3897         // results for these names get cached in namespace lookup tables (these
3898         // names should never be looked up in a namespace).
3899         assert(Result.empty() && "Cannot have a constructor or conversion "
3900                                  "function name in a namespace!");
3901         continue;
3902       }
3903 
3904       for (NamedDecl *ND : Result)
3905         if (!ND->isFromASTFile())
3906           GetDeclRef(ND);
3907     }
3908 
3909     return 0;
3910   }
3911 
3912   if (DC->getPrimaryContext() != DC)
3913     return 0;
3914 
3915   // Skip contexts which don't support name lookup.
3916   if (!DC->isLookupContext())
3917     return 0;
3918 
3919   // If not in C++, we perform name lookup for the translation unit via the
3920   // IdentifierInfo chains, don't bother to build a visible-declarations table.
3921   if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
3922     return 0;
3923 
3924   // Serialize the contents of the mapping used for lookup. Note that,
3925   // although we have two very different code paths, the serialized
3926   // representation is the same for both cases: a declaration name,
3927   // followed by a size, followed by references to the visible
3928   // declarations that have that name.
3929   uint64_t Offset = Stream.GetCurrentBitNo();
3930   StoredDeclsMap *Map = DC->buildLookup();
3931   if (!Map || Map->empty())
3932     return 0;
3933 
3934   // Create the on-disk hash table in a buffer.
3935   SmallString<4096> LookupTable;
3936   GenerateNameLookupTable(DC, LookupTable);
3937 
3938   // Write the lookup table
3939   RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
3940   Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
3941                             LookupTable);
3942   ++NumVisibleDeclContexts;
3943   return Offset;
3944 }
3945 
3946 /// Write an UPDATE_VISIBLE block for the given context.
3947 ///
3948 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
3949 /// DeclContext in a dependent AST file. As such, they only exist for the TU
3950 /// (in C++), for namespaces, and for classes with forward-declared unscoped
3951 /// enumeration members (in C++11).
WriteDeclContextVisibleUpdate(const DeclContext * DC)3952 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
3953   StoredDeclsMap *Map = DC->getLookupPtr();
3954   if (!Map || Map->empty())
3955     return;
3956 
3957   // Create the on-disk hash table in a buffer.
3958   SmallString<4096> LookupTable;
3959   GenerateNameLookupTable(DC, LookupTable);
3960 
3961   // If we're updating a namespace, select a key declaration as the key for the
3962   // update record; those are the only ones that will be checked on reload.
3963   if (isa<NamespaceDecl>(DC))
3964     DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
3965 
3966   // Write the lookup table
3967   RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))};
3968   Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
3969 }
3970 
3971 /// Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
WriteFPPragmaOptions(const FPOptionsOverride & Opts)3972 void ASTWriter::WriteFPPragmaOptions(const FPOptionsOverride &Opts) {
3973   RecordData::value_type Record[] = {Opts.getAsOpaqueInt()};
3974   Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
3975 }
3976 
3977 /// Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
WriteOpenCLExtensions(Sema & SemaRef)3978 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
3979   if (!SemaRef.Context.getLangOpts().OpenCL)
3980     return;
3981 
3982   const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
3983   RecordData Record;
3984   for (const auto &I:Opts.OptMap) {
3985     AddString(I.getKey(), Record);
3986     auto V = I.getValue();
3987     Record.push_back(V.Supported ? 1 : 0);
3988     Record.push_back(V.Enabled ? 1 : 0);
3989     Record.push_back(V.WithPragma ? 1 : 0);
3990     Record.push_back(V.Avail);
3991     Record.push_back(V.Core);
3992     Record.push_back(V.Opt);
3993   }
3994   Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
3995 }
WriteCUDAPragmas(Sema & SemaRef)3996 void ASTWriter::WriteCUDAPragmas(Sema &SemaRef) {
3997   if (SemaRef.ForceCUDAHostDeviceDepth > 0) {
3998     RecordData::value_type Record[] = {SemaRef.ForceCUDAHostDeviceDepth};
3999     Stream.EmitRecord(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH, Record);
4000   }
4001 }
4002 
WriteObjCCategories()4003 void ASTWriter::WriteObjCCategories() {
4004   SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
4005   RecordData Categories;
4006 
4007   for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
4008     unsigned Size = 0;
4009     unsigned StartIndex = Categories.size();
4010 
4011     ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
4012 
4013     // Allocate space for the size.
4014     Categories.push_back(0);
4015 
4016     // Add the categories.
4017     for (ObjCInterfaceDecl::known_categories_iterator
4018            Cat = Class->known_categories_begin(),
4019            CatEnd = Class->known_categories_end();
4020          Cat != CatEnd; ++Cat, ++Size) {
4021       assert(getDeclID(*Cat) != 0 && "Bogus category");
4022       AddDeclRef(*Cat, Categories);
4023     }
4024 
4025     // Update the size.
4026     Categories[StartIndex] = Size;
4027 
4028     // Record this interface -> category map.
4029     ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
4030     CategoriesMap.push_back(CatInfo);
4031   }
4032 
4033   // Sort the categories map by the definition ID, since the reader will be
4034   // performing binary searches on this information.
4035   llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
4036 
4037   // Emit the categories map.
4038   using namespace llvm;
4039 
4040   auto Abbrev = std::make_shared<BitCodeAbbrev>();
4041   Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
4042   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
4043   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4044   unsigned AbbrevID = Stream.EmitAbbrev(std::move(Abbrev));
4045 
4046   RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
4047   Stream.EmitRecordWithBlob(AbbrevID, Record,
4048                             reinterpret_cast<char *>(CategoriesMap.data()),
4049                             CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
4050 
4051   // Emit the category lists.
4052   Stream.EmitRecord(OBJC_CATEGORIES, Categories);
4053 }
4054 
WriteLateParsedTemplates(Sema & SemaRef)4055 void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
4056   Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
4057 
4058   if (LPTMap.empty())
4059     return;
4060 
4061   RecordData Record;
4062   for (auto &LPTMapEntry : LPTMap) {
4063     const FunctionDecl *FD = LPTMapEntry.first;
4064     LateParsedTemplate &LPT = *LPTMapEntry.second;
4065     AddDeclRef(FD, Record);
4066     AddDeclRef(LPT.D, Record);
4067     Record.push_back(LPT.Toks.size());
4068 
4069     for (const auto &Tok : LPT.Toks) {
4070       AddToken(Tok, Record);
4071     }
4072   }
4073   Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
4074 }
4075 
4076 /// Write the state of 'pragma clang optimize' at the end of the module.
WriteOptimizePragmaOptions(Sema & SemaRef)4077 void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
4078   RecordData Record;
4079   SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
4080   AddSourceLocation(PragmaLoc, Record);
4081   Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
4082 }
4083 
4084 /// Write the state of 'pragma ms_struct' at the end of the module.
WriteMSStructPragmaOptions(Sema & SemaRef)4085 void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
4086   RecordData Record;
4087   Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF);
4088   Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
4089 }
4090 
4091 /// Write the state of 'pragma pointers_to_members' at the end of the
4092 //module.
WriteMSPointersToMembersPragmaOptions(Sema & SemaRef)4093 void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
4094   RecordData Record;
4095   Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod);
4096   AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record);
4097   Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
4098 }
4099 
4100 /// Write the state of 'pragma align/pack' at the end of the module.
WritePackPragmaOptions(Sema & SemaRef)4101 void ASTWriter::WritePackPragmaOptions(Sema &SemaRef) {
4102   // Don't serialize pragma align/pack state for modules, since it should only
4103   // take effect on a per-submodule basis.
4104   if (WritingModule)
4105     return;
4106 
4107   RecordData Record;
4108   AddAlignPackInfo(SemaRef.AlignPackStack.CurrentValue, Record);
4109   AddSourceLocation(SemaRef.AlignPackStack.CurrentPragmaLocation, Record);
4110   Record.push_back(SemaRef.AlignPackStack.Stack.size());
4111   for (const auto &StackEntry : SemaRef.AlignPackStack.Stack) {
4112     AddAlignPackInfo(StackEntry.Value, Record);
4113     AddSourceLocation(StackEntry.PragmaLocation, Record);
4114     AddSourceLocation(StackEntry.PragmaPushLocation, Record);
4115     AddString(StackEntry.StackSlotLabel, Record);
4116   }
4117   Stream.EmitRecord(ALIGN_PACK_PRAGMA_OPTIONS, Record);
4118 }
4119 
4120 /// Write the state of 'pragma float_control' at the end of the module.
WriteFloatControlPragmaOptions(Sema & SemaRef)4121 void ASTWriter::WriteFloatControlPragmaOptions(Sema &SemaRef) {
4122   // Don't serialize pragma float_control state for modules,
4123   // since it should only take effect on a per-submodule basis.
4124   if (WritingModule)
4125     return;
4126 
4127   RecordData Record;
4128   Record.push_back(SemaRef.FpPragmaStack.CurrentValue.getAsOpaqueInt());
4129   AddSourceLocation(SemaRef.FpPragmaStack.CurrentPragmaLocation, Record);
4130   Record.push_back(SemaRef.FpPragmaStack.Stack.size());
4131   for (const auto &StackEntry : SemaRef.FpPragmaStack.Stack) {
4132     Record.push_back(StackEntry.Value.getAsOpaqueInt());
4133     AddSourceLocation(StackEntry.PragmaLocation, Record);
4134     AddSourceLocation(StackEntry.PragmaPushLocation, Record);
4135     AddString(StackEntry.StackSlotLabel, Record);
4136   }
4137   Stream.EmitRecord(FLOAT_CONTROL_PRAGMA_OPTIONS, Record);
4138 }
4139 
WriteModuleFileExtension(Sema & SemaRef,ModuleFileExtensionWriter & Writer)4140 void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
4141                                          ModuleFileExtensionWriter &Writer) {
4142   // Enter the extension block.
4143   Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
4144 
4145   // Emit the metadata record abbreviation.
4146   auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
4147   Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
4148   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4149   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4150   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4151   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4152   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4153   unsigned Abbrev = Stream.EmitAbbrev(std::move(Abv));
4154 
4155   // Emit the metadata record.
4156   RecordData Record;
4157   auto Metadata = Writer.getExtension()->getExtensionMetadata();
4158   Record.push_back(EXTENSION_METADATA);
4159   Record.push_back(Metadata.MajorVersion);
4160   Record.push_back(Metadata.MinorVersion);
4161   Record.push_back(Metadata.BlockName.size());
4162   Record.push_back(Metadata.UserInfo.size());
4163   SmallString<64> Buffer;
4164   Buffer += Metadata.BlockName;
4165   Buffer += Metadata.UserInfo;
4166   Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
4167 
4168   // Emit the contents of the extension block.
4169   Writer.writeExtensionContents(SemaRef, Stream);
4170 
4171   // Exit the extension block.
4172   Stream.ExitBlock();
4173 }
4174 
4175 //===----------------------------------------------------------------------===//
4176 // General Serialization Routines
4177 //===----------------------------------------------------------------------===//
4178 
AddAttr(const Attr * A)4179 void ASTRecordWriter::AddAttr(const Attr *A) {
4180   auto &Record = *this;
4181   if (!A)
4182     return Record.push_back(0);
4183   Record.push_back(A->getKind() + 1); // FIXME: stable encoding, target attrs
4184 
4185   Record.AddIdentifierRef(A->getAttrName());
4186   Record.AddIdentifierRef(A->getScopeName());
4187   Record.AddSourceRange(A->getRange());
4188   Record.AddSourceLocation(A->getScopeLoc());
4189   Record.push_back(A->getParsedKind());
4190   Record.push_back(A->getSyntax());
4191   Record.push_back(A->getAttributeSpellingListIndexRaw());
4192 
4193 #include "clang/Serialization/AttrPCHWrite.inc"
4194 }
4195 
4196 /// Emit the list of attributes to the specified record.
AddAttributes(ArrayRef<const Attr * > Attrs)4197 void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) {
4198   push_back(Attrs.size());
4199   for (const auto *A : Attrs)
4200     AddAttr(A);
4201 }
4202 
AddToken(const Token & Tok,RecordDataImpl & Record)4203 void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
4204   AddSourceLocation(Tok.getLocation(), Record);
4205   Record.push_back(Tok.getLength());
4206 
4207   // FIXME: When reading literal tokens, reconstruct the literal pointer
4208   // if it is needed.
4209   AddIdentifierRef(Tok.getIdentifierInfo(), Record);
4210   // FIXME: Should translate token kind to a stable encoding.
4211   Record.push_back(Tok.getKind());
4212   // FIXME: Should translate token flags to a stable encoding.
4213   Record.push_back(Tok.getFlags());
4214 }
4215 
AddString(StringRef Str,RecordDataImpl & Record)4216 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
4217   Record.push_back(Str.size());
4218   Record.insert(Record.end(), Str.begin(), Str.end());
4219 }
4220 
PreparePathForOutput(SmallVectorImpl<char> & Path)4221 bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
4222   assert(Context && "should have context when outputting path");
4223 
4224   bool Changed =
4225       cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
4226 
4227   // Remove a prefix to make the path relative, if relevant.
4228   const char *PathBegin = Path.data();
4229   const char *PathPtr =
4230       adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
4231   if (PathPtr != PathBegin) {
4232     Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
4233     Changed = true;
4234   }
4235 
4236   return Changed;
4237 }
4238 
AddPath(StringRef Path,RecordDataImpl & Record)4239 void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
4240   SmallString<128> FilePath(Path);
4241   PreparePathForOutput(FilePath);
4242   AddString(FilePath, Record);
4243 }
4244 
EmitRecordWithPath(unsigned Abbrev,RecordDataRef Record,StringRef Path)4245 void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
4246                                    StringRef Path) {
4247   SmallString<128> FilePath(Path);
4248   PreparePathForOutput(FilePath);
4249   Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
4250 }
4251 
AddVersionTuple(const VersionTuple & Version,RecordDataImpl & Record)4252 void ASTWriter::AddVersionTuple(const VersionTuple &Version,
4253                                 RecordDataImpl &Record) {
4254   Record.push_back(Version.getMajor());
4255   if (Optional<unsigned> Minor = Version.getMinor())
4256     Record.push_back(*Minor + 1);
4257   else
4258     Record.push_back(0);
4259   if (Optional<unsigned> Subminor = Version.getSubminor())
4260     Record.push_back(*Subminor + 1);
4261   else
4262     Record.push_back(0);
4263 }
4264 
4265 /// Note that the identifier II occurs at the given offset
4266 /// within the identifier table.
SetIdentifierOffset(const IdentifierInfo * II,uint32_t Offset)4267 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
4268   IdentID ID = IdentifierIDs[II];
4269   // Only store offsets new to this AST file. Other identifier names are looked
4270   // up earlier in the chain and thus don't need an offset.
4271   if (ID >= FirstIdentID)
4272     IdentifierOffsets[ID - FirstIdentID] = Offset;
4273 }
4274 
4275 /// Note that the selector Sel occurs at the given offset
4276 /// within the method pool/selector table.
SetSelectorOffset(Selector Sel,uint32_t Offset)4277 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
4278   unsigned ID = SelectorIDs[Sel];
4279   assert(ID && "Unknown selector");
4280   // Don't record offsets for selectors that are also available in a different
4281   // file.
4282   if (ID < FirstSelectorID)
4283     return;
4284   SelectorOffsets[ID - FirstSelectorID] = Offset;
4285 }
4286 
ASTWriter(llvm::BitstreamWriter & Stream,SmallVectorImpl<char> & Buffer,InMemoryModuleCache & ModuleCache,ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,bool IncludeTimestamps)4287 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream,
4288                      SmallVectorImpl<char> &Buffer,
4289                      InMemoryModuleCache &ModuleCache,
4290                      ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
4291                      bool IncludeTimestamps)
4292     : Stream(Stream), Buffer(Buffer), ModuleCache(ModuleCache),
4293       IncludeTimestamps(IncludeTimestamps) {
4294   for (const auto &Ext : Extensions) {
4295     if (auto Writer = Ext->createExtensionWriter(*this))
4296       ModuleFileExtensionWriters.push_back(std::move(Writer));
4297   }
4298 }
4299 
4300 ASTWriter::~ASTWriter() = default;
4301 
getLangOpts() const4302 const LangOptions &ASTWriter::getLangOpts() const {
4303   assert(WritingAST && "can't determine lang opts when not writing AST");
4304   return Context->getLangOpts();
4305 }
4306 
getTimestampForOutput(const FileEntry * E) const4307 time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const {
4308   return IncludeTimestamps ? E->getModificationTime() : 0;
4309 }
4310 
WriteAST(Sema & SemaRef,const std::string & OutputFile,Module * WritingModule,StringRef isysroot,bool hasErrors,bool ShouldCacheASTInMemory)4311 ASTFileSignature ASTWriter::WriteAST(Sema &SemaRef,
4312                                      const std::string &OutputFile,
4313                                      Module *WritingModule, StringRef isysroot,
4314                                      bool hasErrors,
4315                                      bool ShouldCacheASTInMemory) {
4316   WritingAST = true;
4317 
4318   ASTHasCompilerErrors = hasErrors;
4319 
4320   // Emit the file header.
4321   Stream.Emit((unsigned)'C', 8);
4322   Stream.Emit((unsigned)'P', 8);
4323   Stream.Emit((unsigned)'C', 8);
4324   Stream.Emit((unsigned)'H', 8);
4325 
4326   WriteBlockInfoBlock();
4327 
4328   Context = &SemaRef.Context;
4329   PP = &SemaRef.PP;
4330   this->WritingModule = WritingModule;
4331   ASTFileSignature Signature =
4332       WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
4333   Context = nullptr;
4334   PP = nullptr;
4335   this->WritingModule = nullptr;
4336   this->BaseDirectory.clear();
4337 
4338   WritingAST = false;
4339   if (ShouldCacheASTInMemory) {
4340     // Construct MemoryBuffer and update buffer manager.
4341     ModuleCache.addBuiltPCM(OutputFile,
4342                             llvm::MemoryBuffer::getMemBufferCopy(
4343                                 StringRef(Buffer.begin(), Buffer.size())));
4344   }
4345   return Signature;
4346 }
4347 
4348 template<typename Vector>
AddLazyVectorDecls(ASTWriter & Writer,Vector & Vec,ASTWriter::RecordData & Record)4349 static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4350                                ASTWriter::RecordData &Record) {
4351   for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4352        I != E; ++I) {
4353     Writer.AddDeclRef(*I, Record);
4354   }
4355 }
4356 
WriteASTCore(Sema & SemaRef,StringRef isysroot,const std::string & OutputFile,Module * WritingModule)4357 ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
4358                                          const std::string &OutputFile,
4359                                          Module *WritingModule) {
4360   using namespace llvm;
4361 
4362   bool isModule = WritingModule != nullptr;
4363 
4364   // Make sure that the AST reader knows to finalize itself.
4365   if (Chain)
4366     Chain->finalizeForWriting();
4367 
4368   ASTContext &Context = SemaRef.Context;
4369   Preprocessor &PP = SemaRef.PP;
4370 
4371   // Set up predefined declaration IDs.
4372   auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
4373     if (D) {
4374       assert(D->isCanonicalDecl() && "predefined decl is not canonical");
4375       DeclIDs[D] = ID;
4376     }
4377   };
4378   RegisterPredefDecl(Context.getTranslationUnitDecl(),
4379                      PREDEF_DECL_TRANSLATION_UNIT_ID);
4380   RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
4381   RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
4382   RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
4383   RegisterPredefDecl(Context.ObjCProtocolClassDecl,
4384                      PREDEF_DECL_OBJC_PROTOCOL_ID);
4385   RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
4386   RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
4387   RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
4388                      PREDEF_DECL_OBJC_INSTANCETYPE_ID);
4389   RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
4390   RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
4391   RegisterPredefDecl(Context.BuiltinMSVaListDecl,
4392                      PREDEF_DECL_BUILTIN_MS_VA_LIST_ID);
4393   RegisterPredefDecl(Context.MSGuidTagDecl,
4394                      PREDEF_DECL_BUILTIN_MS_GUID_ID);
4395   RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
4396   RegisterPredefDecl(Context.MakeIntegerSeqDecl,
4397                      PREDEF_DECL_MAKE_INTEGER_SEQ_ID);
4398   RegisterPredefDecl(Context.CFConstantStringTypeDecl,
4399                      PREDEF_DECL_CF_CONSTANT_STRING_ID);
4400   RegisterPredefDecl(Context.CFConstantStringTagDecl,
4401                      PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID);
4402   RegisterPredefDecl(Context.TypePackElementDecl,
4403                      PREDEF_DECL_TYPE_PACK_ELEMENT_ID);
4404 
4405   // Build a record containing all of the tentative definitions in this file, in
4406   // TentativeDefinitions order.  Generally, this record will be empty for
4407   // headers.
4408   RecordData TentativeDefinitions;
4409   AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
4410 
4411   // Build a record containing all of the file scoped decls in this file.
4412   RecordData UnusedFileScopedDecls;
4413   if (!isModule)
4414     AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
4415                        UnusedFileScopedDecls);
4416 
4417   // Build a record containing all of the delegating constructors we still need
4418   // to resolve.
4419   RecordData DelegatingCtorDecls;
4420   if (!isModule)
4421     AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
4422 
4423   // Write the set of weak, undeclared identifiers. We always write the
4424   // entire table, since later PCH files in a PCH chain are only interested in
4425   // the results at the end of the chain.
4426   RecordData WeakUndeclaredIdentifiers;
4427   for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) {
4428     IdentifierInfo *II = WeakUndeclaredIdentifier.first;
4429     WeakInfo &WI = WeakUndeclaredIdentifier.second;
4430     AddIdentifierRef(II, WeakUndeclaredIdentifiers);
4431     AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
4432     AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
4433     WeakUndeclaredIdentifiers.push_back(WI.getUsed());
4434   }
4435 
4436   // Build a record containing all of the ext_vector declarations.
4437   RecordData ExtVectorDecls;
4438   AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
4439 
4440   // Build a record containing all of the VTable uses information.
4441   RecordData VTableUses;
4442   if (!SemaRef.VTableUses.empty()) {
4443     for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4444       AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4445       AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4446       VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4447     }
4448   }
4449 
4450   // Build a record containing all of the UnusedLocalTypedefNameCandidates.
4451   RecordData UnusedLocalTypedefNameCandidates;
4452   for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4453     AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
4454 
4455   // Build a record containing all of pending implicit instantiations.
4456   RecordData PendingInstantiations;
4457   for (const auto &I : SemaRef.PendingInstantiations) {
4458     AddDeclRef(I.first, PendingInstantiations);
4459     AddSourceLocation(I.second, PendingInstantiations);
4460   }
4461   assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4462          "There are local ones at end of translation unit!");
4463 
4464   // Build a record containing some declaration references.
4465   RecordData SemaDeclRefs;
4466   if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) {
4467     AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4468     AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
4469     AddDeclRef(SemaRef.getStdAlignValT(), SemaDeclRefs);
4470   }
4471 
4472   RecordData CUDASpecialDeclRefs;
4473   if (Context.getcudaConfigureCallDecl()) {
4474     AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4475   }
4476 
4477   // Build a record containing all of the known namespaces.
4478   RecordData KnownNamespaces;
4479   for (const auto &I : SemaRef.KnownNamespaces) {
4480     if (!I.second)
4481       AddDeclRef(I.first, KnownNamespaces);
4482   }
4483 
4484   // Build a record of all used, undefined objects that require definitions.
4485   RecordData UndefinedButUsed;
4486 
4487   SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
4488   SemaRef.getUndefinedButUsed(Undefined);
4489   for (const auto &I : Undefined) {
4490     AddDeclRef(I.first, UndefinedButUsed);
4491     AddSourceLocation(I.second, UndefinedButUsed);
4492   }
4493 
4494   // Build a record containing all delete-expressions that we would like to
4495   // analyze later in AST.
4496   RecordData DeleteExprsToAnalyze;
4497 
4498   if (!isModule) {
4499     for (const auto &DeleteExprsInfo :
4500          SemaRef.getMismatchingDeleteExpressions()) {
4501       AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
4502       DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
4503       for (const auto &DeleteLoc : DeleteExprsInfo.second) {
4504         AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
4505         DeleteExprsToAnalyze.push_back(DeleteLoc.second);
4506       }
4507     }
4508   }
4509 
4510   // Write the control block
4511   WriteControlBlock(PP, Context, isysroot, OutputFile);
4512 
4513   // Write the remaining AST contents.
4514   Stream.FlushToWord();
4515   ASTBlockRange.first = Stream.GetCurrentBitNo();
4516   Stream.EnterSubblock(AST_BLOCK_ID, 5);
4517   ASTBlockStartOffset = Stream.GetCurrentBitNo();
4518 
4519   // This is so that older clang versions, before the introduction
4520   // of the control block, can read and reject the newer PCH format.
4521   {
4522     RecordData Record = {VERSION_MAJOR};
4523     Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4524   }
4525 
4526   // Create a lexical update block containing all of the declarations in the
4527   // translation unit that do not come from other AST files.
4528   const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
4529   SmallVector<uint32_t, 128> NewGlobalKindDeclPairs;
4530   for (const auto *D : TU->noload_decls()) {
4531     if (!D->isFromASTFile()) {
4532       NewGlobalKindDeclPairs.push_back(D->getKind());
4533       NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
4534     }
4535   }
4536 
4537   auto Abv = std::make_shared<BitCodeAbbrev>();
4538   Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4539   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4540   unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv));
4541   {
4542     RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
4543     Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4544                               bytes(NewGlobalKindDeclPairs));
4545   }
4546 
4547   // And a visible updates block for the translation unit.
4548   Abv = std::make_shared<BitCodeAbbrev>();
4549   Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4550   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4551   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4552   UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv));
4553   WriteDeclContextVisibleUpdate(TU);
4554 
4555   // If we have any extern "C" names, write out a visible update for them.
4556   if (Context.ExternCContext)
4557     WriteDeclContextVisibleUpdate(Context.ExternCContext);
4558 
4559   // If the translation unit has an anonymous namespace, and we don't already
4560   // have an update block for it, write it as an update block.
4561   // FIXME: Why do we not do this if there's already an update block?
4562   if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4563     ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
4564     if (Record.empty())
4565       Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
4566   }
4567 
4568   // Add update records for all mangling numbers and static local numbers.
4569   // These aren't really update records, but this is a convenient way of
4570   // tagging this rare extra data onto the declarations.
4571   for (const auto &Number : Context.MangleNumbers)
4572     if (!Number.first->isFromASTFile())
4573       DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4574                                                      Number.second));
4575   for (const auto &Number : Context.StaticLocalNumbers)
4576     if (!Number.first->isFromASTFile())
4577       DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4578                                                      Number.second));
4579 
4580   // Make sure visible decls, added to DeclContexts previously loaded from
4581   // an AST file, are registered for serialization. Likewise for template
4582   // specializations added to imported templates.
4583   for (const auto *I : DeclsToEmitEvenIfUnreferenced) {
4584     GetDeclRef(I);
4585   }
4586 
4587   // Make sure all decls associated with an identifier are registered for
4588   // serialization, if we're storing decls with identifiers.
4589   if (!WritingModule || !getLangOpts().CPlusPlus) {
4590     llvm::SmallVector<const IdentifierInfo*, 256> IIs;
4591     for (const auto &ID : PP.getIdentifierTable()) {
4592       const IdentifierInfo *II = ID.second;
4593       if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
4594         IIs.push_back(II);
4595     }
4596     // Sort the identifiers to visit based on their name.
4597     llvm::sort(IIs, llvm::deref<std::less<>>());
4598     for (const IdentifierInfo *II : IIs) {
4599       for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4600                                      DEnd = SemaRef.IdResolver.end();
4601            D != DEnd; ++D) {
4602         GetDeclRef(*D);
4603       }
4604     }
4605   }
4606 
4607   // For method pool in the module, if it contains an entry for a selector,
4608   // the entry should be complete, containing everything introduced by that
4609   // module and all modules it imports. It's possible that the entry is out of
4610   // date, so we need to pull in the new content here.
4611 
4612   // It's possible that updateOutOfDateSelector can update SelectorIDs. To be
4613   // safe, we copy all selectors out.
4614   llvm::SmallVector<Selector, 256> AllSelectors;
4615   for (auto &SelectorAndID : SelectorIDs)
4616     AllSelectors.push_back(SelectorAndID.first);
4617   for (auto &Selector : AllSelectors)
4618     SemaRef.updateOutOfDateSelector(Selector);
4619 
4620   // Form the record of special types.
4621   RecordData SpecialTypes;
4622   AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
4623   AddTypeRef(Context.getFILEType(), SpecialTypes);
4624   AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4625   AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4626   AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4627   AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
4628   AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
4629   AddTypeRef(Context.getucontext_tType(), SpecialTypes);
4630 
4631   if (Chain) {
4632     // Write the mapping information describing our module dependencies and how
4633     // each of those modules were mapped into our own offset/ID space, so that
4634     // the reader can build the appropriate mapping to its own offset/ID space.
4635     // The map consists solely of a blob with the following format:
4636     // *(module-kind:i8
4637     //   module-name-len:i16 module-name:len*i8
4638     //   source-location-offset:i32
4639     //   identifier-id:i32
4640     //   preprocessed-entity-id:i32
4641     //   macro-definition-id:i32
4642     //   submodule-id:i32
4643     //   selector-id:i32
4644     //   declaration-id:i32
4645     //   c++-base-specifiers-id:i32
4646     //   type-id:i32)
4647     //
4648     // module-kind is the ModuleKind enum value. If it is MK_PrebuiltModule,
4649     // MK_ExplicitModule or MK_ImplicitModule, then the module-name is the
4650     // module name. Otherwise, it is the module file name.
4651     auto Abbrev = std::make_shared<BitCodeAbbrev>();
4652     Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4653     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4654     unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
4655     SmallString<2048> Buffer;
4656     {
4657       llvm::raw_svector_ostream Out(Buffer);
4658       for (ModuleFile &M : Chain->ModuleMgr) {
4659         using namespace llvm::support;
4660 
4661         endian::Writer LE(Out, little);
4662         LE.write<uint8_t>(static_cast<uint8_t>(M.Kind));
4663         StringRef Name = M.isModule() ? M.ModuleName : M.FileName;
4664         LE.write<uint16_t>(Name.size());
4665         Out.write(Name.data(), Name.size());
4666 
4667         // Note: if a base ID was uint max, it would not be possible to load
4668         // another module after it or have more than one entity inside it.
4669         uint32_t None = std::numeric_limits<uint32_t>::max();
4670 
4671         auto writeBaseIDOrNone = [&](auto BaseID, bool ShouldWrite) {
4672           assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
4673           if (ShouldWrite)
4674             LE.write<uint32_t>(BaseID);
4675           else
4676             LE.write<uint32_t>(None);
4677         };
4678 
4679         // These values should be unique within a chain, since they will be read
4680         // as keys into ContinuousRangeMaps.
4681         writeBaseIDOrNone(M.SLocEntryBaseOffset, M.LocalNumSLocEntries);
4682         writeBaseIDOrNone(M.BaseIdentifierID, M.LocalNumIdentifiers);
4683         writeBaseIDOrNone(M.BaseMacroID, M.LocalNumMacros);
4684         writeBaseIDOrNone(M.BasePreprocessedEntityID,
4685                           M.NumPreprocessedEntities);
4686         writeBaseIDOrNone(M.BaseSubmoduleID, M.LocalNumSubmodules);
4687         writeBaseIDOrNone(M.BaseSelectorID, M.LocalNumSelectors);
4688         writeBaseIDOrNone(M.BaseDeclID, M.LocalNumDecls);
4689         writeBaseIDOrNone(M.BaseTypeIndex, M.LocalNumTypes);
4690       }
4691     }
4692     RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
4693     Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4694                               Buffer.data(), Buffer.size());
4695   }
4696 
4697   // Build a record containing all of the DeclsToCheckForDeferredDiags.
4698   SmallVector<serialization::DeclID, 64> DeclsToCheckForDeferredDiags;
4699   for (auto *D : SemaRef.DeclsToCheckForDeferredDiags)
4700     DeclsToCheckForDeferredDiags.push_back(GetDeclRef(D));
4701 
4702   RecordData DeclUpdatesOffsetsRecord;
4703 
4704   // Keep writing types, declarations, and declaration update records
4705   // until we've emitted all of them.
4706   Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
4707   DeclTypesBlockStartOffset = Stream.GetCurrentBitNo();
4708   WriteTypeAbbrevs();
4709   WriteDeclAbbrevs();
4710   do {
4711     WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
4712     while (!DeclTypesToEmit.empty()) {
4713       DeclOrType DOT = DeclTypesToEmit.front();
4714       DeclTypesToEmit.pop();
4715       if (DOT.isType())
4716         WriteType(DOT.getType());
4717       else
4718         WriteDecl(Context, DOT.getDecl());
4719     }
4720   } while (!DeclUpdates.empty());
4721   Stream.ExitBlock();
4722 
4723   DoneWritingDeclsAndTypes = true;
4724 
4725   // These things can only be done once we've written out decls and types.
4726   WriteTypeDeclOffsets();
4727   if (!DeclUpdatesOffsetsRecord.empty())
4728     Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
4729   WriteFileDeclIDsMap();
4730   WriteSourceManagerBlock(Context.getSourceManager(), PP);
4731   WriteComments();
4732   WritePreprocessor(PP, isModule);
4733   WriteHeaderSearch(PP.getHeaderSearchInfo());
4734   WriteSelectors(SemaRef);
4735   WriteReferencedSelectorsPool(SemaRef);
4736   WriteLateParsedTemplates(SemaRef);
4737   WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
4738   WriteFPPragmaOptions(SemaRef.CurFPFeatureOverrides());
4739   WriteOpenCLExtensions(SemaRef);
4740   WriteCUDAPragmas(SemaRef);
4741 
4742   // If we're emitting a module, write out the submodule information.
4743   if (WritingModule)
4744     WriteSubmodules(WritingModule);
4745 
4746   Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
4747 
4748   // Write the record containing external, unnamed definitions.
4749   if (!EagerlyDeserializedDecls.empty())
4750     Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
4751 
4752   if (!ModularCodegenDecls.empty())
4753     Stream.EmitRecord(MODULAR_CODEGEN_DECLS, ModularCodegenDecls);
4754 
4755   // Write the record containing tentative definitions.
4756   if (!TentativeDefinitions.empty())
4757     Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
4758 
4759   // Write the record containing unused file scoped decls.
4760   if (!UnusedFileScopedDecls.empty())
4761     Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
4762 
4763   // Write the record containing weak undeclared identifiers.
4764   if (!WeakUndeclaredIdentifiers.empty())
4765     Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
4766                       WeakUndeclaredIdentifiers);
4767 
4768   // Write the record containing ext_vector type names.
4769   if (!ExtVectorDecls.empty())
4770     Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
4771 
4772   // Write the record containing VTable uses information.
4773   if (!VTableUses.empty())
4774     Stream.EmitRecord(VTABLE_USES, VTableUses);
4775 
4776   // Write the record containing potentially unused local typedefs.
4777   if (!UnusedLocalTypedefNameCandidates.empty())
4778     Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
4779                       UnusedLocalTypedefNameCandidates);
4780 
4781   // Write the record containing pending implicit instantiations.
4782   if (!PendingInstantiations.empty())
4783     Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
4784 
4785   // Write the record containing declaration references of Sema.
4786   if (!SemaDeclRefs.empty())
4787     Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
4788 
4789   // Write the record containing decls to be checked for deferred diags.
4790   if (!DeclsToCheckForDeferredDiags.empty())
4791     Stream.EmitRecord(DECLS_TO_CHECK_FOR_DEFERRED_DIAGS,
4792         DeclsToCheckForDeferredDiags);
4793 
4794   // Write the record containing CUDA-specific declaration references.
4795   if (!CUDASpecialDeclRefs.empty())
4796     Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
4797 
4798   // Write the delegating constructors.
4799   if (!DelegatingCtorDecls.empty())
4800     Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
4801 
4802   // Write the known namespaces.
4803   if (!KnownNamespaces.empty())
4804     Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
4805 
4806   // Write the undefined internal functions and variables, and inline functions.
4807   if (!UndefinedButUsed.empty())
4808     Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
4809 
4810   if (!DeleteExprsToAnalyze.empty())
4811     Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
4812 
4813   // Write the visible updates to DeclContexts.
4814   for (auto *DC : UpdatedDeclContexts)
4815     WriteDeclContextVisibleUpdate(DC);
4816 
4817   if (!WritingModule) {
4818     // Write the submodules that were imported, if any.
4819     struct ModuleInfo {
4820       uint64_t ID;
4821       Module *M;
4822       ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
4823     };
4824     llvm::SmallVector<ModuleInfo, 64> Imports;
4825     for (const auto *I : Context.local_imports()) {
4826       assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
4827       Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
4828                          I->getImportedModule()));
4829     }
4830 
4831     if (!Imports.empty()) {
4832       auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
4833         return A.ID < B.ID;
4834       };
4835       auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
4836         return A.ID == B.ID;
4837       };
4838 
4839       // Sort and deduplicate module IDs.
4840       llvm::sort(Imports, Cmp);
4841       Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
4842                     Imports.end());
4843 
4844       RecordData ImportedModules;
4845       for (const auto &Import : Imports) {
4846         ImportedModules.push_back(Import.ID);
4847         // FIXME: If the module has macros imported then later has declarations
4848         // imported, this location won't be the right one as a location for the
4849         // declaration imports.
4850         AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
4851       }
4852 
4853       Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
4854     }
4855   }
4856 
4857   WriteObjCCategories();
4858   if(!WritingModule) {
4859     WriteOptimizePragmaOptions(SemaRef);
4860     WriteMSStructPragmaOptions(SemaRef);
4861     WriteMSPointersToMembersPragmaOptions(SemaRef);
4862   }
4863   WritePackPragmaOptions(SemaRef);
4864   WriteFloatControlPragmaOptions(SemaRef);
4865 
4866   // Some simple statistics
4867   RecordData::value_type Record[] = {
4868       NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts};
4869   Stream.EmitRecord(STATISTICS, Record);
4870   Stream.ExitBlock();
4871   Stream.FlushToWord();
4872   ASTBlockRange.second = Stream.GetCurrentBitNo();
4873 
4874   // Write the module file extension blocks.
4875   for (const auto &ExtWriter : ModuleFileExtensionWriters)
4876     WriteModuleFileExtension(SemaRef, *ExtWriter);
4877 
4878   return writeUnhashedControlBlock(PP, Context);
4879 }
4880 
WriteDeclUpdatesBlocks(RecordDataImpl & OffsetsRecord)4881 void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
4882   if (DeclUpdates.empty())
4883     return;
4884 
4885   DeclUpdateMap LocalUpdates;
4886   LocalUpdates.swap(DeclUpdates);
4887 
4888   for (auto &DeclUpdate : LocalUpdates) {
4889     const Decl *D = DeclUpdate.first;
4890 
4891     bool HasUpdatedBody = false;
4892     RecordData RecordData;
4893     ASTRecordWriter Record(*this, RecordData);
4894     for (auto &Update : DeclUpdate.second) {
4895       DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
4896 
4897       // An updated body is emitted last, so that the reader doesn't need
4898       // to skip over the lazy body to reach statements for other records.
4899       if (Kind == UPD_CXX_ADDED_FUNCTION_DEFINITION)
4900         HasUpdatedBody = true;
4901       else
4902         Record.push_back(Kind);
4903 
4904       switch (Kind) {
4905       case UPD_CXX_ADDED_IMPLICIT_MEMBER:
4906       case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4907       case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
4908         assert(Update.getDecl() && "no decl to add?");
4909         Record.push_back(GetDeclRef(Update.getDecl()));
4910         break;
4911 
4912       case UPD_CXX_ADDED_FUNCTION_DEFINITION:
4913         break;
4914 
4915       case UPD_CXX_POINT_OF_INSTANTIATION:
4916         // FIXME: Do we need to also save the template specialization kind here?
4917         Record.AddSourceLocation(Update.getLoc());
4918         break;
4919 
4920       case UPD_CXX_ADDED_VAR_DEFINITION: {
4921         const VarDecl *VD = cast<VarDecl>(D);
4922         Record.push_back(VD->isInline());
4923         Record.push_back(VD->isInlineSpecified());
4924         Record.AddVarDeclInit(VD);
4925         break;
4926       }
4927 
4928       case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT:
4929         Record.AddStmt(const_cast<Expr *>(
4930             cast<ParmVarDecl>(Update.getDecl())->getDefaultArg()));
4931         break;
4932 
4933       case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER:
4934         Record.AddStmt(
4935             cast<FieldDecl>(Update.getDecl())->getInClassInitializer());
4936         break;
4937 
4938       case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
4939         auto *RD = cast<CXXRecordDecl>(D);
4940         UpdatedDeclContexts.insert(RD->getPrimaryContext());
4941         Record.push_back(RD->isParamDestroyedInCallee());
4942         Record.push_back(RD->getArgPassingRestrictions());
4943         Record.AddCXXDefinitionData(RD);
4944         Record.AddOffset(WriteDeclContextLexicalBlock(
4945             *Context, const_cast<CXXRecordDecl *>(RD)));
4946 
4947         // This state is sometimes updated by template instantiation, when we
4948         // switch from the specialization referring to the template declaration
4949         // to it referring to the template definition.
4950         if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
4951           Record.push_back(MSInfo->getTemplateSpecializationKind());
4952           Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
4953         } else {
4954           auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
4955           Record.push_back(Spec->getTemplateSpecializationKind());
4956           Record.AddSourceLocation(Spec->getPointOfInstantiation());
4957 
4958           // The instantiation might have been resolved to a partial
4959           // specialization. If so, record which one.
4960           auto From = Spec->getInstantiatedFrom();
4961           if (auto PartialSpec =
4962                 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
4963             Record.push_back(true);
4964             Record.AddDeclRef(PartialSpec);
4965             Record.AddTemplateArgumentList(
4966                 &Spec->getTemplateInstantiationArgs());
4967           } else {
4968             Record.push_back(false);
4969           }
4970         }
4971         Record.push_back(RD->getTagKind());
4972         Record.AddSourceLocation(RD->getLocation());
4973         Record.AddSourceLocation(RD->getBeginLoc());
4974         Record.AddSourceRange(RD->getBraceRange());
4975 
4976         // Instantiation may change attributes; write them all out afresh.
4977         Record.push_back(D->hasAttrs());
4978         if (D->hasAttrs())
4979           Record.AddAttributes(D->getAttrs());
4980 
4981         // FIXME: Ensure we don't get here for explicit instantiations.
4982         break;
4983       }
4984 
4985       case UPD_CXX_RESOLVED_DTOR_DELETE:
4986         Record.AddDeclRef(Update.getDecl());
4987         Record.AddStmt(cast<CXXDestructorDecl>(D)->getOperatorDeleteThisArg());
4988         break;
4989 
4990       case UPD_CXX_RESOLVED_EXCEPTION_SPEC: {
4991         auto prototype =
4992           cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>();
4993         Record.writeExceptionSpecInfo(prototype->getExceptionSpecInfo());
4994         break;
4995       }
4996 
4997       case UPD_CXX_DEDUCED_RETURN_TYPE:
4998         Record.push_back(GetOrCreateTypeID(Update.getType()));
4999         break;
5000 
5001       case UPD_DECL_MARKED_USED:
5002         break;
5003 
5004       case UPD_MANGLING_NUMBER:
5005       case UPD_STATIC_LOCAL_NUMBER:
5006         Record.push_back(Update.getNumber());
5007         break;
5008 
5009       case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
5010         Record.AddSourceRange(
5011             D->getAttr<OMPThreadPrivateDeclAttr>()->getRange());
5012         break;
5013 
5014       case UPD_DECL_MARKED_OPENMP_ALLOCATE: {
5015         auto *A = D->getAttr<OMPAllocateDeclAttr>();
5016         Record.push_back(A->getAllocatorType());
5017         Record.AddStmt(A->getAllocator());
5018         Record.AddSourceRange(A->getRange());
5019         break;
5020       }
5021 
5022       case UPD_DECL_MARKED_OPENMP_DECLARETARGET:
5023         Record.push_back(D->getAttr<OMPDeclareTargetDeclAttr>()->getMapType());
5024         Record.AddSourceRange(
5025             D->getAttr<OMPDeclareTargetDeclAttr>()->getRange());
5026         break;
5027 
5028       case UPD_DECL_EXPORTED:
5029         Record.push_back(getSubmoduleID(Update.getModule()));
5030         break;
5031 
5032       case UPD_ADDED_ATTR_TO_RECORD:
5033         Record.AddAttributes(llvm::makeArrayRef(Update.getAttr()));
5034         break;
5035       }
5036     }
5037 
5038     if (HasUpdatedBody) {
5039       const auto *Def = cast<FunctionDecl>(D);
5040       Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
5041       Record.push_back(Def->isInlined());
5042       Record.AddSourceLocation(Def->getInnerLocStart());
5043       Record.AddFunctionDefinition(Def);
5044     }
5045 
5046     OffsetsRecord.push_back(GetDeclRef(D));
5047     OffsetsRecord.push_back(Record.Emit(DECL_UPDATES));
5048   }
5049 }
5050 
AddAlignPackInfo(const Sema::AlignPackInfo & Info,RecordDataImpl & Record)5051 void ASTWriter::AddAlignPackInfo(const Sema::AlignPackInfo &Info,
5052                                  RecordDataImpl &Record) {
5053   uint32_t Raw = Sema::AlignPackInfo::getRawEncoding(Info);
5054   Record.push_back(Raw);
5055 }
5056 
AddSourceLocation(SourceLocation Loc,RecordDataImpl & Record)5057 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
5058   SourceLocation::UIntTy Raw = Loc.getRawEncoding();
5059   Record.push_back((Raw << 1) | (Raw >> (8 * sizeof(Raw) - 1)));
5060 }
5061 
AddSourceRange(SourceRange Range,RecordDataImpl & Record)5062 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
5063   AddSourceLocation(Range.getBegin(), Record);
5064   AddSourceLocation(Range.getEnd(), Record);
5065 }
5066 
AddAPFloat(const llvm::APFloat & Value)5067 void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) {
5068   AddAPInt(Value.bitcastToAPInt());
5069 }
5070 
AddIdentifierRef(const IdentifierInfo * II,RecordDataImpl & Record)5071 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
5072   Record.push_back(getIdentifierRef(II));
5073 }
5074 
getIdentifierRef(const IdentifierInfo * II)5075 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
5076   if (!II)
5077     return 0;
5078 
5079   IdentID &ID = IdentifierIDs[II];
5080   if (ID == 0)
5081     ID = NextIdentID++;
5082   return ID;
5083 }
5084 
getMacroRef(MacroInfo * MI,const IdentifierInfo * Name)5085 MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
5086   // Don't emit builtin macros like __LINE__ to the AST file unless they
5087   // have been redefined by the header (in which case they are not
5088   // isBuiltinMacro).
5089   if (!MI || MI->isBuiltinMacro())
5090     return 0;
5091 
5092   MacroID &ID = MacroIDs[MI];
5093   if (ID == 0) {
5094     ID = NextMacroID++;
5095     MacroInfoToEmitData Info = { Name, MI, ID };
5096     MacroInfosToEmit.push_back(Info);
5097   }
5098   return ID;
5099 }
5100 
getMacroID(MacroInfo * MI)5101 MacroID ASTWriter::getMacroID(MacroInfo *MI) {
5102   if (!MI || MI->isBuiltinMacro())
5103     return 0;
5104 
5105   assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
5106   return MacroIDs[MI];
5107 }
5108 
getMacroDirectivesOffset(const IdentifierInfo * Name)5109 uint32_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
5110   return IdentMacroDirectivesOffsetMap.lookup(Name);
5111 }
5112 
AddSelectorRef(const Selector SelRef)5113 void ASTRecordWriter::AddSelectorRef(const Selector SelRef) {
5114   Record->push_back(Writer->getSelectorRef(SelRef));
5115 }
5116 
getSelectorRef(Selector Sel)5117 SelectorID ASTWriter::getSelectorRef(Selector Sel) {
5118   if (Sel.getAsOpaquePtr() == nullptr) {
5119     return 0;
5120   }
5121 
5122   SelectorID SID = SelectorIDs[Sel];
5123   if (SID == 0 && Chain) {
5124     // This might trigger a ReadSelector callback, which will set the ID for
5125     // this selector.
5126     Chain->LoadSelector(Sel);
5127     SID = SelectorIDs[Sel];
5128   }
5129   if (SID == 0) {
5130     SID = NextSelectorID++;
5131     SelectorIDs[Sel] = SID;
5132   }
5133   return SID;
5134 }
5135 
AddCXXTemporary(const CXXTemporary * Temp)5136 void ASTRecordWriter::AddCXXTemporary(const CXXTemporary *Temp) {
5137   AddDeclRef(Temp->getDestructor());
5138 }
5139 
AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,const TemplateArgumentLocInfo & Arg)5140 void ASTRecordWriter::AddTemplateArgumentLocInfo(
5141     TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg) {
5142   switch (Kind) {
5143   case TemplateArgument::Expression:
5144     AddStmt(Arg.getAsExpr());
5145     break;
5146   case TemplateArgument::Type:
5147     AddTypeSourceInfo(Arg.getAsTypeSourceInfo());
5148     break;
5149   case TemplateArgument::Template:
5150     AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5151     AddSourceLocation(Arg.getTemplateNameLoc());
5152     break;
5153   case TemplateArgument::TemplateExpansion:
5154     AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5155     AddSourceLocation(Arg.getTemplateNameLoc());
5156     AddSourceLocation(Arg.getTemplateEllipsisLoc());
5157     break;
5158   case TemplateArgument::Null:
5159   case TemplateArgument::Integral:
5160   case TemplateArgument::Declaration:
5161   case TemplateArgument::NullPtr:
5162   case TemplateArgument::Pack:
5163     // FIXME: Is this right?
5164     break;
5165   }
5166 }
5167 
AddTemplateArgumentLoc(const TemplateArgumentLoc & Arg)5168 void ASTRecordWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg) {
5169   AddTemplateArgument(Arg.getArgument());
5170 
5171   if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
5172     bool InfoHasSameExpr
5173       = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
5174     Record->push_back(InfoHasSameExpr);
5175     if (InfoHasSameExpr)
5176       return; // Avoid storing the same expr twice.
5177   }
5178   AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo());
5179 }
5180 
AddTypeSourceInfo(TypeSourceInfo * TInfo)5181 void ASTRecordWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo) {
5182   if (!TInfo) {
5183     AddTypeRef(QualType());
5184     return;
5185   }
5186 
5187   AddTypeRef(TInfo->getType());
5188   AddTypeLoc(TInfo->getTypeLoc());
5189 }
5190 
AddTypeLoc(TypeLoc TL)5191 void ASTRecordWriter::AddTypeLoc(TypeLoc TL) {
5192   TypeLocWriter TLW(*this);
5193   for (; !TL.isNull(); TL = TL.getNextTypeLoc())
5194     TLW.Visit(TL);
5195 }
5196 
AddTypeRef(QualType T,RecordDataImpl & Record)5197 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
5198   Record.push_back(GetOrCreateTypeID(T));
5199 }
5200 
GetOrCreateTypeID(QualType T)5201 TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
5202   assert(Context);
5203   return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5204     if (T.isNull())
5205       return TypeIdx();
5206     assert(!T.getLocalFastQualifiers());
5207 
5208     TypeIdx &Idx = TypeIdxs[T];
5209     if (Idx.getIndex() == 0) {
5210       if (DoneWritingDeclsAndTypes) {
5211         assert(0 && "New type seen after serializing all the types to emit!");
5212         return TypeIdx();
5213       }
5214 
5215       // We haven't seen this type before. Assign it a new ID and put it
5216       // into the queue of types to emit.
5217       Idx = TypeIdx(NextTypeID++);
5218       DeclTypesToEmit.push(T);
5219     }
5220     return Idx;
5221   });
5222 }
5223 
getTypeID(QualType T) const5224 TypeID ASTWriter::getTypeID(QualType T) const {
5225   assert(Context);
5226   return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5227     if (T.isNull())
5228       return TypeIdx();
5229     assert(!T.getLocalFastQualifiers());
5230 
5231     TypeIdxMap::const_iterator I = TypeIdxs.find(T);
5232     assert(I != TypeIdxs.end() && "Type not emitted!");
5233     return I->second;
5234   });
5235 }
5236 
AddDeclRef(const Decl * D,RecordDataImpl & Record)5237 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
5238   Record.push_back(GetDeclRef(D));
5239 }
5240 
GetDeclRef(const Decl * D)5241 DeclID ASTWriter::GetDeclRef(const Decl *D) {
5242   assert(WritingAST && "Cannot request a declaration ID before AST writing");
5243 
5244   if (!D) {
5245     return 0;
5246   }
5247 
5248   // If D comes from an AST file, its declaration ID is already known and
5249   // fixed.
5250   if (D->isFromASTFile())
5251     return D->getGlobalID();
5252 
5253   assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
5254   DeclID &ID = DeclIDs[D];
5255   if (ID == 0) {
5256     if (DoneWritingDeclsAndTypes) {
5257       assert(0 && "New decl seen after serializing all the decls to emit!");
5258       return 0;
5259     }
5260 
5261     // We haven't seen this declaration before. Give it a new ID and
5262     // enqueue it in the list of declarations to emit.
5263     ID = NextDeclID++;
5264     DeclTypesToEmit.push(const_cast<Decl *>(D));
5265   }
5266 
5267   return ID;
5268 }
5269 
getDeclID(const Decl * D)5270 DeclID ASTWriter::getDeclID(const Decl *D) {
5271   if (!D)
5272     return 0;
5273 
5274   // If D comes from an AST file, its declaration ID is already known and
5275   // fixed.
5276   if (D->isFromASTFile())
5277     return D->getGlobalID();
5278 
5279   assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
5280   return DeclIDs[D];
5281 }
5282 
associateDeclWithFile(const Decl * D,DeclID ID)5283 void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
5284   assert(ID);
5285   assert(D);
5286 
5287   SourceLocation Loc = D->getLocation();
5288   if (Loc.isInvalid())
5289     return;
5290 
5291   // We only keep track of the file-level declarations of each file.
5292   if (!D->getLexicalDeclContext()->isFileContext())
5293     return;
5294   // FIXME: ParmVarDecls that are part of a function type of a parameter of
5295   // a function/objc method, should not have TU as lexical context.
5296   // TemplateTemplateParmDecls that are part of an alias template, should not
5297   // have TU as lexical context.
5298   if (isa<ParmVarDecl>(D) || isa<TemplateTemplateParmDecl>(D))
5299     return;
5300 
5301   SourceManager &SM = Context->getSourceManager();
5302   SourceLocation FileLoc = SM.getFileLoc(Loc);
5303   assert(SM.isLocalSourceLocation(FileLoc));
5304   FileID FID;
5305   unsigned Offset;
5306   std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
5307   if (FID.isInvalid())
5308     return;
5309   assert(SM.getSLocEntry(FID).isFile());
5310 
5311   std::unique_ptr<DeclIDInFileInfo> &Info = FileDeclIDs[FID];
5312   if (!Info)
5313     Info = std::make_unique<DeclIDInFileInfo>();
5314 
5315   std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
5316   LocDeclIDsTy &Decls = Info->DeclIDs;
5317 
5318   if (Decls.empty() || Decls.back().first <= Offset) {
5319     Decls.push_back(LocDecl);
5320     return;
5321   }
5322 
5323   LocDeclIDsTy::iterator I =
5324       llvm::upper_bound(Decls, LocDecl, llvm::less_first());
5325 
5326   Decls.insert(I, LocDecl);
5327 }
5328 
getAnonymousDeclarationNumber(const NamedDecl * D)5329 unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
5330   assert(needsAnonymousDeclarationNumber(D) &&
5331          "expected an anonymous declaration");
5332 
5333   // Number the anonymous declarations within this context, if we've not
5334   // already done so.
5335   auto It = AnonymousDeclarationNumbers.find(D);
5336   if (It == AnonymousDeclarationNumbers.end()) {
5337     auto *DC = D->getLexicalDeclContext();
5338     numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
5339       AnonymousDeclarationNumbers[ND] = Number;
5340     });
5341 
5342     It = AnonymousDeclarationNumbers.find(D);
5343     assert(It != AnonymousDeclarationNumbers.end() &&
5344            "declaration not found within its lexical context");
5345   }
5346 
5347   return It->second;
5348 }
5349 
AddDeclarationNameLoc(const DeclarationNameLoc & DNLoc,DeclarationName Name)5350 void ASTRecordWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
5351                                             DeclarationName Name) {
5352   switch (Name.getNameKind()) {
5353   case DeclarationName::CXXConstructorName:
5354   case DeclarationName::CXXDestructorName:
5355   case DeclarationName::CXXConversionFunctionName:
5356     AddTypeSourceInfo(DNLoc.getNamedTypeInfo());
5357     break;
5358 
5359   case DeclarationName::CXXOperatorName:
5360     AddSourceRange(DNLoc.getCXXOperatorNameRange());
5361     break;
5362 
5363   case DeclarationName::CXXLiteralOperatorName:
5364     AddSourceLocation(DNLoc.getCXXLiteralOperatorNameLoc());
5365     break;
5366 
5367   case DeclarationName::Identifier:
5368   case DeclarationName::ObjCZeroArgSelector:
5369   case DeclarationName::ObjCOneArgSelector:
5370   case DeclarationName::ObjCMultiArgSelector:
5371   case DeclarationName::CXXUsingDirective:
5372   case DeclarationName::CXXDeductionGuideName:
5373     break;
5374   }
5375 }
5376 
AddDeclarationNameInfo(const DeclarationNameInfo & NameInfo)5377 void ASTRecordWriter::AddDeclarationNameInfo(
5378     const DeclarationNameInfo &NameInfo) {
5379   AddDeclarationName(NameInfo.getName());
5380   AddSourceLocation(NameInfo.getLoc());
5381   AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName());
5382 }
5383 
AddQualifierInfo(const QualifierInfo & Info)5384 void ASTRecordWriter::AddQualifierInfo(const QualifierInfo &Info) {
5385   AddNestedNameSpecifierLoc(Info.QualifierLoc);
5386   Record->push_back(Info.NumTemplParamLists);
5387   for (unsigned i = 0, e = Info.NumTemplParamLists; i != e; ++i)
5388     AddTemplateParameterList(Info.TemplParamLists[i]);
5389 }
5390 
AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS)5391 void ASTRecordWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
5392   // Nested name specifiers usually aren't too long. I think that 8 would
5393   // typically accommodate the vast majority.
5394   SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
5395 
5396   // Push each of the nested-name-specifiers's onto a stack for
5397   // serialization in reverse order.
5398   while (NNS) {
5399     NestedNames.push_back(NNS);
5400     NNS = NNS.getPrefix();
5401   }
5402 
5403   Record->push_back(NestedNames.size());
5404   while(!NestedNames.empty()) {
5405     NNS = NestedNames.pop_back_val();
5406     NestedNameSpecifier::SpecifierKind Kind
5407       = NNS.getNestedNameSpecifier()->getKind();
5408     Record->push_back(Kind);
5409     switch (Kind) {
5410     case NestedNameSpecifier::Identifier:
5411       AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier());
5412       AddSourceRange(NNS.getLocalSourceRange());
5413       break;
5414 
5415     case NestedNameSpecifier::Namespace:
5416       AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace());
5417       AddSourceRange(NNS.getLocalSourceRange());
5418       break;
5419 
5420     case NestedNameSpecifier::NamespaceAlias:
5421       AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias());
5422       AddSourceRange(NNS.getLocalSourceRange());
5423       break;
5424 
5425     case NestedNameSpecifier::TypeSpec:
5426     case NestedNameSpecifier::TypeSpecWithTemplate:
5427       Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5428       AddTypeRef(NNS.getTypeLoc().getType());
5429       AddTypeLoc(NNS.getTypeLoc());
5430       AddSourceLocation(NNS.getLocalSourceRange().getEnd());
5431       break;
5432 
5433     case NestedNameSpecifier::Global:
5434       AddSourceLocation(NNS.getLocalSourceRange().getEnd());
5435       break;
5436 
5437     case NestedNameSpecifier::Super:
5438       AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl());
5439       AddSourceRange(NNS.getLocalSourceRange());
5440       break;
5441     }
5442   }
5443 }
5444 
AddTemplateParameterList(const TemplateParameterList * TemplateParams)5445 void ASTRecordWriter::AddTemplateParameterList(
5446     const TemplateParameterList *TemplateParams) {
5447   assert(TemplateParams && "No TemplateParams!");
5448   AddSourceLocation(TemplateParams->getTemplateLoc());
5449   AddSourceLocation(TemplateParams->getLAngleLoc());
5450   AddSourceLocation(TemplateParams->getRAngleLoc());
5451 
5452   Record->push_back(TemplateParams->size());
5453   for (const auto &P : *TemplateParams)
5454     AddDeclRef(P);
5455   if (const Expr *RequiresClause = TemplateParams->getRequiresClause()) {
5456     Record->push_back(true);
5457     AddStmt(const_cast<Expr*>(RequiresClause));
5458   } else {
5459     Record->push_back(false);
5460   }
5461 }
5462 
5463 /// Emit a template argument list.
AddTemplateArgumentList(const TemplateArgumentList * TemplateArgs)5464 void ASTRecordWriter::AddTemplateArgumentList(
5465     const TemplateArgumentList *TemplateArgs) {
5466   assert(TemplateArgs && "No TemplateArgs!");
5467   Record->push_back(TemplateArgs->size());
5468   for (int i = 0, e = TemplateArgs->size(); i != e; ++i)
5469     AddTemplateArgument(TemplateArgs->get(i));
5470 }
5471 
AddASTTemplateArgumentListInfo(const ASTTemplateArgumentListInfo * ASTTemplArgList)5472 void ASTRecordWriter::AddASTTemplateArgumentListInfo(
5473     const ASTTemplateArgumentListInfo *ASTTemplArgList) {
5474   assert(ASTTemplArgList && "No ASTTemplArgList!");
5475   AddSourceLocation(ASTTemplArgList->LAngleLoc);
5476   AddSourceLocation(ASTTemplArgList->RAngleLoc);
5477   Record->push_back(ASTTemplArgList->NumTemplateArgs);
5478   const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
5479   for (int i = 0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
5480     AddTemplateArgumentLoc(TemplArgs[i]);
5481 }
5482 
AddUnresolvedSet(const ASTUnresolvedSet & Set)5483 void ASTRecordWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set) {
5484   Record->push_back(Set.size());
5485   for (ASTUnresolvedSet::const_iterator
5486          I = Set.begin(), E = Set.end(); I != E; ++I) {
5487     AddDeclRef(I.getDecl());
5488     Record->push_back(I.getAccess());
5489   }
5490 }
5491 
5492 // FIXME: Move this out of the main ASTRecordWriter interface.
AddCXXBaseSpecifier(const CXXBaseSpecifier & Base)5493 void ASTRecordWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
5494   Record->push_back(Base.isVirtual());
5495   Record->push_back(Base.isBaseOfClass());
5496   Record->push_back(Base.getAccessSpecifierAsWritten());
5497   Record->push_back(Base.getInheritConstructors());
5498   AddTypeSourceInfo(Base.getTypeSourceInfo());
5499   AddSourceRange(Base.getSourceRange());
5500   AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
5501                                           : SourceLocation());
5502 }
5503 
EmitCXXBaseSpecifiers(ASTWriter & W,ArrayRef<CXXBaseSpecifier> Bases)5504 static uint64_t EmitCXXBaseSpecifiers(ASTWriter &W,
5505                                       ArrayRef<CXXBaseSpecifier> Bases) {
5506   ASTWriter::RecordData Record;
5507   ASTRecordWriter Writer(W, Record);
5508   Writer.push_back(Bases.size());
5509 
5510   for (auto &Base : Bases)
5511     Writer.AddCXXBaseSpecifier(Base);
5512 
5513   return Writer.Emit(serialization::DECL_CXX_BASE_SPECIFIERS);
5514 }
5515 
5516 // FIXME: Move this out of the main ASTRecordWriter interface.
AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases)5517 void ASTRecordWriter::AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases) {
5518   AddOffset(EmitCXXBaseSpecifiers(*Writer, Bases));
5519 }
5520 
5521 static uint64_t
EmitCXXCtorInitializers(ASTWriter & W,ArrayRef<CXXCtorInitializer * > CtorInits)5522 EmitCXXCtorInitializers(ASTWriter &W,
5523                         ArrayRef<CXXCtorInitializer *> CtorInits) {
5524   ASTWriter::RecordData Record;
5525   ASTRecordWriter Writer(W, Record);
5526   Writer.push_back(CtorInits.size());
5527 
5528   for (auto *Init : CtorInits) {
5529     if (Init->isBaseInitializer()) {
5530       Writer.push_back(CTOR_INITIALIZER_BASE);
5531       Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
5532       Writer.push_back(Init->isBaseVirtual());
5533     } else if (Init->isDelegatingInitializer()) {
5534       Writer.push_back(CTOR_INITIALIZER_DELEGATING);
5535       Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
5536     } else if (Init->isMemberInitializer()){
5537       Writer.push_back(CTOR_INITIALIZER_MEMBER);
5538       Writer.AddDeclRef(Init->getMember());
5539     } else {
5540       Writer.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
5541       Writer.AddDeclRef(Init->getIndirectMember());
5542     }
5543 
5544     Writer.AddSourceLocation(Init->getMemberLocation());
5545     Writer.AddStmt(Init->getInit());
5546     Writer.AddSourceLocation(Init->getLParenLoc());
5547     Writer.AddSourceLocation(Init->getRParenLoc());
5548     Writer.push_back(Init->isWritten());
5549     if (Init->isWritten())
5550       Writer.push_back(Init->getSourceOrder());
5551   }
5552 
5553   return Writer.Emit(serialization::DECL_CXX_CTOR_INITIALIZERS);
5554 }
5555 
5556 // FIXME: Move this out of the main ASTRecordWriter interface.
AddCXXCtorInitializers(ArrayRef<CXXCtorInitializer * > CtorInits)5557 void ASTRecordWriter::AddCXXCtorInitializers(
5558     ArrayRef<CXXCtorInitializer *> CtorInits) {
5559   AddOffset(EmitCXXCtorInitializers(*Writer, CtorInits));
5560 }
5561 
AddCXXDefinitionData(const CXXRecordDecl * D)5562 void ASTRecordWriter::AddCXXDefinitionData(const CXXRecordDecl *D) {
5563   auto &Data = D->data();
5564   Record->push_back(Data.IsLambda);
5565 
5566   #define FIELD(Name, Width, Merge) \
5567   Record->push_back(Data.Name);
5568   #include "clang/AST/CXXRecordDeclDefinitionBits.def"
5569 
5570   // getODRHash will compute the ODRHash if it has not been previously computed.
5571   Record->push_back(D->getODRHash());
5572   bool ModulesDebugInfo =
5573       Writer->Context->getLangOpts().ModulesDebugInfo && !D->isDependentType();
5574   Record->push_back(ModulesDebugInfo);
5575   if (ModulesDebugInfo)
5576     Writer->ModularCodegenDecls.push_back(Writer->GetDeclRef(D));
5577 
5578   // IsLambda bit is already saved.
5579 
5580   Record->push_back(Data.NumBases);
5581   if (Data.NumBases > 0)
5582     AddCXXBaseSpecifiers(Data.bases());
5583 
5584   // FIXME: Make VBases lazily computed when needed to avoid storing them.
5585   Record->push_back(Data.NumVBases);
5586   if (Data.NumVBases > 0)
5587     AddCXXBaseSpecifiers(Data.vbases());
5588 
5589   AddUnresolvedSet(Data.Conversions.get(*Writer->Context));
5590   Record->push_back(Data.ComputedVisibleConversions);
5591   if (Data.ComputedVisibleConversions)
5592     AddUnresolvedSet(Data.VisibleConversions.get(*Writer->Context));
5593   // Data.Definition is the owning decl, no need to write it.
5594   AddDeclRef(D->getFirstFriend());
5595 
5596   // Add lambda-specific data.
5597   if (Data.IsLambda) {
5598     auto &Lambda = D->getLambdaData();
5599     Record->push_back(Lambda.Dependent);
5600     Record->push_back(Lambda.IsGenericLambda);
5601     Record->push_back(Lambda.CaptureDefault);
5602     Record->push_back(Lambda.NumCaptures);
5603     Record->push_back(Lambda.NumExplicitCaptures);
5604     Record->push_back(Lambda.HasKnownInternalLinkage);
5605     Record->push_back(Lambda.ManglingNumber);
5606     Record->push_back(D->getDeviceLambdaManglingNumber());
5607     AddDeclRef(D->getLambdaContextDecl());
5608     AddTypeSourceInfo(Lambda.MethodTyInfo);
5609     for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
5610       const LambdaCapture &Capture = Lambda.Captures[I];
5611       AddSourceLocation(Capture.getLocation());
5612       Record->push_back(Capture.isImplicit());
5613       Record->push_back(Capture.getCaptureKind());
5614       switch (Capture.getCaptureKind()) {
5615       case LCK_StarThis:
5616       case LCK_This:
5617       case LCK_VLAType:
5618         break;
5619       case LCK_ByCopy:
5620       case LCK_ByRef:
5621         VarDecl *Var =
5622             Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
5623         AddDeclRef(Var);
5624         AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
5625                                                     : SourceLocation());
5626         break;
5627       }
5628     }
5629   }
5630 }
5631 
AddVarDeclInit(const VarDecl * VD)5632 void ASTRecordWriter::AddVarDeclInit(const VarDecl *VD) {
5633   const Expr *Init = VD->getInit();
5634   if (!Init) {
5635     push_back(0);
5636     return;
5637   }
5638 
5639   unsigned Val = 1;
5640   if (EvaluatedStmt *ES = VD->getEvaluatedStmt()) {
5641     Val |= (ES->HasConstantInitialization ? 2 : 0);
5642     Val |= (ES->HasConstantDestruction ? 4 : 0);
5643     // FIXME: Also emit the constant initializer value.
5644   }
5645   push_back(Val);
5646   writeStmtRef(Init);
5647 }
5648 
ReaderInitialized(ASTReader * Reader)5649 void ASTWriter::ReaderInitialized(ASTReader *Reader) {
5650   assert(Reader && "Cannot remove chain");
5651   assert((!Chain || Chain == Reader) && "Cannot replace chain");
5652   assert(FirstDeclID == NextDeclID &&
5653          FirstTypeID == NextTypeID &&
5654          FirstIdentID == NextIdentID &&
5655          FirstMacroID == NextMacroID &&
5656          FirstSubmoduleID == NextSubmoduleID &&
5657          FirstSelectorID == NextSelectorID &&
5658          "Setting chain after writing has started.");
5659 
5660   Chain = Reader;
5661 
5662   // Note, this will get called multiple times, once one the reader starts up
5663   // and again each time it's done reading a PCH or module.
5664   FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
5665   FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
5666   FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
5667   FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
5668   FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
5669   FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
5670   NextDeclID = FirstDeclID;
5671   NextTypeID = FirstTypeID;
5672   NextIdentID = FirstIdentID;
5673   NextMacroID = FirstMacroID;
5674   NextSelectorID = FirstSelectorID;
5675   NextSubmoduleID = FirstSubmoduleID;
5676 }
5677 
IdentifierRead(IdentID ID,IdentifierInfo * II)5678 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
5679   // Always keep the highest ID. See \p TypeRead() for more information.
5680   IdentID &StoredID = IdentifierIDs[II];
5681   if (ID > StoredID)
5682     StoredID = ID;
5683 }
5684 
MacroRead(serialization::MacroID ID,MacroInfo * MI)5685 void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
5686   // Always keep the highest ID. See \p TypeRead() for more information.
5687   MacroID &StoredID = MacroIDs[MI];
5688   if (ID > StoredID)
5689     StoredID = ID;
5690 }
5691 
TypeRead(TypeIdx Idx,QualType T)5692 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
5693   // Always take the highest-numbered type index. This copes with an interesting
5694   // case for chained AST writing where we schedule writing the type and then,
5695   // later, deserialize the type from another AST. In this case, we want to
5696   // keep the higher-numbered entry so that we can properly write it out to
5697   // the AST file.
5698   TypeIdx &StoredIdx = TypeIdxs[T];
5699   if (Idx.getIndex() >= StoredIdx.getIndex())
5700     StoredIdx = Idx;
5701 }
5702 
SelectorRead(SelectorID ID,Selector S)5703 void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
5704   // Always keep the highest ID. See \p TypeRead() for more information.
5705   SelectorID &StoredID = SelectorIDs[S];
5706   if (ID > StoredID)
5707     StoredID = ID;
5708 }
5709 
MacroDefinitionRead(serialization::PreprocessedEntityID ID,MacroDefinitionRecord * MD)5710 void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
5711                                     MacroDefinitionRecord *MD) {
5712   assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
5713   MacroDefinitions[MD] = ID;
5714 }
5715 
ModuleRead(serialization::SubmoduleID ID,Module * Mod)5716 void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
5717   assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
5718   SubmoduleIDs[Mod] = ID;
5719 }
5720 
CompletedTagDefinition(const TagDecl * D)5721 void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
5722   if (Chain && Chain->isProcessingUpdateRecords()) return;
5723   assert(D->isCompleteDefinition());
5724   assert(!WritingAST && "Already writing the AST!");
5725   if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
5726     // We are interested when a PCH decl is modified.
5727     if (RD->isFromASTFile()) {
5728       // A forward reference was mutated into a definition. Rewrite it.
5729       // FIXME: This happens during template instantiation, should we
5730       // have created a new definition decl instead ?
5731       assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
5732              "completed a tag from another module but not by instantiation?");
5733       DeclUpdates[RD].push_back(
5734           DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION));
5735     }
5736   }
5737 }
5738 
isImportedDeclContext(ASTReader * Chain,const Decl * D)5739 static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) {
5740   if (D->isFromASTFile())
5741     return true;
5742 
5743   // The predefined __va_list_tag struct is imported if we imported any decls.
5744   // FIXME: This is a gross hack.
5745   return D == D->getASTContext().getVaListTagDecl();
5746 }
5747 
AddedVisibleDecl(const DeclContext * DC,const Decl * D)5748 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
5749   if (Chain && Chain->isProcessingUpdateRecords()) return;
5750   assert(DC->isLookupContext() &&
5751           "Should not add lookup results to non-lookup contexts!");
5752 
5753   // TU is handled elsewhere.
5754   if (isa<TranslationUnitDecl>(DC))
5755     return;
5756 
5757   // Namespaces are handled elsewhere, except for template instantiations of
5758   // FunctionTemplateDecls in namespaces. We are interested in cases where the
5759   // local instantiations are added to an imported context. Only happens when
5760   // adding ADL lookup candidates, for example templated friends.
5761   if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None &&
5762       !isa<FunctionTemplateDecl>(D))
5763     return;
5764 
5765   // We're only interested in cases where a local declaration is added to an
5766   // imported context.
5767   if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC)))
5768     return;
5769 
5770   assert(DC == DC->getPrimaryContext() && "added to non-primary context");
5771   assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
5772   assert(!WritingAST && "Already writing the AST!");
5773   if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) {
5774     // We're adding a visible declaration to a predefined decl context. Ensure
5775     // that we write out all of its lookup results so we don't get a nasty
5776     // surprise when we try to emit its lookup table.
5777     for (auto *Child : DC->decls())
5778       DeclsToEmitEvenIfUnreferenced.push_back(Child);
5779   }
5780   DeclsToEmitEvenIfUnreferenced.push_back(D);
5781 }
5782 
AddedCXXImplicitMember(const CXXRecordDecl * RD,const Decl * D)5783 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
5784   if (Chain && Chain->isProcessingUpdateRecords()) return;
5785   assert(D->isImplicit());
5786 
5787   // We're only interested in cases where a local declaration is added to an
5788   // imported context.
5789   if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD))
5790     return;
5791 
5792   if (!isa<CXXMethodDecl>(D))
5793     return;
5794 
5795   // A decl coming from PCH was modified.
5796   assert(RD->isCompleteDefinition());
5797   assert(!WritingAST && "Already writing the AST!");
5798   DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
5799 }
5800 
ResolvedExceptionSpec(const FunctionDecl * FD)5801 void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
5802   if (Chain && Chain->isProcessingUpdateRecords()) return;
5803   assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
5804   if (!Chain) return;
5805   Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
5806     // If we don't already know the exception specification for this redecl
5807     // chain, add an update record for it.
5808     if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
5809                                       ->getType()
5810                                       ->castAs<FunctionProtoType>()
5811                                       ->getExceptionSpecType()))
5812       DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
5813   });
5814 }
5815 
DeducedReturnType(const FunctionDecl * FD,QualType ReturnType)5816 void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
5817   if (Chain && Chain->isProcessingUpdateRecords()) return;
5818   assert(!WritingAST && "Already writing the AST!");
5819   if (!Chain) return;
5820   Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
5821     DeclUpdates[D].push_back(
5822         DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
5823   });
5824 }
5825 
ResolvedOperatorDelete(const CXXDestructorDecl * DD,const FunctionDecl * Delete,Expr * ThisArg)5826 void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
5827                                        const FunctionDecl *Delete,
5828                                        Expr *ThisArg) {
5829   if (Chain && Chain->isProcessingUpdateRecords()) return;
5830   assert(!WritingAST && "Already writing the AST!");
5831   assert(Delete && "Not given an operator delete");
5832   if (!Chain) return;
5833   Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
5834     DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete));
5835   });
5836 }
5837 
CompletedImplicitDefinition(const FunctionDecl * D)5838 void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
5839   if (Chain && Chain->isProcessingUpdateRecords()) return;
5840   assert(!WritingAST && "Already writing the AST!");
5841   if (!D->isFromASTFile())
5842     return; // Declaration not imported from PCH.
5843 
5844   // Implicit function decl from a PCH was defined.
5845   DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
5846 }
5847 
VariableDefinitionInstantiated(const VarDecl * D)5848 void ASTWriter::VariableDefinitionInstantiated(const VarDecl *D) {
5849   if (Chain && Chain->isProcessingUpdateRecords()) return;
5850   assert(!WritingAST && "Already writing the AST!");
5851   if (!D->isFromASTFile())
5852     return;
5853 
5854   DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_VAR_DEFINITION));
5855 }
5856 
FunctionDefinitionInstantiated(const FunctionDecl * D)5857 void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
5858   if (Chain && Chain->isProcessingUpdateRecords()) return;
5859   assert(!WritingAST && "Already writing the AST!");
5860   if (!D->isFromASTFile())
5861     return;
5862 
5863   DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
5864 }
5865 
InstantiationRequested(const ValueDecl * D)5866 void ASTWriter::InstantiationRequested(const ValueDecl *D) {
5867   if (Chain && Chain->isProcessingUpdateRecords()) return;
5868   assert(!WritingAST && "Already writing the AST!");
5869   if (!D->isFromASTFile())
5870     return;
5871 
5872   // Since the actual instantiation is delayed, this really means that we need
5873   // to update the instantiation location.
5874   SourceLocation POI;
5875   if (auto *VD = dyn_cast<VarDecl>(D))
5876     POI = VD->getPointOfInstantiation();
5877   else
5878     POI = cast<FunctionDecl>(D)->getPointOfInstantiation();
5879   DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_POINT_OF_INSTANTIATION, POI));
5880 }
5881 
DefaultArgumentInstantiated(const ParmVarDecl * D)5882 void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) {
5883   if (Chain && Chain->isProcessingUpdateRecords()) return;
5884   assert(!WritingAST && "Already writing the AST!");
5885   if (!D->isFromASTFile())
5886     return;
5887 
5888   DeclUpdates[D].push_back(
5889       DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D));
5890 }
5891 
DefaultMemberInitializerInstantiated(const FieldDecl * D)5892 void ASTWriter::DefaultMemberInitializerInstantiated(const FieldDecl *D) {
5893   assert(!WritingAST && "Already writing the AST!");
5894   if (!D->isFromASTFile())
5895     return;
5896 
5897   DeclUpdates[D].push_back(
5898       DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER, D));
5899 }
5900 
AddedObjCCategoryToInterface(const ObjCCategoryDecl * CatD,const ObjCInterfaceDecl * IFD)5901 void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
5902                                              const ObjCInterfaceDecl *IFD) {
5903   if (Chain && Chain->isProcessingUpdateRecords()) return;
5904   assert(!WritingAST && "Already writing the AST!");
5905   if (!IFD->isFromASTFile())
5906     return; // Declaration not imported from PCH.
5907 
5908   assert(IFD->getDefinition() && "Category on a class without a definition?");
5909   ObjCClassesWithCategories.insert(
5910     const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
5911 }
5912 
DeclarationMarkedUsed(const Decl * D)5913 void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
5914   if (Chain && Chain->isProcessingUpdateRecords()) return;
5915   assert(!WritingAST && "Already writing the AST!");
5916 
5917   // If there is *any* declaration of the entity that's not from an AST file,
5918   // we can skip writing the update record. We make sure that isUsed() triggers
5919   // completion of the redeclaration chain of the entity.
5920   for (auto Prev = D->getMostRecentDecl(); Prev; Prev = Prev->getPreviousDecl())
5921     if (IsLocalDecl(Prev))
5922       return;
5923 
5924   DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
5925 }
5926 
DeclarationMarkedOpenMPThreadPrivate(const Decl * D)5927 void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
5928   if (Chain && Chain->isProcessingUpdateRecords()) return;
5929   assert(!WritingAST && "Already writing the AST!");
5930   if (!D->isFromASTFile())
5931     return;
5932 
5933   DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE));
5934 }
5935 
DeclarationMarkedOpenMPAllocate(const Decl * D,const Attr * A)5936 void ASTWriter::DeclarationMarkedOpenMPAllocate(const Decl *D, const Attr *A) {
5937   if (Chain && Chain->isProcessingUpdateRecords()) return;
5938   assert(!WritingAST && "Already writing the AST!");
5939   if (!D->isFromASTFile())
5940     return;
5941 
5942   DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_ALLOCATE, A));
5943 }
5944 
DeclarationMarkedOpenMPDeclareTarget(const Decl * D,const Attr * Attr)5945 void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
5946                                                      const Attr *Attr) {
5947   if (Chain && Chain->isProcessingUpdateRecords()) return;
5948   assert(!WritingAST && "Already writing the AST!");
5949   if (!D->isFromASTFile())
5950     return;
5951 
5952   DeclUpdates[D].push_back(
5953       DeclUpdate(UPD_DECL_MARKED_OPENMP_DECLARETARGET, Attr));
5954 }
5955 
RedefinedHiddenDefinition(const NamedDecl * D,Module * M)5956 void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
5957   if (Chain && Chain->isProcessingUpdateRecords()) return;
5958   assert(!WritingAST && "Already writing the AST!");
5959   assert(!D->isUnconditionallyVisible() && "expected a hidden declaration");
5960   DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M));
5961 }
5962 
AddedAttributeToRecord(const Attr * Attr,const RecordDecl * Record)5963 void ASTWriter::AddedAttributeToRecord(const Attr *Attr,
5964                                        const RecordDecl *Record) {
5965   if (Chain && Chain->isProcessingUpdateRecords()) return;
5966   assert(!WritingAST && "Already writing the AST!");
5967   if (!Record->isFromASTFile())
5968     return;
5969   DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr));
5970 }
5971 
AddedCXXTemplateSpecialization(const ClassTemplateDecl * TD,const ClassTemplateSpecializationDecl * D)5972 void ASTWriter::AddedCXXTemplateSpecialization(
5973     const ClassTemplateDecl *TD, const ClassTemplateSpecializationDecl *D) {
5974   assert(!WritingAST && "Already writing the AST!");
5975 
5976   if (!TD->getFirstDecl()->isFromASTFile())
5977     return;
5978   if (Chain && Chain->isProcessingUpdateRecords())
5979     return;
5980 
5981   DeclsToEmitEvenIfUnreferenced.push_back(D);
5982 }
5983 
AddedCXXTemplateSpecialization(const VarTemplateDecl * TD,const VarTemplateSpecializationDecl * D)5984 void ASTWriter::AddedCXXTemplateSpecialization(
5985     const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) {
5986   assert(!WritingAST && "Already writing the AST!");
5987 
5988   if (!TD->getFirstDecl()->isFromASTFile())
5989     return;
5990   if (Chain && Chain->isProcessingUpdateRecords())
5991     return;
5992 
5993   DeclsToEmitEvenIfUnreferenced.push_back(D);
5994 }
5995 
AddedCXXTemplateSpecialization(const FunctionTemplateDecl * TD,const FunctionDecl * D)5996 void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
5997                                                const FunctionDecl *D) {
5998   assert(!WritingAST && "Already writing the AST!");
5999 
6000   if (!TD->getFirstDecl()->isFromASTFile())
6001     return;
6002   if (Chain && Chain->isProcessingUpdateRecords())
6003     return;
6004 
6005   DeclsToEmitEvenIfUnreferenced.push_back(D);
6006 }
6007 
6008 //===----------------------------------------------------------------------===//
6009 //// OMPClause Serialization
6010 ////===----------------------------------------------------------------------===//
6011 
6012 namespace {
6013 
6014 class OMPClauseWriter : public OMPClauseVisitor<OMPClauseWriter> {
6015   ASTRecordWriter &Record;
6016 
6017 public:
OMPClauseWriter(ASTRecordWriter & Record)6018   OMPClauseWriter(ASTRecordWriter &Record) : Record(Record) {}
6019 #define GEN_CLANG_CLAUSE_CLASS
6020 #define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *S);
6021 #include "llvm/Frontend/OpenMP/OMP.inc"
6022   void writeClause(OMPClause *C);
6023   void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C);
6024   void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C);
6025 };
6026 
6027 }
6028 
writeOMPClause(OMPClause * C)6029 void ASTRecordWriter::writeOMPClause(OMPClause *C) {
6030   OMPClauseWriter(*this).writeClause(C);
6031 }
6032 
writeClause(OMPClause * C)6033 void OMPClauseWriter::writeClause(OMPClause *C) {
6034   Record.push_back(unsigned(C->getClauseKind()));
6035   Visit(C);
6036   Record.AddSourceLocation(C->getBeginLoc());
6037   Record.AddSourceLocation(C->getEndLoc());
6038 }
6039 
VisitOMPClauseWithPreInit(OMPClauseWithPreInit * C)6040 void OMPClauseWriter::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
6041   Record.push_back(uint64_t(C->getCaptureRegion()));
6042   Record.AddStmt(C->getPreInitStmt());
6043 }
6044 
VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate * C)6045 void OMPClauseWriter::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
6046   VisitOMPClauseWithPreInit(C);
6047   Record.AddStmt(C->getPostUpdateExpr());
6048 }
6049 
VisitOMPIfClause(OMPIfClause * C)6050 void OMPClauseWriter::VisitOMPIfClause(OMPIfClause *C) {
6051   VisitOMPClauseWithPreInit(C);
6052   Record.push_back(uint64_t(C->getNameModifier()));
6053   Record.AddSourceLocation(C->getNameModifierLoc());
6054   Record.AddSourceLocation(C->getColonLoc());
6055   Record.AddStmt(C->getCondition());
6056   Record.AddSourceLocation(C->getLParenLoc());
6057 }
6058 
VisitOMPFinalClause(OMPFinalClause * C)6059 void OMPClauseWriter::VisitOMPFinalClause(OMPFinalClause *C) {
6060   VisitOMPClauseWithPreInit(C);
6061   Record.AddStmt(C->getCondition());
6062   Record.AddSourceLocation(C->getLParenLoc());
6063 }
6064 
VisitOMPNumThreadsClause(OMPNumThreadsClause * C)6065 void OMPClauseWriter::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
6066   VisitOMPClauseWithPreInit(C);
6067   Record.AddStmt(C->getNumThreads());
6068   Record.AddSourceLocation(C->getLParenLoc());
6069 }
6070 
VisitOMPSafelenClause(OMPSafelenClause * C)6071 void OMPClauseWriter::VisitOMPSafelenClause(OMPSafelenClause *C) {
6072   Record.AddStmt(C->getSafelen());
6073   Record.AddSourceLocation(C->getLParenLoc());
6074 }
6075 
VisitOMPSimdlenClause(OMPSimdlenClause * C)6076 void OMPClauseWriter::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
6077   Record.AddStmt(C->getSimdlen());
6078   Record.AddSourceLocation(C->getLParenLoc());
6079 }
6080 
VisitOMPSizesClause(OMPSizesClause * C)6081 void OMPClauseWriter::VisitOMPSizesClause(OMPSizesClause *C) {
6082   Record.push_back(C->getNumSizes());
6083   for (Expr *Size : C->getSizesRefs())
6084     Record.AddStmt(Size);
6085   Record.AddSourceLocation(C->getLParenLoc());
6086 }
6087 
VisitOMPFullClause(OMPFullClause * C)6088 void OMPClauseWriter::VisitOMPFullClause(OMPFullClause *C) {}
6089 
VisitOMPPartialClause(OMPPartialClause * C)6090 void OMPClauseWriter::VisitOMPPartialClause(OMPPartialClause *C) {
6091   Record.AddStmt(C->getFactor());
6092   Record.AddSourceLocation(C->getLParenLoc());
6093 }
6094 
VisitOMPAllocatorClause(OMPAllocatorClause * C)6095 void OMPClauseWriter::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
6096   Record.AddStmt(C->getAllocator());
6097   Record.AddSourceLocation(C->getLParenLoc());
6098 }
6099 
VisitOMPCollapseClause(OMPCollapseClause * C)6100 void OMPClauseWriter::VisitOMPCollapseClause(OMPCollapseClause *C) {
6101   Record.AddStmt(C->getNumForLoops());
6102   Record.AddSourceLocation(C->getLParenLoc());
6103 }
6104 
VisitOMPDetachClause(OMPDetachClause * C)6105 void OMPClauseWriter::VisitOMPDetachClause(OMPDetachClause *C) {
6106   Record.AddStmt(C->getEventHandler());
6107   Record.AddSourceLocation(C->getLParenLoc());
6108 }
6109 
VisitOMPDefaultClause(OMPDefaultClause * C)6110 void OMPClauseWriter::VisitOMPDefaultClause(OMPDefaultClause *C) {
6111   Record.push_back(unsigned(C->getDefaultKind()));
6112   Record.AddSourceLocation(C->getLParenLoc());
6113   Record.AddSourceLocation(C->getDefaultKindKwLoc());
6114 }
6115 
VisitOMPProcBindClause(OMPProcBindClause * C)6116 void OMPClauseWriter::VisitOMPProcBindClause(OMPProcBindClause *C) {
6117   Record.push_back(unsigned(C->getProcBindKind()));
6118   Record.AddSourceLocation(C->getLParenLoc());
6119   Record.AddSourceLocation(C->getProcBindKindKwLoc());
6120 }
6121 
VisitOMPScheduleClause(OMPScheduleClause * C)6122 void OMPClauseWriter::VisitOMPScheduleClause(OMPScheduleClause *C) {
6123   VisitOMPClauseWithPreInit(C);
6124   Record.push_back(C->getScheduleKind());
6125   Record.push_back(C->getFirstScheduleModifier());
6126   Record.push_back(C->getSecondScheduleModifier());
6127   Record.AddStmt(C->getChunkSize());
6128   Record.AddSourceLocation(C->getLParenLoc());
6129   Record.AddSourceLocation(C->getFirstScheduleModifierLoc());
6130   Record.AddSourceLocation(C->getSecondScheduleModifierLoc());
6131   Record.AddSourceLocation(C->getScheduleKindLoc());
6132   Record.AddSourceLocation(C->getCommaLoc());
6133 }
6134 
VisitOMPOrderedClause(OMPOrderedClause * C)6135 void OMPClauseWriter::VisitOMPOrderedClause(OMPOrderedClause *C) {
6136   Record.push_back(C->getLoopNumIterations().size());
6137   Record.AddStmt(C->getNumForLoops());
6138   for (Expr *NumIter : C->getLoopNumIterations())
6139     Record.AddStmt(NumIter);
6140   for (unsigned I = 0, E = C->getLoopNumIterations().size(); I <E; ++I)
6141     Record.AddStmt(C->getLoopCounter(I));
6142   Record.AddSourceLocation(C->getLParenLoc());
6143 }
6144 
VisitOMPNowaitClause(OMPNowaitClause *)6145 void OMPClauseWriter::VisitOMPNowaitClause(OMPNowaitClause *) {}
6146 
VisitOMPUntiedClause(OMPUntiedClause *)6147 void OMPClauseWriter::VisitOMPUntiedClause(OMPUntiedClause *) {}
6148 
VisitOMPMergeableClause(OMPMergeableClause *)6149 void OMPClauseWriter::VisitOMPMergeableClause(OMPMergeableClause *) {}
6150 
VisitOMPReadClause(OMPReadClause *)6151 void OMPClauseWriter::VisitOMPReadClause(OMPReadClause *) {}
6152 
VisitOMPWriteClause(OMPWriteClause *)6153 void OMPClauseWriter::VisitOMPWriteClause(OMPWriteClause *) {}
6154 
VisitOMPUpdateClause(OMPUpdateClause * C)6155 void OMPClauseWriter::VisitOMPUpdateClause(OMPUpdateClause *C) {
6156   Record.push_back(C->isExtended() ? 1 : 0);
6157   if (C->isExtended()) {
6158     Record.AddSourceLocation(C->getLParenLoc());
6159     Record.AddSourceLocation(C->getArgumentLoc());
6160     Record.writeEnum(C->getDependencyKind());
6161   }
6162 }
6163 
VisitOMPCaptureClause(OMPCaptureClause *)6164 void OMPClauseWriter::VisitOMPCaptureClause(OMPCaptureClause *) {}
6165 
VisitOMPSeqCstClause(OMPSeqCstClause *)6166 void OMPClauseWriter::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
6167 
VisitOMPAcqRelClause(OMPAcqRelClause *)6168 void OMPClauseWriter::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
6169 
VisitOMPAcquireClause(OMPAcquireClause *)6170 void OMPClauseWriter::VisitOMPAcquireClause(OMPAcquireClause *) {}
6171 
VisitOMPReleaseClause(OMPReleaseClause *)6172 void OMPClauseWriter::VisitOMPReleaseClause(OMPReleaseClause *) {}
6173 
VisitOMPRelaxedClause(OMPRelaxedClause *)6174 void OMPClauseWriter::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
6175 
VisitOMPThreadsClause(OMPThreadsClause *)6176 void OMPClauseWriter::VisitOMPThreadsClause(OMPThreadsClause *) {}
6177 
VisitOMPSIMDClause(OMPSIMDClause *)6178 void OMPClauseWriter::VisitOMPSIMDClause(OMPSIMDClause *) {}
6179 
VisitOMPNogroupClause(OMPNogroupClause *)6180 void OMPClauseWriter::VisitOMPNogroupClause(OMPNogroupClause *) {}
6181 
VisitOMPInitClause(OMPInitClause * C)6182 void OMPClauseWriter::VisitOMPInitClause(OMPInitClause *C) {
6183   Record.push_back(C->varlist_size());
6184   for (Expr *VE : C->varlists())
6185     Record.AddStmt(VE);
6186   Record.writeBool(C->getIsTarget());
6187   Record.writeBool(C->getIsTargetSync());
6188   Record.AddSourceLocation(C->getLParenLoc());
6189   Record.AddSourceLocation(C->getVarLoc());
6190 }
6191 
VisitOMPUseClause(OMPUseClause * C)6192 void OMPClauseWriter::VisitOMPUseClause(OMPUseClause *C) {
6193   Record.AddStmt(C->getInteropVar());
6194   Record.AddSourceLocation(C->getLParenLoc());
6195   Record.AddSourceLocation(C->getVarLoc());
6196 }
6197 
VisitOMPDestroyClause(OMPDestroyClause * C)6198 void OMPClauseWriter::VisitOMPDestroyClause(OMPDestroyClause *C) {
6199   Record.AddStmt(C->getInteropVar());
6200   Record.AddSourceLocation(C->getLParenLoc());
6201   Record.AddSourceLocation(C->getVarLoc());
6202 }
6203 
VisitOMPNovariantsClause(OMPNovariantsClause * C)6204 void OMPClauseWriter::VisitOMPNovariantsClause(OMPNovariantsClause *C) {
6205   VisitOMPClauseWithPreInit(C);
6206   Record.AddStmt(C->getCondition());
6207   Record.AddSourceLocation(C->getLParenLoc());
6208 }
6209 
VisitOMPNocontextClause(OMPNocontextClause * C)6210 void OMPClauseWriter::VisitOMPNocontextClause(OMPNocontextClause *C) {
6211   VisitOMPClauseWithPreInit(C);
6212   Record.AddStmt(C->getCondition());
6213   Record.AddSourceLocation(C->getLParenLoc());
6214 }
6215 
VisitOMPFilterClause(OMPFilterClause * C)6216 void OMPClauseWriter::VisitOMPFilterClause(OMPFilterClause *C) {
6217   VisitOMPClauseWithPreInit(C);
6218   Record.AddStmt(C->getThreadID());
6219   Record.AddSourceLocation(C->getLParenLoc());
6220 }
6221 
VisitOMPPrivateClause(OMPPrivateClause * C)6222 void OMPClauseWriter::VisitOMPPrivateClause(OMPPrivateClause *C) {
6223   Record.push_back(C->varlist_size());
6224   Record.AddSourceLocation(C->getLParenLoc());
6225   for (auto *VE : C->varlists()) {
6226     Record.AddStmt(VE);
6227   }
6228   for (auto *VE : C->private_copies()) {
6229     Record.AddStmt(VE);
6230   }
6231 }
6232 
VisitOMPFirstprivateClause(OMPFirstprivateClause * C)6233 void OMPClauseWriter::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
6234   Record.push_back(C->varlist_size());
6235   VisitOMPClauseWithPreInit(C);
6236   Record.AddSourceLocation(C->getLParenLoc());
6237   for (auto *VE : C->varlists()) {
6238     Record.AddStmt(VE);
6239   }
6240   for (auto *VE : C->private_copies()) {
6241     Record.AddStmt(VE);
6242   }
6243   for (auto *VE : C->inits()) {
6244     Record.AddStmt(VE);
6245   }
6246 }
6247 
VisitOMPLastprivateClause(OMPLastprivateClause * C)6248 void OMPClauseWriter::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
6249   Record.push_back(C->varlist_size());
6250   VisitOMPClauseWithPostUpdate(C);
6251   Record.AddSourceLocation(C->getLParenLoc());
6252   Record.writeEnum(C->getKind());
6253   Record.AddSourceLocation(C->getKindLoc());
6254   Record.AddSourceLocation(C->getColonLoc());
6255   for (auto *VE : C->varlists())
6256     Record.AddStmt(VE);
6257   for (auto *E : C->private_copies())
6258     Record.AddStmt(E);
6259   for (auto *E : C->source_exprs())
6260     Record.AddStmt(E);
6261   for (auto *E : C->destination_exprs())
6262     Record.AddStmt(E);
6263   for (auto *E : C->assignment_ops())
6264     Record.AddStmt(E);
6265 }
6266 
VisitOMPSharedClause(OMPSharedClause * C)6267 void OMPClauseWriter::VisitOMPSharedClause(OMPSharedClause *C) {
6268   Record.push_back(C->varlist_size());
6269   Record.AddSourceLocation(C->getLParenLoc());
6270   for (auto *VE : C->varlists())
6271     Record.AddStmt(VE);
6272 }
6273 
VisitOMPReductionClause(OMPReductionClause * C)6274 void OMPClauseWriter::VisitOMPReductionClause(OMPReductionClause *C) {
6275   Record.push_back(C->varlist_size());
6276   Record.writeEnum(C->getModifier());
6277   VisitOMPClauseWithPostUpdate(C);
6278   Record.AddSourceLocation(C->getLParenLoc());
6279   Record.AddSourceLocation(C->getModifierLoc());
6280   Record.AddSourceLocation(C->getColonLoc());
6281   Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
6282   Record.AddDeclarationNameInfo(C->getNameInfo());
6283   for (auto *VE : C->varlists())
6284     Record.AddStmt(VE);
6285   for (auto *VE : C->privates())
6286     Record.AddStmt(VE);
6287   for (auto *E : C->lhs_exprs())
6288     Record.AddStmt(E);
6289   for (auto *E : C->rhs_exprs())
6290     Record.AddStmt(E);
6291   for (auto *E : C->reduction_ops())
6292     Record.AddStmt(E);
6293   if (C->getModifier() == clang::OMPC_REDUCTION_inscan) {
6294     for (auto *E : C->copy_ops())
6295       Record.AddStmt(E);
6296     for (auto *E : C->copy_array_temps())
6297       Record.AddStmt(E);
6298     for (auto *E : C->copy_array_elems())
6299       Record.AddStmt(E);
6300   }
6301 }
6302 
VisitOMPTaskReductionClause(OMPTaskReductionClause * C)6303 void OMPClauseWriter::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
6304   Record.push_back(C->varlist_size());
6305   VisitOMPClauseWithPostUpdate(C);
6306   Record.AddSourceLocation(C->getLParenLoc());
6307   Record.AddSourceLocation(C->getColonLoc());
6308   Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
6309   Record.AddDeclarationNameInfo(C->getNameInfo());
6310   for (auto *VE : C->varlists())
6311     Record.AddStmt(VE);
6312   for (auto *VE : C->privates())
6313     Record.AddStmt(VE);
6314   for (auto *E : C->lhs_exprs())
6315     Record.AddStmt(E);
6316   for (auto *E : C->rhs_exprs())
6317     Record.AddStmt(E);
6318   for (auto *E : C->reduction_ops())
6319     Record.AddStmt(E);
6320 }
6321 
VisitOMPInReductionClause(OMPInReductionClause * C)6322 void OMPClauseWriter::VisitOMPInReductionClause(OMPInReductionClause *C) {
6323   Record.push_back(C->varlist_size());
6324   VisitOMPClauseWithPostUpdate(C);
6325   Record.AddSourceLocation(C->getLParenLoc());
6326   Record.AddSourceLocation(C->getColonLoc());
6327   Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
6328   Record.AddDeclarationNameInfo(C->getNameInfo());
6329   for (auto *VE : C->varlists())
6330     Record.AddStmt(VE);
6331   for (auto *VE : C->privates())
6332     Record.AddStmt(VE);
6333   for (auto *E : C->lhs_exprs())
6334     Record.AddStmt(E);
6335   for (auto *E : C->rhs_exprs())
6336     Record.AddStmt(E);
6337   for (auto *E : C->reduction_ops())
6338     Record.AddStmt(E);
6339   for (auto *E : C->taskgroup_descriptors())
6340     Record.AddStmt(E);
6341 }
6342 
VisitOMPLinearClause(OMPLinearClause * C)6343 void OMPClauseWriter::VisitOMPLinearClause(OMPLinearClause *C) {
6344   Record.push_back(C->varlist_size());
6345   VisitOMPClauseWithPostUpdate(C);
6346   Record.AddSourceLocation(C->getLParenLoc());
6347   Record.AddSourceLocation(C->getColonLoc());
6348   Record.push_back(C->getModifier());
6349   Record.AddSourceLocation(C->getModifierLoc());
6350   for (auto *VE : C->varlists()) {
6351     Record.AddStmt(VE);
6352   }
6353   for (auto *VE : C->privates()) {
6354     Record.AddStmt(VE);
6355   }
6356   for (auto *VE : C->inits()) {
6357     Record.AddStmt(VE);
6358   }
6359   for (auto *VE : C->updates()) {
6360     Record.AddStmt(VE);
6361   }
6362   for (auto *VE : C->finals()) {
6363     Record.AddStmt(VE);
6364   }
6365   Record.AddStmt(C->getStep());
6366   Record.AddStmt(C->getCalcStep());
6367   for (auto *VE : C->used_expressions())
6368     Record.AddStmt(VE);
6369 }
6370 
VisitOMPAlignedClause(OMPAlignedClause * C)6371 void OMPClauseWriter::VisitOMPAlignedClause(OMPAlignedClause *C) {
6372   Record.push_back(C->varlist_size());
6373   Record.AddSourceLocation(C->getLParenLoc());
6374   Record.AddSourceLocation(C->getColonLoc());
6375   for (auto *VE : C->varlists())
6376     Record.AddStmt(VE);
6377   Record.AddStmt(C->getAlignment());
6378 }
6379 
VisitOMPCopyinClause(OMPCopyinClause * C)6380 void OMPClauseWriter::VisitOMPCopyinClause(OMPCopyinClause *C) {
6381   Record.push_back(C->varlist_size());
6382   Record.AddSourceLocation(C->getLParenLoc());
6383   for (auto *VE : C->varlists())
6384     Record.AddStmt(VE);
6385   for (auto *E : C->source_exprs())
6386     Record.AddStmt(E);
6387   for (auto *E : C->destination_exprs())
6388     Record.AddStmt(E);
6389   for (auto *E : C->assignment_ops())
6390     Record.AddStmt(E);
6391 }
6392 
VisitOMPCopyprivateClause(OMPCopyprivateClause * C)6393 void OMPClauseWriter::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
6394   Record.push_back(C->varlist_size());
6395   Record.AddSourceLocation(C->getLParenLoc());
6396   for (auto *VE : C->varlists())
6397     Record.AddStmt(VE);
6398   for (auto *E : C->source_exprs())
6399     Record.AddStmt(E);
6400   for (auto *E : C->destination_exprs())
6401     Record.AddStmt(E);
6402   for (auto *E : C->assignment_ops())
6403     Record.AddStmt(E);
6404 }
6405 
VisitOMPFlushClause(OMPFlushClause * C)6406 void OMPClauseWriter::VisitOMPFlushClause(OMPFlushClause *C) {
6407   Record.push_back(C->varlist_size());
6408   Record.AddSourceLocation(C->getLParenLoc());
6409   for (auto *VE : C->varlists())
6410     Record.AddStmt(VE);
6411 }
6412 
VisitOMPDepobjClause(OMPDepobjClause * C)6413 void OMPClauseWriter::VisitOMPDepobjClause(OMPDepobjClause *C) {
6414   Record.AddStmt(C->getDepobj());
6415   Record.AddSourceLocation(C->getLParenLoc());
6416 }
6417 
VisitOMPDependClause(OMPDependClause * C)6418 void OMPClauseWriter::VisitOMPDependClause(OMPDependClause *C) {
6419   Record.push_back(C->varlist_size());
6420   Record.push_back(C->getNumLoops());
6421   Record.AddSourceLocation(C->getLParenLoc());
6422   Record.AddStmt(C->getModifier());
6423   Record.push_back(C->getDependencyKind());
6424   Record.AddSourceLocation(C->getDependencyLoc());
6425   Record.AddSourceLocation(C->getColonLoc());
6426   for (auto *VE : C->varlists())
6427     Record.AddStmt(VE);
6428   for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
6429     Record.AddStmt(C->getLoopData(I));
6430 }
6431 
VisitOMPDeviceClause(OMPDeviceClause * C)6432 void OMPClauseWriter::VisitOMPDeviceClause(OMPDeviceClause *C) {
6433   VisitOMPClauseWithPreInit(C);
6434   Record.writeEnum(C->getModifier());
6435   Record.AddStmt(C->getDevice());
6436   Record.AddSourceLocation(C->getModifierLoc());
6437   Record.AddSourceLocation(C->getLParenLoc());
6438 }
6439 
VisitOMPMapClause(OMPMapClause * C)6440 void OMPClauseWriter::VisitOMPMapClause(OMPMapClause *C) {
6441   Record.push_back(C->varlist_size());
6442   Record.push_back(C->getUniqueDeclarationsNum());
6443   Record.push_back(C->getTotalComponentListNum());
6444   Record.push_back(C->getTotalComponentsNum());
6445   Record.AddSourceLocation(C->getLParenLoc());
6446   for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
6447     Record.push_back(C->getMapTypeModifier(I));
6448     Record.AddSourceLocation(C->getMapTypeModifierLoc(I));
6449   }
6450   Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
6451   Record.AddDeclarationNameInfo(C->getMapperIdInfo());
6452   Record.push_back(C->getMapType());
6453   Record.AddSourceLocation(C->getMapLoc());
6454   Record.AddSourceLocation(C->getColonLoc());
6455   for (auto *E : C->varlists())
6456     Record.AddStmt(E);
6457   for (auto *E : C->mapperlists())
6458     Record.AddStmt(E);
6459   for (auto *D : C->all_decls())
6460     Record.AddDeclRef(D);
6461   for (auto N : C->all_num_lists())
6462     Record.push_back(N);
6463   for (auto N : C->all_lists_sizes())
6464     Record.push_back(N);
6465   for (auto &M : C->all_components()) {
6466     Record.AddStmt(M.getAssociatedExpression());
6467     Record.AddDeclRef(M.getAssociatedDeclaration());
6468   }
6469 }
6470 
VisitOMPAllocateClause(OMPAllocateClause * C)6471 void OMPClauseWriter::VisitOMPAllocateClause(OMPAllocateClause *C) {
6472   Record.push_back(C->varlist_size());
6473   Record.AddSourceLocation(C->getLParenLoc());
6474   Record.AddSourceLocation(C->getColonLoc());
6475   Record.AddStmt(C->getAllocator());
6476   for (auto *VE : C->varlists())
6477     Record.AddStmt(VE);
6478 }
6479 
VisitOMPNumTeamsClause(OMPNumTeamsClause * C)6480 void OMPClauseWriter::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
6481   VisitOMPClauseWithPreInit(C);
6482   Record.AddStmt(C->getNumTeams());
6483   Record.AddSourceLocation(C->getLParenLoc());
6484 }
6485 
VisitOMPThreadLimitClause(OMPThreadLimitClause * C)6486 void OMPClauseWriter::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
6487   VisitOMPClauseWithPreInit(C);
6488   Record.AddStmt(C->getThreadLimit());
6489   Record.AddSourceLocation(C->getLParenLoc());
6490 }
6491 
VisitOMPPriorityClause(OMPPriorityClause * C)6492 void OMPClauseWriter::VisitOMPPriorityClause(OMPPriorityClause *C) {
6493   VisitOMPClauseWithPreInit(C);
6494   Record.AddStmt(C->getPriority());
6495   Record.AddSourceLocation(C->getLParenLoc());
6496 }
6497 
VisitOMPGrainsizeClause(OMPGrainsizeClause * C)6498 void OMPClauseWriter::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
6499   VisitOMPClauseWithPreInit(C);
6500   Record.AddStmt(C->getGrainsize());
6501   Record.AddSourceLocation(C->getLParenLoc());
6502 }
6503 
VisitOMPNumTasksClause(OMPNumTasksClause * C)6504 void OMPClauseWriter::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
6505   VisitOMPClauseWithPreInit(C);
6506   Record.AddStmt(C->getNumTasks());
6507   Record.AddSourceLocation(C->getLParenLoc());
6508 }
6509 
VisitOMPHintClause(OMPHintClause * C)6510 void OMPClauseWriter::VisitOMPHintClause(OMPHintClause *C) {
6511   Record.AddStmt(C->getHint());
6512   Record.AddSourceLocation(C->getLParenLoc());
6513 }
6514 
VisitOMPDistScheduleClause(OMPDistScheduleClause * C)6515 void OMPClauseWriter::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
6516   VisitOMPClauseWithPreInit(C);
6517   Record.push_back(C->getDistScheduleKind());
6518   Record.AddStmt(C->getChunkSize());
6519   Record.AddSourceLocation(C->getLParenLoc());
6520   Record.AddSourceLocation(C->getDistScheduleKindLoc());
6521   Record.AddSourceLocation(C->getCommaLoc());
6522 }
6523 
VisitOMPDefaultmapClause(OMPDefaultmapClause * C)6524 void OMPClauseWriter::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
6525   Record.push_back(C->getDefaultmapKind());
6526   Record.push_back(C->getDefaultmapModifier());
6527   Record.AddSourceLocation(C->getLParenLoc());
6528   Record.AddSourceLocation(C->getDefaultmapModifierLoc());
6529   Record.AddSourceLocation(C->getDefaultmapKindLoc());
6530 }
6531 
VisitOMPToClause(OMPToClause * C)6532 void OMPClauseWriter::VisitOMPToClause(OMPToClause *C) {
6533   Record.push_back(C->varlist_size());
6534   Record.push_back(C->getUniqueDeclarationsNum());
6535   Record.push_back(C->getTotalComponentListNum());
6536   Record.push_back(C->getTotalComponentsNum());
6537   Record.AddSourceLocation(C->getLParenLoc());
6538   for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
6539     Record.push_back(C->getMotionModifier(I));
6540     Record.AddSourceLocation(C->getMotionModifierLoc(I));
6541   }
6542   Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
6543   Record.AddDeclarationNameInfo(C->getMapperIdInfo());
6544   Record.AddSourceLocation(C->getColonLoc());
6545   for (auto *E : C->varlists())
6546     Record.AddStmt(E);
6547   for (auto *E : C->mapperlists())
6548     Record.AddStmt(E);
6549   for (auto *D : C->all_decls())
6550     Record.AddDeclRef(D);
6551   for (auto N : C->all_num_lists())
6552     Record.push_back(N);
6553   for (auto N : C->all_lists_sizes())
6554     Record.push_back(N);
6555   for (auto &M : C->all_components()) {
6556     Record.AddStmt(M.getAssociatedExpression());
6557     Record.writeBool(M.isNonContiguous());
6558     Record.AddDeclRef(M.getAssociatedDeclaration());
6559   }
6560 }
6561 
VisitOMPFromClause(OMPFromClause * C)6562 void OMPClauseWriter::VisitOMPFromClause(OMPFromClause *C) {
6563   Record.push_back(C->varlist_size());
6564   Record.push_back(C->getUniqueDeclarationsNum());
6565   Record.push_back(C->getTotalComponentListNum());
6566   Record.push_back(C->getTotalComponentsNum());
6567   Record.AddSourceLocation(C->getLParenLoc());
6568   for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
6569     Record.push_back(C->getMotionModifier(I));
6570     Record.AddSourceLocation(C->getMotionModifierLoc(I));
6571   }
6572   Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
6573   Record.AddDeclarationNameInfo(C->getMapperIdInfo());
6574   Record.AddSourceLocation(C->getColonLoc());
6575   for (auto *E : C->varlists())
6576     Record.AddStmt(E);
6577   for (auto *E : C->mapperlists())
6578     Record.AddStmt(E);
6579   for (auto *D : C->all_decls())
6580     Record.AddDeclRef(D);
6581   for (auto N : C->all_num_lists())
6582     Record.push_back(N);
6583   for (auto N : C->all_lists_sizes())
6584     Record.push_back(N);
6585   for (auto &M : C->all_components()) {
6586     Record.AddStmt(M.getAssociatedExpression());
6587     Record.writeBool(M.isNonContiguous());
6588     Record.AddDeclRef(M.getAssociatedDeclaration());
6589   }
6590 }
6591 
VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause * C)6592 void OMPClauseWriter::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
6593   Record.push_back(C->varlist_size());
6594   Record.push_back(C->getUniqueDeclarationsNum());
6595   Record.push_back(C->getTotalComponentListNum());
6596   Record.push_back(C->getTotalComponentsNum());
6597   Record.AddSourceLocation(C->getLParenLoc());
6598   for (auto *E : C->varlists())
6599     Record.AddStmt(E);
6600   for (auto *VE : C->private_copies())
6601     Record.AddStmt(VE);
6602   for (auto *VE : C->inits())
6603     Record.AddStmt(VE);
6604   for (auto *D : C->all_decls())
6605     Record.AddDeclRef(D);
6606   for (auto N : C->all_num_lists())
6607     Record.push_back(N);
6608   for (auto N : C->all_lists_sizes())
6609     Record.push_back(N);
6610   for (auto &M : C->all_components()) {
6611     Record.AddStmt(M.getAssociatedExpression());
6612     Record.AddDeclRef(M.getAssociatedDeclaration());
6613   }
6614 }
6615 
VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause * C)6616 void OMPClauseWriter::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
6617   Record.push_back(C->varlist_size());
6618   Record.push_back(C->getUniqueDeclarationsNum());
6619   Record.push_back(C->getTotalComponentListNum());
6620   Record.push_back(C->getTotalComponentsNum());
6621   Record.AddSourceLocation(C->getLParenLoc());
6622   for (auto *E : C->varlists())
6623     Record.AddStmt(E);
6624   for (auto *D : C->all_decls())
6625     Record.AddDeclRef(D);
6626   for (auto N : C->all_num_lists())
6627     Record.push_back(N);
6628   for (auto N : C->all_lists_sizes())
6629     Record.push_back(N);
6630   for (auto &M : C->all_components()) {
6631     Record.AddStmt(M.getAssociatedExpression());
6632     Record.AddDeclRef(M.getAssociatedDeclaration());
6633   }
6634 }
6635 
VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause * C)6636 void OMPClauseWriter::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
6637   Record.push_back(C->varlist_size());
6638   Record.push_back(C->getUniqueDeclarationsNum());
6639   Record.push_back(C->getTotalComponentListNum());
6640   Record.push_back(C->getTotalComponentsNum());
6641   Record.AddSourceLocation(C->getLParenLoc());
6642   for (auto *E : C->varlists())
6643     Record.AddStmt(E);
6644   for (auto *D : C->all_decls())
6645     Record.AddDeclRef(D);
6646   for (auto N : C->all_num_lists())
6647     Record.push_back(N);
6648   for (auto N : C->all_lists_sizes())
6649     Record.push_back(N);
6650   for (auto &M : C->all_components()) {
6651     Record.AddStmt(M.getAssociatedExpression());
6652     Record.AddDeclRef(M.getAssociatedDeclaration());
6653   }
6654 }
6655 
VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *)6656 void OMPClauseWriter::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
6657 
VisitOMPUnifiedSharedMemoryClause(OMPUnifiedSharedMemoryClause *)6658 void OMPClauseWriter::VisitOMPUnifiedSharedMemoryClause(
6659     OMPUnifiedSharedMemoryClause *) {}
6660 
VisitOMPReverseOffloadClause(OMPReverseOffloadClause *)6661 void OMPClauseWriter::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
6662 
6663 void
VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *)6664 OMPClauseWriter::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
6665 }
6666 
VisitOMPAtomicDefaultMemOrderClause(OMPAtomicDefaultMemOrderClause * C)6667 void OMPClauseWriter::VisitOMPAtomicDefaultMemOrderClause(
6668     OMPAtomicDefaultMemOrderClause *C) {
6669   Record.push_back(C->getAtomicDefaultMemOrderKind());
6670   Record.AddSourceLocation(C->getLParenLoc());
6671   Record.AddSourceLocation(C->getAtomicDefaultMemOrderKindKwLoc());
6672 }
6673 
VisitOMPNontemporalClause(OMPNontemporalClause * C)6674 void OMPClauseWriter::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
6675   Record.push_back(C->varlist_size());
6676   Record.AddSourceLocation(C->getLParenLoc());
6677   for (auto *VE : C->varlists())
6678     Record.AddStmt(VE);
6679   for (auto *E : C->private_refs())
6680     Record.AddStmt(E);
6681 }
6682 
VisitOMPInclusiveClause(OMPInclusiveClause * C)6683 void OMPClauseWriter::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
6684   Record.push_back(C->varlist_size());
6685   Record.AddSourceLocation(C->getLParenLoc());
6686   for (auto *VE : C->varlists())
6687     Record.AddStmt(VE);
6688 }
6689 
VisitOMPExclusiveClause(OMPExclusiveClause * C)6690 void OMPClauseWriter::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
6691   Record.push_back(C->varlist_size());
6692   Record.AddSourceLocation(C->getLParenLoc());
6693   for (auto *VE : C->varlists())
6694     Record.AddStmt(VE);
6695 }
6696 
VisitOMPOrderClause(OMPOrderClause * C)6697 void OMPClauseWriter::VisitOMPOrderClause(OMPOrderClause *C) {
6698   Record.writeEnum(C->getKind());
6699   Record.AddSourceLocation(C->getLParenLoc());
6700   Record.AddSourceLocation(C->getKindKwLoc());
6701 }
6702 
VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause * C)6703 void OMPClauseWriter::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
6704   Record.push_back(C->getNumberOfAllocators());
6705   Record.AddSourceLocation(C->getLParenLoc());
6706   for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) {
6707     OMPUsesAllocatorsClause::Data Data = C->getAllocatorData(I);
6708     Record.AddStmt(Data.Allocator);
6709     Record.AddStmt(Data.AllocatorTraits);
6710     Record.AddSourceLocation(Data.LParenLoc);
6711     Record.AddSourceLocation(Data.RParenLoc);
6712   }
6713 }
6714 
VisitOMPAffinityClause(OMPAffinityClause * C)6715 void OMPClauseWriter::VisitOMPAffinityClause(OMPAffinityClause *C) {
6716   Record.push_back(C->varlist_size());
6717   Record.AddSourceLocation(C->getLParenLoc());
6718   Record.AddStmt(C->getModifier());
6719   Record.AddSourceLocation(C->getColonLoc());
6720   for (Expr *E : C->varlists())
6721     Record.AddStmt(E);
6722 }
6723 
writeOMPTraitInfo(const OMPTraitInfo * TI)6724 void ASTRecordWriter::writeOMPTraitInfo(const OMPTraitInfo *TI) {
6725   writeUInt32(TI->Sets.size());
6726   for (const auto &Set : TI->Sets) {
6727     writeEnum(Set.Kind);
6728     writeUInt32(Set.Selectors.size());
6729     for (const auto &Selector : Set.Selectors) {
6730       writeEnum(Selector.Kind);
6731       writeBool(Selector.ScoreOrCondition);
6732       if (Selector.ScoreOrCondition)
6733         writeExprRef(Selector.ScoreOrCondition);
6734       writeUInt32(Selector.Properties.size());
6735       for (const auto &Property : Selector.Properties)
6736         writeEnum(Property.Kind);
6737     }
6738   }
6739 }
6740 
writeOMPChildren(OMPChildren * Data)6741 void ASTRecordWriter::writeOMPChildren(OMPChildren *Data) {
6742   if (!Data)
6743     return;
6744   writeUInt32(Data->getNumClauses());
6745   writeUInt32(Data->getNumChildren());
6746   writeBool(Data->hasAssociatedStmt());
6747   for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)
6748     writeOMPClause(Data->getClauses()[I]);
6749   if (Data->hasAssociatedStmt())
6750     AddStmt(Data->getAssociatedStmt());
6751   for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
6752     AddStmt(Data->getChildren()[I]);
6753 }
6754