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().findResolvedModulesForHeader(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   SortedFileDeclIDs.reserve(FileDeclIDs.size());
2903   for (const auto &P : FileDeclIDs)
2904     SortedFileDeclIDs.push_back(std::make_pair(P.first, P.second.get()));
2905   llvm::sort(SortedFileDeclIDs, llvm::less_first());
2906 
2907   // Join the vectors of DeclIDs from all files.
2908   SmallVector<DeclID, 256> FileGroupedDeclIDs;
2909   for (auto &FileDeclEntry : SortedFileDeclIDs) {
2910     DeclIDInFileInfo &Info = *FileDeclEntry.second;
2911     Info.FirstDeclIndex = FileGroupedDeclIDs.size();
2912     for (auto &LocDeclEntry : Info.DeclIDs)
2913       FileGroupedDeclIDs.push_back(LocDeclEntry.second);
2914   }
2915 
2916   auto Abbrev = std::make_shared<BitCodeAbbrev>();
2917   Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
2918   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2919   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2920   unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
2921   RecordData::value_type Record[] = {FILE_SORTED_DECLS,
2922                                      FileGroupedDeclIDs.size()};
2923   Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
2924 }
2925 
2926 void ASTWriter::WriteComments() {
2927   Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
2928   auto _ = llvm::make_scope_exit([this] { Stream.ExitBlock(); });
2929   if (!PP->getPreprocessorOpts().WriteCommentListToPCH)
2930     return;
2931   RecordData Record;
2932   for (const auto &FO : Context->Comments.OrderedComments) {
2933     for (const auto &OC : FO.second) {
2934       const RawComment *I = OC.second;
2935       Record.clear();
2936       AddSourceRange(I->getSourceRange(), Record);
2937       Record.push_back(I->getKind());
2938       Record.push_back(I->isTrailingComment());
2939       Record.push_back(I->isAlmostTrailingComment());
2940       Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
2941     }
2942   }
2943 }
2944 
2945 //===----------------------------------------------------------------------===//
2946 // Global Method Pool and Selector Serialization
2947 //===----------------------------------------------------------------------===//
2948 
2949 namespace {
2950 
2951 // Trait used for the on-disk hash table used in the method pool.
2952 class ASTMethodPoolTrait {
2953   ASTWriter &Writer;
2954 
2955 public:
2956   using key_type = Selector;
2957   using key_type_ref = key_type;
2958 
2959   struct data_type {
2960     SelectorID ID;
2961     ObjCMethodList Instance, Factory;
2962   };
2963   using data_type_ref = const data_type &;
2964 
2965   using hash_value_type = unsigned;
2966   using offset_type = unsigned;
2967 
2968   explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) {}
2969 
2970   static hash_value_type ComputeHash(Selector Sel) {
2971     return serialization::ComputeHash(Sel);
2972   }
2973 
2974   std::pair<unsigned, unsigned>
2975     EmitKeyDataLength(raw_ostream& Out, Selector Sel,
2976                       data_type_ref Methods) {
2977     using namespace llvm::support;
2978 
2979     endian::Writer LE(Out, little);
2980     unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
2981     LE.write<uint16_t>(KeyLen);
2982     unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
2983     for (const ObjCMethodList *Method = &Methods.Instance; Method;
2984          Method = Method->getNext())
2985       if (Method->getMethod())
2986         DataLen += 4;
2987     for (const ObjCMethodList *Method = &Methods.Factory; Method;
2988          Method = Method->getNext())
2989       if (Method->getMethod())
2990         DataLen += 4;
2991     LE.write<uint16_t>(DataLen);
2992     return std::make_pair(KeyLen, DataLen);
2993   }
2994 
2995   void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
2996     using namespace llvm::support;
2997 
2998     endian::Writer LE(Out, little);
2999     uint64_t Start = Out.tell();
3000     assert((Start >> 32) == 0 && "Selector key offset too large");
3001     Writer.SetSelectorOffset(Sel, Start);
3002     unsigned N = Sel.getNumArgs();
3003     LE.write<uint16_t>(N);
3004     if (N == 0)
3005       N = 1;
3006     for (unsigned I = 0; I != N; ++I)
3007       LE.write<uint32_t>(
3008           Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
3009   }
3010 
3011   void EmitData(raw_ostream& Out, key_type_ref,
3012                 data_type_ref Methods, unsigned DataLen) {
3013     using namespace llvm::support;
3014 
3015     endian::Writer LE(Out, little);
3016     uint64_t Start = Out.tell(); (void)Start;
3017     LE.write<uint32_t>(Methods.ID);
3018     unsigned NumInstanceMethods = 0;
3019     for (const ObjCMethodList *Method = &Methods.Instance; Method;
3020          Method = Method->getNext())
3021       if (Method->getMethod())
3022         ++NumInstanceMethods;
3023 
3024     unsigned NumFactoryMethods = 0;
3025     for (const ObjCMethodList *Method = &Methods.Factory; Method;
3026          Method = Method->getNext())
3027       if (Method->getMethod())
3028         ++NumFactoryMethods;
3029 
3030     unsigned InstanceBits = Methods.Instance.getBits();
3031     assert(InstanceBits < 4);
3032     unsigned InstanceHasMoreThanOneDeclBit =
3033         Methods.Instance.hasMoreThanOneDecl();
3034     unsigned FullInstanceBits = (NumInstanceMethods << 3) |
3035                                 (InstanceHasMoreThanOneDeclBit << 2) |
3036                                 InstanceBits;
3037     unsigned FactoryBits = Methods.Factory.getBits();
3038     assert(FactoryBits < 4);
3039     unsigned FactoryHasMoreThanOneDeclBit =
3040         Methods.Factory.hasMoreThanOneDecl();
3041     unsigned FullFactoryBits = (NumFactoryMethods << 3) |
3042                                (FactoryHasMoreThanOneDeclBit << 2) |
3043                                FactoryBits;
3044     LE.write<uint16_t>(FullInstanceBits);
3045     LE.write<uint16_t>(FullFactoryBits);
3046     for (const ObjCMethodList *Method = &Methods.Instance; Method;
3047          Method = Method->getNext())
3048       if (Method->getMethod())
3049         LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
3050     for (const ObjCMethodList *Method = &Methods.Factory; Method;
3051          Method = Method->getNext())
3052       if (Method->getMethod())
3053         LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
3054 
3055     assert(Out.tell() - Start == DataLen && "Data length is wrong");
3056   }
3057 };
3058 
3059 } // namespace
3060 
3061 /// Write ObjC data: selectors and the method pool.
3062 ///
3063 /// The method pool contains both instance and factory methods, stored
3064 /// in an on-disk hash table indexed by the selector. The hash table also
3065 /// contains an empty entry for every other selector known to Sema.
3066 void ASTWriter::WriteSelectors(Sema &SemaRef) {
3067   using namespace llvm;
3068 
3069   // Do we have to do anything at all?
3070   if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
3071     return;
3072   unsigned NumTableEntries = 0;
3073   // Create and write out the blob that contains selectors and the method pool.
3074   {
3075     llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
3076     ASTMethodPoolTrait Trait(*this);
3077 
3078     // Create the on-disk hash table representation. We walk through every
3079     // selector we've seen and look it up in the method pool.
3080     SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
3081     for (auto &SelectorAndID : SelectorIDs) {
3082       Selector S = SelectorAndID.first;
3083       SelectorID ID = SelectorAndID.second;
3084       Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
3085       ASTMethodPoolTrait::data_type Data = {
3086         ID,
3087         ObjCMethodList(),
3088         ObjCMethodList()
3089       };
3090       if (F != SemaRef.MethodPool.end()) {
3091         Data.Instance = F->second.first;
3092         Data.Factory = F->second.second;
3093       }
3094       // Only write this selector if it's not in an existing AST or something
3095       // changed.
3096       if (Chain && ID < FirstSelectorID) {
3097         // Selector already exists. Did it change?
3098         bool changed = false;
3099         for (ObjCMethodList *M = &Data.Instance;
3100              !changed && M && M->getMethod(); M = M->getNext()) {
3101           if (!M->getMethod()->isFromASTFile())
3102             changed = true;
3103         }
3104         for (ObjCMethodList *M = &Data.Factory; !changed && M && M->getMethod();
3105              M = M->getNext()) {
3106           if (!M->getMethod()->isFromASTFile())
3107             changed = true;
3108         }
3109         if (!changed)
3110           continue;
3111       } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
3112         // A new method pool entry.
3113         ++NumTableEntries;
3114       }
3115       Generator.insert(S, Data, Trait);
3116     }
3117 
3118     // Create the on-disk hash table in a buffer.
3119     SmallString<4096> MethodPool;
3120     uint32_t BucketOffset;
3121     {
3122       using namespace llvm::support;
3123 
3124       ASTMethodPoolTrait Trait(*this);
3125       llvm::raw_svector_ostream Out(MethodPool);
3126       // Make sure that no bucket is at offset 0
3127       endian::write<uint32_t>(Out, 0, little);
3128       BucketOffset = Generator.Emit(Out, Trait);
3129     }
3130 
3131     // Create a blob abbreviation
3132     auto Abbrev = std::make_shared<BitCodeAbbrev>();
3133     Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
3134     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3135     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3136     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3137     unsigned MethodPoolAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3138 
3139     // Write the method pool
3140     {
3141       RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3142                                          NumTableEntries};
3143       Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3144     }
3145 
3146     // Create a blob abbreviation for the selector table offsets.
3147     Abbrev = std::make_shared<BitCodeAbbrev>();
3148     Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
3149     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
3150     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3151     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3152     unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3153 
3154     // Write the selector offsets table.
3155     {
3156       RecordData::value_type Record[] = {
3157           SELECTOR_OFFSETS, SelectorOffsets.size(),
3158           FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3159       Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3160                                 bytes(SelectorOffsets));
3161     }
3162   }
3163 }
3164 
3165 /// Write the selectors referenced in @selector expression into AST file.
3166 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
3167   using namespace llvm;
3168 
3169   if (SemaRef.ReferencedSelectors.empty())
3170     return;
3171 
3172   RecordData Record;
3173   ASTRecordWriter Writer(*this, Record);
3174 
3175   // Note: this writes out all references even for a dependent AST. But it is
3176   // very tricky to fix, and given that @selector shouldn't really appear in
3177   // headers, probably not worth it. It's not a correctness issue.
3178   for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
3179     Selector Sel = SelectorAndLocation.first;
3180     SourceLocation Loc = SelectorAndLocation.second;
3181     Writer.AddSelectorRef(Sel);
3182     Writer.AddSourceLocation(Loc);
3183   }
3184   Writer.Emit(REFERENCED_SELECTOR_POOL);
3185 }
3186 
3187 //===----------------------------------------------------------------------===//
3188 // Identifier Table Serialization
3189 //===----------------------------------------------------------------------===//
3190 
3191 /// Determine the declaration that should be put into the name lookup table to
3192 /// represent the given declaration in this module. This is usually D itself,
3193 /// but if D was imported and merged into a local declaration, we want the most
3194 /// recent local declaration instead. The chosen declaration will be the most
3195 /// recent declaration in any module that imports this one.
3196 static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
3197                                         NamedDecl *D) {
3198   if (!LangOpts.Modules || !D->isFromASTFile())
3199     return D;
3200 
3201   if (Decl *Redecl = D->getPreviousDecl()) {
3202     // For Redeclarable decls, a prior declaration might be local.
3203     for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
3204       // If we find a local decl, we're done.
3205       if (!Redecl->isFromASTFile()) {
3206         // Exception: in very rare cases (for injected-class-names), not all
3207         // redeclarations are in the same semantic context. Skip ones in a
3208         // different context. They don't go in this lookup table at all.
3209         if (!Redecl->getDeclContext()->getRedeclContext()->Equals(
3210                 D->getDeclContext()->getRedeclContext()))
3211           continue;
3212         return cast<NamedDecl>(Redecl);
3213       }
3214 
3215       // If we find a decl from a (chained-)PCH stop since we won't find a
3216       // local one.
3217       if (Redecl->getOwningModuleID() == 0)
3218         break;
3219     }
3220   } else if (Decl *First = D->getCanonicalDecl()) {
3221     // For Mergeable decls, the first decl might be local.
3222     if (!First->isFromASTFile())
3223       return cast<NamedDecl>(First);
3224   }
3225 
3226   // All declarations are imported. Our most recent declaration will also be
3227   // the most recent one in anyone who imports us.
3228   return D;
3229 }
3230 
3231 namespace {
3232 
3233 class ASTIdentifierTableTrait {
3234   ASTWriter &Writer;
3235   Preprocessor &PP;
3236   IdentifierResolver &IdResolver;
3237   bool IsModule;
3238   bool NeedDecls;
3239   ASTWriter::RecordData *InterestingIdentifierOffsets;
3240 
3241   /// Determines whether this is an "interesting" identifier that needs a
3242   /// full IdentifierInfo structure written into the hash table. Notably, this
3243   /// doesn't check whether the name has macros defined; use PublicMacroIterator
3244   /// to check that.
3245   bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
3246     if (MacroOffset ||
3247         II->isPoisoned() ||
3248         (IsModule ? II->hasRevertedBuiltin() : II->getObjCOrBuiltinID()) ||
3249         II->hasRevertedTokenIDToIdentifier() ||
3250         (NeedDecls && II->getFETokenInfo()))
3251       return true;
3252 
3253     return false;
3254   }
3255 
3256 public:
3257   using key_type = IdentifierInfo *;
3258   using key_type_ref = key_type;
3259 
3260   using data_type = IdentID;
3261   using data_type_ref = data_type;
3262 
3263   using hash_value_type = unsigned;
3264   using offset_type = unsigned;
3265 
3266   ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
3267                           IdentifierResolver &IdResolver, bool IsModule,
3268                           ASTWriter::RecordData *InterestingIdentifierOffsets)
3269       : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
3270         NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3271         InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
3272 
3273   bool needDecls() const { return NeedDecls; }
3274 
3275   static hash_value_type ComputeHash(const IdentifierInfo* II) {
3276     return llvm::djbHash(II->getName());
3277   }
3278 
3279   bool isInterestingIdentifier(const IdentifierInfo *II) {
3280     auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3281     return isInterestingIdentifier(II, MacroOffset);
3282   }
3283 
3284   bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) {
3285     return isInterestingIdentifier(II, 0);
3286   }
3287 
3288   std::pair<unsigned, unsigned>
3289   EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
3290     unsigned KeyLen = II->getLength() + 1;
3291     unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
3292     auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3293     if (isInterestingIdentifier(II, MacroOffset)) {
3294       DataLen += 2; // 2 bytes for builtin ID
3295       DataLen += 2; // 2 bytes for flags
3296       if (MacroOffset)
3297         DataLen += 4; // MacroDirectives offset.
3298 
3299       if (NeedDecls) {
3300         for (IdentifierResolver::iterator D = IdResolver.begin(II),
3301                                        DEnd = IdResolver.end();
3302              D != DEnd; ++D)
3303           DataLen += 4;
3304       }
3305     }
3306 
3307     using namespace llvm::support;
3308 
3309     endian::Writer LE(Out, little);
3310 
3311     assert((uint16_t)DataLen == DataLen && (uint16_t)KeyLen == KeyLen);
3312     LE.write<uint16_t>(DataLen);
3313     // We emit the key length after the data length so that every
3314     // string is preceded by a 16-bit length. This matches the PTH
3315     // format for storing identifiers.
3316     LE.write<uint16_t>(KeyLen);
3317     return std::make_pair(KeyLen, DataLen);
3318   }
3319 
3320   void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
3321                unsigned KeyLen) {
3322     // Record the location of the key data.  This is used when generating
3323     // the mapping from persistent IDs to strings.
3324     Writer.SetIdentifierOffset(II, Out.tell());
3325 
3326     // Emit the offset of the key/data length information to the interesting
3327     // identifiers table if necessary.
3328     if (InterestingIdentifierOffsets && isInterestingIdentifier(II))
3329       InterestingIdentifierOffsets->push_back(Out.tell() - 4);
3330 
3331     Out.write(II->getNameStart(), KeyLen);
3332   }
3333 
3334   void EmitData(raw_ostream& Out, IdentifierInfo* II,
3335                 IdentID ID, unsigned) {
3336     using namespace llvm::support;
3337 
3338     endian::Writer LE(Out, little);
3339 
3340     auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3341     if (!isInterestingIdentifier(II, MacroOffset)) {
3342       LE.write<uint32_t>(ID << 1);
3343       return;
3344     }
3345 
3346     LE.write<uint32_t>((ID << 1) | 0x01);
3347     uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3348     assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
3349     LE.write<uint16_t>(Bits);
3350     Bits = 0;
3351     bool HadMacroDefinition = MacroOffset != 0;
3352     Bits = (Bits << 1) | unsigned(HadMacroDefinition);
3353     Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3354     Bits = (Bits << 1) | unsigned(II->isPoisoned());
3355     Bits = (Bits << 1) | unsigned(II->hasRevertedBuiltin());
3356     Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
3357     Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
3358     LE.write<uint16_t>(Bits);
3359 
3360     if (HadMacroDefinition)
3361       LE.write<uint32_t>(MacroOffset);
3362 
3363     if (NeedDecls) {
3364       // Emit the declaration IDs in reverse order, because the
3365       // IdentifierResolver provides the declarations as they would be
3366       // visible (e.g., the function "stat" would come before the struct
3367       // "stat"), but the ASTReader adds declarations to the end of the list
3368       // (so we need to see the struct "stat" before the function "stat").
3369       // Only emit declarations that aren't from a chained PCH, though.
3370       SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II),
3371                                          IdResolver.end());
3372       for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(),
3373                                                           DEnd = Decls.rend();
3374            D != DEnd; ++D)
3375         LE.write<uint32_t>(
3376             Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D)));
3377     }
3378   }
3379 };
3380 
3381 } // namespace
3382 
3383 /// Write the identifier table into the AST file.
3384 ///
3385 /// The identifier table consists of a blob containing string data
3386 /// (the actual identifiers themselves) and a separate "offsets" index
3387 /// that maps identifier IDs to locations within the blob.
3388 void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3389                                      IdentifierResolver &IdResolver,
3390                                      bool IsModule) {
3391   using namespace llvm;
3392 
3393   RecordData InterestingIdents;
3394 
3395   // Create and write out the blob that contains the identifier
3396   // strings.
3397   {
3398     llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
3399     ASTIdentifierTableTrait Trait(
3400         *this, PP, IdResolver, IsModule,
3401         (getLangOpts().CPlusPlus && IsModule) ? &InterestingIdents : nullptr);
3402 
3403     // Look for any identifiers that were named while processing the
3404     // headers, but are otherwise not needed. We add these to the hash
3405     // table to enable checking of the predefines buffer in the case
3406     // where the user adds new macro definitions when building the AST
3407     // file.
3408     SmallVector<const IdentifierInfo *, 128> IIs;
3409     for (const auto &ID : PP.getIdentifierTable())
3410       IIs.push_back(ID.second);
3411     // Sort the identifiers lexicographically before getting them references so
3412     // that their order is stable.
3413     llvm::sort(IIs, llvm::deref<std::less<>>());
3414     for (const IdentifierInfo *II : IIs)
3415       if (Trait.isInterestingNonMacroIdentifier(II))
3416         getIdentifierRef(II);
3417 
3418     // Create the on-disk hash table representation. We only store offsets
3419     // for identifiers that appear here for the first time.
3420     IdentifierOffsets.resize(NextIdentID - FirstIdentID);
3421     for (auto IdentIDPair : IdentifierIDs) {
3422       auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
3423       IdentID ID = IdentIDPair.second;
3424       assert(II && "NULL identifier in identifier table");
3425       // Write out identifiers if either the ID is local or the identifier has
3426       // changed since it was loaded.
3427       if (ID >= FirstIdentID || !Chain || !II->isFromAST()
3428           || II->hasChangedSinceDeserialization() ||
3429           (Trait.needDecls() &&
3430            II->hasFETokenInfoChangedSinceDeserialization()))
3431         Generator.insert(II, ID, Trait);
3432     }
3433 
3434     // Create the on-disk hash table in a buffer.
3435     SmallString<4096> IdentifierTable;
3436     uint32_t BucketOffset;
3437     {
3438       using namespace llvm::support;
3439 
3440       llvm::raw_svector_ostream Out(IdentifierTable);
3441       // Make sure that no bucket is at offset 0
3442       endian::write<uint32_t>(Out, 0, little);
3443       BucketOffset = Generator.Emit(Out, Trait);
3444     }
3445 
3446     // Create a blob abbreviation
3447     auto Abbrev = std::make_shared<BitCodeAbbrev>();
3448     Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
3449     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3450     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3451     unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3452 
3453     // Write the identifier table
3454     RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
3455     Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
3456   }
3457 
3458   // Write the offsets table for identifier IDs.
3459   auto Abbrev = std::make_shared<BitCodeAbbrev>();
3460   Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
3461   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
3462   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3463   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3464   unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3465 
3466 #ifndef NDEBUG
3467   for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3468     assert(IdentifierOffsets[I] && "Missing identifier offset?");
3469 #endif
3470 
3471   RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
3472                                      IdentifierOffsets.size(),
3473                                      FirstIdentID - NUM_PREDEF_IDENT_IDS};
3474   Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
3475                             bytes(IdentifierOffsets));
3476 
3477   // In C++, write the list of interesting identifiers (those that are
3478   // defined as macros, poisoned, or similar unusual things).
3479   if (!InterestingIdents.empty())
3480     Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
3481 }
3482 
3483 //===----------------------------------------------------------------------===//
3484 // DeclContext's Name Lookup Table Serialization
3485 //===----------------------------------------------------------------------===//
3486 
3487 namespace {
3488 
3489 // Trait used for the on-disk hash table used in the method pool.
3490 class ASTDeclContextNameLookupTrait {
3491   ASTWriter &Writer;
3492   llvm::SmallVector<DeclID, 64> DeclIDs;
3493 
3494 public:
3495   using key_type = DeclarationNameKey;
3496   using key_type_ref = key_type;
3497 
3498   /// A start and end index into DeclIDs, representing a sequence of decls.
3499   using data_type = std::pair<unsigned, unsigned>;
3500   using data_type_ref = const data_type &;
3501 
3502   using hash_value_type = unsigned;
3503   using offset_type = unsigned;
3504 
3505   explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) {}
3506 
3507   template<typename Coll>
3508   data_type getData(const Coll &Decls) {
3509     unsigned Start = DeclIDs.size();
3510     for (NamedDecl *D : Decls) {
3511       DeclIDs.push_back(
3512           Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3513     }
3514     return std::make_pair(Start, DeclIDs.size());
3515   }
3516 
3517   data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
3518     unsigned Start = DeclIDs.size();
3519     for (auto ID : FromReader)
3520       DeclIDs.push_back(ID);
3521     return std::make_pair(Start, DeclIDs.size());
3522   }
3523 
3524   static bool EqualKey(key_type_ref a, key_type_ref b) {
3525     return a == b;
3526   }
3527 
3528   hash_value_type ComputeHash(DeclarationNameKey Name) {
3529     return Name.getHash();
3530   }
3531 
3532   void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
3533     assert(Writer.hasChain() &&
3534            "have reference to loaded module file but no chain?");
3535 
3536     using namespace llvm::support;
3537 
3538     endian::write<uint32_t>(Out, Writer.getChain()->getModuleFileID(F), little);
3539   }
3540 
3541   std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
3542                                                   DeclarationNameKey Name,
3543                                                   data_type_ref Lookup) {
3544     using namespace llvm::support;
3545 
3546     endian::Writer LE(Out, little);
3547     unsigned KeyLen = 1;
3548     switch (Name.getKind()) {
3549     case DeclarationName::Identifier:
3550     case DeclarationName::ObjCZeroArgSelector:
3551     case DeclarationName::ObjCOneArgSelector:
3552     case DeclarationName::ObjCMultiArgSelector:
3553     case DeclarationName::CXXLiteralOperatorName:
3554     case DeclarationName::CXXDeductionGuideName:
3555       KeyLen += 4;
3556       break;
3557     case DeclarationName::CXXOperatorName:
3558       KeyLen += 1;
3559       break;
3560     case DeclarationName::CXXConstructorName:
3561     case DeclarationName::CXXDestructorName:
3562     case DeclarationName::CXXConversionFunctionName:
3563     case DeclarationName::CXXUsingDirective:
3564       break;
3565     }
3566     LE.write<uint16_t>(KeyLen);
3567 
3568     // 4 bytes for each DeclID.
3569     unsigned DataLen = 4 * (Lookup.second - Lookup.first);
3570     assert(uint16_t(DataLen) == DataLen &&
3571            "too many decls for serialized lookup result");
3572     LE.write<uint16_t>(DataLen);
3573 
3574     return std::make_pair(KeyLen, DataLen);
3575   }
3576 
3577   void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
3578     using namespace llvm::support;
3579 
3580     endian::Writer LE(Out, little);
3581     LE.write<uint8_t>(Name.getKind());
3582     switch (Name.getKind()) {
3583     case DeclarationName::Identifier:
3584     case DeclarationName::CXXLiteralOperatorName:
3585     case DeclarationName::CXXDeductionGuideName:
3586       LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier()));
3587       return;
3588     case DeclarationName::ObjCZeroArgSelector:
3589     case DeclarationName::ObjCOneArgSelector:
3590     case DeclarationName::ObjCMultiArgSelector:
3591       LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
3592       return;
3593     case DeclarationName::CXXOperatorName:
3594       assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
3595              "Invalid operator?");
3596       LE.write<uint8_t>(Name.getOperatorKind());
3597       return;
3598     case DeclarationName::CXXConstructorName:
3599     case DeclarationName::CXXDestructorName:
3600     case DeclarationName::CXXConversionFunctionName:
3601     case DeclarationName::CXXUsingDirective:
3602       return;
3603     }
3604 
3605     llvm_unreachable("Invalid name kind?");
3606   }
3607 
3608   void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
3609                 unsigned DataLen) {
3610     using namespace llvm::support;
3611 
3612     endian::Writer LE(Out, little);
3613     uint64_t Start = Out.tell(); (void)Start;
3614     for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
3615       LE.write<uint32_t>(DeclIDs[I]);
3616     assert(Out.tell() - Start == DataLen && "Data length is wrong");
3617   }
3618 };
3619 
3620 } // namespace
3621 
3622 bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
3623                                        DeclContext *DC) {
3624   return Result.hasExternalDecls() &&
3625          DC->hasNeedToReconcileExternalVisibleStorage();
3626 }
3627 
3628 bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
3629                                                DeclContext *DC) {
3630   for (auto *D : Result.getLookupResult())
3631     if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
3632       return false;
3633 
3634   return true;
3635 }
3636 
3637 void
3638 ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
3639                                    llvm::SmallVectorImpl<char> &LookupTable) {
3640   assert(!ConstDC->hasLazyLocalLexicalLookups() &&
3641          !ConstDC->hasLazyExternalLexicalLookups() &&
3642          "must call buildLookups first");
3643 
3644   // FIXME: We need to build the lookups table, which is logically const.
3645   auto *DC = const_cast<DeclContext*>(ConstDC);
3646   assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
3647 
3648   // Create the on-disk hash table representation.
3649   MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait,
3650                                 ASTDeclContextNameLookupTrait> Generator;
3651   ASTDeclContextNameLookupTrait Trait(*this);
3652 
3653   // The first step is to collect the declaration names which we need to
3654   // serialize into the name lookup table, and to collect them in a stable
3655   // order.
3656   SmallVector<DeclarationName, 16> Names;
3657 
3658   // We also build up small sets of the constructor and conversion function
3659   // names which are visible.
3660   llvm::SmallSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
3661 
3662   for (auto &Lookup : *DC->buildLookup()) {
3663     auto &Name = Lookup.first;
3664     auto &Result = Lookup.second;
3665 
3666     // If there are no local declarations in our lookup result, we
3667     // don't need to write an entry for the name at all. If we can't
3668     // write out a lookup set without performing more deserialization,
3669     // just skip this entry.
3670     if (isLookupResultExternal(Result, DC) &&
3671         isLookupResultEntirelyExternal(Result, DC))
3672       continue;
3673 
3674     // We also skip empty results. If any of the results could be external and
3675     // the currently available results are empty, then all of the results are
3676     // external and we skip it above. So the only way we get here with an empty
3677     // results is when no results could have been external *and* we have
3678     // external results.
3679     //
3680     // FIXME: While we might want to start emitting on-disk entries for negative
3681     // lookups into a decl context as an optimization, today we *have* to skip
3682     // them because there are names with empty lookup results in decl contexts
3683     // which we can't emit in any stable ordering: we lookup constructors and
3684     // conversion functions in the enclosing namespace scope creating empty
3685     // results for them. This in almost certainly a bug in Clang's name lookup,
3686     // but that is likely to be hard or impossible to fix and so we tolerate it
3687     // here by omitting lookups with empty results.
3688     if (Lookup.second.getLookupResult().empty())
3689       continue;
3690 
3691     switch (Lookup.first.getNameKind()) {
3692     default:
3693       Names.push_back(Lookup.first);
3694       break;
3695 
3696     case DeclarationName::CXXConstructorName:
3697       assert(isa<CXXRecordDecl>(DC) &&
3698              "Cannot have a constructor name outside of a class!");
3699       ConstructorNameSet.insert(Name);
3700       break;
3701 
3702     case DeclarationName::CXXConversionFunctionName:
3703       assert(isa<CXXRecordDecl>(DC) &&
3704              "Cannot have a conversion function name outside of a class!");
3705       ConversionNameSet.insert(Name);
3706       break;
3707     }
3708   }
3709 
3710   // Sort the names into a stable order.
3711   llvm::sort(Names);
3712 
3713   if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
3714     // We need to establish an ordering of constructor and conversion function
3715     // names, and they don't have an intrinsic ordering.
3716 
3717     // First we try the easy case by forming the current context's constructor
3718     // name and adding that name first. This is a very useful optimization to
3719     // avoid walking the lexical declarations in many cases, and it also
3720     // handles the only case where a constructor name can come from some other
3721     // lexical context -- when that name is an implicit constructor merged from
3722     // another declaration in the redecl chain. Any non-implicit constructor or
3723     // conversion function which doesn't occur in all the lexical contexts
3724     // would be an ODR violation.
3725     auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
3726         Context->getCanonicalType(Context->getRecordType(D)));
3727     if (ConstructorNameSet.erase(ImplicitCtorName))
3728       Names.push_back(ImplicitCtorName);
3729 
3730     // If we still have constructors or conversion functions, we walk all the
3731     // names in the decl and add the constructors and conversion functions
3732     // which are visible in the order they lexically occur within the context.
3733     if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
3734       for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
3735         if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
3736           auto Name = ChildND->getDeclName();
3737           switch (Name.getNameKind()) {
3738           default:
3739             continue;
3740 
3741           case DeclarationName::CXXConstructorName:
3742             if (ConstructorNameSet.erase(Name))
3743               Names.push_back(Name);
3744             break;
3745 
3746           case DeclarationName::CXXConversionFunctionName:
3747             if (ConversionNameSet.erase(Name))
3748               Names.push_back(Name);
3749             break;
3750           }
3751 
3752           if (ConstructorNameSet.empty() && ConversionNameSet.empty())
3753             break;
3754         }
3755 
3756     assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
3757                                          "constructors by walking all the "
3758                                          "lexical members of the context.");
3759     assert(ConversionNameSet.empty() && "Failed to find all of the visible "
3760                                         "conversion functions by walking all "
3761                                         "the lexical members of the context.");
3762   }
3763 
3764   // Next we need to do a lookup with each name into this decl context to fully
3765   // populate any results from external sources. We don't actually use the
3766   // results of these lookups because we only want to use the results after all
3767   // results have been loaded and the pointers into them will be stable.
3768   for (auto &Name : Names)
3769     DC->lookup(Name);
3770 
3771   // Now we need to insert the results for each name into the hash table. For
3772   // constructor names and conversion function names, we actually need to merge
3773   // all of the results for them into one list of results each and insert
3774   // those.
3775   SmallVector<NamedDecl *, 8> ConstructorDecls;
3776   SmallVector<NamedDecl *, 8> ConversionDecls;
3777 
3778   // Now loop over the names, either inserting them or appending for the two
3779   // special cases.
3780   for (auto &Name : Names) {
3781     DeclContext::lookup_result Result = DC->noload_lookup(Name);
3782 
3783     switch (Name.getNameKind()) {
3784     default:
3785       Generator.insert(Name, Trait.getData(Result), Trait);
3786       break;
3787 
3788     case DeclarationName::CXXConstructorName:
3789       ConstructorDecls.append(Result.begin(), Result.end());
3790       break;
3791 
3792     case DeclarationName::CXXConversionFunctionName:
3793       ConversionDecls.append(Result.begin(), Result.end());
3794       break;
3795     }
3796   }
3797 
3798   // Handle our two special cases if we ended up having any. We arbitrarily use
3799   // the first declaration's name here because the name itself isn't part of
3800   // the key, only the kind of name is used.
3801   if (!ConstructorDecls.empty())
3802     Generator.insert(ConstructorDecls.front()->getDeclName(),
3803                      Trait.getData(ConstructorDecls), Trait);
3804   if (!ConversionDecls.empty())
3805     Generator.insert(ConversionDecls.front()->getDeclName(),
3806                      Trait.getData(ConversionDecls), Trait);
3807 
3808   // Create the on-disk hash table. Also emit the existing imported and
3809   // merged table if there is one.
3810   auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr;
3811   Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr);
3812 }
3813 
3814 /// Write the block containing all of the declaration IDs
3815 /// visible from the given DeclContext.
3816 ///
3817 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
3818 /// bitstream, or 0 if no block was written.
3819 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
3820                                                  DeclContext *DC) {
3821   // If we imported a key declaration of this namespace, write the visible
3822   // lookup results as an update record for it rather than including them
3823   // on this declaration. We will only look at key declarations on reload.
3824   if (isa<NamespaceDecl>(DC) && Chain &&
3825       Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) {
3826     // Only do this once, for the first local declaration of the namespace.
3827     for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
3828          Prev = Prev->getPreviousDecl())
3829       if (!Prev->isFromASTFile())
3830         return 0;
3831 
3832     // Note that we need to emit an update record for the primary context.
3833     UpdatedDeclContexts.insert(DC->getPrimaryContext());
3834 
3835     // Make sure all visible decls are written. They will be recorded later. We
3836     // do this using a side data structure so we can sort the names into
3837     // a deterministic order.
3838     StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup();
3839     SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16>
3840         LookupResults;
3841     if (Map) {
3842       LookupResults.reserve(Map->size());
3843       for (auto &Entry : *Map)
3844         LookupResults.push_back(
3845             std::make_pair(Entry.first, Entry.second.getLookupResult()));
3846     }
3847 
3848     llvm::sort(LookupResults, llvm::less_first());
3849     for (auto &NameAndResult : LookupResults) {
3850       DeclarationName Name = NameAndResult.first;
3851       DeclContext::lookup_result Result = NameAndResult.second;
3852       if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
3853           Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
3854         // We have to work around a name lookup bug here where negative lookup
3855         // results for these names get cached in namespace lookup tables (these
3856         // names should never be looked up in a namespace).
3857         assert(Result.empty() && "Cannot have a constructor or conversion "
3858                                  "function name in a namespace!");
3859         continue;
3860       }
3861 
3862       for (NamedDecl *ND : Result)
3863         if (!ND->isFromASTFile())
3864           GetDeclRef(ND);
3865     }
3866 
3867     return 0;
3868   }
3869 
3870   if (DC->getPrimaryContext() != DC)
3871     return 0;
3872 
3873   // Skip contexts which don't support name lookup.
3874   if (!DC->isLookupContext())
3875     return 0;
3876 
3877   // If not in C++, we perform name lookup for the translation unit via the
3878   // IdentifierInfo chains, don't bother to build a visible-declarations table.
3879   if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
3880     return 0;
3881 
3882   // Serialize the contents of the mapping used for lookup. Note that,
3883   // although we have two very different code paths, the serialized
3884   // representation is the same for both cases: a declaration name,
3885   // followed by a size, followed by references to the visible
3886   // declarations that have that name.
3887   uint64_t Offset = Stream.GetCurrentBitNo();
3888   StoredDeclsMap *Map = DC->buildLookup();
3889   if (!Map || Map->empty())
3890     return 0;
3891 
3892   // Create the on-disk hash table in a buffer.
3893   SmallString<4096> LookupTable;
3894   GenerateNameLookupTable(DC, LookupTable);
3895 
3896   // Write the lookup table
3897   RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
3898   Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
3899                             LookupTable);
3900   ++NumVisibleDeclContexts;
3901   return Offset;
3902 }
3903 
3904 /// Write an UPDATE_VISIBLE block for the given context.
3905 ///
3906 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
3907 /// DeclContext in a dependent AST file. As such, they only exist for the TU
3908 /// (in C++), for namespaces, and for classes with forward-declared unscoped
3909 /// enumeration members (in C++11).
3910 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
3911   StoredDeclsMap *Map = DC->getLookupPtr();
3912   if (!Map || Map->empty())
3913     return;
3914 
3915   // Create the on-disk hash table in a buffer.
3916   SmallString<4096> LookupTable;
3917   GenerateNameLookupTable(DC, LookupTable);
3918 
3919   // If we're updating a namespace, select a key declaration as the key for the
3920   // update record; those are the only ones that will be checked on reload.
3921   if (isa<NamespaceDecl>(DC))
3922     DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
3923 
3924   // Write the lookup table
3925   RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))};
3926   Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
3927 }
3928 
3929 /// Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
3930 void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
3931   RecordData::value_type Record[] = {Opts.getAsOpaqueInt()};
3932   Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
3933 }
3934 
3935 /// Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
3936 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
3937   if (!SemaRef.Context.getLangOpts().OpenCL)
3938     return;
3939 
3940   const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
3941   RecordData Record;
3942   for (const auto &I:Opts.OptMap) {
3943     AddString(I.getKey(), Record);
3944     auto V = I.getValue();
3945     Record.push_back(V.Supported ? 1 : 0);
3946     Record.push_back(V.Enabled ? 1 : 0);
3947     Record.push_back(V.Avail);
3948     Record.push_back(V.Core);
3949   }
3950   Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
3951 }
3952 
3953 void ASTWriter::WriteOpenCLExtensionTypes(Sema &SemaRef) {
3954   if (!SemaRef.Context.getLangOpts().OpenCL)
3955     return;
3956 
3957   // Sort the elements of the map OpenCLTypeExtMap by TypeIDs,
3958   // without copying them.
3959   const llvm::DenseMap<const Type *, std::set<std::string>> &OpenCLTypeExtMap =
3960       SemaRef.OpenCLTypeExtMap;
3961   using ElementTy = std::pair<TypeID, const std::set<std::string> *>;
3962   llvm::SmallVector<ElementTy, 8> StableOpenCLTypeExtMap;
3963   StableOpenCLTypeExtMap.reserve(OpenCLTypeExtMap.size());
3964 
3965   for (const auto &I : OpenCLTypeExtMap)
3966     StableOpenCLTypeExtMap.emplace_back(
3967         getTypeID(I.first->getCanonicalTypeInternal()), &I.second);
3968 
3969   auto CompareByTypeID = [](const ElementTy &E1, const ElementTy &E2) -> bool {
3970     return E1.first < E2.first;
3971   };
3972   llvm::sort(StableOpenCLTypeExtMap, CompareByTypeID);
3973 
3974   RecordData Record;
3975   for (const ElementTy &E : StableOpenCLTypeExtMap) {
3976     Record.push_back(E.first); // TypeID
3977     const std::set<std::string> *ExtSet = E.second;
3978     Record.push_back(static_cast<unsigned>(ExtSet->size()));
3979     for (const std::string &Ext : *ExtSet)
3980       AddString(Ext, Record);
3981   }
3982 
3983   Stream.EmitRecord(OPENCL_EXTENSION_TYPES, Record);
3984 }
3985 
3986 void ASTWriter::WriteOpenCLExtensionDecls(Sema &SemaRef) {
3987   if (!SemaRef.Context.getLangOpts().OpenCL)
3988     return;
3989 
3990   // Sort the elements of the map OpenCLDeclExtMap by DeclIDs,
3991   // without copying them.
3992   const llvm::DenseMap<const Decl *, std::set<std::string>> &OpenCLDeclExtMap =
3993       SemaRef.OpenCLDeclExtMap;
3994   using ElementTy = std::pair<DeclID, const std::set<std::string> *>;
3995   llvm::SmallVector<ElementTy, 8> StableOpenCLDeclExtMap;
3996   StableOpenCLDeclExtMap.reserve(OpenCLDeclExtMap.size());
3997 
3998   for (const auto &I : OpenCLDeclExtMap)
3999     StableOpenCLDeclExtMap.emplace_back(getDeclID(I.first), &I.second);
4000 
4001   auto CompareByDeclID = [](const ElementTy &E1, const ElementTy &E2) -> bool {
4002     return E1.first < E2.first;
4003   };
4004   llvm::sort(StableOpenCLDeclExtMap, CompareByDeclID);
4005 
4006   RecordData Record;
4007   for (const ElementTy &E : StableOpenCLDeclExtMap) {
4008     Record.push_back(E.first); // DeclID
4009     const std::set<std::string> *ExtSet = E.second;
4010     Record.push_back(static_cast<unsigned>(ExtSet->size()));
4011     for (const std::string &Ext : *ExtSet)
4012       AddString(Ext, Record);
4013   }
4014 
4015   Stream.EmitRecord(OPENCL_EXTENSION_DECLS, Record);
4016 }
4017 
4018 void ASTWriter::WriteCUDAPragmas(Sema &SemaRef) {
4019   if (SemaRef.ForceCUDAHostDeviceDepth > 0) {
4020     RecordData::value_type Record[] = {SemaRef.ForceCUDAHostDeviceDepth};
4021     Stream.EmitRecord(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH, Record);
4022   }
4023 }
4024 
4025 void ASTWriter::WriteObjCCategories() {
4026   SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
4027   RecordData Categories;
4028 
4029   for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
4030     unsigned Size = 0;
4031     unsigned StartIndex = Categories.size();
4032 
4033     ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
4034 
4035     // Allocate space for the size.
4036     Categories.push_back(0);
4037 
4038     // Add the categories.
4039     for (ObjCInterfaceDecl::known_categories_iterator
4040            Cat = Class->known_categories_begin(),
4041            CatEnd = Class->known_categories_end();
4042          Cat != CatEnd; ++Cat, ++Size) {
4043       assert(getDeclID(*Cat) != 0 && "Bogus category");
4044       AddDeclRef(*Cat, Categories);
4045     }
4046 
4047     // Update the size.
4048     Categories[StartIndex] = Size;
4049 
4050     // Record this interface -> category map.
4051     ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
4052     CategoriesMap.push_back(CatInfo);
4053   }
4054 
4055   // Sort the categories map by the definition ID, since the reader will be
4056   // performing binary searches on this information.
4057   llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
4058 
4059   // Emit the categories map.
4060   using namespace llvm;
4061 
4062   auto Abbrev = std::make_shared<BitCodeAbbrev>();
4063   Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
4064   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
4065   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4066   unsigned AbbrevID = Stream.EmitAbbrev(std::move(Abbrev));
4067 
4068   RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
4069   Stream.EmitRecordWithBlob(AbbrevID, Record,
4070                             reinterpret_cast<char *>(CategoriesMap.data()),
4071                             CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
4072 
4073   // Emit the category lists.
4074   Stream.EmitRecord(OBJC_CATEGORIES, Categories);
4075 }
4076 
4077 void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
4078   Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
4079 
4080   if (LPTMap.empty())
4081     return;
4082 
4083   RecordData Record;
4084   for (auto &LPTMapEntry : LPTMap) {
4085     const FunctionDecl *FD = LPTMapEntry.first;
4086     LateParsedTemplate &LPT = *LPTMapEntry.second;
4087     AddDeclRef(FD, Record);
4088     AddDeclRef(LPT.D, Record);
4089     Record.push_back(LPT.Toks.size());
4090 
4091     for (const auto &Tok : LPT.Toks) {
4092       AddToken(Tok, Record);
4093     }
4094   }
4095   Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
4096 }
4097 
4098 /// Write the state of 'pragma clang optimize' at the end of the module.
4099 void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
4100   RecordData Record;
4101   SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
4102   AddSourceLocation(PragmaLoc, Record);
4103   Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
4104 }
4105 
4106 /// Write the state of 'pragma ms_struct' at the end of the module.
4107 void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
4108   RecordData Record;
4109   Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF);
4110   Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
4111 }
4112 
4113 /// Write the state of 'pragma pointers_to_members' at the end of the
4114 //module.
4115 void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
4116   RecordData Record;
4117   Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod);
4118   AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record);
4119   Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
4120 }
4121 
4122 /// Write the state of 'pragma pack' at the end of the module.
4123 void ASTWriter::WritePackPragmaOptions(Sema &SemaRef) {
4124   // Don't serialize pragma pack state for modules, since it should only take
4125   // effect on a per-submodule basis.
4126   if (WritingModule)
4127     return;
4128 
4129   RecordData Record;
4130   Record.push_back(SemaRef.PackStack.CurrentValue);
4131   AddSourceLocation(SemaRef.PackStack.CurrentPragmaLocation, Record);
4132   Record.push_back(SemaRef.PackStack.Stack.size());
4133   for (const auto &StackEntry : SemaRef.PackStack.Stack) {
4134     Record.push_back(StackEntry.Value);
4135     AddSourceLocation(StackEntry.PragmaLocation, Record);
4136     AddSourceLocation(StackEntry.PragmaPushLocation, Record);
4137     AddString(StackEntry.StackSlotLabel, Record);
4138   }
4139   Stream.EmitRecord(PACK_PRAGMA_OPTIONS, Record);
4140 }
4141 
4142 /// Write the state of 'pragma float_control' at the end of the module.
4143 void ASTWriter::WriteFloatControlPragmaOptions(Sema &SemaRef) {
4144   // Don't serialize pragma float_control state for modules,
4145   // since it should only take effect on a per-submodule basis.
4146   if (WritingModule)
4147     return;
4148 
4149   RecordData Record;
4150   Record.push_back(SemaRef.FpPragmaStack.CurrentValue);
4151   AddSourceLocation(SemaRef.FpPragmaStack.CurrentPragmaLocation, Record);
4152   Record.push_back(SemaRef.FpPragmaStack.Stack.size());
4153   for (const auto &StackEntry : SemaRef.FpPragmaStack.Stack) {
4154     Record.push_back(StackEntry.Value);
4155     AddSourceLocation(StackEntry.PragmaLocation, Record);
4156     AddSourceLocation(StackEntry.PragmaPushLocation, Record);
4157     AddString(StackEntry.StackSlotLabel, Record);
4158   }
4159   Stream.EmitRecord(FLOAT_CONTROL_PRAGMA_OPTIONS, Record);
4160 }
4161 
4162 void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
4163                                          ModuleFileExtensionWriter &Writer) {
4164   // Enter the extension block.
4165   Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
4166 
4167   // Emit the metadata record abbreviation.
4168   auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
4169   Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
4170   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4171   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4172   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4173   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4174   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4175   unsigned Abbrev = Stream.EmitAbbrev(std::move(Abv));
4176 
4177   // Emit the metadata record.
4178   RecordData Record;
4179   auto Metadata = Writer.getExtension()->getExtensionMetadata();
4180   Record.push_back(EXTENSION_METADATA);
4181   Record.push_back(Metadata.MajorVersion);
4182   Record.push_back(Metadata.MinorVersion);
4183   Record.push_back(Metadata.BlockName.size());
4184   Record.push_back(Metadata.UserInfo.size());
4185   SmallString<64> Buffer;
4186   Buffer += Metadata.BlockName;
4187   Buffer += Metadata.UserInfo;
4188   Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
4189 
4190   // Emit the contents of the extension block.
4191   Writer.writeExtensionContents(SemaRef, Stream);
4192 
4193   // Exit the extension block.
4194   Stream.ExitBlock();
4195 }
4196 
4197 //===----------------------------------------------------------------------===//
4198 // General Serialization Routines
4199 //===----------------------------------------------------------------------===//
4200 
4201 void ASTRecordWriter::AddAttr(const Attr *A) {
4202   auto &Record = *this;
4203   if (!A)
4204     return Record.push_back(0);
4205   Record.push_back(A->getKind() + 1); // FIXME: stable encoding, target attrs
4206 
4207   Record.AddIdentifierRef(A->getAttrName());
4208   Record.AddIdentifierRef(A->getScopeName());
4209   Record.AddSourceRange(A->getRange());
4210   Record.AddSourceLocation(A->getScopeLoc());
4211   Record.push_back(A->getParsedKind());
4212   Record.push_back(A->getSyntax());
4213   Record.push_back(A->getAttributeSpellingListIndexRaw());
4214 
4215 #include "clang/Serialization/AttrPCHWrite.inc"
4216 }
4217 
4218 /// Emit the list of attributes to the specified record.
4219 void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) {
4220   push_back(Attrs.size());
4221   for (const auto *A : Attrs)
4222     AddAttr(A);
4223 }
4224 
4225 void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
4226   AddSourceLocation(Tok.getLocation(), Record);
4227   Record.push_back(Tok.getLength());
4228 
4229   // FIXME: When reading literal tokens, reconstruct the literal pointer
4230   // if it is needed.
4231   AddIdentifierRef(Tok.getIdentifierInfo(), Record);
4232   // FIXME: Should translate token kind to a stable encoding.
4233   Record.push_back(Tok.getKind());
4234   // FIXME: Should translate token flags to a stable encoding.
4235   Record.push_back(Tok.getFlags());
4236 }
4237 
4238 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
4239   Record.push_back(Str.size());
4240   Record.insert(Record.end(), Str.begin(), Str.end());
4241 }
4242 
4243 bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
4244   assert(Context && "should have context when outputting path");
4245 
4246   bool Changed =
4247       cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
4248 
4249   // Remove a prefix to make the path relative, if relevant.
4250   const char *PathBegin = Path.data();
4251   const char *PathPtr =
4252       adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
4253   if (PathPtr != PathBegin) {
4254     Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
4255     Changed = true;
4256   }
4257 
4258   return Changed;
4259 }
4260 
4261 void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
4262   SmallString<128> FilePath(Path);
4263   PreparePathForOutput(FilePath);
4264   AddString(FilePath, Record);
4265 }
4266 
4267 void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
4268                                    StringRef Path) {
4269   SmallString<128> FilePath(Path);
4270   PreparePathForOutput(FilePath);
4271   Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
4272 }
4273 
4274 void ASTWriter::AddVersionTuple(const VersionTuple &Version,
4275                                 RecordDataImpl &Record) {
4276   Record.push_back(Version.getMajor());
4277   if (Optional<unsigned> Minor = Version.getMinor())
4278     Record.push_back(*Minor + 1);
4279   else
4280     Record.push_back(0);
4281   if (Optional<unsigned> Subminor = Version.getSubminor())
4282     Record.push_back(*Subminor + 1);
4283   else
4284     Record.push_back(0);
4285 }
4286 
4287 /// Note that the identifier II occurs at the given offset
4288 /// within the identifier table.
4289 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
4290   IdentID ID = IdentifierIDs[II];
4291   // Only store offsets new to this AST file. Other identifier names are looked
4292   // up earlier in the chain and thus don't need an offset.
4293   if (ID >= FirstIdentID)
4294     IdentifierOffsets[ID - FirstIdentID] = Offset;
4295 }
4296 
4297 /// Note that the selector Sel occurs at the given offset
4298 /// within the method pool/selector table.
4299 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
4300   unsigned ID = SelectorIDs[Sel];
4301   assert(ID && "Unknown selector");
4302   // Don't record offsets for selectors that are also available in a different
4303   // file.
4304   if (ID < FirstSelectorID)
4305     return;
4306   SelectorOffsets[ID - FirstSelectorID] = Offset;
4307 }
4308 
4309 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream,
4310                      SmallVectorImpl<char> &Buffer,
4311                      InMemoryModuleCache &ModuleCache,
4312                      ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
4313                      bool IncludeTimestamps)
4314     : Stream(Stream), Buffer(Buffer), ModuleCache(ModuleCache),
4315       IncludeTimestamps(IncludeTimestamps) {
4316   for (const auto &Ext : Extensions) {
4317     if (auto Writer = Ext->createExtensionWriter(*this))
4318       ModuleFileExtensionWriters.push_back(std::move(Writer));
4319   }
4320 }
4321 
4322 ASTWriter::~ASTWriter() = default;
4323 
4324 const LangOptions &ASTWriter::getLangOpts() const {
4325   assert(WritingAST && "can't determine lang opts when not writing AST");
4326   return Context->getLangOpts();
4327 }
4328 
4329 time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const {
4330   return IncludeTimestamps ? E->getModificationTime() : 0;
4331 }
4332 
4333 ASTFileSignature ASTWriter::WriteAST(Sema &SemaRef,
4334                                      const std::string &OutputFile,
4335                                      Module *WritingModule, StringRef isysroot,
4336                                      bool hasErrors,
4337                                      bool ShouldCacheASTInMemory) {
4338   WritingAST = true;
4339 
4340   ASTHasCompilerErrors = hasErrors;
4341 
4342   // Emit the file header.
4343   Stream.Emit((unsigned)'C', 8);
4344   Stream.Emit((unsigned)'P', 8);
4345   Stream.Emit((unsigned)'C', 8);
4346   Stream.Emit((unsigned)'H', 8);
4347 
4348   WriteBlockInfoBlock();
4349 
4350   Context = &SemaRef.Context;
4351   PP = &SemaRef.PP;
4352   this->WritingModule = WritingModule;
4353   ASTFileSignature Signature =
4354       WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
4355   Context = nullptr;
4356   PP = nullptr;
4357   this->WritingModule = nullptr;
4358   this->BaseDirectory.clear();
4359 
4360   WritingAST = false;
4361   if (ShouldCacheASTInMemory) {
4362     // Construct MemoryBuffer and update buffer manager.
4363     ModuleCache.addBuiltPCM(OutputFile,
4364                             llvm::MemoryBuffer::getMemBufferCopy(
4365                                 StringRef(Buffer.begin(), Buffer.size())));
4366   }
4367   return Signature;
4368 }
4369 
4370 template<typename Vector>
4371 static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4372                                ASTWriter::RecordData &Record) {
4373   for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4374        I != E; ++I) {
4375     Writer.AddDeclRef(*I, Record);
4376   }
4377 }
4378 
4379 ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
4380                                          const std::string &OutputFile,
4381                                          Module *WritingModule) {
4382   using namespace llvm;
4383 
4384   bool isModule = WritingModule != nullptr;
4385 
4386   // Make sure that the AST reader knows to finalize itself.
4387   if (Chain)
4388     Chain->finalizeForWriting();
4389 
4390   ASTContext &Context = SemaRef.Context;
4391   Preprocessor &PP = SemaRef.PP;
4392 
4393   // Set up predefined declaration IDs.
4394   auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
4395     if (D) {
4396       assert(D->isCanonicalDecl() && "predefined decl is not canonical");
4397       DeclIDs[D] = ID;
4398     }
4399   };
4400   RegisterPredefDecl(Context.getTranslationUnitDecl(),
4401                      PREDEF_DECL_TRANSLATION_UNIT_ID);
4402   RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
4403   RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
4404   RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
4405   RegisterPredefDecl(Context.ObjCProtocolClassDecl,
4406                      PREDEF_DECL_OBJC_PROTOCOL_ID);
4407   RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
4408   RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
4409   RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
4410                      PREDEF_DECL_OBJC_INSTANCETYPE_ID);
4411   RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
4412   RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
4413   RegisterPredefDecl(Context.BuiltinMSVaListDecl,
4414                      PREDEF_DECL_BUILTIN_MS_VA_LIST_ID);
4415   RegisterPredefDecl(Context.MSGuidTagDecl,
4416                      PREDEF_DECL_BUILTIN_MS_GUID_ID);
4417   RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
4418   RegisterPredefDecl(Context.MakeIntegerSeqDecl,
4419                      PREDEF_DECL_MAKE_INTEGER_SEQ_ID);
4420   RegisterPredefDecl(Context.CFConstantStringTypeDecl,
4421                      PREDEF_DECL_CF_CONSTANT_STRING_ID);
4422   RegisterPredefDecl(Context.CFConstantStringTagDecl,
4423                      PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID);
4424   RegisterPredefDecl(Context.TypePackElementDecl,
4425                      PREDEF_DECL_TYPE_PACK_ELEMENT_ID);
4426 
4427   // Build a record containing all of the tentative definitions in this file, in
4428   // TentativeDefinitions order.  Generally, this record will be empty for
4429   // headers.
4430   RecordData TentativeDefinitions;
4431   AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
4432 
4433   // Build a record containing all of the file scoped decls in this file.
4434   RecordData UnusedFileScopedDecls;
4435   if (!isModule)
4436     AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
4437                        UnusedFileScopedDecls);
4438 
4439   // Build a record containing all of the delegating constructors we still need
4440   // to resolve.
4441   RecordData DelegatingCtorDecls;
4442   if (!isModule)
4443     AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
4444 
4445   // Write the set of weak, undeclared identifiers. We always write the
4446   // entire table, since later PCH files in a PCH chain are only interested in
4447   // the results at the end of the chain.
4448   RecordData WeakUndeclaredIdentifiers;
4449   for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) {
4450     IdentifierInfo *II = WeakUndeclaredIdentifier.first;
4451     WeakInfo &WI = WeakUndeclaredIdentifier.second;
4452     AddIdentifierRef(II, WeakUndeclaredIdentifiers);
4453     AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
4454     AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
4455     WeakUndeclaredIdentifiers.push_back(WI.getUsed());
4456   }
4457 
4458   // Build a record containing all of the ext_vector declarations.
4459   RecordData ExtVectorDecls;
4460   AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
4461 
4462   // Build a record containing all of the VTable uses information.
4463   RecordData VTableUses;
4464   if (!SemaRef.VTableUses.empty()) {
4465     for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4466       AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4467       AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4468       VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4469     }
4470   }
4471 
4472   // Build a record containing all of the UnusedLocalTypedefNameCandidates.
4473   RecordData UnusedLocalTypedefNameCandidates;
4474   for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4475     AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
4476 
4477   // Build a record containing all of pending implicit instantiations.
4478   RecordData PendingInstantiations;
4479   for (const auto &I : SemaRef.PendingInstantiations) {
4480     AddDeclRef(I.first, PendingInstantiations);
4481     AddSourceLocation(I.second, PendingInstantiations);
4482   }
4483   assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4484          "There are local ones at end of translation unit!");
4485 
4486   // Build a record containing some declaration references.
4487   RecordData SemaDeclRefs;
4488   if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) {
4489     AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4490     AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
4491     AddDeclRef(SemaRef.getStdAlignValT(), SemaDeclRefs);
4492   }
4493 
4494   RecordData CUDASpecialDeclRefs;
4495   if (Context.getcudaConfigureCallDecl()) {
4496     AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4497   }
4498 
4499   // Build a record containing all of the known namespaces.
4500   RecordData KnownNamespaces;
4501   for (const auto &I : SemaRef.KnownNamespaces) {
4502     if (!I.second)
4503       AddDeclRef(I.first, KnownNamespaces);
4504   }
4505 
4506   // Build a record of all used, undefined objects that require definitions.
4507   RecordData UndefinedButUsed;
4508 
4509   SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
4510   SemaRef.getUndefinedButUsed(Undefined);
4511   for (const auto &I : Undefined) {
4512     AddDeclRef(I.first, UndefinedButUsed);
4513     AddSourceLocation(I.second, UndefinedButUsed);
4514   }
4515 
4516   // Build a record containing all delete-expressions that we would like to
4517   // analyze later in AST.
4518   RecordData DeleteExprsToAnalyze;
4519 
4520   if (!isModule) {
4521     for (const auto &DeleteExprsInfo :
4522          SemaRef.getMismatchingDeleteExpressions()) {
4523       AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
4524       DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
4525       for (const auto &DeleteLoc : DeleteExprsInfo.second) {
4526         AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
4527         DeleteExprsToAnalyze.push_back(DeleteLoc.second);
4528       }
4529     }
4530   }
4531 
4532   // Write the control block
4533   WriteControlBlock(PP, Context, isysroot, OutputFile);
4534 
4535   // Write the remaining AST contents.
4536   Stream.EnterSubblock(AST_BLOCK_ID, 5);
4537 
4538   // This is so that older clang versions, before the introduction
4539   // of the control block, can read and reject the newer PCH format.
4540   {
4541     RecordData Record = {VERSION_MAJOR};
4542     Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4543   }
4544 
4545   // Create a lexical update block containing all of the declarations in the
4546   // translation unit that do not come from other AST files.
4547   const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
4548   SmallVector<uint32_t, 128> NewGlobalKindDeclPairs;
4549   for (const auto *D : TU->noload_decls()) {
4550     if (!D->isFromASTFile()) {
4551       NewGlobalKindDeclPairs.push_back(D->getKind());
4552       NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
4553     }
4554   }
4555 
4556   auto Abv = std::make_shared<BitCodeAbbrev>();
4557   Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4558   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4559   unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv));
4560   {
4561     RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
4562     Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4563                               bytes(NewGlobalKindDeclPairs));
4564   }
4565 
4566   // And a visible updates block for the translation unit.
4567   Abv = std::make_shared<BitCodeAbbrev>();
4568   Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4569   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4570   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4571   UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv));
4572   WriteDeclContextVisibleUpdate(TU);
4573 
4574   // If we have any extern "C" names, write out a visible update for them.
4575   if (Context.ExternCContext)
4576     WriteDeclContextVisibleUpdate(Context.ExternCContext);
4577 
4578   // If the translation unit has an anonymous namespace, and we don't already
4579   // have an update block for it, write it as an update block.
4580   // FIXME: Why do we not do this if there's already an update block?
4581   if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4582     ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
4583     if (Record.empty())
4584       Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
4585   }
4586 
4587   // Add update records for all mangling numbers and static local numbers.
4588   // These aren't really update records, but this is a convenient way of
4589   // tagging this rare extra data onto the declarations.
4590   for (const auto &Number : Context.MangleNumbers)
4591     if (!Number.first->isFromASTFile())
4592       DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4593                                                      Number.second));
4594   for (const auto &Number : Context.StaticLocalNumbers)
4595     if (!Number.first->isFromASTFile())
4596       DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4597                                                      Number.second));
4598 
4599   // Make sure visible decls, added to DeclContexts previously loaded from
4600   // an AST file, are registered for serialization. Likewise for template
4601   // specializations added to imported templates.
4602   for (const auto *I : DeclsToEmitEvenIfUnreferenced) {
4603     GetDeclRef(I);
4604   }
4605 
4606   // Make sure all decls associated with an identifier are registered for
4607   // serialization, if we're storing decls with identifiers.
4608   if (!WritingModule || !getLangOpts().CPlusPlus) {
4609     llvm::SmallVector<const IdentifierInfo*, 256> IIs;
4610     for (const auto &ID : PP.getIdentifierTable()) {
4611       const IdentifierInfo *II = ID.second;
4612       if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
4613         IIs.push_back(II);
4614     }
4615     // Sort the identifiers to visit based on their name.
4616     llvm::sort(IIs, llvm::deref<std::less<>>());
4617     for (const IdentifierInfo *II : IIs) {
4618       for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4619                                      DEnd = SemaRef.IdResolver.end();
4620            D != DEnd; ++D) {
4621         GetDeclRef(*D);
4622       }
4623     }
4624   }
4625 
4626   // For method pool in the module, if it contains an entry for a selector,
4627   // the entry should be complete, containing everything introduced by that
4628   // module and all modules it imports. It's possible that the entry is out of
4629   // date, so we need to pull in the new content here.
4630 
4631   // It's possible that updateOutOfDateSelector can update SelectorIDs. To be
4632   // safe, we copy all selectors out.
4633   llvm::SmallVector<Selector, 256> AllSelectors;
4634   for (auto &SelectorAndID : SelectorIDs)
4635     AllSelectors.push_back(SelectorAndID.first);
4636   for (auto &Selector : AllSelectors)
4637     SemaRef.updateOutOfDateSelector(Selector);
4638 
4639   // Form the record of special types.
4640   RecordData SpecialTypes;
4641   AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
4642   AddTypeRef(Context.getFILEType(), SpecialTypes);
4643   AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4644   AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4645   AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4646   AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
4647   AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
4648   AddTypeRef(Context.getucontext_tType(), SpecialTypes);
4649 
4650   if (Chain) {
4651     // Write the mapping information describing our module dependencies and how
4652     // each of those modules were mapped into our own offset/ID space, so that
4653     // the reader can build the appropriate mapping to its own offset/ID space.
4654     // The map consists solely of a blob with the following format:
4655     // *(module-kind:i8
4656     //   module-name-len:i16 module-name:len*i8
4657     //   source-location-offset:i32
4658     //   identifier-id:i32
4659     //   preprocessed-entity-id:i32
4660     //   macro-definition-id:i32
4661     //   submodule-id:i32
4662     //   selector-id:i32
4663     //   declaration-id:i32
4664     //   c++-base-specifiers-id:i32
4665     //   type-id:i32)
4666     //
4667     // module-kind is the ModuleKind enum value. If it is MK_PrebuiltModule or
4668     // MK_ExplicitModule, then the module-name is the module name. Otherwise,
4669     // it is the module file name.
4670     auto Abbrev = std::make_shared<BitCodeAbbrev>();
4671     Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4672     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4673     unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
4674     SmallString<2048> Buffer;
4675     {
4676       llvm::raw_svector_ostream Out(Buffer);
4677       for (ModuleFile &M : Chain->ModuleMgr) {
4678         using namespace llvm::support;
4679 
4680         endian::Writer LE(Out, little);
4681         LE.write<uint8_t>(static_cast<uint8_t>(M.Kind));
4682         StringRef Name =
4683           M.Kind == MK_PrebuiltModule || M.Kind == MK_ExplicitModule
4684           ? M.ModuleName
4685           : M.FileName;
4686         LE.write<uint16_t>(Name.size());
4687         Out.write(Name.data(), Name.size());
4688 
4689         // Note: if a base ID was uint max, it would not be possible to load
4690         // another module after it or have more than one entity inside it.
4691         uint32_t None = std::numeric_limits<uint32_t>::max();
4692 
4693         auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) {
4694           assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
4695           if (ShouldWrite)
4696             LE.write<uint32_t>(BaseID);
4697           else
4698             LE.write<uint32_t>(None);
4699         };
4700 
4701         // These values should be unique within a chain, since they will be read
4702         // as keys into ContinuousRangeMaps.
4703         writeBaseIDOrNone(M.SLocEntryBaseOffset, M.LocalNumSLocEntries);
4704         writeBaseIDOrNone(M.BaseIdentifierID, M.LocalNumIdentifiers);
4705         writeBaseIDOrNone(M.BaseMacroID, M.LocalNumMacros);
4706         writeBaseIDOrNone(M.BasePreprocessedEntityID,
4707                           M.NumPreprocessedEntities);
4708         writeBaseIDOrNone(M.BaseSubmoduleID, M.LocalNumSubmodules);
4709         writeBaseIDOrNone(M.BaseSelectorID, M.LocalNumSelectors);
4710         writeBaseIDOrNone(M.BaseDeclID, M.LocalNumDecls);
4711         writeBaseIDOrNone(M.BaseTypeIndex, M.LocalNumTypes);
4712       }
4713     }
4714     RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
4715     Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4716                               Buffer.data(), Buffer.size());
4717   }
4718 
4719   // Build a record containing all of the DeclsToCheckForDeferredDiags.
4720   RecordData DeclsToCheckForDeferredDiags;
4721   for (auto *D : SemaRef.DeclsToCheckForDeferredDiags)
4722     AddDeclRef(D, DeclsToCheckForDeferredDiags);
4723 
4724   RecordData DeclUpdatesOffsetsRecord;
4725 
4726   // Keep writing types, declarations, and declaration update records
4727   // until we've emitted all of them.
4728   Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
4729   WriteTypeAbbrevs();
4730   WriteDeclAbbrevs();
4731   do {
4732     WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
4733     while (!DeclTypesToEmit.empty()) {
4734       DeclOrType DOT = DeclTypesToEmit.front();
4735       DeclTypesToEmit.pop();
4736       if (DOT.isType())
4737         WriteType(DOT.getType());
4738       else
4739         WriteDecl(Context, DOT.getDecl());
4740     }
4741   } while (!DeclUpdates.empty());
4742   Stream.ExitBlock();
4743 
4744   DoneWritingDeclsAndTypes = true;
4745 
4746   // These things can only be done once we've written out decls and types.
4747   WriteTypeDeclOffsets();
4748   if (!DeclUpdatesOffsetsRecord.empty())
4749     Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
4750   WriteFileDeclIDsMap();
4751   WriteSourceManagerBlock(Context.getSourceManager(), PP);
4752   WriteComments();
4753   WritePreprocessor(PP, isModule);
4754   WriteHeaderSearch(PP.getHeaderSearchInfo());
4755   WriteSelectors(SemaRef);
4756   WriteReferencedSelectorsPool(SemaRef);
4757   WriteLateParsedTemplates(SemaRef);
4758   WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
4759   WriteFPPragmaOptions(SemaRef.getCurFPFeatures());
4760   WriteOpenCLExtensions(SemaRef);
4761   WriteOpenCLExtensionTypes(SemaRef);
4762   WriteCUDAPragmas(SemaRef);
4763 
4764   // If we're emitting a module, write out the submodule information.
4765   if (WritingModule)
4766     WriteSubmodules(WritingModule);
4767 
4768   // We need to have information about submodules to correctly deserialize
4769   // decls from OpenCLExtensionDecls block
4770   WriteOpenCLExtensionDecls(SemaRef);
4771 
4772   Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
4773 
4774   // Write the record containing external, unnamed definitions.
4775   if (!EagerlyDeserializedDecls.empty())
4776     Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
4777 
4778   if (!ModularCodegenDecls.empty())
4779     Stream.EmitRecord(MODULAR_CODEGEN_DECLS, ModularCodegenDecls);
4780 
4781   // Write the record containing tentative definitions.
4782   if (!TentativeDefinitions.empty())
4783     Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
4784 
4785   // Write the record containing unused file scoped decls.
4786   if (!UnusedFileScopedDecls.empty())
4787     Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
4788 
4789   // Write the record containing weak undeclared identifiers.
4790   if (!WeakUndeclaredIdentifiers.empty())
4791     Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
4792                       WeakUndeclaredIdentifiers);
4793 
4794   // Write the record containing ext_vector type names.
4795   if (!ExtVectorDecls.empty())
4796     Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
4797 
4798   // Write the record containing VTable uses information.
4799   if (!VTableUses.empty())
4800     Stream.EmitRecord(VTABLE_USES, VTableUses);
4801 
4802   // Write the record containing potentially unused local typedefs.
4803   if (!UnusedLocalTypedefNameCandidates.empty())
4804     Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
4805                       UnusedLocalTypedefNameCandidates);
4806 
4807   // Write the record containing pending implicit instantiations.
4808   if (!PendingInstantiations.empty())
4809     Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
4810 
4811   // Write the record containing declaration references of Sema.
4812   if (!SemaDeclRefs.empty())
4813     Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
4814 
4815   // Write the record containing decls to be checked for deferred diags.
4816   if (!DeclsToCheckForDeferredDiags.empty())
4817     Stream.EmitRecord(DECLS_TO_CHECK_FOR_DEFERRED_DIAGS,
4818         DeclsToCheckForDeferredDiags);
4819 
4820   // Write the record containing CUDA-specific declaration references.
4821   if (!CUDASpecialDeclRefs.empty())
4822     Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
4823 
4824   // Write the delegating constructors.
4825   if (!DelegatingCtorDecls.empty())
4826     Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
4827 
4828   // Write the known namespaces.
4829   if (!KnownNamespaces.empty())
4830     Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
4831 
4832   // Write the undefined internal functions and variables, and inline functions.
4833   if (!UndefinedButUsed.empty())
4834     Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
4835 
4836   if (!DeleteExprsToAnalyze.empty())
4837     Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
4838 
4839   // Write the visible updates to DeclContexts.
4840   for (auto *DC : UpdatedDeclContexts)
4841     WriteDeclContextVisibleUpdate(DC);
4842 
4843   if (!WritingModule) {
4844     // Write the submodules that were imported, if any.
4845     struct ModuleInfo {
4846       uint64_t ID;
4847       Module *M;
4848       ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
4849     };
4850     llvm::SmallVector<ModuleInfo, 64> Imports;
4851     for (const auto *I : Context.local_imports()) {
4852       assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
4853       Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
4854                          I->getImportedModule()));
4855     }
4856 
4857     if (!Imports.empty()) {
4858       auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
4859         return A.ID < B.ID;
4860       };
4861       auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
4862         return A.ID == B.ID;
4863       };
4864 
4865       // Sort and deduplicate module IDs.
4866       llvm::sort(Imports, Cmp);
4867       Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
4868                     Imports.end());
4869 
4870       RecordData ImportedModules;
4871       for (const auto &Import : Imports) {
4872         ImportedModules.push_back(Import.ID);
4873         // FIXME: If the module has macros imported then later has declarations
4874         // imported, this location won't be the right one as a location for the
4875         // declaration imports.
4876         AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
4877       }
4878 
4879       Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
4880     }
4881   }
4882 
4883   WriteObjCCategories();
4884   if(!WritingModule) {
4885     WriteOptimizePragmaOptions(SemaRef);
4886     WriteMSStructPragmaOptions(SemaRef);
4887     WriteMSPointersToMembersPragmaOptions(SemaRef);
4888   }
4889   WritePackPragmaOptions(SemaRef);
4890   WriteFloatControlPragmaOptions(SemaRef);
4891 
4892   // Some simple statistics
4893   RecordData::value_type Record[] = {
4894       NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts};
4895   Stream.EmitRecord(STATISTICS, Record);
4896   Stream.ExitBlock();
4897 
4898   // Write the module file extension blocks.
4899   for (const auto &ExtWriter : ModuleFileExtensionWriters)
4900     WriteModuleFileExtension(SemaRef, *ExtWriter);
4901 
4902   return writeUnhashedControlBlock(PP, Context);
4903 }
4904 
4905 void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
4906   if (DeclUpdates.empty())
4907     return;
4908 
4909   DeclUpdateMap LocalUpdates;
4910   LocalUpdates.swap(DeclUpdates);
4911 
4912   for (auto &DeclUpdate : LocalUpdates) {
4913     const Decl *D = DeclUpdate.first;
4914 
4915     bool HasUpdatedBody = false;
4916     RecordData RecordData;
4917     ASTRecordWriter Record(*this, RecordData);
4918     for (auto &Update : DeclUpdate.second) {
4919       DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
4920 
4921       // An updated body is emitted last, so that the reader doesn't need
4922       // to skip over the lazy body to reach statements for other records.
4923       if (Kind == UPD_CXX_ADDED_FUNCTION_DEFINITION)
4924         HasUpdatedBody = true;
4925       else
4926         Record.push_back(Kind);
4927 
4928       switch (Kind) {
4929       case UPD_CXX_ADDED_IMPLICIT_MEMBER:
4930       case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4931       case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
4932         assert(Update.getDecl() && "no decl to add?");
4933         Record.push_back(GetDeclRef(Update.getDecl()));
4934         break;
4935 
4936       case UPD_CXX_ADDED_FUNCTION_DEFINITION:
4937         break;
4938 
4939       case UPD_CXX_POINT_OF_INSTANTIATION:
4940         // FIXME: Do we need to also save the template specialization kind here?
4941         Record.AddSourceLocation(Update.getLoc());
4942         break;
4943 
4944       case UPD_CXX_ADDED_VAR_DEFINITION: {
4945         const VarDecl *VD = cast<VarDecl>(D);
4946         Record.push_back(VD->isInline());
4947         Record.push_back(VD->isInlineSpecified());
4948         if (VD->getInit()) {
4949           Record.push_back(!VD->isInitKnownICE() ? 1
4950                                                  : (VD->isInitICE() ? 3 : 2));
4951           Record.AddStmt(const_cast<Expr*>(VD->getInit()));
4952         } else {
4953           Record.push_back(0);
4954         }
4955         break;
4956       }
4957 
4958       case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT:
4959         Record.AddStmt(const_cast<Expr *>(
4960             cast<ParmVarDecl>(Update.getDecl())->getDefaultArg()));
4961         break;
4962 
4963       case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER:
4964         Record.AddStmt(
4965             cast<FieldDecl>(Update.getDecl())->getInClassInitializer());
4966         break;
4967 
4968       case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
4969         auto *RD = cast<CXXRecordDecl>(D);
4970         UpdatedDeclContexts.insert(RD->getPrimaryContext());
4971         Record.push_back(RD->isParamDestroyedInCallee());
4972         Record.push_back(RD->getArgPassingRestrictions());
4973         Record.AddCXXDefinitionData(RD);
4974         Record.AddOffset(WriteDeclContextLexicalBlock(
4975             *Context, const_cast<CXXRecordDecl *>(RD)));
4976 
4977         // This state is sometimes updated by template instantiation, when we
4978         // switch from the specialization referring to the template declaration
4979         // to it referring to the template definition.
4980         if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
4981           Record.push_back(MSInfo->getTemplateSpecializationKind());
4982           Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
4983         } else {
4984           auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
4985           Record.push_back(Spec->getTemplateSpecializationKind());
4986           Record.AddSourceLocation(Spec->getPointOfInstantiation());
4987 
4988           // The instantiation might have been resolved to a partial
4989           // specialization. If so, record which one.
4990           auto From = Spec->getInstantiatedFrom();
4991           if (auto PartialSpec =
4992                 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
4993             Record.push_back(true);
4994             Record.AddDeclRef(PartialSpec);
4995             Record.AddTemplateArgumentList(
4996                 &Spec->getTemplateInstantiationArgs());
4997           } else {
4998             Record.push_back(false);
4999           }
5000         }
5001         Record.push_back(RD->getTagKind());
5002         Record.AddSourceLocation(RD->getLocation());
5003         Record.AddSourceLocation(RD->getBeginLoc());
5004         Record.AddSourceRange(RD->getBraceRange());
5005 
5006         // Instantiation may change attributes; write them all out afresh.
5007         Record.push_back(D->hasAttrs());
5008         if (D->hasAttrs())
5009           Record.AddAttributes(D->getAttrs());
5010 
5011         // FIXME: Ensure we don't get here for explicit instantiations.
5012         break;
5013       }
5014 
5015       case UPD_CXX_RESOLVED_DTOR_DELETE:
5016         Record.AddDeclRef(Update.getDecl());
5017         Record.AddStmt(cast<CXXDestructorDecl>(D)->getOperatorDeleteThisArg());
5018         break;
5019 
5020       case UPD_CXX_RESOLVED_EXCEPTION_SPEC: {
5021         auto prototype =
5022           cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>();
5023         Record.writeExceptionSpecInfo(prototype->getExceptionSpecInfo());
5024         break;
5025       }
5026 
5027       case UPD_CXX_DEDUCED_RETURN_TYPE:
5028         Record.push_back(GetOrCreateTypeID(Update.getType()));
5029         break;
5030 
5031       case UPD_DECL_MARKED_USED:
5032         break;
5033 
5034       case UPD_MANGLING_NUMBER:
5035       case UPD_STATIC_LOCAL_NUMBER:
5036         Record.push_back(Update.getNumber());
5037         break;
5038 
5039       case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
5040         Record.AddSourceRange(
5041             D->getAttr<OMPThreadPrivateDeclAttr>()->getRange());
5042         break;
5043 
5044       case UPD_DECL_MARKED_OPENMP_ALLOCATE: {
5045         auto *A = D->getAttr<OMPAllocateDeclAttr>();
5046         Record.push_back(A->getAllocatorType());
5047         Record.AddStmt(A->getAllocator());
5048         Record.AddSourceRange(A->getRange());
5049         break;
5050       }
5051 
5052       case UPD_DECL_MARKED_OPENMP_DECLARETARGET:
5053         Record.push_back(D->getAttr<OMPDeclareTargetDeclAttr>()->getMapType());
5054         Record.AddSourceRange(
5055             D->getAttr<OMPDeclareTargetDeclAttr>()->getRange());
5056         break;
5057 
5058       case UPD_DECL_EXPORTED:
5059         Record.push_back(getSubmoduleID(Update.getModule()));
5060         break;
5061 
5062       case UPD_ADDED_ATTR_TO_RECORD:
5063         Record.AddAttributes(llvm::makeArrayRef(Update.getAttr()));
5064         break;
5065       }
5066     }
5067 
5068     if (HasUpdatedBody) {
5069       const auto *Def = cast<FunctionDecl>(D);
5070       Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
5071       Record.push_back(Def->isInlined());
5072       Record.AddSourceLocation(Def->getInnerLocStart());
5073       Record.AddFunctionDefinition(Def);
5074     }
5075 
5076     OffsetsRecord.push_back(GetDeclRef(D));
5077     OffsetsRecord.push_back(Record.Emit(DECL_UPDATES));
5078   }
5079 }
5080 
5081 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
5082   uint32_t Raw = Loc.getRawEncoding();
5083   Record.push_back((Raw << 1) | (Raw >> 31));
5084 }
5085 
5086 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
5087   AddSourceLocation(Range.getBegin(), Record);
5088   AddSourceLocation(Range.getEnd(), Record);
5089 }
5090 
5091 void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) {
5092   AddAPInt(Value.bitcastToAPInt());
5093 }
5094 
5095 static void WriteFixedPointSemantics(ASTRecordWriter &Record,
5096                                      FixedPointSemantics FPSema) {
5097   Record.push_back(FPSema.getWidth());
5098   Record.push_back(FPSema.getScale());
5099   Record.push_back(FPSema.isSigned() | FPSema.isSaturated() << 1 |
5100                    FPSema.hasUnsignedPadding() << 2);
5101 }
5102 
5103 void ASTRecordWriter::AddAPValue(const APValue &Value) {
5104   APValue::ValueKind Kind = Value.getKind();
5105   push_back(static_cast<uint64_t>(Kind));
5106   switch (Kind) {
5107   case APValue::None:
5108   case APValue::Indeterminate:
5109     return;
5110   case APValue::Int:
5111     AddAPSInt(Value.getInt());
5112     return;
5113   case APValue::Float:
5114     push_back(static_cast<uint64_t>(
5115         llvm::APFloatBase::SemanticsToEnum(Value.getFloat().getSemantics())));
5116     AddAPFloat(Value.getFloat());
5117     return;
5118   case APValue::FixedPoint: {
5119     WriteFixedPointSemantics(*this, Value.getFixedPoint().getSemantics());
5120     AddAPSInt(Value.getFixedPoint().getValue());
5121     return;
5122   }
5123   case APValue::ComplexInt: {
5124     AddAPSInt(Value.getComplexIntReal());
5125     AddAPSInt(Value.getComplexIntImag());
5126     return;
5127   }
5128   case APValue::ComplexFloat: {
5129     push_back(static_cast<uint64_t>(llvm::APFloatBase::SemanticsToEnum(
5130         Value.getComplexFloatReal().getSemantics())));
5131     AddAPFloat(Value.getComplexFloatReal());
5132     push_back(static_cast<uint64_t>(llvm::APFloatBase::SemanticsToEnum(
5133         Value.getComplexFloatImag().getSemantics())));
5134     AddAPFloat(Value.getComplexFloatImag());
5135     return;
5136   }
5137   case APValue::LValue:
5138   case APValue::Vector:
5139   case APValue::Array:
5140   case APValue::Struct:
5141   case APValue::Union:
5142   case APValue::MemberPointer:
5143   case APValue::AddrLabelDiff:
5144     // TODO : Handle all these APValue::ValueKind.
5145     return;
5146   }
5147   llvm_unreachable("Invalid APValue::ValueKind");
5148 }
5149 
5150 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
5151   Record.push_back(getIdentifierRef(II));
5152 }
5153 
5154 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
5155   if (!II)
5156     return 0;
5157 
5158   IdentID &ID = IdentifierIDs[II];
5159   if (ID == 0)
5160     ID = NextIdentID++;
5161   return ID;
5162 }
5163 
5164 MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
5165   // Don't emit builtin macros like __LINE__ to the AST file unless they
5166   // have been redefined by the header (in which case they are not
5167   // isBuiltinMacro).
5168   if (!MI || MI->isBuiltinMacro())
5169     return 0;
5170 
5171   MacroID &ID = MacroIDs[MI];
5172   if (ID == 0) {
5173     ID = NextMacroID++;
5174     MacroInfoToEmitData Info = { Name, MI, ID };
5175     MacroInfosToEmit.push_back(Info);
5176   }
5177   return ID;
5178 }
5179 
5180 MacroID ASTWriter::getMacroID(MacroInfo *MI) {
5181   if (!MI || MI->isBuiltinMacro())
5182     return 0;
5183 
5184   assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
5185   return MacroIDs[MI];
5186 }
5187 
5188 uint32_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
5189   return IdentMacroDirectivesOffsetMap.lookup(Name);
5190 }
5191 
5192 void ASTRecordWriter::AddSelectorRef(const Selector SelRef) {
5193   Record->push_back(Writer->getSelectorRef(SelRef));
5194 }
5195 
5196 SelectorID ASTWriter::getSelectorRef(Selector Sel) {
5197   if (Sel.getAsOpaquePtr() == nullptr) {
5198     return 0;
5199   }
5200 
5201   SelectorID SID = SelectorIDs[Sel];
5202   if (SID == 0 && Chain) {
5203     // This might trigger a ReadSelector callback, which will set the ID for
5204     // this selector.
5205     Chain->LoadSelector(Sel);
5206     SID = SelectorIDs[Sel];
5207   }
5208   if (SID == 0) {
5209     SID = NextSelectorID++;
5210     SelectorIDs[Sel] = SID;
5211   }
5212   return SID;
5213 }
5214 
5215 void ASTRecordWriter::AddCXXTemporary(const CXXTemporary *Temp) {
5216   AddDeclRef(Temp->getDestructor());
5217 }
5218 
5219 void ASTRecordWriter::AddTemplateArgumentLocInfo(
5220     TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg) {
5221   switch (Kind) {
5222   case TemplateArgument::Expression:
5223     AddStmt(Arg.getAsExpr());
5224     break;
5225   case TemplateArgument::Type:
5226     AddTypeSourceInfo(Arg.getAsTypeSourceInfo());
5227     break;
5228   case TemplateArgument::Template:
5229     AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5230     AddSourceLocation(Arg.getTemplateNameLoc());
5231     break;
5232   case TemplateArgument::TemplateExpansion:
5233     AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5234     AddSourceLocation(Arg.getTemplateNameLoc());
5235     AddSourceLocation(Arg.getTemplateEllipsisLoc());
5236     break;
5237   case TemplateArgument::Null:
5238   case TemplateArgument::Integral:
5239   case TemplateArgument::Declaration:
5240   case TemplateArgument::NullPtr:
5241   case TemplateArgument::Pack:
5242     // FIXME: Is this right?
5243     break;
5244   }
5245 }
5246 
5247 void ASTRecordWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg) {
5248   AddTemplateArgument(Arg.getArgument());
5249 
5250   if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
5251     bool InfoHasSameExpr
5252       = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
5253     Record->push_back(InfoHasSameExpr);
5254     if (InfoHasSameExpr)
5255       return; // Avoid storing the same expr twice.
5256   }
5257   AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo());
5258 }
5259 
5260 void ASTRecordWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo) {
5261   if (!TInfo) {
5262     AddTypeRef(QualType());
5263     return;
5264   }
5265 
5266   AddTypeRef(TInfo->getType());
5267   AddTypeLoc(TInfo->getTypeLoc());
5268 }
5269 
5270 void ASTRecordWriter::AddTypeLoc(TypeLoc TL) {
5271   TypeLocWriter TLW(*this);
5272   for (; !TL.isNull(); TL = TL.getNextTypeLoc())
5273     TLW.Visit(TL);
5274 }
5275 
5276 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
5277   Record.push_back(GetOrCreateTypeID(T));
5278 }
5279 
5280 TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
5281   assert(Context);
5282   return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5283     if (T.isNull())
5284       return TypeIdx();
5285     assert(!T.getLocalFastQualifiers());
5286 
5287     TypeIdx &Idx = TypeIdxs[T];
5288     if (Idx.getIndex() == 0) {
5289       if (DoneWritingDeclsAndTypes) {
5290         assert(0 && "New type seen after serializing all the types to emit!");
5291         return TypeIdx();
5292       }
5293 
5294       // We haven't seen this type before. Assign it a new ID and put it
5295       // into the queue of types to emit.
5296       Idx = TypeIdx(NextTypeID++);
5297       DeclTypesToEmit.push(T);
5298     }
5299     return Idx;
5300   });
5301 }
5302 
5303 TypeID ASTWriter::getTypeID(QualType T) const {
5304   assert(Context);
5305   return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5306     if (T.isNull())
5307       return TypeIdx();
5308     assert(!T.getLocalFastQualifiers());
5309 
5310     TypeIdxMap::const_iterator I = TypeIdxs.find(T);
5311     assert(I != TypeIdxs.end() && "Type not emitted!");
5312     return I->second;
5313   });
5314 }
5315 
5316 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
5317   Record.push_back(GetDeclRef(D));
5318 }
5319 
5320 DeclID ASTWriter::GetDeclRef(const Decl *D) {
5321   assert(WritingAST && "Cannot request a declaration ID before AST writing");
5322 
5323   if (!D) {
5324     return 0;
5325   }
5326 
5327   // If D comes from an AST file, its declaration ID is already known and
5328   // fixed.
5329   if (D->isFromASTFile())
5330     return D->getGlobalID();
5331 
5332   assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
5333   DeclID &ID = DeclIDs[D];
5334   if (ID == 0) {
5335     if (DoneWritingDeclsAndTypes) {
5336       assert(0 && "New decl seen after serializing all the decls to emit!");
5337       return 0;
5338     }
5339 
5340     // We haven't seen this declaration before. Give it a new ID and
5341     // enqueue it in the list of declarations to emit.
5342     ID = NextDeclID++;
5343     DeclTypesToEmit.push(const_cast<Decl *>(D));
5344   }
5345 
5346   return ID;
5347 }
5348 
5349 DeclID ASTWriter::getDeclID(const Decl *D) {
5350   if (!D)
5351     return 0;
5352 
5353   // If D comes from an AST file, its declaration ID is already known and
5354   // fixed.
5355   if (D->isFromASTFile())
5356     return D->getGlobalID();
5357 
5358   assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
5359   return DeclIDs[D];
5360 }
5361 
5362 void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
5363   assert(ID);
5364   assert(D);
5365 
5366   SourceLocation Loc = D->getLocation();
5367   if (Loc.isInvalid())
5368     return;
5369 
5370   // We only keep track of the file-level declarations of each file.
5371   if (!D->getLexicalDeclContext()->isFileContext())
5372     return;
5373   // FIXME: ParmVarDecls that are part of a function type of a parameter of
5374   // a function/objc method, should not have TU as lexical context.
5375   // TemplateTemplateParmDecls that are part of an alias template, should not
5376   // have TU as lexical context.
5377   if (isa<ParmVarDecl>(D) || isa<TemplateTemplateParmDecl>(D))
5378     return;
5379 
5380   SourceManager &SM = Context->getSourceManager();
5381   SourceLocation FileLoc = SM.getFileLoc(Loc);
5382   assert(SM.isLocalSourceLocation(FileLoc));
5383   FileID FID;
5384   unsigned Offset;
5385   std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
5386   if (FID.isInvalid())
5387     return;
5388   assert(SM.getSLocEntry(FID).isFile());
5389 
5390   std::unique_ptr<DeclIDInFileInfo> &Info = FileDeclIDs[FID];
5391   if (!Info)
5392     Info = std::make_unique<DeclIDInFileInfo>();
5393 
5394   std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
5395   LocDeclIDsTy &Decls = Info->DeclIDs;
5396 
5397   if (Decls.empty() || Decls.back().first <= Offset) {
5398     Decls.push_back(LocDecl);
5399     return;
5400   }
5401 
5402   LocDeclIDsTy::iterator I =
5403       llvm::upper_bound(Decls, LocDecl, llvm::less_first());
5404 
5405   Decls.insert(I, LocDecl);
5406 }
5407 
5408 unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
5409   assert(needsAnonymousDeclarationNumber(D) &&
5410          "expected an anonymous declaration");
5411 
5412   // Number the anonymous declarations within this context, if we've not
5413   // already done so.
5414   auto It = AnonymousDeclarationNumbers.find(D);
5415   if (It == AnonymousDeclarationNumbers.end()) {
5416     auto *DC = D->getLexicalDeclContext();
5417     numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
5418       AnonymousDeclarationNumbers[ND] = Number;
5419     });
5420 
5421     It = AnonymousDeclarationNumbers.find(D);
5422     assert(It != AnonymousDeclarationNumbers.end() &&
5423            "declaration not found within its lexical context");
5424   }
5425 
5426   return It->second;
5427 }
5428 
5429 void ASTRecordWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
5430                                             DeclarationName Name) {
5431   switch (Name.getNameKind()) {
5432   case DeclarationName::CXXConstructorName:
5433   case DeclarationName::CXXDestructorName:
5434   case DeclarationName::CXXConversionFunctionName:
5435     AddTypeSourceInfo(DNLoc.NamedType.TInfo);
5436     break;
5437 
5438   case DeclarationName::CXXOperatorName:
5439     AddSourceLocation(SourceLocation::getFromRawEncoding(
5440         DNLoc.CXXOperatorName.BeginOpNameLoc));
5441     AddSourceLocation(
5442         SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc));
5443     break;
5444 
5445   case DeclarationName::CXXLiteralOperatorName:
5446     AddSourceLocation(SourceLocation::getFromRawEncoding(
5447         DNLoc.CXXLiteralOperatorName.OpNameLoc));
5448     break;
5449 
5450   case DeclarationName::Identifier:
5451   case DeclarationName::ObjCZeroArgSelector:
5452   case DeclarationName::ObjCOneArgSelector:
5453   case DeclarationName::ObjCMultiArgSelector:
5454   case DeclarationName::CXXUsingDirective:
5455   case DeclarationName::CXXDeductionGuideName:
5456     break;
5457   }
5458 }
5459 
5460 void ASTRecordWriter::AddDeclarationNameInfo(
5461     const DeclarationNameInfo &NameInfo) {
5462   AddDeclarationName(NameInfo.getName());
5463   AddSourceLocation(NameInfo.getLoc());
5464   AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName());
5465 }
5466 
5467 void ASTRecordWriter::AddQualifierInfo(const QualifierInfo &Info) {
5468   AddNestedNameSpecifierLoc(Info.QualifierLoc);
5469   Record->push_back(Info.NumTemplParamLists);
5470   for (unsigned i = 0, e = Info.NumTemplParamLists; i != e; ++i)
5471     AddTemplateParameterList(Info.TemplParamLists[i]);
5472 }
5473 
5474 void ASTRecordWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
5475   // Nested name specifiers usually aren't too long. I think that 8 would
5476   // typically accommodate the vast majority.
5477   SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
5478 
5479   // Push each of the nested-name-specifiers's onto a stack for
5480   // serialization in reverse order.
5481   while (NNS) {
5482     NestedNames.push_back(NNS);
5483     NNS = NNS.getPrefix();
5484   }
5485 
5486   Record->push_back(NestedNames.size());
5487   while(!NestedNames.empty()) {
5488     NNS = NestedNames.pop_back_val();
5489     NestedNameSpecifier::SpecifierKind Kind
5490       = NNS.getNestedNameSpecifier()->getKind();
5491     Record->push_back(Kind);
5492     switch (Kind) {
5493     case NestedNameSpecifier::Identifier:
5494       AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier());
5495       AddSourceRange(NNS.getLocalSourceRange());
5496       break;
5497 
5498     case NestedNameSpecifier::Namespace:
5499       AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace());
5500       AddSourceRange(NNS.getLocalSourceRange());
5501       break;
5502 
5503     case NestedNameSpecifier::NamespaceAlias:
5504       AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias());
5505       AddSourceRange(NNS.getLocalSourceRange());
5506       break;
5507 
5508     case NestedNameSpecifier::TypeSpec:
5509     case NestedNameSpecifier::TypeSpecWithTemplate:
5510       Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5511       AddTypeRef(NNS.getTypeLoc().getType());
5512       AddTypeLoc(NNS.getTypeLoc());
5513       AddSourceLocation(NNS.getLocalSourceRange().getEnd());
5514       break;
5515 
5516     case NestedNameSpecifier::Global:
5517       AddSourceLocation(NNS.getLocalSourceRange().getEnd());
5518       break;
5519 
5520     case NestedNameSpecifier::Super:
5521       AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl());
5522       AddSourceRange(NNS.getLocalSourceRange());
5523       break;
5524     }
5525   }
5526 }
5527 
5528 void ASTRecordWriter::AddTemplateParameterList(
5529     const TemplateParameterList *TemplateParams) {
5530   assert(TemplateParams && "No TemplateParams!");
5531   AddSourceLocation(TemplateParams->getTemplateLoc());
5532   AddSourceLocation(TemplateParams->getLAngleLoc());
5533   AddSourceLocation(TemplateParams->getRAngleLoc());
5534 
5535   Record->push_back(TemplateParams->size());
5536   for (const auto &P : *TemplateParams)
5537     AddDeclRef(P);
5538   if (const Expr *RequiresClause = TemplateParams->getRequiresClause()) {
5539     Record->push_back(true);
5540     AddStmt(const_cast<Expr*>(RequiresClause));
5541   } else {
5542     Record->push_back(false);
5543   }
5544 }
5545 
5546 /// Emit a template argument list.
5547 void ASTRecordWriter::AddTemplateArgumentList(
5548     const TemplateArgumentList *TemplateArgs) {
5549   assert(TemplateArgs && "No TemplateArgs!");
5550   Record->push_back(TemplateArgs->size());
5551   for (int i = 0, e = TemplateArgs->size(); i != e; ++i)
5552     AddTemplateArgument(TemplateArgs->get(i));
5553 }
5554 
5555 void ASTRecordWriter::AddASTTemplateArgumentListInfo(
5556     const ASTTemplateArgumentListInfo *ASTTemplArgList) {
5557   assert(ASTTemplArgList && "No ASTTemplArgList!");
5558   AddSourceLocation(ASTTemplArgList->LAngleLoc);
5559   AddSourceLocation(ASTTemplArgList->RAngleLoc);
5560   Record->push_back(ASTTemplArgList->NumTemplateArgs);
5561   const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
5562   for (int i = 0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
5563     AddTemplateArgumentLoc(TemplArgs[i]);
5564 }
5565 
5566 void ASTRecordWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set) {
5567   Record->push_back(Set.size());
5568   for (ASTUnresolvedSet::const_iterator
5569          I = Set.begin(), E = Set.end(); I != E; ++I) {
5570     AddDeclRef(I.getDecl());
5571     Record->push_back(I.getAccess());
5572   }
5573 }
5574 
5575 // FIXME: Move this out of the main ASTRecordWriter interface.
5576 void ASTRecordWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
5577   Record->push_back(Base.isVirtual());
5578   Record->push_back(Base.isBaseOfClass());
5579   Record->push_back(Base.getAccessSpecifierAsWritten());
5580   Record->push_back(Base.getInheritConstructors());
5581   AddTypeSourceInfo(Base.getTypeSourceInfo());
5582   AddSourceRange(Base.getSourceRange());
5583   AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
5584                                           : SourceLocation());
5585 }
5586 
5587 static uint64_t EmitCXXBaseSpecifiers(ASTWriter &W,
5588                                       ArrayRef<CXXBaseSpecifier> Bases) {
5589   ASTWriter::RecordData Record;
5590   ASTRecordWriter Writer(W, Record);
5591   Writer.push_back(Bases.size());
5592 
5593   for (auto &Base : Bases)
5594     Writer.AddCXXBaseSpecifier(Base);
5595 
5596   return Writer.Emit(serialization::DECL_CXX_BASE_SPECIFIERS);
5597 }
5598 
5599 // FIXME: Move this out of the main ASTRecordWriter interface.
5600 void ASTRecordWriter::AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases) {
5601   AddOffset(EmitCXXBaseSpecifiers(*Writer, Bases));
5602 }
5603 
5604 static uint64_t
5605 EmitCXXCtorInitializers(ASTWriter &W,
5606                         ArrayRef<CXXCtorInitializer *> CtorInits) {
5607   ASTWriter::RecordData Record;
5608   ASTRecordWriter Writer(W, Record);
5609   Writer.push_back(CtorInits.size());
5610 
5611   for (auto *Init : CtorInits) {
5612     if (Init->isBaseInitializer()) {
5613       Writer.push_back(CTOR_INITIALIZER_BASE);
5614       Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
5615       Writer.push_back(Init->isBaseVirtual());
5616     } else if (Init->isDelegatingInitializer()) {
5617       Writer.push_back(CTOR_INITIALIZER_DELEGATING);
5618       Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
5619     } else if (Init->isMemberInitializer()){
5620       Writer.push_back(CTOR_INITIALIZER_MEMBER);
5621       Writer.AddDeclRef(Init->getMember());
5622     } else {
5623       Writer.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
5624       Writer.AddDeclRef(Init->getIndirectMember());
5625     }
5626 
5627     Writer.AddSourceLocation(Init->getMemberLocation());
5628     Writer.AddStmt(Init->getInit());
5629     Writer.AddSourceLocation(Init->getLParenLoc());
5630     Writer.AddSourceLocation(Init->getRParenLoc());
5631     Writer.push_back(Init->isWritten());
5632     if (Init->isWritten())
5633       Writer.push_back(Init->getSourceOrder());
5634   }
5635 
5636   return Writer.Emit(serialization::DECL_CXX_CTOR_INITIALIZERS);
5637 }
5638 
5639 // FIXME: Move this out of the main ASTRecordWriter interface.
5640 void ASTRecordWriter::AddCXXCtorInitializers(
5641     ArrayRef<CXXCtorInitializer *> CtorInits) {
5642   AddOffset(EmitCXXCtorInitializers(*Writer, CtorInits));
5643 }
5644 
5645 void ASTRecordWriter::AddCXXDefinitionData(const CXXRecordDecl *D) {
5646   auto &Data = D->data();
5647   Record->push_back(Data.IsLambda);
5648 
5649   #define FIELD(Name, Width, Merge) \
5650   Record->push_back(Data.Name);
5651   #include "clang/AST/CXXRecordDeclDefinitionBits.def"
5652 
5653   // getODRHash will compute the ODRHash if it has not been previously computed.
5654   Record->push_back(D->getODRHash());
5655   bool ModulesDebugInfo = Writer->Context->getLangOpts().ModulesDebugInfo &&
5656                           Writer->WritingModule && !D->isDependentType();
5657   Record->push_back(ModulesDebugInfo);
5658   if (ModulesDebugInfo)
5659     Writer->ModularCodegenDecls.push_back(Writer->GetDeclRef(D));
5660 
5661   // IsLambda bit is already saved.
5662 
5663   Record->push_back(Data.NumBases);
5664   if (Data.NumBases > 0)
5665     AddCXXBaseSpecifiers(Data.bases());
5666 
5667   // FIXME: Make VBases lazily computed when needed to avoid storing them.
5668   Record->push_back(Data.NumVBases);
5669   if (Data.NumVBases > 0)
5670     AddCXXBaseSpecifiers(Data.vbases());
5671 
5672   AddUnresolvedSet(Data.Conversions.get(*Writer->Context));
5673   Record->push_back(Data.ComputedVisibleConversions);
5674   if (Data.ComputedVisibleConversions)
5675     AddUnresolvedSet(Data.VisibleConversions.get(*Writer->Context));
5676   // Data.Definition is the owning decl, no need to write it.
5677   AddDeclRef(D->getFirstFriend());
5678 
5679   // Add lambda-specific data.
5680   if (Data.IsLambda) {
5681     auto &Lambda = D->getLambdaData();
5682     Record->push_back(Lambda.Dependent);
5683     Record->push_back(Lambda.IsGenericLambda);
5684     Record->push_back(Lambda.CaptureDefault);
5685     Record->push_back(Lambda.NumCaptures);
5686     Record->push_back(Lambda.NumExplicitCaptures);
5687     Record->push_back(Lambda.HasKnownInternalLinkage);
5688     Record->push_back(Lambda.ManglingNumber);
5689     AddDeclRef(D->getLambdaContextDecl());
5690     AddTypeSourceInfo(Lambda.MethodTyInfo);
5691     for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
5692       const LambdaCapture &Capture = Lambda.Captures[I];
5693       AddSourceLocation(Capture.getLocation());
5694       Record->push_back(Capture.isImplicit());
5695       Record->push_back(Capture.getCaptureKind());
5696       switch (Capture.getCaptureKind()) {
5697       case LCK_StarThis:
5698       case LCK_This:
5699       case LCK_VLAType:
5700         break;
5701       case LCK_ByCopy:
5702       case LCK_ByRef:
5703         VarDecl *Var =
5704             Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
5705         AddDeclRef(Var);
5706         AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
5707                                                     : SourceLocation());
5708         break;
5709       }
5710     }
5711   }
5712 }
5713 
5714 void ASTWriter::ReaderInitialized(ASTReader *Reader) {
5715   assert(Reader && "Cannot remove chain");
5716   assert((!Chain || Chain == Reader) && "Cannot replace chain");
5717   assert(FirstDeclID == NextDeclID &&
5718          FirstTypeID == NextTypeID &&
5719          FirstIdentID == NextIdentID &&
5720          FirstMacroID == NextMacroID &&
5721          FirstSubmoduleID == NextSubmoduleID &&
5722          FirstSelectorID == NextSelectorID &&
5723          "Setting chain after writing has started.");
5724 
5725   Chain = Reader;
5726 
5727   // Note, this will get called multiple times, once one the reader starts up
5728   // and again each time it's done reading a PCH or module.
5729   FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
5730   FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
5731   FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
5732   FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
5733   FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
5734   FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
5735   NextDeclID = FirstDeclID;
5736   NextTypeID = FirstTypeID;
5737   NextIdentID = FirstIdentID;
5738   NextMacroID = FirstMacroID;
5739   NextSelectorID = FirstSelectorID;
5740   NextSubmoduleID = FirstSubmoduleID;
5741 }
5742 
5743 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
5744   // Always keep the highest ID. See \p TypeRead() for more information.
5745   IdentID &StoredID = IdentifierIDs[II];
5746   if (ID > StoredID)
5747     StoredID = ID;
5748 }
5749 
5750 void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
5751   // Always keep the highest ID. See \p TypeRead() for more information.
5752   MacroID &StoredID = MacroIDs[MI];
5753   if (ID > StoredID)
5754     StoredID = ID;
5755 }
5756 
5757 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
5758   // Always take the highest-numbered type index. This copes with an interesting
5759   // case for chained AST writing where we schedule writing the type and then,
5760   // later, deserialize the type from another AST. In this case, we want to
5761   // keep the higher-numbered entry so that we can properly write it out to
5762   // the AST file.
5763   TypeIdx &StoredIdx = TypeIdxs[T];
5764   if (Idx.getIndex() >= StoredIdx.getIndex())
5765     StoredIdx = Idx;
5766 }
5767 
5768 void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
5769   // Always keep the highest ID. See \p TypeRead() for more information.
5770   SelectorID &StoredID = SelectorIDs[S];
5771   if (ID > StoredID)
5772     StoredID = ID;
5773 }
5774 
5775 void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
5776                                     MacroDefinitionRecord *MD) {
5777   assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
5778   MacroDefinitions[MD] = ID;
5779 }
5780 
5781 void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
5782   assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
5783   SubmoduleIDs[Mod] = ID;
5784 }
5785 
5786 void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
5787   if (Chain && Chain->isProcessingUpdateRecords()) return;
5788   assert(D->isCompleteDefinition());
5789   assert(!WritingAST && "Already writing the AST!");
5790   if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
5791     // We are interested when a PCH decl is modified.
5792     if (RD->isFromASTFile()) {
5793       // A forward reference was mutated into a definition. Rewrite it.
5794       // FIXME: This happens during template instantiation, should we
5795       // have created a new definition decl instead ?
5796       assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
5797              "completed a tag from another module but not by instantiation?");
5798       DeclUpdates[RD].push_back(
5799           DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION));
5800     }
5801   }
5802 }
5803 
5804 static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) {
5805   if (D->isFromASTFile())
5806     return true;
5807 
5808   // The predefined __va_list_tag struct is imported if we imported any decls.
5809   // FIXME: This is a gross hack.
5810   return D == D->getASTContext().getVaListTagDecl();
5811 }
5812 
5813 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
5814   if (Chain && Chain->isProcessingUpdateRecords()) return;
5815   assert(DC->isLookupContext() &&
5816           "Should not add lookup results to non-lookup contexts!");
5817 
5818   // TU is handled elsewhere.
5819   if (isa<TranslationUnitDecl>(DC))
5820     return;
5821 
5822   // Namespaces are handled elsewhere, except for template instantiations of
5823   // FunctionTemplateDecls in namespaces. We are interested in cases where the
5824   // local instantiations are added to an imported context. Only happens when
5825   // adding ADL lookup candidates, for example templated friends.
5826   if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None &&
5827       !isa<FunctionTemplateDecl>(D))
5828     return;
5829 
5830   // We're only interested in cases where a local declaration is added to an
5831   // imported context.
5832   if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC)))
5833     return;
5834 
5835   assert(DC == DC->getPrimaryContext() && "added to non-primary context");
5836   assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
5837   assert(!WritingAST && "Already writing the AST!");
5838   if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) {
5839     // We're adding a visible declaration to a predefined decl context. Ensure
5840     // that we write out all of its lookup results so we don't get a nasty
5841     // surprise when we try to emit its lookup table.
5842     for (auto *Child : DC->decls())
5843       DeclsToEmitEvenIfUnreferenced.push_back(Child);
5844   }
5845   DeclsToEmitEvenIfUnreferenced.push_back(D);
5846 }
5847 
5848 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
5849   if (Chain && Chain->isProcessingUpdateRecords()) return;
5850   assert(D->isImplicit());
5851 
5852   // We're only interested in cases where a local declaration is added to an
5853   // imported context.
5854   if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD))
5855     return;
5856 
5857   if (!isa<CXXMethodDecl>(D))
5858     return;
5859 
5860   // A decl coming from PCH was modified.
5861   assert(RD->isCompleteDefinition());
5862   assert(!WritingAST && "Already writing the AST!");
5863   DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
5864 }
5865 
5866 void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
5867   if (Chain && Chain->isProcessingUpdateRecords()) return;
5868   assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
5869   if (!Chain) return;
5870   Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
5871     // If we don't already know the exception specification for this redecl
5872     // chain, add an update record for it.
5873     if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
5874                                       ->getType()
5875                                       ->castAs<FunctionProtoType>()
5876                                       ->getExceptionSpecType()))
5877       DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
5878   });
5879 }
5880 
5881 void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
5882   if (Chain && Chain->isProcessingUpdateRecords()) return;
5883   assert(!WritingAST && "Already writing the AST!");
5884   if (!Chain) return;
5885   Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
5886     DeclUpdates[D].push_back(
5887         DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
5888   });
5889 }
5890 
5891 void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
5892                                        const FunctionDecl *Delete,
5893                                        Expr *ThisArg) {
5894   if (Chain && Chain->isProcessingUpdateRecords()) return;
5895   assert(!WritingAST && "Already writing the AST!");
5896   assert(Delete && "Not given an operator delete");
5897   if (!Chain) return;
5898   Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
5899     DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete));
5900   });
5901 }
5902 
5903 void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
5904   if (Chain && Chain->isProcessingUpdateRecords()) return;
5905   assert(!WritingAST && "Already writing the AST!");
5906   if (!D->isFromASTFile())
5907     return; // Declaration not imported from PCH.
5908 
5909   // Implicit function decl from a PCH was defined.
5910   DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
5911 }
5912 
5913 void ASTWriter::VariableDefinitionInstantiated(const VarDecl *D) {
5914   if (Chain && Chain->isProcessingUpdateRecords()) return;
5915   assert(!WritingAST && "Already writing the AST!");
5916   if (!D->isFromASTFile())
5917     return;
5918 
5919   DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_VAR_DEFINITION));
5920 }
5921 
5922 void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
5923   if (Chain && Chain->isProcessingUpdateRecords()) return;
5924   assert(!WritingAST && "Already writing the AST!");
5925   if (!D->isFromASTFile())
5926     return;
5927 
5928   DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
5929 }
5930 
5931 void ASTWriter::InstantiationRequested(const ValueDecl *D) {
5932   if (Chain && Chain->isProcessingUpdateRecords()) return;
5933   assert(!WritingAST && "Already writing the AST!");
5934   if (!D->isFromASTFile())
5935     return;
5936 
5937   // Since the actual instantiation is delayed, this really means that we need
5938   // to update the instantiation location.
5939   SourceLocation POI;
5940   if (auto *VD = dyn_cast<VarDecl>(D))
5941     POI = VD->getPointOfInstantiation();
5942   else
5943     POI = cast<FunctionDecl>(D)->getPointOfInstantiation();
5944   DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_POINT_OF_INSTANTIATION, POI));
5945 }
5946 
5947 void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) {
5948   if (Chain && Chain->isProcessingUpdateRecords()) return;
5949   assert(!WritingAST && "Already writing the AST!");
5950   if (!D->isFromASTFile())
5951     return;
5952 
5953   DeclUpdates[D].push_back(
5954       DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D));
5955 }
5956 
5957 void ASTWriter::DefaultMemberInitializerInstantiated(const FieldDecl *D) {
5958   assert(!WritingAST && "Already writing the AST!");
5959   if (!D->isFromASTFile())
5960     return;
5961 
5962   DeclUpdates[D].push_back(
5963       DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER, D));
5964 }
5965 
5966 void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
5967                                              const ObjCInterfaceDecl *IFD) {
5968   if (Chain && Chain->isProcessingUpdateRecords()) return;
5969   assert(!WritingAST && "Already writing the AST!");
5970   if (!IFD->isFromASTFile())
5971     return; // Declaration not imported from PCH.
5972 
5973   assert(IFD->getDefinition() && "Category on a class without a definition?");
5974   ObjCClassesWithCategories.insert(
5975     const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
5976 }
5977 
5978 void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
5979   if (Chain && Chain->isProcessingUpdateRecords()) return;
5980   assert(!WritingAST && "Already writing the AST!");
5981 
5982   // If there is *any* declaration of the entity that's not from an AST file,
5983   // we can skip writing the update record. We make sure that isUsed() triggers
5984   // completion of the redeclaration chain of the entity.
5985   for (auto Prev = D->getMostRecentDecl(); Prev; Prev = Prev->getPreviousDecl())
5986     if (IsLocalDecl(Prev))
5987       return;
5988 
5989   DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
5990 }
5991 
5992 void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
5993   if (Chain && Chain->isProcessingUpdateRecords()) return;
5994   assert(!WritingAST && "Already writing the AST!");
5995   if (!D->isFromASTFile())
5996     return;
5997 
5998   DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE));
5999 }
6000 
6001 void ASTWriter::DeclarationMarkedOpenMPAllocate(const Decl *D, const Attr *A) {
6002   if (Chain && Chain->isProcessingUpdateRecords()) return;
6003   assert(!WritingAST && "Already writing the AST!");
6004   if (!D->isFromASTFile())
6005     return;
6006 
6007   DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_ALLOCATE, A));
6008 }
6009 
6010 void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
6011                                                      const Attr *Attr) {
6012   if (Chain && Chain->isProcessingUpdateRecords()) return;
6013   assert(!WritingAST && "Already writing the AST!");
6014   if (!D->isFromASTFile())
6015     return;
6016 
6017   DeclUpdates[D].push_back(
6018       DeclUpdate(UPD_DECL_MARKED_OPENMP_DECLARETARGET, Attr));
6019 }
6020 
6021 void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
6022   if (Chain && Chain->isProcessingUpdateRecords()) return;
6023   assert(!WritingAST && "Already writing the AST!");
6024   assert(D->isHidden() && "expected a hidden declaration");
6025   DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M));
6026 }
6027 
6028 void ASTWriter::AddedAttributeToRecord(const Attr *Attr,
6029                                        const RecordDecl *Record) {
6030   if (Chain && Chain->isProcessingUpdateRecords()) return;
6031   assert(!WritingAST && "Already writing the AST!");
6032   if (!Record->isFromASTFile())
6033     return;
6034   DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr));
6035 }
6036 
6037 void ASTWriter::AddedCXXTemplateSpecialization(
6038     const ClassTemplateDecl *TD, const ClassTemplateSpecializationDecl *D) {
6039   assert(!WritingAST && "Already writing the AST!");
6040 
6041   if (!TD->getFirstDecl()->isFromASTFile())
6042     return;
6043   if (Chain && Chain->isProcessingUpdateRecords())
6044     return;
6045 
6046   DeclsToEmitEvenIfUnreferenced.push_back(D);
6047 }
6048 
6049 void ASTWriter::AddedCXXTemplateSpecialization(
6050     const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) {
6051   assert(!WritingAST && "Already writing the AST!");
6052 
6053   if (!TD->getFirstDecl()->isFromASTFile())
6054     return;
6055   if (Chain && Chain->isProcessingUpdateRecords())
6056     return;
6057 
6058   DeclsToEmitEvenIfUnreferenced.push_back(D);
6059 }
6060 
6061 void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
6062                                                const FunctionDecl *D) {
6063   assert(!WritingAST && "Already writing the AST!");
6064 
6065   if (!TD->getFirstDecl()->isFromASTFile())
6066     return;
6067   if (Chain && Chain->isProcessingUpdateRecords())
6068     return;
6069 
6070   DeclsToEmitEvenIfUnreferenced.push_back(D);
6071 }
6072 
6073 //===----------------------------------------------------------------------===//
6074 //// OMPClause Serialization
6075 ////===----------------------------------------------------------------------===//
6076 
6077 namespace {
6078 
6079 class OMPClauseWriter : public OMPClauseVisitor<OMPClauseWriter> {
6080   ASTRecordWriter &Record;
6081 
6082 public:
6083   OMPClauseWriter(ASTRecordWriter &Record) : Record(Record) {}
6084 #define OMP_CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *S);
6085 #include "llvm/Frontend/OpenMP/OMPKinds.def"
6086   void writeClause(OMPClause *C);
6087   void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C);
6088   void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C);
6089 };
6090 
6091 }
6092 
6093 void ASTRecordWriter::writeOMPClause(OMPClause *C) {
6094   OMPClauseWriter(*this).writeClause(C);
6095 }
6096 
6097 void OMPClauseWriter::writeClause(OMPClause *C) {
6098   Record.push_back(unsigned(C->getClauseKind()));
6099   Visit(C);
6100   Record.AddSourceLocation(C->getBeginLoc());
6101   Record.AddSourceLocation(C->getEndLoc());
6102 }
6103 
6104 void OMPClauseWriter::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
6105   Record.push_back(uint64_t(C->getCaptureRegion()));
6106   Record.AddStmt(C->getPreInitStmt());
6107 }
6108 
6109 void OMPClauseWriter::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
6110   VisitOMPClauseWithPreInit(C);
6111   Record.AddStmt(C->getPostUpdateExpr());
6112 }
6113 
6114 void OMPClauseWriter::VisitOMPIfClause(OMPIfClause *C) {
6115   VisitOMPClauseWithPreInit(C);
6116   Record.push_back(uint64_t(C->getNameModifier()));
6117   Record.AddSourceLocation(C->getNameModifierLoc());
6118   Record.AddSourceLocation(C->getColonLoc());
6119   Record.AddStmt(C->getCondition());
6120   Record.AddSourceLocation(C->getLParenLoc());
6121 }
6122 
6123 void OMPClauseWriter::VisitOMPFinalClause(OMPFinalClause *C) {
6124   VisitOMPClauseWithPreInit(C);
6125   Record.AddStmt(C->getCondition());
6126   Record.AddSourceLocation(C->getLParenLoc());
6127 }
6128 
6129 void OMPClauseWriter::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
6130   VisitOMPClauseWithPreInit(C);
6131   Record.AddStmt(C->getNumThreads());
6132   Record.AddSourceLocation(C->getLParenLoc());
6133 }
6134 
6135 void OMPClauseWriter::VisitOMPSafelenClause(OMPSafelenClause *C) {
6136   Record.AddStmt(C->getSafelen());
6137   Record.AddSourceLocation(C->getLParenLoc());
6138 }
6139 
6140 void OMPClauseWriter::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
6141   Record.AddStmt(C->getSimdlen());
6142   Record.AddSourceLocation(C->getLParenLoc());
6143 }
6144 
6145 void OMPClauseWriter::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
6146   Record.AddStmt(C->getAllocator());
6147   Record.AddSourceLocation(C->getLParenLoc());
6148 }
6149 
6150 void OMPClauseWriter::VisitOMPCollapseClause(OMPCollapseClause *C) {
6151   Record.AddStmt(C->getNumForLoops());
6152   Record.AddSourceLocation(C->getLParenLoc());
6153 }
6154 
6155 void OMPClauseWriter::VisitOMPDetachClause(OMPDetachClause *C) {
6156   Record.AddStmt(C->getEventHandler());
6157   Record.AddSourceLocation(C->getLParenLoc());
6158 }
6159 
6160 void OMPClauseWriter::VisitOMPDefaultClause(OMPDefaultClause *C) {
6161   Record.push_back(unsigned(C->getDefaultKind()));
6162   Record.AddSourceLocation(C->getLParenLoc());
6163   Record.AddSourceLocation(C->getDefaultKindKwLoc());
6164 }
6165 
6166 void OMPClauseWriter::VisitOMPProcBindClause(OMPProcBindClause *C) {
6167   Record.push_back(unsigned(C->getProcBindKind()));
6168   Record.AddSourceLocation(C->getLParenLoc());
6169   Record.AddSourceLocation(C->getProcBindKindKwLoc());
6170 }
6171 
6172 void OMPClauseWriter::VisitOMPScheduleClause(OMPScheduleClause *C) {
6173   VisitOMPClauseWithPreInit(C);
6174   Record.push_back(C->getScheduleKind());
6175   Record.push_back(C->getFirstScheduleModifier());
6176   Record.push_back(C->getSecondScheduleModifier());
6177   Record.AddStmt(C->getChunkSize());
6178   Record.AddSourceLocation(C->getLParenLoc());
6179   Record.AddSourceLocation(C->getFirstScheduleModifierLoc());
6180   Record.AddSourceLocation(C->getSecondScheduleModifierLoc());
6181   Record.AddSourceLocation(C->getScheduleKindLoc());
6182   Record.AddSourceLocation(C->getCommaLoc());
6183 }
6184 
6185 void OMPClauseWriter::VisitOMPOrderedClause(OMPOrderedClause *C) {
6186   Record.push_back(C->getLoopNumIterations().size());
6187   Record.AddStmt(C->getNumForLoops());
6188   for (Expr *NumIter : C->getLoopNumIterations())
6189     Record.AddStmt(NumIter);
6190   for (unsigned I = 0, E = C->getLoopNumIterations().size(); I <E; ++I)
6191     Record.AddStmt(C->getLoopCounter(I));
6192   Record.AddSourceLocation(C->getLParenLoc());
6193 }
6194 
6195 void OMPClauseWriter::VisitOMPNowaitClause(OMPNowaitClause *) {}
6196 
6197 void OMPClauseWriter::VisitOMPUntiedClause(OMPUntiedClause *) {}
6198 
6199 void OMPClauseWriter::VisitOMPMergeableClause(OMPMergeableClause *) {}
6200 
6201 void OMPClauseWriter::VisitOMPReadClause(OMPReadClause *) {}
6202 
6203 void OMPClauseWriter::VisitOMPWriteClause(OMPWriteClause *) {}
6204 
6205 void OMPClauseWriter::VisitOMPUpdateClause(OMPUpdateClause *C) {
6206   Record.push_back(C->isExtended() ? 1 : 0);
6207   if (C->isExtended()) {
6208     Record.AddSourceLocation(C->getLParenLoc());
6209     Record.AddSourceLocation(C->getArgumentLoc());
6210     Record.writeEnum(C->getDependencyKind());
6211   }
6212 }
6213 
6214 void OMPClauseWriter::VisitOMPCaptureClause(OMPCaptureClause *) {}
6215 
6216 void OMPClauseWriter::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
6217 
6218 void OMPClauseWriter::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
6219 
6220 void OMPClauseWriter::VisitOMPAcquireClause(OMPAcquireClause *) {}
6221 
6222 void OMPClauseWriter::VisitOMPReleaseClause(OMPReleaseClause *) {}
6223 
6224 void OMPClauseWriter::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
6225 
6226 void OMPClauseWriter::VisitOMPThreadsClause(OMPThreadsClause *) {}
6227 
6228 void OMPClauseWriter::VisitOMPSIMDClause(OMPSIMDClause *) {}
6229 
6230 void OMPClauseWriter::VisitOMPNogroupClause(OMPNogroupClause *) {}
6231 
6232 void OMPClauseWriter::VisitOMPDestroyClause(OMPDestroyClause *) {}
6233 
6234 void OMPClauseWriter::VisitOMPPrivateClause(OMPPrivateClause *C) {
6235   Record.push_back(C->varlist_size());
6236   Record.AddSourceLocation(C->getLParenLoc());
6237   for (auto *VE : C->varlists()) {
6238     Record.AddStmt(VE);
6239   }
6240   for (auto *VE : C->private_copies()) {
6241     Record.AddStmt(VE);
6242   }
6243 }
6244 
6245 void OMPClauseWriter::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
6246   Record.push_back(C->varlist_size());
6247   VisitOMPClauseWithPreInit(C);
6248   Record.AddSourceLocation(C->getLParenLoc());
6249   for (auto *VE : C->varlists()) {
6250     Record.AddStmt(VE);
6251   }
6252   for (auto *VE : C->private_copies()) {
6253     Record.AddStmt(VE);
6254   }
6255   for (auto *VE : C->inits()) {
6256     Record.AddStmt(VE);
6257   }
6258 }
6259 
6260 void OMPClauseWriter::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
6261   Record.push_back(C->varlist_size());
6262   VisitOMPClauseWithPostUpdate(C);
6263   Record.AddSourceLocation(C->getLParenLoc());
6264   Record.writeEnum(C->getKind());
6265   Record.AddSourceLocation(C->getKindLoc());
6266   Record.AddSourceLocation(C->getColonLoc());
6267   for (auto *VE : C->varlists())
6268     Record.AddStmt(VE);
6269   for (auto *E : C->private_copies())
6270     Record.AddStmt(E);
6271   for (auto *E : C->source_exprs())
6272     Record.AddStmt(E);
6273   for (auto *E : C->destination_exprs())
6274     Record.AddStmt(E);
6275   for (auto *E : C->assignment_ops())
6276     Record.AddStmt(E);
6277 }
6278 
6279 void OMPClauseWriter::VisitOMPSharedClause(OMPSharedClause *C) {
6280   Record.push_back(C->varlist_size());
6281   Record.AddSourceLocation(C->getLParenLoc());
6282   for (auto *VE : C->varlists())
6283     Record.AddStmt(VE);
6284 }
6285 
6286 void OMPClauseWriter::VisitOMPReductionClause(OMPReductionClause *C) {
6287   Record.push_back(C->varlist_size());
6288   VisitOMPClauseWithPostUpdate(C);
6289   Record.AddSourceLocation(C->getLParenLoc());
6290   Record.AddSourceLocation(C->getModifierLoc());
6291   Record.AddSourceLocation(C->getColonLoc());
6292   Record.writeEnum(C->getModifier());
6293   Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
6294   Record.AddDeclarationNameInfo(C->getNameInfo());
6295   for (auto *VE : C->varlists())
6296     Record.AddStmt(VE);
6297   for (auto *VE : C->privates())
6298     Record.AddStmt(VE);
6299   for (auto *E : C->lhs_exprs())
6300     Record.AddStmt(E);
6301   for (auto *E : C->rhs_exprs())
6302     Record.AddStmt(E);
6303   for (auto *E : C->reduction_ops())
6304     Record.AddStmt(E);
6305 }
6306 
6307 void OMPClauseWriter::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
6308   Record.push_back(C->varlist_size());
6309   VisitOMPClauseWithPostUpdate(C);
6310   Record.AddSourceLocation(C->getLParenLoc());
6311   Record.AddSourceLocation(C->getColonLoc());
6312   Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
6313   Record.AddDeclarationNameInfo(C->getNameInfo());
6314   for (auto *VE : C->varlists())
6315     Record.AddStmt(VE);
6316   for (auto *VE : C->privates())
6317     Record.AddStmt(VE);
6318   for (auto *E : C->lhs_exprs())
6319     Record.AddStmt(E);
6320   for (auto *E : C->rhs_exprs())
6321     Record.AddStmt(E);
6322   for (auto *E : C->reduction_ops())
6323     Record.AddStmt(E);
6324 }
6325 
6326 void OMPClauseWriter::VisitOMPInReductionClause(OMPInReductionClause *C) {
6327   Record.push_back(C->varlist_size());
6328   VisitOMPClauseWithPostUpdate(C);
6329   Record.AddSourceLocation(C->getLParenLoc());
6330   Record.AddSourceLocation(C->getColonLoc());
6331   Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
6332   Record.AddDeclarationNameInfo(C->getNameInfo());
6333   for (auto *VE : C->varlists())
6334     Record.AddStmt(VE);
6335   for (auto *VE : C->privates())
6336     Record.AddStmt(VE);
6337   for (auto *E : C->lhs_exprs())
6338     Record.AddStmt(E);
6339   for (auto *E : C->rhs_exprs())
6340     Record.AddStmt(E);
6341   for (auto *E : C->reduction_ops())
6342     Record.AddStmt(E);
6343   for (auto *E : C->taskgroup_descriptors())
6344     Record.AddStmt(E);
6345 }
6346 
6347 void OMPClauseWriter::VisitOMPLinearClause(OMPLinearClause *C) {
6348   Record.push_back(C->varlist_size());
6349   VisitOMPClauseWithPostUpdate(C);
6350   Record.AddSourceLocation(C->getLParenLoc());
6351   Record.AddSourceLocation(C->getColonLoc());
6352   Record.push_back(C->getModifier());
6353   Record.AddSourceLocation(C->getModifierLoc());
6354   for (auto *VE : C->varlists()) {
6355     Record.AddStmt(VE);
6356   }
6357   for (auto *VE : C->privates()) {
6358     Record.AddStmt(VE);
6359   }
6360   for (auto *VE : C->inits()) {
6361     Record.AddStmt(VE);
6362   }
6363   for (auto *VE : C->updates()) {
6364     Record.AddStmt(VE);
6365   }
6366   for (auto *VE : C->finals()) {
6367     Record.AddStmt(VE);
6368   }
6369   Record.AddStmt(C->getStep());
6370   Record.AddStmt(C->getCalcStep());
6371   for (auto *VE : C->used_expressions())
6372     Record.AddStmt(VE);
6373 }
6374 
6375 void OMPClauseWriter::VisitOMPAlignedClause(OMPAlignedClause *C) {
6376   Record.push_back(C->varlist_size());
6377   Record.AddSourceLocation(C->getLParenLoc());
6378   Record.AddSourceLocation(C->getColonLoc());
6379   for (auto *VE : C->varlists())
6380     Record.AddStmt(VE);
6381   Record.AddStmt(C->getAlignment());
6382 }
6383 
6384 void OMPClauseWriter::VisitOMPCopyinClause(OMPCopyinClause *C) {
6385   Record.push_back(C->varlist_size());
6386   Record.AddSourceLocation(C->getLParenLoc());
6387   for (auto *VE : C->varlists())
6388     Record.AddStmt(VE);
6389   for (auto *E : C->source_exprs())
6390     Record.AddStmt(E);
6391   for (auto *E : C->destination_exprs())
6392     Record.AddStmt(E);
6393   for (auto *E : C->assignment_ops())
6394     Record.AddStmt(E);
6395 }
6396 
6397 void OMPClauseWriter::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
6398   Record.push_back(C->varlist_size());
6399   Record.AddSourceLocation(C->getLParenLoc());
6400   for (auto *VE : C->varlists())
6401     Record.AddStmt(VE);
6402   for (auto *E : C->source_exprs())
6403     Record.AddStmt(E);
6404   for (auto *E : C->destination_exprs())
6405     Record.AddStmt(E);
6406   for (auto *E : C->assignment_ops())
6407     Record.AddStmt(E);
6408 }
6409 
6410 void OMPClauseWriter::VisitOMPFlushClause(OMPFlushClause *C) {
6411   Record.push_back(C->varlist_size());
6412   Record.AddSourceLocation(C->getLParenLoc());
6413   for (auto *VE : C->varlists())
6414     Record.AddStmt(VE);
6415 }
6416 
6417 void OMPClauseWriter::VisitOMPDepobjClause(OMPDepobjClause *C) {
6418   Record.AddStmt(C->getDepobj());
6419   Record.AddSourceLocation(C->getLParenLoc());
6420 }
6421 
6422 void OMPClauseWriter::VisitOMPDependClause(OMPDependClause *C) {
6423   Record.push_back(C->varlist_size());
6424   Record.push_back(C->getNumLoops());
6425   Record.AddSourceLocation(C->getLParenLoc());
6426   Record.AddStmt(C->getModifier());
6427   Record.push_back(C->getDependencyKind());
6428   Record.AddSourceLocation(C->getDependencyLoc());
6429   Record.AddSourceLocation(C->getColonLoc());
6430   for (auto *VE : C->varlists())
6431     Record.AddStmt(VE);
6432   for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
6433     Record.AddStmt(C->getLoopData(I));
6434 }
6435 
6436 void OMPClauseWriter::VisitOMPDeviceClause(OMPDeviceClause *C) {
6437   VisitOMPClauseWithPreInit(C);
6438   Record.writeEnum(C->getModifier());
6439   Record.AddStmt(C->getDevice());
6440   Record.AddSourceLocation(C->getModifierLoc());
6441   Record.AddSourceLocation(C->getLParenLoc());
6442 }
6443 
6444 void OMPClauseWriter::VisitOMPMapClause(OMPMapClause *C) {
6445   Record.push_back(C->varlist_size());
6446   Record.push_back(C->getUniqueDeclarationsNum());
6447   Record.push_back(C->getTotalComponentListNum());
6448   Record.push_back(C->getTotalComponentsNum());
6449   Record.AddSourceLocation(C->getLParenLoc());
6450   for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
6451     Record.push_back(C->getMapTypeModifier(I));
6452     Record.AddSourceLocation(C->getMapTypeModifierLoc(I));
6453   }
6454   Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
6455   Record.AddDeclarationNameInfo(C->getMapperIdInfo());
6456   Record.push_back(C->getMapType());
6457   Record.AddSourceLocation(C->getMapLoc());
6458   Record.AddSourceLocation(C->getColonLoc());
6459   for (auto *E : C->varlists())
6460     Record.AddStmt(E);
6461   for (auto *E : C->mapperlists())
6462     Record.AddStmt(E);
6463   for (auto *D : C->all_decls())
6464     Record.AddDeclRef(D);
6465   for (auto N : C->all_num_lists())
6466     Record.push_back(N);
6467   for (auto N : C->all_lists_sizes())
6468     Record.push_back(N);
6469   for (auto &M : C->all_components()) {
6470     Record.AddStmt(M.getAssociatedExpression());
6471     Record.AddDeclRef(M.getAssociatedDeclaration());
6472   }
6473 }
6474 
6475 void OMPClauseWriter::VisitOMPAllocateClause(OMPAllocateClause *C) {
6476   Record.push_back(C->varlist_size());
6477   Record.AddSourceLocation(C->getLParenLoc());
6478   Record.AddSourceLocation(C->getColonLoc());
6479   Record.AddStmt(C->getAllocator());
6480   for (auto *VE : C->varlists())
6481     Record.AddStmt(VE);
6482 }
6483 
6484 void OMPClauseWriter::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
6485   VisitOMPClauseWithPreInit(C);
6486   Record.AddStmt(C->getNumTeams());
6487   Record.AddSourceLocation(C->getLParenLoc());
6488 }
6489 
6490 void OMPClauseWriter::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
6491   VisitOMPClauseWithPreInit(C);
6492   Record.AddStmt(C->getThreadLimit());
6493   Record.AddSourceLocation(C->getLParenLoc());
6494 }
6495 
6496 void OMPClauseWriter::VisitOMPPriorityClause(OMPPriorityClause *C) {
6497   VisitOMPClauseWithPreInit(C);
6498   Record.AddStmt(C->getPriority());
6499   Record.AddSourceLocation(C->getLParenLoc());
6500 }
6501 
6502 void OMPClauseWriter::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
6503   VisitOMPClauseWithPreInit(C);
6504   Record.AddStmt(C->getGrainsize());
6505   Record.AddSourceLocation(C->getLParenLoc());
6506 }
6507 
6508 void OMPClauseWriter::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
6509   VisitOMPClauseWithPreInit(C);
6510   Record.AddStmt(C->getNumTasks());
6511   Record.AddSourceLocation(C->getLParenLoc());
6512 }
6513 
6514 void OMPClauseWriter::VisitOMPHintClause(OMPHintClause *C) {
6515   Record.AddStmt(C->getHint());
6516   Record.AddSourceLocation(C->getLParenLoc());
6517 }
6518 
6519 void OMPClauseWriter::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
6520   VisitOMPClauseWithPreInit(C);
6521   Record.push_back(C->getDistScheduleKind());
6522   Record.AddStmt(C->getChunkSize());
6523   Record.AddSourceLocation(C->getLParenLoc());
6524   Record.AddSourceLocation(C->getDistScheduleKindLoc());
6525   Record.AddSourceLocation(C->getCommaLoc());
6526 }
6527 
6528 void OMPClauseWriter::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
6529   Record.push_back(C->getDefaultmapKind());
6530   Record.push_back(C->getDefaultmapModifier());
6531   Record.AddSourceLocation(C->getLParenLoc());
6532   Record.AddSourceLocation(C->getDefaultmapModifierLoc());
6533   Record.AddSourceLocation(C->getDefaultmapKindLoc());
6534 }
6535 
6536 void OMPClauseWriter::VisitOMPToClause(OMPToClause *C) {
6537   Record.push_back(C->varlist_size());
6538   Record.push_back(C->getUniqueDeclarationsNum());
6539   Record.push_back(C->getTotalComponentListNum());
6540   Record.push_back(C->getTotalComponentsNum());
6541   Record.AddSourceLocation(C->getLParenLoc());
6542   Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
6543   Record.AddDeclarationNameInfo(C->getMapperIdInfo());
6544   for (auto *E : C->varlists())
6545     Record.AddStmt(E);
6546   for (auto *E : C->mapperlists())
6547     Record.AddStmt(E);
6548   for (auto *D : C->all_decls())
6549     Record.AddDeclRef(D);
6550   for (auto N : C->all_num_lists())
6551     Record.push_back(N);
6552   for (auto N : C->all_lists_sizes())
6553     Record.push_back(N);
6554   for (auto &M : C->all_components()) {
6555     Record.AddStmt(M.getAssociatedExpression());
6556     Record.AddDeclRef(M.getAssociatedDeclaration());
6557   }
6558 }
6559 
6560 void OMPClauseWriter::VisitOMPFromClause(OMPFromClause *C) {
6561   Record.push_back(C->varlist_size());
6562   Record.push_back(C->getUniqueDeclarationsNum());
6563   Record.push_back(C->getTotalComponentListNum());
6564   Record.push_back(C->getTotalComponentsNum());
6565   Record.AddSourceLocation(C->getLParenLoc());
6566   Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
6567   Record.AddDeclarationNameInfo(C->getMapperIdInfo());
6568   for (auto *E : C->varlists())
6569     Record.AddStmt(E);
6570   for (auto *E : C->mapperlists())
6571     Record.AddStmt(E);
6572   for (auto *D : C->all_decls())
6573     Record.AddDeclRef(D);
6574   for (auto N : C->all_num_lists())
6575     Record.push_back(N);
6576   for (auto N : C->all_lists_sizes())
6577     Record.push_back(N);
6578   for (auto &M : C->all_components()) {
6579     Record.AddStmt(M.getAssociatedExpression());
6580     Record.AddDeclRef(M.getAssociatedDeclaration());
6581   }
6582 }
6583 
6584 void OMPClauseWriter::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
6585   Record.push_back(C->varlist_size());
6586   Record.push_back(C->getUniqueDeclarationsNum());
6587   Record.push_back(C->getTotalComponentListNum());
6588   Record.push_back(C->getTotalComponentsNum());
6589   Record.AddSourceLocation(C->getLParenLoc());
6590   for (auto *E : C->varlists())
6591     Record.AddStmt(E);
6592   for (auto *VE : C->private_copies())
6593     Record.AddStmt(VE);
6594   for (auto *VE : C->inits())
6595     Record.AddStmt(VE);
6596   for (auto *D : C->all_decls())
6597     Record.AddDeclRef(D);
6598   for (auto N : C->all_num_lists())
6599     Record.push_back(N);
6600   for (auto N : C->all_lists_sizes())
6601     Record.push_back(N);
6602   for (auto &M : C->all_components()) {
6603     Record.AddStmt(M.getAssociatedExpression());
6604     Record.AddDeclRef(M.getAssociatedDeclaration());
6605   }
6606 }
6607 
6608 void OMPClauseWriter::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
6609   Record.push_back(C->varlist_size());
6610   Record.push_back(C->getUniqueDeclarationsNum());
6611   Record.push_back(C->getTotalComponentListNum());
6612   Record.push_back(C->getTotalComponentsNum());
6613   Record.AddSourceLocation(C->getLParenLoc());
6614   for (auto *E : C->varlists())
6615     Record.AddStmt(E);
6616   for (auto *D : C->all_decls())
6617     Record.AddDeclRef(D);
6618   for (auto N : C->all_num_lists())
6619     Record.push_back(N);
6620   for (auto N : C->all_lists_sizes())
6621     Record.push_back(N);
6622   for (auto &M : C->all_components()) {
6623     Record.AddStmt(M.getAssociatedExpression());
6624     Record.AddDeclRef(M.getAssociatedDeclaration());
6625   }
6626 }
6627 
6628 void OMPClauseWriter::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
6629 
6630 void OMPClauseWriter::VisitOMPUnifiedSharedMemoryClause(
6631     OMPUnifiedSharedMemoryClause *) {}
6632 
6633 void OMPClauseWriter::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
6634 
6635 void
6636 OMPClauseWriter::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
6637 }
6638 
6639 void OMPClauseWriter::VisitOMPAtomicDefaultMemOrderClause(
6640     OMPAtomicDefaultMemOrderClause *C) {
6641   Record.push_back(C->getAtomicDefaultMemOrderKind());
6642   Record.AddSourceLocation(C->getLParenLoc());
6643   Record.AddSourceLocation(C->getAtomicDefaultMemOrderKindKwLoc());
6644 }
6645 
6646 void OMPClauseWriter::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
6647   Record.push_back(C->varlist_size());
6648   Record.AddSourceLocation(C->getLParenLoc());
6649   for (auto *VE : C->varlists())
6650     Record.AddStmt(VE);
6651   for (auto *E : C->private_refs())
6652     Record.AddStmt(E);
6653 }
6654 
6655 void OMPClauseWriter::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
6656   Record.push_back(C->varlist_size());
6657   Record.AddSourceLocation(C->getLParenLoc());
6658   for (auto *VE : C->varlists())
6659     Record.AddStmt(VE);
6660 }
6661 
6662 void OMPClauseWriter::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
6663   Record.push_back(C->varlist_size());
6664   Record.AddSourceLocation(C->getLParenLoc());
6665   for (auto *VE : C->varlists())
6666     Record.AddStmt(VE);
6667 }
6668 
6669 void OMPClauseWriter::VisitOMPOrderClause(OMPOrderClause *C) {
6670   Record.writeEnum(C->getKind());
6671   Record.AddSourceLocation(C->getLParenLoc());
6672   Record.AddSourceLocation(C->getKindKwLoc());
6673 }
6674 
6675 void OMPClauseWriter::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
6676   Record.push_back(C->getNumberOfAllocators());
6677   Record.AddSourceLocation(C->getLParenLoc());
6678   for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) {
6679     OMPUsesAllocatorsClause::Data Data = C->getAllocatorData(I);
6680     Record.AddStmt(Data.Allocator);
6681     Record.AddStmt(Data.AllocatorTraits);
6682     Record.AddSourceLocation(Data.LParenLoc);
6683     Record.AddSourceLocation(Data.RParenLoc);
6684   }
6685 }
6686 
6687 void ASTRecordWriter::writeOMPTraitInfo(const OMPTraitInfo *TI) {
6688   writeUInt32(TI->Sets.size());
6689   for (const auto &Set : TI->Sets) {
6690     writeEnum(Set.Kind);
6691     writeUInt32(Set.Selectors.size());
6692     for (const auto &Selector : Set.Selectors) {
6693       writeEnum(Selector.Kind);
6694       writeBool(Selector.ScoreOrCondition);
6695       if (Selector.ScoreOrCondition)
6696         writeExprRef(Selector.ScoreOrCondition);
6697       writeUInt32(Selector.Properties.size());
6698       for (const auto &Property : Selector.Properties)
6699         writeEnum(Property.Kind);
6700     }
6701   }
6702 }
6703