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