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