Clang Project

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