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