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