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