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