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