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