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