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