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