clang  3.8.0
ASTWriter.cpp
Go to the documentation of this file.
1 //===--- ASTWriter.cpp - AST File Writer ------------------------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the ASTWriter class, which writes AST files.
11 //
12 //===----------------------------------------------------------------------===//
13 
16 #include "ASTCommon.h"
17 #include "ASTReaderInternals.h"
18 #include "MultiOnDiskHashTable.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/Decl.h"
22 #include "clang/AST/DeclFriend.h"
23 #include "clang/AST/DeclLookups.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/Type.h"
34 #include "clang/Basic/TargetInfo.h"
36 #include "clang/Basic/Version.h"
38 #include "clang/Lex/HeaderSearch.h"
40 #include "clang/Lex/MacroInfo.h"
42 #include "clang/Lex/Preprocessor.h"
45 #include "clang/Sema/Sema.h"
48 #include "llvm/ADT/APFloat.h"
49 #include "llvm/ADT/APInt.h"
50 #include "llvm/ADT/Hashing.h"
51 #include "llvm/ADT/StringExtras.h"
52 #include "llvm/Bitcode/BitstreamWriter.h"
53 #include "llvm/Support/EndianStream.h"
54 #include "llvm/Support/FileSystem.h"
55 #include "llvm/Support/MemoryBuffer.h"
56 #include "llvm/Support/OnDiskHashTable.h"
57 #include "llvm/Support/Path.h"
58 #include "llvm/Support/Process.h"
59 #include <algorithm>
60 #include <cstdio>
61 #include <string.h>
62 #include <utility>
63 
64 using namespace clang;
65 using namespace clang::serialization;
66 
67 template <typename T, typename Allocator>
68 static StringRef bytes(const std::vector<T, Allocator> &v) {
69  if (v.empty()) return StringRef();
70  return StringRef(reinterpret_cast<const char*>(&v[0]),
71  sizeof(T) * v.size());
72 }
73 
74 template <typename T>
75 static StringRef bytes(const SmallVectorImpl<T> &v) {
76  return StringRef(reinterpret_cast<const char*>(v.data()),
77  sizeof(T) * v.size());
78 }
79 
80 //===----------------------------------------------------------------------===//
81 // Type serialization
82 //===----------------------------------------------------------------------===//
83 
84 namespace {
85  class ASTTypeWriter {
86  ASTWriter &Writer;
88 
89  public:
90  /// \brief Type code that corresponds to the record generated.
91  TypeCode Code;
92  /// \brief Abbreviation to use for the record, if any.
93  unsigned AbbrevToUse;
94 
95  ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
96  : Writer(Writer), Record(Record), Code(TYPE_EXT_QUAL) { }
97 
98  void VisitArrayType(const ArrayType *T);
99  void VisitFunctionType(const FunctionType *T);
100  void VisitTagType(const TagType *T);
101 
102 #define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
103 #define ABSTRACT_TYPE(Class, Base)
104 #include "clang/AST/TypeNodes.def"
105  };
106 } // end anonymous namespace
107 
108 void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
109  llvm_unreachable("Built-in types are never serialized");
110 }
111 
112 void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
113  Writer.AddTypeRef(T->getElementType(), Record);
114  Code = TYPE_COMPLEX;
115 }
116 
117 void ASTTypeWriter::VisitPointerType(const PointerType *T) {
118  Writer.AddTypeRef(T->getPointeeType(), Record);
119  Code = TYPE_POINTER;
120 }
121 
122 void ASTTypeWriter::VisitDecayedType(const DecayedType *T) {
123  Writer.AddTypeRef(T->getOriginalType(), Record);
124  Code = TYPE_DECAYED;
125 }
126 
127 void ASTTypeWriter::VisitAdjustedType(const AdjustedType *T) {
128  Writer.AddTypeRef(T->getOriginalType(), Record);
129  Writer.AddTypeRef(T->getAdjustedType(), Record);
130  Code = TYPE_ADJUSTED;
131 }
132 
133 void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
134  Writer.AddTypeRef(T->getPointeeType(), Record);
135  Code = TYPE_BLOCK_POINTER;
136 }
137 
138 void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
139  Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
140  Record.push_back(T->isSpelledAsLValue());
141  Code = TYPE_LVALUE_REFERENCE;
142 }
143 
144 void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
145  Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
146  Code = TYPE_RVALUE_REFERENCE;
147 }
148 
149 void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
150  Writer.AddTypeRef(T->getPointeeType(), Record);
151  Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
152  Code = TYPE_MEMBER_POINTER;
153 }
154 
155 void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
156  Writer.AddTypeRef(T->getElementType(), Record);
157  Record.push_back(T->getSizeModifier()); // FIXME: stable values
158  Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
159 }
160 
161 void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
162  VisitArrayType(T);
163  Writer.AddAPInt(T->getSize(), Record);
164  Code = TYPE_CONSTANT_ARRAY;
165 }
166 
167 void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
168  VisitArrayType(T);
169  Code = TYPE_INCOMPLETE_ARRAY;
170 }
171 
172 void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
173  VisitArrayType(T);
174  Writer.AddSourceLocation(T->getLBracketLoc(), Record);
175  Writer.AddSourceLocation(T->getRBracketLoc(), Record);
176  Writer.AddStmt(T->getSizeExpr());
177  Code = TYPE_VARIABLE_ARRAY;
178 }
179 
180 void ASTTypeWriter::VisitVectorType(const VectorType *T) {
181  Writer.AddTypeRef(T->getElementType(), Record);
182  Record.push_back(T->getNumElements());
183  Record.push_back(T->getVectorKind());
184  Code = TYPE_VECTOR;
185 }
186 
187 void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
188  VisitVectorType(T);
189  Code = TYPE_EXT_VECTOR;
190 }
191 
192 void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
193  Writer.AddTypeRef(T->getReturnType(), Record);
195  Record.push_back(C.getNoReturn());
196  Record.push_back(C.getHasRegParm());
197  Record.push_back(C.getRegParm());
198  // FIXME: need to stabilize encoding of calling convention...
199  Record.push_back(C.getCC());
200  Record.push_back(C.getProducesResult());
201 
202  if (C.getHasRegParm() || C.getRegParm() || C.getProducesResult())
203  AbbrevToUse = 0;
204 }
205 
206 void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
207  VisitFunctionType(T);
208  Code = TYPE_FUNCTION_NO_PROTO;
209 }
210 
211 static void addExceptionSpec(ASTWriter &Writer, const FunctionProtoType *T,
212  ASTWriter::RecordDataImpl &Record) {
213  Record.push_back(T->getExceptionSpecType());
214  if (T->getExceptionSpecType() == EST_Dynamic) {
215  Record.push_back(T->getNumExceptions());
216  for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
217  Writer.AddTypeRef(T->getExceptionType(I), Record);
218  } else if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
219  Writer.AddStmt(T->getNoexceptExpr());
220  } else if (T->getExceptionSpecType() == EST_Uninstantiated) {
221  Writer.AddDeclRef(T->getExceptionSpecDecl(), Record);
222  Writer.AddDeclRef(T->getExceptionSpecTemplate(), Record);
223  } else if (T->getExceptionSpecType() == EST_Unevaluated) {
224  Writer.AddDeclRef(T->getExceptionSpecDecl(), Record);
225  }
226 }
227 
228 void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
229  VisitFunctionType(T);
230 
231  Record.push_back(T->isVariadic());
232  Record.push_back(T->hasTrailingReturn());
233  Record.push_back(T->getTypeQuals());
234  Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
235  addExceptionSpec(Writer, T, Record);
236 
237  Record.push_back(T->getNumParams());
238  for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
239  Writer.AddTypeRef(T->getParamType(I), Record);
240 
241  if (T->isVariadic() || T->hasTrailingReturn() || T->getTypeQuals() ||
243  AbbrevToUse = 0;
244 
245  Code = TYPE_FUNCTION_PROTO;
246 }
247 
248 void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
249  Writer.AddDeclRef(T->getDecl(), Record);
250  Code = TYPE_UNRESOLVED_USING;
251 }
252 
253 void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
254  Writer.AddDeclRef(T->getDecl(), Record);
255  assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
256  Writer.AddTypeRef(T->getCanonicalTypeInternal(), Record);
257  Code = TYPE_TYPEDEF;
258 }
259 
260 void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
261  Writer.AddStmt(T->getUnderlyingExpr());
262  Code = TYPE_TYPEOF_EXPR;
263 }
264 
265 void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
266  Writer.AddTypeRef(T->getUnderlyingType(), Record);
267  Code = TYPE_TYPEOF;
268 }
269 
270 void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
271  Writer.AddTypeRef(T->getUnderlyingType(), Record);
272  Writer.AddStmt(T->getUnderlyingExpr());
273  Code = TYPE_DECLTYPE;
274 }
275 
276 void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
277  Writer.AddTypeRef(T->getBaseType(), Record);
278  Writer.AddTypeRef(T->getUnderlyingType(), Record);
279  Record.push_back(T->getUTTKind());
280  Code = TYPE_UNARY_TRANSFORM;
281 }
282 
283 void ASTTypeWriter::VisitAutoType(const AutoType *T) {
284  Writer.AddTypeRef(T->getDeducedType(), Record);
285  Record.push_back((unsigned)T->getKeyword());
286  if (T->getDeducedType().isNull())
287  Record.push_back(T->isDependentType());
288  Code = TYPE_AUTO;
289 }
290 
291 void ASTTypeWriter::VisitTagType(const TagType *T) {
292  Record.push_back(T->isDependentType());
293  Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
294  assert(!T->isBeingDefined() &&
295  "Cannot serialize in the middle of a type definition");
296 }
297 
298 void ASTTypeWriter::VisitRecordType(const RecordType *T) {
299  VisitTagType(T);
300  Code = TYPE_RECORD;
301 }
302 
303 void ASTTypeWriter::VisitEnumType(const EnumType *T) {
304  VisitTagType(T);
305  Code = TYPE_ENUM;
306 }
307 
308 void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
309  Writer.AddTypeRef(T->getModifiedType(), Record);
310  Writer.AddTypeRef(T->getEquivalentType(), Record);
311  Record.push_back(T->getAttrKind());
312  Code = TYPE_ATTRIBUTED;
313 }
314 
315 void
316 ASTTypeWriter::VisitSubstTemplateTypeParmType(
317  const SubstTemplateTypeParmType *T) {
318  Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
319  Writer.AddTypeRef(T->getReplacementType(), Record);
321 }
322 
323 void
324 ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
326  Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
327  Writer.AddTemplateArgument(T->getArgumentPack(), Record);
329 }
330 
331 void
332 ASTTypeWriter::VisitTemplateSpecializationType(
333  const TemplateSpecializationType *T) {
334  Record.push_back(T->isDependentType());
335  Writer.AddTemplateName(T->getTemplateName(), Record);
336  Record.push_back(T->getNumArgs());
337  for (const auto &ArgI : *T)
338  Writer.AddTemplateArgument(ArgI, Record);
339  Writer.AddTypeRef(T->isTypeAlias() ? T->getAliasedType() :
340  T->isCanonicalUnqualified() ? QualType()
341  : T->getCanonicalTypeInternal(),
342  Record);
344 }
345 
346 void
347 ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
348  VisitArrayType(T);
349  Writer.AddStmt(T->getSizeExpr());
350  Writer.AddSourceRange(T->getBracketsRange(), Record);
352 }
353 
354 void
355 ASTTypeWriter::VisitDependentSizedExtVectorType(
356  const DependentSizedExtVectorType *T) {
357  // FIXME: Serialize this type (C++ only)
358  llvm_unreachable("Cannot serialize dependent sized extended vector types");
359 }
360 
361 void
362 ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
363  Record.push_back(T->getDepth());
364  Record.push_back(T->getIndex());
365  Record.push_back(T->isParameterPack());
366  Writer.AddDeclRef(T->getDecl(), Record);
368 }
369 
370 void
371 ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
372  Record.push_back(T->getKeyword());
373  Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
374  Writer.AddIdentifierRef(T->getIdentifier(), Record);
375  Writer.AddTypeRef(T->isCanonicalUnqualified() ? QualType()
376  : T->getCanonicalTypeInternal(),
377  Record);
378  Code = TYPE_DEPENDENT_NAME;
379 }
380 
381 void
382 ASTTypeWriter::VisitDependentTemplateSpecializationType(
384  Record.push_back(T->getKeyword());
385  Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
386  Writer.AddIdentifierRef(T->getIdentifier(), Record);
387  Record.push_back(T->getNumArgs());
388  for (const auto &I : *T)
389  Writer.AddTemplateArgument(I, Record);
391 }
392 
393 void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
394  Writer.AddTypeRef(T->getPattern(), Record);
395  if (Optional<unsigned> NumExpansions = T->getNumExpansions())
396  Record.push_back(*NumExpansions + 1);
397  else
398  Record.push_back(0);
399  Code = TYPE_PACK_EXPANSION;
400 }
401 
402 void ASTTypeWriter::VisitParenType(const ParenType *T) {
403  Writer.AddTypeRef(T->getInnerType(), Record);
404  Code = TYPE_PAREN;
405 }
406 
407 void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
408  Record.push_back(T->getKeyword());
409  Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
410  Writer.AddTypeRef(T->getNamedType(), Record);
411  Code = TYPE_ELABORATED;
412 }
413 
414 void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
415  Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
416  Writer.AddTypeRef(T->getInjectedSpecializationType(), Record);
418 }
419 
420 void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
421  Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
422  Code = TYPE_OBJC_INTERFACE;
423 }
424 
425 void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
426  Writer.AddTypeRef(T->getBaseType(), Record);
427  Record.push_back(T->getTypeArgsAsWritten().size());
428  for (auto TypeArg : T->getTypeArgsAsWritten())
429  Writer.AddTypeRef(TypeArg, Record);
430  Record.push_back(T->getNumProtocols());
431  for (const auto *I : T->quals())
432  Writer.AddDeclRef(I, Record);
433  Record.push_back(T->isKindOfTypeAsWritten());
434  Code = TYPE_OBJC_OBJECT;
435 }
436 
437 void
438 ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
439  Writer.AddTypeRef(T->getPointeeType(), Record);
441 }
442 
443 void
444 ASTTypeWriter::VisitAtomicType(const AtomicType *T) {
445  Writer.AddTypeRef(T->getValueType(), Record);
446  Code = TYPE_ATOMIC;
447 }
448 
449 void
450 ASTTypeWriter::VisitPipeType(const PipeType *T) {
451  Writer.AddTypeRef(T->getElementType(), Record);
452  Code = TYPE_PIPE;
453 }
454 
455 namespace {
456 
457 class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
458  ASTWriter &Writer;
460 
461 public:
462  TypeLocWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
463  : Writer(Writer), Record(Record) { }
464 
465 #define ABSTRACT_TYPELOC(CLASS, PARENT)
466 #define TYPELOC(CLASS, PARENT) \
467  void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
468 #include "clang/AST/TypeLocNodes.def"
469 
470  void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
471  void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
472 };
473 
474 } // end anonymous namespace
475 
476 void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
477  // nothing to do
478 }
479 void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
480  Writer.AddSourceLocation(TL.getBuiltinLoc(), Record);
481  if (TL.needsExtraLocalData()) {
482  Record.push_back(TL.getWrittenTypeSpec());
483  Record.push_back(TL.getWrittenSignSpec());
484  Record.push_back(TL.getWrittenWidthSpec());
485  Record.push_back(TL.hasModeAttr());
486  }
487 }
488 void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
489  Writer.AddSourceLocation(TL.getNameLoc(), Record);
490 }
491 void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
492  Writer.AddSourceLocation(TL.getStarLoc(), Record);
493 }
494 void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
495  // nothing to do
496 }
497 void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
498  // nothing to do
499 }
500 void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
501  Writer.AddSourceLocation(TL.getCaretLoc(), Record);
502 }
503 void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
504  Writer.AddSourceLocation(TL.getAmpLoc(), Record);
505 }
506 void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
507  Writer.AddSourceLocation(TL.getAmpAmpLoc(), Record);
508 }
509 void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
510  Writer.AddSourceLocation(TL.getStarLoc(), Record);
511  Writer.AddTypeSourceInfo(TL.getClassTInfo(), Record);
512 }
513 void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
514  Writer.AddSourceLocation(TL.getLBracketLoc(), Record);
515  Writer.AddSourceLocation(TL.getRBracketLoc(), Record);
516  Record.push_back(TL.getSizeExpr() ? 1 : 0);
517  if (TL.getSizeExpr())
518  Writer.AddStmt(TL.getSizeExpr());
519 }
520 void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
521  VisitArrayTypeLoc(TL);
522 }
523 void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
524  VisitArrayTypeLoc(TL);
525 }
526 void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
527  VisitArrayTypeLoc(TL);
528 }
529 void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
531  VisitArrayTypeLoc(TL);
532 }
533 void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
535  Writer.AddSourceLocation(TL.getNameLoc(), Record);
536 }
537 void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
538  Writer.AddSourceLocation(TL.getNameLoc(), Record);
539 }
540 void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
541  Writer.AddSourceLocation(TL.getNameLoc(), Record);
542 }
543 void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
544  Writer.AddSourceLocation(TL.getLocalRangeBegin(), Record);
545  Writer.AddSourceLocation(TL.getLParenLoc(), Record);
546  Writer.AddSourceLocation(TL.getRParenLoc(), Record);
547  Writer.AddSourceLocation(TL.getLocalRangeEnd(), Record);
548  for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
549  Writer.AddDeclRef(TL.getParam(i), Record);
550 }
551 void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
552  VisitFunctionTypeLoc(TL);
553 }
554 void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
555  VisitFunctionTypeLoc(TL);
556 }
557 void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
558  Writer.AddSourceLocation(TL.getNameLoc(), Record);
559 }
560 void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
561  Writer.AddSourceLocation(TL.getNameLoc(), Record);
562 }
563 void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
564  Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
565  Writer.AddSourceLocation(TL.getLParenLoc(), Record);
566  Writer.AddSourceLocation(TL.getRParenLoc(), Record);
567 }
568 void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
569  Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
570  Writer.AddSourceLocation(TL.getLParenLoc(), Record);
571  Writer.AddSourceLocation(TL.getRParenLoc(), Record);
572  Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
573 }
574 void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
575  Writer.AddSourceLocation(TL.getNameLoc(), Record);
576 }
577 void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
578  Writer.AddSourceLocation(TL.getKWLoc(), Record);
579  Writer.AddSourceLocation(TL.getLParenLoc(), Record);
580  Writer.AddSourceLocation(TL.getRParenLoc(), Record);
581  Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
582 }
583 void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
584  Writer.AddSourceLocation(TL.getNameLoc(), Record);
585 }
586 void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
587  Writer.AddSourceLocation(TL.getNameLoc(), Record);
588 }
589 void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
590  Writer.AddSourceLocation(TL.getNameLoc(), Record);
591 }
592 void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
593  Writer.AddSourceLocation(TL.getAttrNameLoc(), Record);
594  if (TL.hasAttrOperand()) {
596  Writer.AddSourceLocation(range.getBegin(), Record);
597  Writer.AddSourceLocation(range.getEnd(), Record);
598  }
599  if (TL.hasAttrExprOperand()) {
600  Expr *operand = TL.getAttrExprOperand();
601  Record.push_back(operand ? 1 : 0);
602  if (operand) Writer.AddStmt(operand);
603  } else if (TL.hasAttrEnumOperand()) {
604  Writer.AddSourceLocation(TL.getAttrEnumOperandLoc(), Record);
605  }
606 }
607 void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
608  Writer.AddSourceLocation(TL.getNameLoc(), Record);
609 }
610 void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
612  Writer.AddSourceLocation(TL.getNameLoc(), Record);
613 }
614 void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
616  Writer.AddSourceLocation(TL.getNameLoc(), Record);
617 }
618 void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
620  Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record);
621  Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
622  Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
623  Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
624  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
625  Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
626  TL.getArgLoc(i).getLocInfo(), Record);
627 }
628 void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
629  Writer.AddSourceLocation(TL.getLParenLoc(), Record);
630  Writer.AddSourceLocation(TL.getRParenLoc(), Record);
631 }
632 void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
633  Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
634  Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
635 }
636 void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
637  Writer.AddSourceLocation(TL.getNameLoc(), Record);
638 }
639 void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
640  Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
641  Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
642  Writer.AddSourceLocation(TL.getNameLoc(), Record);
643 }
644 void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
646  Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
647  Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
648  Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record);
649  Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
650  Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
651  Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
652  for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
653  Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
654  TL.getArgLoc(I).getLocInfo(), Record);
655 }
656 void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
657  Writer.AddSourceLocation(TL.getEllipsisLoc(), Record);
658 }
659 void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
660  Writer.AddSourceLocation(TL.getNameLoc(), Record);
661 }
662 void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
663  Record.push_back(TL.hasBaseTypeAsWritten());
664  Writer.AddSourceLocation(TL.getTypeArgsLAngleLoc(), Record);
665  Writer.AddSourceLocation(TL.getTypeArgsRAngleLoc(), Record);
666  for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
667  Writer.AddTypeSourceInfo(TL.getTypeArgTInfo(i), Record);
668  Writer.AddSourceLocation(TL.getProtocolLAngleLoc(), Record);
669  Writer.AddSourceLocation(TL.getProtocolRAngleLoc(), Record);
670  for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
671  Writer.AddSourceLocation(TL.getProtocolLoc(i), Record);
672 }
673 void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
674  Writer.AddSourceLocation(TL.getStarLoc(), Record);
675 }
676 void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
677  Writer.AddSourceLocation(TL.getKWLoc(), Record);
678  Writer.AddSourceLocation(TL.getLParenLoc(), Record);
679  Writer.AddSourceLocation(TL.getRParenLoc(), Record);
680 }
681 void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
682  Writer.AddSourceLocation(TL.getKWLoc(), Record);
683 }
684 
685 void ASTWriter::WriteTypeAbbrevs() {
686  using namespace llvm;
687 
688  BitCodeAbbrev *Abv;
689 
690  // Abbreviation for TYPE_EXT_QUAL
691  Abv = new BitCodeAbbrev();
692  Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
693  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
694  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals
695  TypeExtQualAbbrev = Stream.EmitAbbrev(Abv);
696 
697  // Abbreviation for TYPE_FUNCTION_PROTO
698  Abv = new BitCodeAbbrev();
699  Abv->Add(BitCodeAbbrevOp(serialization::TYPE_FUNCTION_PROTO));
700  // FunctionType
701  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ReturnType
702  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NoReturn
703  Abv->Add(BitCodeAbbrevOp(0)); // HasRegParm
704  Abv->Add(BitCodeAbbrevOp(0)); // RegParm
705  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // CC
706  Abv->Add(BitCodeAbbrevOp(0)); // ProducesResult
707  // FunctionProtoType
708  Abv->Add(BitCodeAbbrevOp(0)); // IsVariadic
709  Abv->Add(BitCodeAbbrevOp(0)); // HasTrailingReturn
710  Abv->Add(BitCodeAbbrevOp(0)); // TypeQuals
711  Abv->Add(BitCodeAbbrevOp(0)); // RefQualifier
712  Abv->Add(BitCodeAbbrevOp(EST_None)); // ExceptionSpec
713  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // NumParams
714  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
715  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Params
716  TypeFunctionProtoAbbrev = Stream.EmitAbbrev(Abv);
717 }
718 
719 //===----------------------------------------------------------------------===//
720 // ASTWriter Implementation
721 //===----------------------------------------------------------------------===//
722 
723 static void EmitBlockID(unsigned ID, const char *Name,
724  llvm::BitstreamWriter &Stream,
725  ASTWriter::RecordDataImpl &Record) {
726  Record.clear();
727  Record.push_back(ID);
728  Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
729 
730  // Emit the block name if present.
731  if (!Name || Name[0] == 0)
732  return;
733  Record.clear();
734  while (*Name)
735  Record.push_back(*Name++);
736  Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
737 }
738 
739 static void EmitRecordID(unsigned ID, const char *Name,
740  llvm::BitstreamWriter &Stream,
741  ASTWriter::RecordDataImpl &Record) {
742  Record.clear();
743  Record.push_back(ID);
744  while (*Name)
745  Record.push_back(*Name++);
746  Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
747 }
748 
749 static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
750  ASTWriter::RecordDataImpl &Record) {
751 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
752  RECORD(STMT_STOP);
755  RECORD(STMT_NULL);
757  RECORD(STMT_CASE);
761  RECORD(STMT_IF);
764  RECORD(STMT_DO);
765  RECORD(STMT_FOR);
766  RECORD(STMT_GOTO);
771  RECORD(STMT_DECL);
786  RECORD(EXPR_CALL);
802  RECORD(EXPR_STMT);
875 #undef RECORD
876 }
877 
878 void ASTWriter::WriteBlockInfoBlock() {
879  RecordData Record;
880  Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
881 
882 #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
883 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
884 
885  // Control Block.
886  BLOCK(CONTROL_BLOCK);
887  RECORD(METADATA);
888  RECORD(SIGNATURE);
892  RECORD(IMPORTS);
897 
898  BLOCK(OPTIONS_BLOCK);
905 
906  BLOCK(INPUT_FILES_BLOCK);
908 
909  // AST Top-Level Block.
910  BLOCK(AST_BLOCK);
959 
960  // SourceManager Block.
961  BLOCK(SOURCE_MANAGER_BLOCK);
966 
967  // Preprocessor Block.
968  BLOCK(PREPROCESSOR_BLOCK);
973  RECORD(PP_TOKEN);
974 
975  // Submodule Block.
976  BLOCK(SUBMODULE_BLOCK);
993 
994  // Comments Block.
995  BLOCK(COMMENTS_BLOCK);
997 
998  // Decls and Types block.
999  BLOCK(DECLTYPES_BLOCK);
1018  RECORD(TYPE_ENUM);
1032  RECORD(TYPE_PAREN);
1036  RECORD(TYPE_AUTO);
1044  RECORD(DECL_ENUM);
1059  RECORD(DECL_FIELD);
1061  RECORD(DECL_VAR);
1065  RECORD(DECL_BLOCK);
1070  RECORD(DECL_USING);
1098 
1099  // Statements and Exprs can occur in the Decls and Types block.
1100  AddStmtsExprs(Stream, Record);
1101 
1102  BLOCK(PREPROCESSOR_DETAIL_BLOCK);
1106 
1107  // Decls and Types block.
1108  BLOCK(EXTENSION_BLOCK);
1110 
1111 #undef RECORD
1112 #undef BLOCK
1113  Stream.ExitBlock();
1114 }
1115 
1116 /// \brief Prepares a path for being written to an AST file by converting it
1117 /// to an absolute path and removing nested './'s.
1118 ///
1119 /// \return \c true if the path was changed.
1120 static bool cleanPathForOutput(FileManager &FileMgr,
1121  SmallVectorImpl<char> &Path) {
1122  bool Changed = FileMgr.makeAbsolutePath(Path);
1123  return Changed | llvm::sys::path::remove_dots(Path);
1124 }
1125 
1126 /// \brief Adjusts the given filename to only write out the portion of the
1127 /// filename that is not part of the system root directory.
1128 ///
1129 /// \param Filename the file name to adjust.
1130 ///
1131 /// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
1132 /// the returned filename will be adjusted by this root directory.
1133 ///
1134 /// \returns either the original filename (if it needs no adjustment) or the
1135 /// adjusted filename (which points into the @p Filename parameter).
1136 static const char *
1137 adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
1138  assert(Filename && "No file name to adjust?");
1139 
1140  if (BaseDir.empty())
1141  return Filename;
1142 
1143  // Verify that the filename and the system root have the same prefix.
1144  unsigned Pos = 0;
1145  for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
1146  if (Filename[Pos] != BaseDir[Pos])
1147  return Filename; // Prefixes don't match.
1148 
1149  // We hit the end of the filename before we hit the end of the system root.
1150  if (!Filename[Pos])
1151  return Filename;
1152 
1153  // If there's not a path separator at the end of the base directory nor
1154  // immediately after it, then this isn't within the base directory.
1155  if (!llvm::sys::path::is_separator(Filename[Pos])) {
1156  if (!llvm::sys::path::is_separator(BaseDir.back()))
1157  return Filename;
1158  } else {
1159  // If the file name has a '/' at the current position, skip over the '/'.
1160  // We distinguish relative paths from absolute paths by the
1161  // absence of '/' at the beginning of relative paths.
1162  //
1163  // FIXME: This is wrong. We distinguish them by asking if the path is
1164  // absolute, which isn't the same thing. And there might be multiple '/'s
1165  // in a row. Use a better mechanism to indicate whether we have emitted an
1166  // absolute or relative path.
1167  ++Pos;
1168  }
1169 
1170  return Filename + Pos;
1171 }
1172 
1174  while (1) {
1175  if (ASTFileSignature S = llvm::sys::Process::GetRandomNumber())
1176  return S;
1177  // Rely on GetRandomNumber to eventually return non-zero...
1178  }
1179 }
1180 
1181 /// \brief Write the control block.
1182 uint64_t ASTWriter::WriteControlBlock(Preprocessor &PP,
1184  StringRef isysroot,
1185  const std::string &OutputFile) {
1186  ASTFileSignature Signature = 0;
1187 
1188  using namespace llvm;
1189  Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
1190  RecordData Record;
1191 
1192  // Metadata
1193  auto *MetadataAbbrev = new BitCodeAbbrev();
1194  MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1195  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1196  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1197  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1198  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1199  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
1200  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
1201  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1202  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1203  unsigned MetadataAbbrevCode = Stream.EmitAbbrev(MetadataAbbrev);
1204  assert((!WritingModule || isysroot.empty()) &&
1205  "writing module as a relocatable PCH?");
1206  {
1207  RecordData::value_type Record[] = {METADATA, VERSION_MAJOR, VERSION_MINOR,
1208  CLANG_VERSION_MAJOR, CLANG_VERSION_MINOR,
1209  !isysroot.empty(), IncludeTimestamps,
1210  ASTHasCompilerErrors};
1211  Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1213  }
1214  if (WritingModule) {
1215  // For implicit modules we output a signature that we can use to ensure
1216  // duplicate module builds don't collide in the cache as their output order
1217  // is non-deterministic.
1218  // FIXME: Remove this when output is deterministic.
1219  if (Context.getLangOpts().ImplicitModules) {
1220  Signature = getSignature();
1221  RecordData::value_type Record[] = {Signature};
1222  Stream.EmitRecord(SIGNATURE, Record);
1223  }
1224 
1225  // Module name
1226  auto *Abbrev = new BitCodeAbbrev();
1227  Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1228  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1229  unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1230  RecordData::value_type Record[] = {MODULE_NAME};
1231  Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1232  }
1233 
1234  if (WritingModule && WritingModule->Directory) {
1235  SmallString<128> BaseDir(WritingModule->Directory->getName());
1236  cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
1237 
1238  // If the home of the module is the current working directory, then we
1239  // want to pick up the cwd of the build process loading the module, not
1240  // our cwd, when we load this module.
1241  if (!PP.getHeaderSearchInfo()
1244  WritingModule->Directory->getName() != StringRef(".")) {
1245  // Module directory.
1246  auto *Abbrev = new BitCodeAbbrev();
1247  Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1248  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
1249  unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1250 
1251  RecordData::value_type Record[] = {MODULE_DIRECTORY};
1252  Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
1253  }
1254 
1255  // Write out all other paths relative to the base directory if possible.
1256  BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1257  } else if (!isysroot.empty()) {
1258  // Write out paths relative to the sysroot if possible.
1259  BaseDirectory = isysroot;
1260  }
1261 
1262  // Module map file
1263  if (WritingModule) {
1264  Record.clear();
1265 
1266  auto &Map = PP.getHeaderSearchInfo().getModuleMap();
1267 
1268  // Primary module map file.
1269  AddPath(Map.getModuleMapFileForUniquing(WritingModule)->getName(), Record);
1270 
1271  // Additional module map files.
1272  if (auto *AdditionalModMaps =
1273  Map.getAdditionalModuleMapFiles(WritingModule)) {
1274  Record.push_back(AdditionalModMaps->size());
1275  for (const FileEntry *F : *AdditionalModMaps)
1276  AddPath(F->getName(), Record);
1277  } else {
1278  Record.push_back(0);
1279  }
1280 
1281  Stream.EmitRecord(MODULE_MAP_FILE, Record);
1282  }
1283 
1284  // Imports
1285  if (Chain) {
1286  serialization::ModuleManager &Mgr = Chain->getModuleManager();
1287  Record.clear();
1288 
1289  for (auto *M : Mgr) {
1290  // Skip modules that weren't directly imported.
1291  if (!M->isDirectlyImported())
1292  continue;
1293 
1294  Record.push_back((unsigned)M->Kind); // FIXME: Stable encoding
1295  AddSourceLocation(M->ImportLoc, Record);
1296  Record.push_back(M->File->getSize());
1297  Record.push_back(getTimestampForOutput(M->File));
1298  Record.push_back(M->Signature);
1299  AddPath(M->FileName, Record);
1300  }
1301  Stream.EmitRecord(IMPORTS, Record);
1302  }
1303 
1304  // Write the options block.
1305  Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
1306 
1307  // Language options.
1308  Record.clear();
1309  const LangOptions &LangOpts = Context.getLangOpts();
1310 #define LANGOPT(Name, Bits, Default, Description) \
1311  Record.push_back(LangOpts.Name);
1312 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1313  Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
1314 #include "clang/Basic/LangOptions.def"
1315 #define SANITIZER(NAME, ID) \
1316  Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
1317 #include "clang/Basic/Sanitizers.def"
1318 
1319  Record.push_back(LangOpts.ModuleFeatures.size());
1320  for (StringRef Feature : LangOpts.ModuleFeatures)
1321  AddString(Feature, Record);
1322 
1323  Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1324  AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
1325 
1326  AddString(LangOpts.CurrentModule, Record);
1327 
1328  // Comment options.
1329  Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
1330  for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1331  AddString(I, Record);
1332  }
1333  Record.push_back(LangOpts.CommentOpts.ParseAllComments);
1334 
1335  // OpenMP offloading options.
1336  Record.push_back(LangOpts.OMPTargetTriples.size());
1337  for (auto &T : LangOpts.OMPTargetTriples)
1338  AddString(T.getTriple(), Record);
1339 
1340  AddString(LangOpts.OMPHostIRFile, Record);
1341 
1342  Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1343 
1344  // Target options.
1345  Record.clear();
1346  const TargetInfo &Target = Context.getTargetInfo();
1347  const TargetOptions &TargetOpts = Target.getTargetOpts();
1348  AddString(TargetOpts.Triple, Record);
1349  AddString(TargetOpts.CPU, Record);
1350  AddString(TargetOpts.ABI, Record);
1351  Record.push_back(TargetOpts.FeaturesAsWritten.size());
1352  for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1353  AddString(TargetOpts.FeaturesAsWritten[I], Record);
1354  }
1355  Record.push_back(TargetOpts.Features.size());
1356  for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1357  AddString(TargetOpts.Features[I], Record);
1358  }
1359  Stream.EmitRecord(TARGET_OPTIONS, Record);
1360 
1361  // Diagnostic options.
1362  Record.clear();
1363  const DiagnosticOptions &DiagOpts
1364  = Context.getDiagnostics().getDiagnosticOptions();
1365 #define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1366 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1367  Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1368 #include "clang/Basic/DiagnosticOptions.def"
1369  Record.push_back(DiagOpts.Warnings.size());
1370  for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1371  AddString(DiagOpts.Warnings[I], Record);
1372  Record.push_back(DiagOpts.Remarks.size());
1373  for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1374  AddString(DiagOpts.Remarks[I], Record);
1375  // Note: we don't serialize the log or serialization file names, because they
1376  // are generally transient files and will almost always be overridden.
1377  Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1378 
1379  // File system options.
1380  Record.clear();
1381  const FileSystemOptions &FSOpts =
1383  AddString(FSOpts.WorkingDir, Record);
1384  Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1385 
1386  // Header search options.
1387  Record.clear();
1388  const HeaderSearchOptions &HSOpts
1390  AddString(HSOpts.Sysroot, Record);
1391 
1392  // Include entries.
1393  Record.push_back(HSOpts.UserEntries.size());
1394  for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1395  const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1396  AddString(Entry.Path, Record);
1397  Record.push_back(static_cast<unsigned>(Entry.Group));
1398  Record.push_back(Entry.IsFramework);
1399  Record.push_back(Entry.IgnoreSysRoot);
1400  }
1401 
1402  // System header prefixes.
1403  Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1404  for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1405  AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1406  Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1407  }
1408 
1409  AddString(HSOpts.ResourceDir, Record);
1410  AddString(HSOpts.ModuleCachePath, Record);
1411  AddString(HSOpts.ModuleUserBuildPath, Record);
1412  Record.push_back(HSOpts.DisableModuleHash);
1413  Record.push_back(HSOpts.UseBuiltinIncludes);
1414  Record.push_back(HSOpts.UseStandardSystemIncludes);
1415  Record.push_back(HSOpts.UseStandardCXXIncludes);
1416  Record.push_back(HSOpts.UseLibcxx);
1417  // Write out the specific module cache path that contains the module files.
1418  AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
1419  Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1420 
1421  // Preprocessor options.
1422  Record.clear();
1423  const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1424 
1425  // Macro definitions.
1426  Record.push_back(PPOpts.Macros.size());
1427  for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1428  AddString(PPOpts.Macros[I].first, Record);
1429  Record.push_back(PPOpts.Macros[I].second);
1430  }
1431 
1432  // Includes
1433  Record.push_back(PPOpts.Includes.size());
1434  for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1435  AddString(PPOpts.Includes[I], Record);
1436 
1437  // Macro includes
1438  Record.push_back(PPOpts.MacroIncludes.size());
1439  for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1440  AddString(PPOpts.MacroIncludes[I], Record);
1441 
1442  Record.push_back(PPOpts.UsePredefines);
1443  // Detailed record is important since it is used for the module cache hash.
1444  Record.push_back(PPOpts.DetailedRecord);
1445  AddString(PPOpts.ImplicitPCHInclude, Record);
1446  AddString(PPOpts.ImplicitPTHInclude, Record);
1447  Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1448  Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1449 
1450  // Leave the options block.
1451  Stream.ExitBlock();
1452 
1453  // Original file name and file ID
1454  SourceManager &SM = Context.getSourceManager();
1455  if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1456  auto *FileAbbrev = new BitCodeAbbrev();
1457  FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1458  FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
1459  FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1460  unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
1461 
1462  Record.clear();
1463  Record.push_back(ORIGINAL_FILE);
1464  Record.push_back(SM.getMainFileID().getOpaqueValue());
1465  EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
1466  }
1467 
1468  Record.clear();
1469  Record.push_back(SM.getMainFileID().getOpaqueValue());
1470  Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1471 
1472  // Original PCH directory
1473  if (!OutputFile.empty() && OutputFile != "-") {
1474  auto *Abbrev = new BitCodeAbbrev();
1475  Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1476  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1477  unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1478 
1479  SmallString<128> OutputPath(OutputFile);
1480 
1481  SM.getFileManager().makeAbsolutePath(OutputPath);
1482  StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1483 
1484  RecordData::value_type Record[] = {ORIGINAL_PCH_DIR};
1485  Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1486  }
1487 
1488  WriteInputFiles(Context.SourceMgr,
1490  PP.getLangOpts().Modules);
1491  Stream.ExitBlock();
1492  return Signature;
1493 }
1494 
1495 namespace {
1496  /// \brief An input file.
1497  struct InputFileEntry {
1498  const FileEntry *File;
1499  bool IsSystemFile;
1500  bool IsTransient;
1501  bool BufferOverridden;
1502  };
1503 } // end anonymous namespace
1504 
1505 void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1506  HeaderSearchOptions &HSOpts,
1507  bool Modules) {
1508  using namespace llvm;
1509  Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
1510 
1511  // Create input-file abbreviation.
1512  auto *IFAbbrev = new BitCodeAbbrev();
1513  IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
1514  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
1515  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1516  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1517  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
1518  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
1519  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1520  unsigned IFAbbrevCode = Stream.EmitAbbrev(IFAbbrev);
1521 
1522  // Get all ContentCache objects for files, sorted by whether the file is a
1523  // system one or not. System files go at the back, users files at the front.
1524  std::deque<InputFileEntry> SortedFiles;
1525  for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1526  // Get this source location entry.
1527  const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1528  assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
1529 
1530  // We only care about file entries that were not overridden.
1531  if (!SLoc->isFile())
1532  continue;
1533  const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1534  if (!Cache->OrigEntry)
1535  continue;
1536 
1537  InputFileEntry Entry;
1538  Entry.File = Cache->OrigEntry;
1539  Entry.IsSystemFile = Cache->IsSystemFile;
1540  Entry.IsTransient = Cache->IsTransient;
1541  Entry.BufferOverridden = Cache->BufferOverridden;
1542  if (Cache->IsSystemFile)
1543  SortedFiles.push_back(Entry);
1544  else
1545  SortedFiles.push_front(Entry);
1546  }
1547 
1548  unsigned UserFilesNum = 0;
1549  // Write out all of the input files.
1550  std::vector<uint64_t> InputFileOffsets;
1551  for (const auto &Entry : SortedFiles) {
1552  uint32_t &InputFileID = InputFileIDs[Entry.File];
1553  if (InputFileID != 0)
1554  continue; // already recorded this file.
1555 
1556  // Record this entry's offset.
1557  InputFileOffsets.push_back(Stream.GetCurrentBitNo());
1558 
1559  InputFileID = InputFileOffsets.size();
1560 
1561  if (!Entry.IsSystemFile)
1562  ++UserFilesNum;
1563 
1564  // Emit size/modification time for this file.
1565  // And whether this file was overridden.
1566  RecordData::value_type Record[] = {
1567  INPUT_FILE,
1568  InputFileOffsets.size(),
1569  (uint64_t)Entry.File->getSize(),
1570  (uint64_t)getTimestampForOutput(Entry.File),
1571  Entry.BufferOverridden,
1572  Entry.IsTransient};
1573 
1574  EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
1575  }
1576 
1577  Stream.ExitBlock();
1578 
1579  // Create input file offsets abbreviation.
1580  auto *OffsetsAbbrev = new BitCodeAbbrev();
1581  OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1582  OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
1583  OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1584  // input files
1585  OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
1586  unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(OffsetsAbbrev);
1587 
1588  // Write input file offsets.
1589  RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
1590  InputFileOffsets.size(), UserFilesNum};
1591  Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
1592 }
1593 
1594 //===----------------------------------------------------------------------===//
1595 // Source Manager Serialization
1596 //===----------------------------------------------------------------------===//
1597 
1598 /// \brief Create an abbreviation for the SLocEntry that refers to a
1599 /// file.
1600 static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1601  using namespace llvm;
1602 
1603  auto *Abbrev = new BitCodeAbbrev();
1604  Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1605  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1606  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1607  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1608  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1609  // FileEntry fields.
1610  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
1611  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
1612  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1613  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
1614  return Stream.EmitAbbrev(Abbrev);
1615 }
1616 
1617 /// \brief Create an abbreviation for the SLocEntry that refers to a
1618 /// buffer.
1619 static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1620  using namespace llvm;
1621 
1622  auto *Abbrev = new BitCodeAbbrev();
1623  Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
1624  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1625  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1626  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1627  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1628  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
1629  return Stream.EmitAbbrev(Abbrev);
1630 }
1631 
1632 /// \brief Create an abbreviation for the SLocEntry that refers to a
1633 /// buffer's blob.
1634 static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
1635  using namespace llvm;
1636 
1637  auto *Abbrev = new BitCodeAbbrev();
1638  Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_BLOB));
1639  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
1640  return Stream.EmitAbbrev(Abbrev);
1641 }
1642 
1643 /// \brief Create an abbreviation for the SLocEntry that refers to a macro
1644 /// expansion.
1645 static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
1646  using namespace llvm;
1647 
1648  auto *Abbrev = new BitCodeAbbrev();
1649  Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
1650  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1651  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1652  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1653  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
1654  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
1655  return Stream.EmitAbbrev(Abbrev);
1656 }
1657 
1658 namespace {
1659  // Trait used for the on-disk hash table of header search information.
1660  class HeaderFileInfoTrait {
1661  ASTWriter &Writer;
1662  const HeaderSearch &HS;
1663 
1664  // Keep track of the framework names we've used during serialization.
1665  SmallVector<char, 128> FrameworkStringData;
1666  llvm::StringMap<unsigned> FrameworkNameOffset;
1667 
1668  public:
1669  HeaderFileInfoTrait(ASTWriter &Writer, const HeaderSearch &HS)
1670  : Writer(Writer), HS(HS) { }
1671 
1672  struct key_type {
1673  const FileEntry *FE;
1674  const char *Filename;
1675  };
1676  typedef const key_type &key_type_ref;
1677 
1678  typedef HeaderFileInfo data_type;
1679  typedef const data_type &data_type_ref;
1680  typedef unsigned hash_value_type;
1681  typedef unsigned offset_type;
1682 
1683  hash_value_type ComputeHash(key_type_ref key) {
1684  // The hash is based only on size/time of the file, so that the reader can
1685  // match even when symlinking or excess path elements ("foo/../", "../")
1686  // change the form of the name. However, complete path is still the key.
1687  return llvm::hash_combine(key.FE->getSize(),
1688  Writer.getTimestampForOutput(key.FE));
1689  }
1690 
1691  std::pair<unsigned,unsigned>
1692  EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
1693  using namespace llvm::support;
1694  endian::Writer<little> LE(Out);
1695  unsigned KeyLen = strlen(key.Filename) + 1 + 8 + 8;
1696  LE.write<uint16_t>(KeyLen);
1697  unsigned DataLen = 1 + 2 + 4 + 4;
1698  for (auto ModInfo : HS.getModuleMap().findAllModulesForHeader(key.FE))
1699  if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
1700  DataLen += 4;
1701  LE.write<uint8_t>(DataLen);
1702  return std::make_pair(KeyLen, DataLen);
1703  }
1704 
1705  void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
1706  using namespace llvm::support;
1707  endian::Writer<little> LE(Out);
1708  LE.write<uint64_t>(key.FE->getSize());
1709  KeyLen -= 8;
1710  LE.write<uint64_t>(Writer.getTimestampForOutput(key.FE));
1711  KeyLen -= 8;
1712  Out.write(key.Filename, KeyLen);
1713  }
1714 
1715  void EmitData(raw_ostream &Out, key_type_ref key,
1716  data_type_ref Data, unsigned DataLen) {
1717  using namespace llvm::support;
1718  endian::Writer<little> LE(Out);
1719  uint64_t Start = Out.tell(); (void)Start;
1720 
1721  unsigned char Flags = (Data.isImport << 4)
1722  | (Data.isPragmaOnce << 3)
1723  | (Data.DirInfo << 1)
1724  | Data.IndexHeaderMapHeader;
1725  LE.write<uint8_t>(Flags);
1726  LE.write<uint16_t>(Data.NumIncludes);
1727 
1728  if (!Data.ControllingMacro)
1729  LE.write<uint32_t>(Data.ControllingMacroID);
1730  else
1731  LE.write<uint32_t>(Writer.getIdentifierRef(Data.ControllingMacro));
1732 
1733  unsigned Offset = 0;
1734  if (!Data.Framework.empty()) {
1735  // If this header refers into a framework, save the framework name.
1737  = FrameworkNameOffset.find(Data.Framework);
1738  if (Pos == FrameworkNameOffset.end()) {
1739  Offset = FrameworkStringData.size() + 1;
1740  FrameworkStringData.append(Data.Framework.begin(),
1741  Data.Framework.end());
1742  FrameworkStringData.push_back(0);
1743 
1744  FrameworkNameOffset[Data.Framework] = Offset;
1745  } else
1746  Offset = Pos->second;
1747  }
1748  LE.write<uint32_t>(Offset);
1749 
1750  // FIXME: If the header is excluded, we should write out some
1751  // record of that fact.
1752  for (auto ModInfo : HS.getModuleMap().findAllModulesForHeader(key.FE)) {
1753  if (uint32_t ModID =
1754  Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule())) {
1755  uint32_t Value = (ModID << 2) | (unsigned)ModInfo.getRole();
1756  assert((Value >> 2) == ModID && "overflow in header module info");
1757  LE.write<uint32_t>(Value);
1758  }
1759  }
1760 
1761  assert(Out.tell() - Start == DataLen && "Wrong data length");
1762  }
1763 
1764  const char *strings_begin() const { return FrameworkStringData.begin(); }
1765  const char *strings_end() const { return FrameworkStringData.end(); }
1766  };
1767 } // end anonymous namespace
1768 
1769 /// \brief Write the header search block for the list of files that
1770 ///
1771 /// \param HS The header search structure to save.
1772 void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
1774  HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
1775 
1776  if (FilesByUID.size() > HS.header_file_size())
1777  FilesByUID.resize(HS.header_file_size());
1778 
1779  HeaderFileInfoTrait GeneratorTrait(*this, HS);
1780  llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
1781  SmallVector<const char *, 4> SavedStrings;
1782  unsigned NumHeaderSearchEntries = 0;
1783  for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1784  const FileEntry *File = FilesByUID[UID];
1785  if (!File)
1786  continue;
1787 
1788  // Get the file info. This will load info from the external source if
1789  // necessary. Skip emitting this file if we have no information on it
1790  // as a header file (in which case HFI will be null) or if it hasn't
1791  // changed since it was loaded. Also skip it if it's for a modular header
1792  // from a different module; in that case, we rely on the module(s)
1793  // containing the header to provide this information.
1794  const HeaderFileInfo *HFI =
1795  HS.getExistingFileInfo(File, /*WantExternal*/!Chain);
1796  if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
1797  continue;
1798 
1799  // Massage the file path into an appropriate form.
1800  const char *Filename = File->getName();
1801  SmallString<128> FilenameTmp(Filename);
1802  if (PreparePathForOutput(FilenameTmp)) {
1803  // If we performed any translation on the file name at all, we need to
1804  // save this string, since the generator will refer to it later.
1805  Filename = strdup(FilenameTmp.c_str());
1806  SavedStrings.push_back(Filename);
1807  }
1808 
1809  HeaderFileInfoTrait::key_type key = { File, Filename };
1810  Generator.insert(key, *HFI, GeneratorTrait);
1811  ++NumHeaderSearchEntries;
1812  }
1813 
1814  // Create the on-disk hash table in a buffer.
1815  SmallString<4096> TableData;
1816  uint32_t BucketOffset;
1817  {
1818  using namespace llvm::support;
1819  llvm::raw_svector_ostream Out(TableData);
1820  // Make sure that no bucket is at offset 0
1821  endian::Writer<little>(Out).write<uint32_t>(0);
1822  BucketOffset = Generator.Emit(Out, GeneratorTrait);
1823  }
1824 
1825  // Create a blob abbreviation
1826  using namespace llvm;
1827 
1828  auto *Abbrev = new BitCodeAbbrev();
1829  Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1830  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1831  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1832  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1833  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1834  unsigned TableAbbrev = Stream.EmitAbbrev(Abbrev);
1835 
1836  // Write the header search table
1837  RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
1838  NumHeaderSearchEntries, TableData.size()};
1839  TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
1840  Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
1841 
1842  // Free all of the strings we had to duplicate.
1843  for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
1844  free(const_cast<char *>(SavedStrings[I]));
1845 }
1846 
1847 /// \brief Writes the block containing the serialized form of the
1848 /// source manager.
1849 ///
1850 /// TODO: We should probably use an on-disk hash table (stored in a
1851 /// blob), indexed based on the file name, so that we only create
1852 /// entries for files that we actually need. In the common case (no
1853 /// errors), we probably won't have to create file entries for any of
1854 /// the files in the AST.
1855 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
1856  const Preprocessor &PP) {
1857  RecordData Record;
1858 
1859  // Enter the source manager block.
1860  Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 3);
1861 
1862  // Abbreviations for the various kinds of source-location entries.
1863  unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
1864  unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
1865  unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
1866  unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
1867 
1868  // Write out the source location entry table. We skip the first
1869  // entry, which is always the same dummy entry.
1870  std::vector<uint32_t> SLocEntryOffsets;
1871  RecordData PreloadSLocs;
1872  SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
1873  for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
1874  I != N; ++I) {
1875  // Get this source location entry.
1876  const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1877  FileID FID = FileID::get(I);
1878  assert(&SourceMgr.getSLocEntry(FID) == SLoc);
1879 
1880  // Record the offset of this source-location entry.
1881  SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
1882 
1883  // Figure out which record code to use.
1884  unsigned Code;
1885  if (SLoc->isFile()) {
1886  const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1887  if (Cache->OrigEntry) {
1888  Code = SM_SLOC_FILE_ENTRY;
1889  } else
1890  Code = SM_SLOC_BUFFER_ENTRY;
1891  } else
1892  Code = SM_SLOC_EXPANSION_ENTRY;
1893  Record.clear();
1894  Record.push_back(Code);
1895 
1896  // Starting offset of this entry within this module, so skip the dummy.
1897  Record.push_back(SLoc->getOffset() - 2);
1898  if (SLoc->isFile()) {
1899  const SrcMgr::FileInfo &File = SLoc->getFile();
1900  Record.push_back(File.getIncludeLoc().getRawEncoding());
1901  Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
1902  Record.push_back(File.hasLineDirectives());
1903 
1904  const SrcMgr::ContentCache *Content = File.getContentCache();
1905  if (Content->OrigEntry) {
1906  assert(Content->OrigEntry == Content->ContentsEntry &&
1907  "Writing to AST an overridden file is not supported");
1908 
1909  // The source location entry is a file. Emit input file ID.
1910  assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
1911  Record.push_back(InputFileIDs[Content->OrigEntry]);
1912 
1913  Record.push_back(File.NumCreatedFIDs);
1914 
1915  FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
1916  if (FDI != FileDeclIDs.end()) {
1917  Record.push_back(FDI->second->FirstDeclIndex);
1918  Record.push_back(FDI->second->DeclIDs.size());
1919  } else {
1920  Record.push_back(0);
1921  Record.push_back(0);
1922  }
1923 
1924  Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
1925 
1926  if (Content->BufferOverridden || Content->IsTransient) {
1927  RecordData::value_type Record[] = {SM_SLOC_BUFFER_BLOB};
1928  const llvm::MemoryBuffer *Buffer
1929  = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
1930  Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
1931  StringRef(Buffer->getBufferStart(),
1932  Buffer->getBufferSize() + 1));
1933  }
1934  } else {
1935  // The source location entry is a buffer. The blob associated
1936  // with this entry contains the contents of the buffer.
1937 
1938  // We add one to the size so that we capture the trailing NULL
1939  // that is required by llvm::MemoryBuffer::getMemBuffer (on
1940  // the reader side).
1941  const llvm::MemoryBuffer *Buffer
1942  = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
1943  const char *Name = Buffer->getBufferIdentifier();
1944  Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
1945  StringRef(Name, strlen(Name) + 1));
1946  RecordData::value_type Record[] = {SM_SLOC_BUFFER_BLOB};
1947  Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
1948  StringRef(Buffer->getBufferStart(),
1949  Buffer->getBufferSize() + 1));
1950 
1951  if (strcmp(Name, "<built-in>") == 0) {
1952  PreloadSLocs.push_back(SLocEntryOffsets.size());
1953  }
1954  }
1955  } else {
1956  // The source location entry is a macro expansion.
1957  const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
1958  Record.push_back(Expansion.getSpellingLoc().getRawEncoding());
1959  Record.push_back(Expansion.getExpansionLocStart().getRawEncoding());
1960  Record.push_back(Expansion.isMacroArgExpansion() ? 0
1961  : Expansion.getExpansionLocEnd().getRawEncoding());
1962 
1963  // Compute the token length for this macro expansion.
1964  unsigned NextOffset = SourceMgr.getNextLocalOffset();
1965  if (I + 1 != N)
1966  NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
1967  Record.push_back(NextOffset - SLoc->getOffset() - 1);
1968  Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
1969  }
1970  }
1971 
1972  Stream.ExitBlock();
1973 
1974  if (SLocEntryOffsets.empty())
1975  return;
1976 
1977  // Write the source-location offsets table into the AST block. This
1978  // table is used for lazily loading source-location information.
1979  using namespace llvm;
1980 
1981  auto *Abbrev = new BitCodeAbbrev();
1982  Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
1983  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
1984  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
1985  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
1986  unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
1987  {
1988  RecordData::value_type Record[] = {
1989  SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
1990  SourceMgr.getNextLocalOffset() - 1 /* skip dummy */};
1991  Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
1992  bytes(SLocEntryOffsets));
1993  }
1994  // Write the source location entry preloads array, telling the AST
1995  // reader which source locations entries it should load eagerly.
1996  Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
1997 
1998  // Write the line table. It depends on remapping working, so it must come
1999  // after the source location offsets.
2000  if (SourceMgr.hasLineTable()) {
2001  LineTableInfo &LineTable = SourceMgr.getLineTable();
2002 
2003  Record.clear();
2004 
2005  // Emit the needed file names.
2006  llvm::DenseMap<int, int> FilenameMap;
2007  for (const auto &L : LineTable) {
2008  if (L.first.ID < 0)
2009  continue;
2010  for (auto &LE : L.second) {
2011  if (FilenameMap.insert(std::make_pair(LE.FilenameID,
2012  FilenameMap.size())).second)
2013  AddPath(LineTable.getFilename(LE.FilenameID), Record);
2014  }
2015  }
2016  Record.push_back(0);
2017 
2018  // Emit the line entries
2019  for (const auto &L : LineTable) {
2020  // Only emit entries for local files.
2021  if (L.first.ID < 0)
2022  continue;
2023 
2024  // Emit the file ID
2025  Record.push_back(L.first.ID);
2026 
2027  // Emit the line entries
2028  Record.push_back(L.second.size());
2029  for (const auto &LE : L.second) {
2030  Record.push_back(LE.FileOffset);
2031  Record.push_back(LE.LineNo);
2032  Record.push_back(FilenameMap[LE.FilenameID]);
2033  Record.push_back((unsigned)LE.FileKind);
2034  Record.push_back(LE.IncludeOffset);
2035  }
2036  }
2037 
2038  Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
2039  }
2040 }
2041 
2042 //===----------------------------------------------------------------------===//
2043 // Preprocessor Serialization
2044 //===----------------------------------------------------------------------===//
2045 
2046 static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
2047  const Preprocessor &PP) {
2048  if (MacroInfo *MI = MD->getMacroInfo())
2049  if (MI->isBuiltinMacro())
2050  return true;
2051 
2052  if (IsModule) {
2053  SourceLocation Loc = MD->getLocation();
2054  if (Loc.isInvalid())
2055  return true;
2056  if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
2057  return true;
2058  }
2059 
2060  return false;
2061 }
2062 
2063 /// \brief Writes the block containing the serialized form of the
2064 /// preprocessor.
2065 ///
2066 void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
2068  if (PPRec)
2069  WritePreprocessorDetail(*PPRec);
2070 
2071  RecordData Record;
2072  RecordData ModuleMacroRecord;
2073 
2074  // If the preprocessor __COUNTER__ value has been bumped, remember it.
2075  if (PP.getCounterValue() != 0) {
2076  RecordData::value_type Record[] = {PP.getCounterValue()};
2077  Stream.EmitRecord(PP_COUNTER_VALUE, Record);
2078  }
2079 
2080  // Enter the preprocessor block.
2081  Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
2082 
2083  // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
2084  // FIXME: Include a location for the use, and say which one was used.
2085  if (PP.SawDateOrTime())
2086  PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
2087 
2088  // Loop over all the macro directives that are live at the end of the file,
2089  // emitting each to the PP section.
2090 
2091  // Construct the list of identifiers with macro directives that need to be
2092  // serialized.
2094  for (auto &Id : PP.getIdentifierTable())
2095  if (Id.second->hadMacroDefinition() &&
2096  (!Id.second->isFromAST() ||
2097  Id.second->hasChangedSinceDeserialization()))
2098  MacroIdentifiers.push_back(Id.second);
2099  // Sort the set of macro definitions that need to be serialized by the
2100  // name of the macro, to provide a stable ordering.
2101  std::sort(MacroIdentifiers.begin(), MacroIdentifiers.end(),
2102  llvm::less_ptr<IdentifierInfo>());
2103 
2104  // Emit the macro directives as a list and associate the offset with the
2105  // identifier they belong to.
2106  for (const IdentifierInfo *Name : MacroIdentifiers) {
2108  auto StartOffset = Stream.GetCurrentBitNo();
2109 
2110  // Emit the macro directives in reverse source order.
2111  for (; MD; MD = MD->getPrevious()) {
2112  // Once we hit an ignored macro, we're done: the rest of the chain
2113  // will all be ignored macros.
2114  if (shouldIgnoreMacro(MD, IsModule, PP))
2115  break;
2116 
2117  AddSourceLocation(MD->getLocation(), Record);
2118  Record.push_back(MD->getKind());
2119  if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
2120  Record.push_back(getMacroRef(DefMD->getInfo(), Name));
2121  } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
2122  Record.push_back(VisMD->isPublic());
2123  }
2124  }
2125 
2126  // Write out any exported module macros.
2127  bool EmittedModuleMacros = false;
2128  if (IsModule) {
2129  auto Leafs = PP.getLeafModuleMacros(Name);
2130  SmallVector<ModuleMacro*, 8> Worklist(Leafs.begin(), Leafs.end());
2131  llvm::DenseMap<ModuleMacro*, unsigned> Visits;
2132  while (!Worklist.empty()) {
2133  auto *Macro = Worklist.pop_back_val();
2134 
2135  // Emit a record indicating this submodule exports this macro.
2136  ModuleMacroRecord.push_back(
2137  getSubmoduleID(Macro->getOwningModule()));
2138  ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
2139  for (auto *M : Macro->overrides())
2140  ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
2141 
2142  Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2143  ModuleMacroRecord.clear();
2144 
2145  // Enqueue overridden macros once we've visited all their ancestors.
2146  for (auto *M : Macro->overrides())
2147  if (++Visits[M] == M->getNumOverridingMacros())
2148  Worklist.push_back(M);
2149 
2150  EmittedModuleMacros = true;
2151  }
2152  }
2153 
2154  if (Record.empty() && !EmittedModuleMacros)
2155  continue;
2156 
2157  IdentMacroDirectivesOffsetMap[Name] = StartOffset;
2158  Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2159  Record.clear();
2160  }
2161 
2162  /// \brief Offsets of each of the macros into the bitstream, indexed by
2163  /// the local macro ID
2164  ///
2165  /// For each identifier that is associated with a macro, this map
2166  /// provides the offset into the bitstream where that macro is
2167  /// defined.
2168  std::vector<uint32_t> MacroOffsets;
2169 
2170  for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2171  const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2172  MacroInfo *MI = MacroInfosToEmit[I].MI;
2173  MacroID ID = MacroInfosToEmit[I].ID;
2174 
2175  if (ID < FirstMacroID) {
2176  assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2177  continue;
2178  }
2179 
2180  // Record the local offset of this macro.
2181  unsigned Index = ID - FirstMacroID;
2182  if (Index == MacroOffsets.size())
2183  MacroOffsets.push_back(Stream.GetCurrentBitNo());
2184  else {
2185  if (Index > MacroOffsets.size())
2186  MacroOffsets.resize(Index + 1);
2187 
2188  MacroOffsets[Index] = Stream.GetCurrentBitNo();
2189  }
2190 
2191  AddIdentifierRef(Name, Record);
2192  Record.push_back(inferSubmoduleIDFromLocation(MI->getDefinitionLoc()));
2193  AddSourceLocation(MI->getDefinitionLoc(), Record);
2194  AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2195  Record.push_back(MI->isUsed());
2196  Record.push_back(MI->isUsedForHeaderGuard());
2197  unsigned Code;
2198  if (MI->isObjectLike()) {
2199  Code = PP_MACRO_OBJECT_LIKE;
2200  } else {
2201  Code = PP_MACRO_FUNCTION_LIKE;
2202 
2203  Record.push_back(MI->isC99Varargs());
2204  Record.push_back(MI->isGNUVarargs());
2205  Record.push_back(MI->hasCommaPasting());
2206  Record.push_back(MI->getNumArgs());
2207  for (const IdentifierInfo *Arg : MI->args())
2208  AddIdentifierRef(Arg, Record);
2209  }
2210 
2211  // If we have a detailed preprocessing record, record the macro definition
2212  // ID that corresponds to this macro.
2213  if (PPRec)
2214  Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2215 
2216  Stream.EmitRecord(Code, Record);
2217  Record.clear();
2218 
2219  // Emit the tokens array.
2220  for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2221  // Note that we know that the preprocessor does not have any annotation
2222  // tokens in it because they are created by the parser, and thus can't
2223  // be in a macro definition.
2224  const Token &Tok = MI->getReplacementToken(TokNo);
2225  AddToken(Tok, Record);
2226  Stream.EmitRecord(PP_TOKEN, Record);
2227  Record.clear();
2228  }
2229  ++NumMacros;
2230  }
2231 
2232  Stream.ExitBlock();
2233 
2234  // Write the offsets table for macro IDs.
2235  using namespace llvm;
2236 
2237  auto *Abbrev = new BitCodeAbbrev();
2238  Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2239  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2240  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2241  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2242 
2243  unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2244  {
2245  RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
2246  FirstMacroID - NUM_PREDEF_MACRO_IDS};
2247  Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
2248  }
2249 }
2250 
2251 void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
2252  if (PPRec.local_begin() == PPRec.local_end())
2253  return;
2254 
2255  SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
2256 
2257  // Enter the preprocessor block.
2258  Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
2259 
2260  // If the preprocessor has a preprocessing record, emit it.
2261  unsigned NumPreprocessingRecords = 0;
2262  using namespace llvm;
2263 
2264  // Set up the abbreviation for
2265  unsigned InclusionAbbrev = 0;
2266  {
2267  auto *Abbrev = new BitCodeAbbrev();
2268  Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
2269  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2270  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2271  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
2272  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
2273  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2274  InclusionAbbrev = Stream.EmitAbbrev(Abbrev);
2275  }
2276 
2277  unsigned FirstPreprocessorEntityID
2278  = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
2280  unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
2281  RecordData Record;
2283  EEnd = PPRec.local_end();
2284  E != EEnd;
2285  (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
2286  Record.clear();
2287 
2288  PreprocessedEntityOffsets.push_back(
2289  PPEntityOffset((*E)->getSourceRange(), Stream.GetCurrentBitNo()));
2290 
2291  if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
2292  // Record this macro definition's ID.
2293  MacroDefinitions[MD] = NextPreprocessorEntityID;
2294 
2295  AddIdentifierRef(MD->getName(), Record);
2296  Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2297  continue;
2298  }
2299 
2300  if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
2301  Record.push_back(ME->isBuiltinMacro());
2302  if (ME->isBuiltinMacro())
2303  AddIdentifierRef(ME->getName(), Record);
2304  else
2305  Record.push_back(MacroDefinitions[ME->getDefinition()]);
2306  Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
2307  continue;
2308  }
2309 
2310  if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
2311  Record.push_back(PPD_INCLUSION_DIRECTIVE);
2312  Record.push_back(ID->getFileName().size());
2313  Record.push_back(ID->wasInQuotes());
2314  Record.push_back(static_cast<unsigned>(ID->getKind()));
2315  Record.push_back(ID->importedModule());
2317  Buffer += ID->getFileName();
2318  // Check that the FileEntry is not null because it was not resolved and
2319  // we create a PCH even with compiler errors.
2320  if (ID->getFile())
2321  Buffer += ID->getFile()->getName();
2322  Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
2323  continue;
2324  }
2325 
2326  llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2327  }
2328  Stream.ExitBlock();
2329 
2330  // Write the offsets table for the preprocessing record.
2331  if (NumPreprocessingRecords > 0) {
2332  assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2333 
2334  // Write the offsets table for identifier IDs.
2335  using namespace llvm;
2336 
2337  auto *Abbrev = new BitCodeAbbrev();
2338  Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
2339  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
2340  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2341  unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2342 
2343  RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
2344  FirstPreprocessorEntityID -
2346  Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
2347  bytes(PreprocessedEntityOffsets));
2348  }
2349 }
2350 
2352  if (!Mod)
2353  return 0;
2354 
2355  llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
2356  if (Known != SubmoduleIDs.end())
2357  return Known->second;
2358 
2359  if (Mod->getTopLevelModule() != WritingModule)
2360  return 0;
2361 
2362  return SubmoduleIDs[Mod] = NextSubmoduleID++;
2363 }
2364 
2365 unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2366  // FIXME: This can easily happen, if we have a reference to a submodule that
2367  // did not result in us loading a module file for that submodule. For
2368  // instance, a cross-top-level-module 'conflict' declaration will hit this.
2369  unsigned ID = getLocalOrImportedSubmoduleID(Mod);
2370  assert((ID || !Mod) &&
2371  "asked for module ID for non-local, non-imported module");
2372  return ID;
2373 }
2374 
2375 /// \brief Compute the number of modules within the given tree (including the
2376 /// given module).
2377 static unsigned getNumberOfModules(Module *Mod) {
2378  unsigned ChildModules = 0;
2379  for (auto Sub = Mod->submodule_begin(), SubEnd = Mod->submodule_end();
2380  Sub != SubEnd; ++Sub)
2381  ChildModules += getNumberOfModules(*Sub);
2382 
2383  return ChildModules + 1;
2384 }
2385 
2386 void ASTWriter::WriteSubmodules(Module *WritingModule) {
2387  // Enter the submodule description block.
2388  Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
2389 
2390  // Write the abbreviations needed for the submodules block.
2391  using namespace llvm;
2392 
2393  auto *Abbrev = new BitCodeAbbrev();
2394  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
2395  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
2396  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
2397  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2398  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
2399  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2400  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
2401  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
2402  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
2403  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
2404  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
2405  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2406  unsigned DefinitionAbbrev = Stream.EmitAbbrev(Abbrev);
2407 
2408  Abbrev = new BitCodeAbbrev();
2409  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
2410  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2411  unsigned UmbrellaAbbrev = Stream.EmitAbbrev(Abbrev);
2412 
2413  Abbrev = new BitCodeAbbrev();
2414  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2415  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2416  unsigned HeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2417 
2418  Abbrev = new BitCodeAbbrev();
2419  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2420  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2421  unsigned TopHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2422 
2423  Abbrev = new BitCodeAbbrev();
2424  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2425  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2426  unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(Abbrev);
2427 
2428  Abbrev = new BitCodeAbbrev();
2429  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
2430  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2431  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
2432  unsigned RequiresAbbrev = Stream.EmitAbbrev(Abbrev);
2433 
2434  Abbrev = new BitCodeAbbrev();
2435  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2436  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2437  unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2438 
2439  Abbrev = new BitCodeAbbrev();
2440  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
2441  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2442  unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2443 
2444  Abbrev = new BitCodeAbbrev();
2445  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2446  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2447  unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2448 
2449  Abbrev = new BitCodeAbbrev();
2450  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
2451  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2452  unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2453 
2454  Abbrev = new BitCodeAbbrev();
2455  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2456  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2457  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2458  unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(Abbrev);
2459 
2460  Abbrev = new BitCodeAbbrev();
2461  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2462  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2463  unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(Abbrev);
2464 
2465  Abbrev = new BitCodeAbbrev();
2466  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2467  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
2468  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
2469  unsigned ConflictAbbrev = Stream.EmitAbbrev(Abbrev);
2470 
2471  // Write the submodule metadata block.
2472  RecordData::value_type Record[] = {getNumberOfModules(WritingModule),
2473  FirstSubmoduleID -
2475  Stream.EmitRecord(SUBMODULE_METADATA, Record);
2476 
2477  // Write all of the submodules.
2478  std::queue<Module *> Q;
2479  Q.push(WritingModule);
2480  while (!Q.empty()) {
2481  Module *Mod = Q.front();
2482  Q.pop();
2483  unsigned ID = getSubmoduleID(Mod);
2484 
2485  uint64_t ParentID = 0;
2486  if (Mod->Parent) {
2487  assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
2488  ParentID = SubmoduleIDs[Mod->Parent];
2489  }
2490 
2491  // Emit the definition of the block.
2492  {
2493  RecordData::value_type Record[] = {
2494  SUBMODULE_DEFINITION, ID, ParentID, Mod->IsFramework, Mod->IsExplicit,
2495  Mod->IsSystem, Mod->IsExternC, Mod->InferSubmodules,
2497  Mod->ConfigMacrosExhaustive};
2498  Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2499  }
2500 
2501  // Emit the requirements.
2502  for (const auto &R : Mod->Requirements) {
2503  RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.second};
2504  Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.first);
2505  }
2506 
2507  // Emit the umbrella header, if there is one.
2508  if (auto UmbrellaHeader = Mod->getUmbrellaHeader()) {
2509  RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
2510  Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2511  UmbrellaHeader.NameAsWritten);
2512  } else if (auto UmbrellaDir = Mod->getUmbrellaDir()) {
2513  RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
2514  Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
2515  UmbrellaDir.NameAsWritten);
2516  }
2517 
2518  // Emit the headers.
2519  struct {
2520  unsigned RecordKind;
2521  unsigned Abbrev;
2522  Module::HeaderKind HeaderKind;
2523  } HeaderLists[] = {
2524  {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
2525  {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
2526  {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
2527  {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
2529  {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
2530  };
2531  for (auto &HL : HeaderLists) {
2532  RecordData::value_type Record[] = {HL.RecordKind};
2533  for (auto &H : Mod->Headers[HL.HeaderKind])
2534  Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
2535  }
2536 
2537  // Emit the top headers.
2538  {
2539  auto TopHeaders = Mod->getTopHeaders(PP->getFileManager());
2540  RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
2541  for (auto *H : TopHeaders)
2542  Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, H->getName());
2543  }
2544 
2545  // Emit the imports.
2546  if (!Mod->Imports.empty()) {
2547  RecordData Record;
2548  for (auto *I : Mod->Imports)
2549  Record.push_back(getSubmoduleID(I));
2550  Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2551  }
2552 
2553  // Emit the exports.
2554  if (!Mod->Exports.empty()) {
2555  RecordData Record;
2556  for (const auto &E : Mod->Exports) {
2557  // FIXME: This may fail; we don't require that all exported modules
2558  // are local or imported.
2559  Record.push_back(getSubmoduleID(E.getPointer()));
2560  Record.push_back(E.getInt());
2561  }
2562  Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2563  }
2564 
2565  //FIXME: How do we emit the 'use'd modules? They may not be submodules.
2566  // Might be unnecessary as use declarations are only used to build the
2567  // module itself.
2568 
2569  // Emit the link libraries.
2570  for (const auto &LL : Mod->LinkLibraries) {
2571  RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
2572  LL.IsFramework};
2573  Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library);
2574  }
2575 
2576  // Emit the conflicts.
2577  for (const auto &C : Mod->Conflicts) {
2578  // FIXME: This may fail; we don't require that all conflicting modules
2579  // are local or imported.
2580  RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
2581  getSubmoduleID(C.Other)};
2582  Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message);
2583  }
2584 
2585  // Emit the configuration macros.
2586  for (const auto &CM : Mod->ConfigMacros) {
2587  RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
2588  Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM);
2589  }
2590 
2591  // Queue up the submodules of this module.
2592  for (auto *M : Mod->submodules())
2593  Q.push(M);
2594  }
2595 
2596  Stream.ExitBlock();
2597 
2598  assert((NextSubmoduleID - FirstSubmoduleID ==
2599  getNumberOfModules(WritingModule)) &&
2600  "Wrong # of submodules; found a reference to a non-local, "
2601  "non-imported submodule?");
2602 }
2603 
2606  if (Loc.isInvalid() || !WritingModule)
2607  return 0; // No submodule
2608 
2609  // Find the module that owns this location.
2610  ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
2611  Module *OwningMod
2613  if (!OwningMod)
2614  return 0;
2615 
2616  // Check whether this submodule is part of our own module.
2617  if (WritingModule != OwningMod && !OwningMod->isSubModuleOf(WritingModule))
2618  return 0;
2619 
2620  return getSubmoduleID(OwningMod);
2621 }
2622 
2623 void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
2624  bool isModule) {
2625  // Make sure set diagnostic pragmas don't affect the translation unit that
2626  // imports the module.
2627  // FIXME: Make diagnostic pragma sections work properly with modules.
2628  if (isModule)
2629  return;
2630 
2631  llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
2632  DiagStateIDMap;
2633  unsigned CurrID = 0;
2634  DiagStateIDMap[&Diag.DiagStates.front()] = ++CurrID; // the command-line one.
2635  RecordData Record;
2636  for (DiagnosticsEngine::DiagStatePointsTy::const_iterator
2637  I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end();
2638  I != E; ++I) {
2639  const DiagnosticsEngine::DiagStatePoint &point = *I;
2640  if (point.Loc.isInvalid())
2641  continue;
2642 
2643  Record.push_back(point.Loc.getRawEncoding());
2644  unsigned &DiagStateID = DiagStateIDMap[point.State];
2645  Record.push_back(DiagStateID);
2646 
2647  if (DiagStateID == 0) {
2648  DiagStateID = ++CurrID;
2649  for (const auto &I : *(point.State)) {
2650  if (I.second.isPragma()) {
2651  Record.push_back(I.first);
2652  Record.push_back((unsigned)I.second.getSeverity());
2653  }
2654  }
2655  Record.push_back(-1); // mark the end of the diag/map pairs for this
2656  // location.
2657  }
2658  }
2659 
2660  if (!Record.empty())
2661  Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
2662 }
2663 
2664 void ASTWriter::WriteCXXCtorInitializersOffsets() {
2665  if (CXXCtorInitializersOffsets.empty())
2666  return;
2667 
2668  // Create a blob abbreviation for the C++ ctor initializer offsets.
2669  using namespace llvm;
2670 
2671  auto *Abbrev = new BitCodeAbbrev();
2672  Abbrev->Add(BitCodeAbbrevOp(CXX_CTOR_INITIALIZERS_OFFSETS));
2673  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2674  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2675  unsigned CtorInitializersOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2676 
2677  // Write the base specifier offsets table.
2678  RecordData::value_type Record[] = {CXX_CTOR_INITIALIZERS_OFFSETS,
2679  CXXCtorInitializersOffsets.size()};
2680  Stream.EmitRecordWithBlob(CtorInitializersOffsetAbbrev, Record,
2681  bytes(CXXCtorInitializersOffsets));
2682 }
2683 
2684 void ASTWriter::WriteCXXBaseSpecifiersOffsets() {
2685  if (CXXBaseSpecifiersOffsets.empty())
2686  return;
2687 
2688  // Create a blob abbreviation for the C++ base specifiers offsets.
2689  using namespace llvm;
2690 
2691  auto *Abbrev = new BitCodeAbbrev();
2692  Abbrev->Add(BitCodeAbbrevOp(CXX_BASE_SPECIFIER_OFFSETS));
2693  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2694  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2695  unsigned BaseSpecifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2696 
2697  // Write the base specifier offsets table.
2698  RecordData::value_type Record[] = {CXX_BASE_SPECIFIER_OFFSETS,
2699  CXXBaseSpecifiersOffsets.size()};
2700  Stream.EmitRecordWithBlob(BaseSpecifierOffsetAbbrev, Record,
2701  bytes(CXXBaseSpecifiersOffsets));
2702 }
2703 
2704 //===----------------------------------------------------------------------===//
2705 // Type Serialization
2706 //===----------------------------------------------------------------------===//
2707 
2708 /// \brief Write the representation of a type to the AST stream.
2709 void ASTWriter::WriteType(QualType T) {
2710  TypeIdx &Idx = TypeIdxs[T];
2711  if (Idx.getIndex() == 0) // we haven't seen this type before.
2712  Idx = TypeIdx(NextTypeID++);
2713 
2714  assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
2715 
2716  // Record the offset for this type.
2717  unsigned Index = Idx.getIndex() - FirstTypeID;
2718  if (TypeOffsets.size() == Index)
2719  TypeOffsets.push_back(Stream.GetCurrentBitNo());
2720  else if (TypeOffsets.size() < Index) {
2721  TypeOffsets.resize(Index + 1);
2722  TypeOffsets[Index] = Stream.GetCurrentBitNo();
2723  }
2724 
2725  RecordData Record;
2726 
2727  // Emit the type's representation.
2728  ASTTypeWriter W(*this, Record);
2729  W.AbbrevToUse = 0;
2730 
2731  if (T.hasLocalNonFastQualifiers()) {
2732  Qualifiers Qs = T.getLocalQualifiers();
2733  AddTypeRef(T.getLocalUnqualifiedType(), Record);
2734  Record.push_back(Qs.getAsOpaqueValue());
2735  W.Code = TYPE_EXT_QUAL;
2736  W.AbbrevToUse = TypeExtQualAbbrev;
2737  } else {
2738  switch (T->getTypeClass()) {
2739  // For all of the concrete, non-dependent types, call the
2740  // appropriate visitor function.
2741 #define TYPE(Class, Base) \
2742  case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
2743 #define ABSTRACT_TYPE(Class, Base)
2744 #include "clang/AST/TypeNodes.def"
2745  }
2746  }
2747 
2748  // Emit the serialized record.
2749  Stream.EmitRecord(W.Code, Record, W.AbbrevToUse);
2750 
2751  // Flush any expressions that were written as part of this type.
2752  FlushStmts();
2753 }
2754 
2755 //===----------------------------------------------------------------------===//
2756 // Declaration Serialization
2757 //===----------------------------------------------------------------------===//
2758 
2759 /// \brief Write the block containing all of the declaration IDs
2760 /// lexically declared within the given DeclContext.
2761 ///
2762 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
2763 /// bistream, or 0 if no block was written.
2764 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
2765  DeclContext *DC) {
2766  if (DC->decls_empty())
2767  return 0;
2768 
2769  uint64_t Offset = Stream.GetCurrentBitNo();
2770  SmallVector<uint32_t, 128> KindDeclPairs;
2771  for (const auto *D : DC->decls()) {
2772  KindDeclPairs.push_back(D->getKind());
2773  KindDeclPairs.push_back(GetDeclRef(D));
2774  }
2775 
2776  ++NumLexicalDeclContexts;
2777  RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
2778  Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
2779  bytes(KindDeclPairs));
2780  return Offset;
2781 }
2782 
2783 void ASTWriter::WriteTypeDeclOffsets() {
2784  using namespace llvm;
2785 
2786  // Write the type offsets array
2787  auto *Abbrev = new BitCodeAbbrev();
2788  Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
2789  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
2790  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
2791  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
2792  unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2793  {
2794  RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(),
2795  FirstTypeID - NUM_PREDEF_TYPE_IDS};
2796  Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
2797  }
2798 
2799  // Write the declaration offsets array
2800  Abbrev = new BitCodeAbbrev();
2801  Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
2802  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
2803  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
2804  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
2805  unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2806  {
2807  RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(),
2808  FirstDeclID - NUM_PREDEF_DECL_IDS};
2809  Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
2810  }
2811 }
2812 
2813 void ASTWriter::WriteFileDeclIDsMap() {
2814  using namespace llvm;
2815 
2817  FileDeclIDs.begin(), FileDeclIDs.end());
2818  std::sort(SortedFileDeclIDs.begin(), SortedFileDeclIDs.end(),
2819  llvm::less_first());
2820 
2821  // Join the vectors of DeclIDs from all files.
2822  SmallVector<DeclID, 256> FileGroupedDeclIDs;
2823  for (auto &FileDeclEntry : SortedFileDeclIDs) {
2824  DeclIDInFileInfo &Info = *FileDeclEntry.second;
2825  Info.FirstDeclIndex = FileGroupedDeclIDs.size();
2826  for (auto &LocDeclEntry : Info.DeclIDs)
2827  FileGroupedDeclIDs.push_back(LocDeclEntry.second);
2828  }
2829 
2830  auto *Abbrev = new BitCodeAbbrev();
2831  Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
2832  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2833  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2834  unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
2835  RecordData::value_type Record[] = {FILE_SORTED_DECLS,
2836  FileGroupedDeclIDs.size()};
2837  Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
2838 }
2839 
2840 void ASTWriter::WriteComments() {
2841  Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
2842  ArrayRef<RawComment *> RawComments = Context->Comments.getComments();
2843  RecordData Record;
2844  for (const auto *I : RawComments) {
2845  Record.clear();
2846  AddSourceRange(I->getSourceRange(), Record);
2847  Record.push_back(I->getKind());
2848  Record.push_back(I->isTrailingComment());
2849  Record.push_back(I->isAlmostTrailingComment());
2850  Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
2851  }
2852  Stream.ExitBlock();
2853 }
2854 
2855 //===----------------------------------------------------------------------===//
2856 // Global Method Pool and Selector Serialization
2857 //===----------------------------------------------------------------------===//
2858 
2859 namespace {
2860 // Trait used for the on-disk hash table used in the method pool.
2861 class ASTMethodPoolTrait {
2862  ASTWriter &Writer;
2863 
2864 public:
2865  typedef Selector key_type;
2866  typedef key_type key_type_ref;
2867 
2868  struct data_type {
2869  SelectorID ID;
2870  ObjCMethodList Instance, Factory;
2871  };
2872  typedef const data_type& data_type_ref;
2873 
2874  typedef unsigned hash_value_type;
2875  typedef unsigned offset_type;
2876 
2877  explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { }
2878 
2879  static hash_value_type ComputeHash(Selector Sel) {
2880  return serialization::ComputeHash(Sel);
2881  }
2882 
2883  std::pair<unsigned,unsigned>
2884  EmitKeyDataLength(raw_ostream& Out, Selector Sel,
2885  data_type_ref Methods) {
2886  using namespace llvm::support;
2887  endian::Writer<little> LE(Out);
2888  unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
2889  LE.write<uint16_t>(KeyLen);
2890  unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
2891  for (const ObjCMethodList *Method = &Methods.Instance; Method;
2892  Method = Method->getNext())
2893  if (Method->getMethod())
2894  DataLen += 4;
2895  for (const ObjCMethodList *Method = &Methods.Factory; Method;
2896  Method = Method->getNext())
2897  if (Method->getMethod())
2898  DataLen += 4;
2899  LE.write<uint16_t>(DataLen);
2900  return std::make_pair(KeyLen, DataLen);
2901  }
2902 
2903  void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
2904  using namespace llvm::support;
2905  endian::Writer<little> LE(Out);
2906  uint64_t Start = Out.tell();
2907  assert((Start >> 32) == 0 && "Selector key offset too large");
2908  Writer.SetSelectorOffset(Sel, Start);
2909  unsigned N = Sel.getNumArgs();
2910  LE.write<uint16_t>(N);
2911  if (N == 0)
2912  N = 1;
2913  for (unsigned I = 0; I != N; ++I)
2914  LE.write<uint32_t>(
2915  Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
2916  }
2917 
2918  void EmitData(raw_ostream& Out, key_type_ref,
2919  data_type_ref Methods, unsigned DataLen) {
2920  using namespace llvm::support;
2921  endian::Writer<little> LE(Out);
2922  uint64_t Start = Out.tell(); (void)Start;
2923  LE.write<uint32_t>(Methods.ID);
2924  unsigned NumInstanceMethods = 0;
2925  for (const ObjCMethodList *Method = &Methods.Instance; Method;
2926  Method = Method->getNext())
2927  if (Method->getMethod())
2928  ++NumInstanceMethods;
2929 
2930  unsigned NumFactoryMethods = 0;
2931  for (const ObjCMethodList *Method = &Methods.Factory; Method;
2932  Method = Method->getNext())
2933  if (Method->getMethod())
2934  ++NumFactoryMethods;
2935 
2936  unsigned InstanceBits = Methods.Instance.getBits();
2937  assert(InstanceBits < 4);
2938  unsigned InstanceHasMoreThanOneDeclBit =
2939  Methods.Instance.hasMoreThanOneDecl();
2940  unsigned FullInstanceBits = (NumInstanceMethods << 3) |
2941  (InstanceHasMoreThanOneDeclBit << 2) |
2942  InstanceBits;
2943  unsigned FactoryBits = Methods.Factory.getBits();
2944  assert(FactoryBits < 4);
2945  unsigned FactoryHasMoreThanOneDeclBit =
2946  Methods.Factory.hasMoreThanOneDecl();
2947  unsigned FullFactoryBits = (NumFactoryMethods << 3) |
2948  (FactoryHasMoreThanOneDeclBit << 2) |
2949  FactoryBits;
2950  LE.write<uint16_t>(FullInstanceBits);
2951  LE.write<uint16_t>(FullFactoryBits);
2952  for (const ObjCMethodList *Method = &Methods.Instance; Method;
2953  Method = Method->getNext())
2954  if (Method->getMethod())
2955  LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
2956  for (const ObjCMethodList *Method = &Methods.Factory; Method;
2957  Method = Method->getNext())
2958  if (Method->getMethod())
2959  LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
2960 
2961  assert(Out.tell() - Start == DataLen && "Data length is wrong");
2962  }
2963 };
2964 } // end anonymous namespace
2965 
2966 /// \brief Write ObjC data: selectors and the method pool.
2967 ///
2968 /// The method pool contains both instance and factory methods, stored
2969 /// in an on-disk hash table indexed by the selector. The hash table also
2970 /// contains an empty entry for every other selector known to Sema.
2971 void ASTWriter::WriteSelectors(Sema &SemaRef) {
2972  using namespace llvm;
2973 
2974  // Do we have to do anything at all?
2975  if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
2976  return;
2977  unsigned NumTableEntries = 0;
2978  // Create and write out the blob that contains selectors and the method pool.
2979  {
2980  llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
2981  ASTMethodPoolTrait Trait(*this);
2982 
2983  // Create the on-disk hash table representation. We walk through every
2984  // selector we've seen and look it up in the method pool.
2985  SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
2986  for (auto &SelectorAndID : SelectorIDs) {
2987  Selector S = SelectorAndID.first;
2988  SelectorID ID = SelectorAndID.second;
2989  Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
2990  ASTMethodPoolTrait::data_type Data = {
2991  ID,
2992  ObjCMethodList(),
2993  ObjCMethodList()
2994  };
2995  if (F != SemaRef.MethodPool.end()) {
2996  Data.Instance = F->second.first;
2997  Data.Factory = F->second.second;
2998  }
2999  // Only write this selector if it's not in an existing AST or something
3000  // changed.
3001  if (Chain && ID < FirstSelectorID) {
3002  // Selector already exists. Did it change?
3003  bool changed = false;
3004  for (ObjCMethodList *M = &Data.Instance;
3005  !changed && M && M->getMethod(); M = M->getNext()) {
3006  if (!M->getMethod()->isFromASTFile())
3007  changed = true;
3008  }
3009  for (ObjCMethodList *M = &Data.Factory; !changed && M && M->getMethod();
3010  M = M->getNext()) {
3011  if (!M->getMethod()->isFromASTFile())
3012  changed = true;
3013  }
3014  if (!changed)
3015  continue;
3016  } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
3017  // A new method pool entry.
3018  ++NumTableEntries;
3019  }
3020  Generator.insert(S, Data, Trait);
3021  }
3022 
3023  // Create the on-disk hash table in a buffer.
3024  SmallString<4096> MethodPool;
3025  uint32_t BucketOffset;
3026  {
3027  using namespace llvm::support;
3028  ASTMethodPoolTrait Trait(*this);
3029  llvm::raw_svector_ostream Out(MethodPool);
3030  // Make sure that no bucket is at offset 0
3031  endian::Writer<little>(Out).write<uint32_t>(0);
3032  BucketOffset = Generator.Emit(Out, Trait);
3033  }
3034 
3035  // Create a blob abbreviation
3036  auto *Abbrev = new BitCodeAbbrev();
3037  Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
3038  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3039  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3040  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3041  unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
3042 
3043  // Write the method pool
3044  {
3045  RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3046  NumTableEntries};
3047  Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3048  }
3049 
3050  // Create a blob abbreviation for the selector table offsets.
3051  Abbrev = new BitCodeAbbrev();
3052  Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
3053  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
3054  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3055  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3056  unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
3057 
3058  // Write the selector offsets table.
3059  {
3060  RecordData::value_type Record[] = {
3061  SELECTOR_OFFSETS, SelectorOffsets.size(),
3062  FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3063  Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3064  bytes(SelectorOffsets));
3065  }
3066  }
3067 }
3068 
3069 /// \brief Write the selectors referenced in @selector expression into AST file.
3070 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
3071  using namespace llvm;
3072  if (SemaRef.ReferencedSelectors.empty())
3073  return;
3074 
3075  RecordData Record;
3076 
3077  // Note: this writes out all references even for a dependent AST. But it is
3078  // very tricky to fix, and given that @selector shouldn't really appear in
3079  // headers, probably not worth it. It's not a correctness issue.
3080  for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
3081  Selector Sel = SelectorAndLocation.first;
3082  SourceLocation Loc = SelectorAndLocation.second;
3083  AddSelectorRef(Sel, Record);
3084  AddSourceLocation(Loc, Record);
3085  }
3086  Stream.EmitRecord(REFERENCED_SELECTOR_POOL, Record);
3087 }
3088 
3089 //===----------------------------------------------------------------------===//
3090 // Identifier Table Serialization
3091 //===----------------------------------------------------------------------===//
3092 
3093 /// Determine the declaration that should be put into the name lookup table to
3094 /// represent the given declaration in this module. This is usually D itself,
3095 /// but if D was imported and merged into a local declaration, we want the most
3096 /// recent local declaration instead. The chosen declaration will be the most
3097 /// recent declaration in any module that imports this one.
3099  NamedDecl *D) {
3100  if (!LangOpts.Modules || !D->isFromASTFile())
3101  return D;
3102 
3103  if (Decl *Redecl = D->getPreviousDecl()) {
3104  // For Redeclarable decls, a prior declaration might be local.
3105  for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
3106  if (!Redecl->isFromASTFile())
3107  return cast<NamedDecl>(Redecl);
3108  // If we find a decl from a (chained-)PCH stop since we won't find a
3109  // local one.
3110  if (D->getOwningModuleID() == 0)
3111  break;
3112  }
3113  } else if (Decl *First = D->getCanonicalDecl()) {
3114  // For Mergeable decls, the first decl might be local.
3115  if (!First->isFromASTFile())
3116  return cast<NamedDecl>(First);
3117  }
3118 
3119  // All declarations are imported. Our most recent declaration will also be
3120  // the most recent one in anyone who imports us.
3121  return D;
3122 }
3123 
3124 namespace {
3125 class ASTIdentifierTableTrait {
3126  ASTWriter &Writer;
3127  Preprocessor &PP;
3128  IdentifierResolver &IdResolver;
3129  bool IsModule;
3130  bool NeedDecls;
3131  ASTWriter::RecordData *InterestingIdentifierOffsets;
3132 
3133  /// \brief Determines whether this is an "interesting" identifier that needs a
3134  /// full IdentifierInfo structure written into the hash table. Notably, this
3135  /// doesn't check whether the name has macros defined; use PublicMacroIterator
3136  /// to check that.
3137  bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
3138  if (MacroOffset ||
3139  II->isPoisoned() ||
3140  (IsModule ? II->hasRevertedBuiltin() : II->getObjCOrBuiltinID()) ||
3142  (NeedDecls && II->getFETokenInfo<void>()))
3143  return true;
3144 
3145  return false;
3146  }
3147 
3148 public:
3149  typedef IdentifierInfo* key_type;
3150  typedef key_type key_type_ref;
3151 
3152  typedef IdentID data_type;
3153  typedef data_type data_type_ref;
3154 
3155  typedef unsigned hash_value_type;
3156  typedef unsigned offset_type;
3157 
3158  ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
3159  IdentifierResolver &IdResolver, bool IsModule,
3160  ASTWriter::RecordData *InterestingIdentifierOffsets)
3161  : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
3162  NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3163  InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
3164 
3165  static hash_value_type ComputeHash(const IdentifierInfo* II) {
3166  return llvm::HashString(II->getName());
3167  }
3168 
3169  bool isInterestingIdentifier(const IdentifierInfo *II) {
3170  auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3171  return isInterestingIdentifier(II, MacroOffset);
3172  }
3173  bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) {
3174  return isInterestingIdentifier(II, 0);
3175  }
3176 
3177  std::pair<unsigned,unsigned>
3178  EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
3179  unsigned KeyLen = II->getLength() + 1;
3180  unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
3181  auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3182  if (isInterestingIdentifier(II, MacroOffset)) {
3183  DataLen += 2; // 2 bytes for builtin ID
3184  DataLen += 2; // 2 bytes for flags
3185  if (MacroOffset)
3186  DataLen += 4; // MacroDirectives offset.
3187 
3188  if (NeedDecls) {
3189  for (IdentifierResolver::iterator D = IdResolver.begin(II),
3190  DEnd = IdResolver.end();
3191  D != DEnd; ++D)
3192  DataLen += 4;
3193  }
3194  }
3195  using namespace llvm::support;
3196  endian::Writer<little> LE(Out);
3197 
3198  assert((uint16_t)DataLen == DataLen && (uint16_t)KeyLen == KeyLen);
3199  LE.write<uint16_t>(DataLen);
3200  // We emit the key length after the data length so that every
3201  // string is preceded by a 16-bit length. This matches the PTH
3202  // format for storing identifiers.
3203  LE.write<uint16_t>(KeyLen);
3204  return std::make_pair(KeyLen, DataLen);
3205  }
3206 
3207  void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
3208  unsigned KeyLen) {
3209  // Record the location of the key data. This is used when generating
3210  // the mapping from persistent IDs to strings.
3211  Writer.SetIdentifierOffset(II, Out.tell());
3212 
3213  // Emit the offset of the key/data length information to the interesting
3214  // identifiers table if necessary.
3215  if (InterestingIdentifierOffsets && isInterestingIdentifier(II))
3216  InterestingIdentifierOffsets->push_back(Out.tell() - 4);
3217 
3218  Out.write(II->getNameStart(), KeyLen);
3219  }
3220 
3221  void EmitData(raw_ostream& Out, IdentifierInfo* II,
3222  IdentID ID, unsigned) {
3223  using namespace llvm::support;
3224  endian::Writer<little> LE(Out);
3225 
3226  auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3227  if (!isInterestingIdentifier(II, MacroOffset)) {
3228  LE.write<uint32_t>(ID << 1);
3229  return;
3230  }
3231 
3232  LE.write<uint32_t>((ID << 1) | 0x01);
3233  uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3234  assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
3235  LE.write<uint16_t>(Bits);
3236  Bits = 0;
3237  bool HadMacroDefinition = MacroOffset != 0;
3238  Bits = (Bits << 1) | unsigned(HadMacroDefinition);
3239  Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3240  Bits = (Bits << 1) | unsigned(II->isPoisoned());
3241  Bits = (Bits << 1) | unsigned(II->hasRevertedBuiltin());
3242  Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
3243  Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
3244  LE.write<uint16_t>(Bits);
3245 
3246  if (HadMacroDefinition)
3247  LE.write<uint32_t>(MacroOffset);
3248 
3249  if (NeedDecls) {
3250  // Emit the declaration IDs in reverse order, because the
3251  // IdentifierResolver provides the declarations as they would be
3252  // visible (e.g., the function "stat" would come before the struct
3253  // "stat"), but the ASTReader adds declarations to the end of the list
3254  // (so we need to see the struct "stat" before the function "stat").
3255  // Only emit declarations that aren't from a chained PCH, though.
3256  SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II),
3257  IdResolver.end());
3258  for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(),
3259  DEnd = Decls.rend();
3260  D != DEnd; ++D)
3261  LE.write<uint32_t>(
3262  Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D)));
3263  }
3264  }
3265 };
3266 } // end anonymous namespace
3267 
3268 /// \brief Write the identifier table into the AST file.
3269 ///
3270 /// The identifier table consists of a blob containing string data
3271 /// (the actual identifiers themselves) and a separate "offsets" index
3272 /// that maps identifier IDs to locations within the blob.
3273 void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3274  IdentifierResolver &IdResolver,
3275  bool IsModule) {
3276  using namespace llvm;
3277 
3278  RecordData InterestingIdents;
3279 
3280  // Create and write out the blob that contains the identifier
3281  // strings.
3282  {
3283  llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
3284  ASTIdentifierTableTrait Trait(
3285  *this, PP, IdResolver, IsModule,
3286  (getLangOpts().CPlusPlus && IsModule) ? &InterestingIdents : nullptr);
3287 
3288  // Look for any identifiers that were named while processing the
3289  // headers, but are otherwise not needed. We add these to the hash
3290  // table to enable checking of the predefines buffer in the case
3291  // where the user adds new macro definitions when building the AST
3292  // file.
3294  for (const auto &ID : PP.getIdentifierTable())
3295  IIs.push_back(ID.second);
3296  // Sort the identifiers lexicographically before getting them references so
3297  // that their order is stable.
3298  std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
3299  for (const IdentifierInfo *II : IIs)
3300  if (Trait.isInterestingNonMacroIdentifier(II))
3301  getIdentifierRef(II);
3302 
3303  // Create the on-disk hash table representation. We only store offsets
3304  // for identifiers that appear here for the first time.
3305  IdentifierOffsets.resize(NextIdentID - FirstIdentID);
3306  for (auto IdentIDPair : IdentifierIDs) {
3307  auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
3308  IdentID ID = IdentIDPair.second;
3309  assert(II && "NULL identifier in identifier table");
3310  if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
3311  Generator.insert(II, ID, Trait);
3312  }
3313 
3314  // Create the on-disk hash table in a buffer.
3316  uint32_t BucketOffset;
3317  {
3318  using namespace llvm::support;
3319  llvm::raw_svector_ostream Out(IdentifierTable);
3320  // Make sure that no bucket is at offset 0
3321  endian::Writer<little>(Out).write<uint32_t>(0);
3322  BucketOffset = Generator.Emit(Out, Trait);
3323  }
3324 
3325  // Create a blob abbreviation
3326  auto *Abbrev = new BitCodeAbbrev();
3327  Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
3328  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3329  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3330  unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
3331 
3332  // Write the identifier table
3333  RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
3334  Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
3335  }
3336 
3337  // Write the offsets table for identifier IDs.
3338  auto *Abbrev = new BitCodeAbbrev();
3339  Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
3340  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
3341  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3342  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3343  unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
3344 
3345 #ifndef NDEBUG
3346  for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3347  assert(IdentifierOffsets[I] && "Missing identifier offset?");
3348 #endif
3349 
3350  RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
3351  IdentifierOffsets.size(),
3352  FirstIdentID - NUM_PREDEF_IDENT_IDS};
3353  Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
3354  bytes(IdentifierOffsets));
3355 
3356  // In C++, write the list of interesting identifiers (those that are
3357  // defined as macros, poisoned, or similar unusual things).
3358  if (!InterestingIdents.empty())
3359  Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
3360 }
3361 
3362 //===----------------------------------------------------------------------===//
3363 // DeclContext's Name Lookup Table Serialization
3364 //===----------------------------------------------------------------------===//
3365 
3366 namespace {
3367 // Trait used for the on-disk hash table used in the method pool.
3368 class ASTDeclContextNameLookupTrait {
3369  ASTWriter &Writer;
3371 
3372 public:
3373  typedef DeclarationNameKey key_type;
3374  typedef key_type key_type_ref;
3375 
3376  /// A start and end index into DeclIDs, representing a sequence of decls.
3377  typedef std::pair<unsigned, unsigned> data_type;
3378  typedef const data_type& data_type_ref;
3379 
3380  typedef unsigned hash_value_type;
3381  typedef unsigned offset_type;
3382 
3383  explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { }
3384 
3385  template<typename Coll>
3386  data_type getData(const Coll &Decls) {
3387  unsigned Start = DeclIDs.size();
3388  for (NamedDecl *D : Decls) {
3389  DeclIDs.push_back(
3390  Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3391  }
3392  return std::make_pair(Start, DeclIDs.size());
3393  }
3394 
3395  data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
3396  unsigned Start = DeclIDs.size();
3397  for (auto ID : FromReader)
3398  DeclIDs.push_back(ID);
3399  return std::make_pair(Start, DeclIDs.size());
3400  }
3401 
3402  static bool EqualKey(key_type_ref a, key_type_ref b) {
3403  return a == b;
3404  }
3405 
3406  hash_value_type ComputeHash(DeclarationNameKey Name) {
3407  return Name.getHash();
3408  }
3409 
3410  void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
3411  assert(Writer.hasChain() &&
3412  "have reference to loaded module file but no chain?");
3413 
3414  using namespace llvm::support;
3415  endian::Writer<little>(Out)
3416  .write<uint32_t>(Writer.getChain()->getModuleFileID(F));
3417  }
3418 
3419  std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
3420  DeclarationNameKey Name,
3421  data_type_ref Lookup) {
3422  using namespace llvm::support;
3423  endian::Writer<little> LE(Out);
3424  unsigned KeyLen = 1;
3425  switch (Name.getKind()) {
3431  KeyLen += 4;
3432  break;
3434  KeyLen += 1;
3435  break;
3440  break;
3441  }
3442  LE.write<uint16_t>(KeyLen);
3443 
3444  // 4 bytes for each DeclID.
3445  unsigned DataLen = 4 * (Lookup.second - Lookup.first);
3446  assert(uint16_t(DataLen) == DataLen &&
3447  "too many decls for serialized lookup result");
3448  LE.write<uint16_t>(DataLen);
3449 
3450  return std::make_pair(KeyLen, DataLen);
3451  }
3452 
3453  void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
3454  using namespace llvm::support;
3455  endian::Writer<little> LE(Out);
3456  LE.write<uint8_t>(Name.getKind());
3457  switch (Name.getKind()) {
3460  LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier()));
3461  return;
3465  LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
3466  return;
3468  assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
3469  "Invalid operator?");
3470  LE.write<uint8_t>(Name.getOperatorKind());
3471  return;
3476  return;
3477  }
3478 
3479  llvm_unreachable("Invalid name kind?");
3480  }
3481 
3482  void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
3483  unsigned DataLen) {
3484  using namespace llvm::support;
3485  endian::Writer<little> LE(Out);
3486  uint64_t Start = Out.tell(); (void)Start;
3487  for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
3488  LE.write<uint32_t>(DeclIDs[I]);
3489  assert(Out.tell() - Start == DataLen && "Data length is wrong");
3490  }
3491 };
3492 } // end anonymous namespace
3493 
3494 bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
3495  DeclContext *DC) {
3496  return Result.hasExternalDecls() && DC->NeedToReconcileExternalVisibleStorage;
3497 }
3498 
3499 bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
3500  DeclContext *DC) {
3501  for (auto *D : Result.getLookupResult())
3502  if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
3503  return false;
3504 
3505  return true;
3506 }
3507 
3508 void
3509 ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
3510  llvm::SmallVectorImpl<char> &LookupTable) {
3511  assert(!ConstDC->HasLazyLocalLexicalLookups &&
3512  !ConstDC->HasLazyExternalLexicalLookups &&
3513  "must call buildLookups first");
3514 
3515  // FIXME: We need to build the lookups table, which is logically const.
3516  auto *DC = const_cast<DeclContext*>(ConstDC);
3517  assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
3518 
3519  // Create the on-disk hash table representation.
3521  ASTDeclContextNameLookupTrait> Generator;
3522  ASTDeclContextNameLookupTrait Trait(*this);
3523 
3524  // The first step is to collect the declaration names which we need to
3525  // serialize into the name lookup table, and to collect them in a stable
3526  // order.
3528 
3529  // We also build up small sets of the constructor and conversion function
3530  // names which are visible.
3531  llvm::SmallSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
3532 
3533  for (auto &Lookup : *DC->buildLookup()) {
3534  auto &Name = Lookup.first;
3535  auto &Result = Lookup.second;
3536 
3537  // If there are no local declarations in our lookup result, we
3538  // don't need to write an entry for the name at all. If we can't
3539  // write out a lookup set without performing more deserialization,
3540  // just skip this entry.
3541  if (isLookupResultExternal(Result, DC) &&
3542  isLookupResultEntirelyExternal(Result, DC))
3543  continue;
3544 
3545  // We also skip empty results. If any of the results could be external and
3546  // the currently available results are empty, then all of the results are
3547  // external and we skip it above. So the only way we get here with an empty
3548  // results is when no results could have been external *and* we have
3549  // external results.
3550  //
3551  // FIXME: While we might want to start emitting on-disk entries for negative
3552  // lookups into a decl context as an optimization, today we *have* to skip
3553  // them because there are names with empty lookup results in decl contexts
3554  // which we can't emit in any stable ordering: we lookup constructors and
3555  // conversion functions in the enclosing namespace scope creating empty
3556  // results for them. This in almost certainly a bug in Clang's name lookup,
3557  // but that is likely to be hard or impossible to fix and so we tolerate it
3558  // here by omitting lookups with empty results.
3559  if (Lookup.second.getLookupResult().empty())
3560  continue;
3561 
3562  switch (Lookup.first.getNameKind()) {
3563  default:
3564  Names.push_back(Lookup.first);
3565  break;
3566 
3568  assert(isa<CXXRecordDecl>(DC) &&
3569  "Cannot have a constructor name outside of a class!");
3570  ConstructorNameSet.insert(Name);
3571  break;
3572 
3574  assert(isa<CXXRecordDecl>(DC) &&
3575  "Cannot have a conversion function name outside of a class!");
3576  ConversionNameSet.insert(Name);
3577  break;
3578  }
3579  }
3580 
3581  // Sort the names into a stable order.
3582  std::sort(Names.begin(), Names.end());
3583 
3584  if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
3585  // We need to establish an ordering of constructor and conversion function
3586  // names, and they don't have an intrinsic ordering.
3587 
3588  // First we try the easy case by forming the current context's constructor
3589  // name and adding that name first. This is a very useful optimization to
3590  // avoid walking the lexical declarations in many cases, and it also
3591  // handles the only case where a constructor name can come from some other
3592  // lexical context -- when that name is an implicit constructor merged from
3593  // another declaration in the redecl chain. Any non-implicit constructor or
3594  // conversion function which doesn't occur in all the lexical contexts
3595  // would be an ODR violation.
3596  auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
3597  Context->getCanonicalType(Context->getRecordType(D)));
3598  if (ConstructorNameSet.erase(ImplicitCtorName))
3599  Names.push_back(ImplicitCtorName);
3600 
3601  // If we still have constructors or conversion functions, we walk all the
3602  // names in the decl and add the constructors and conversion functions
3603  // which are visible in the order they lexically occur within the context.
3604  if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
3605  for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
3606  if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
3607  auto Name = ChildND->getDeclName();
3608  switch (Name.getNameKind()) {
3609  default:
3610  continue;
3611 
3613  if (ConstructorNameSet.erase(Name))
3614  Names.push_back(Name);
3615  break;
3616 
3618  if (ConversionNameSet.erase(Name))
3619  Names.push_back(Name);
3620  break;
3621  }
3622 
3623  if (ConstructorNameSet.empty() && ConversionNameSet.empty())
3624  break;
3625  }
3626 
3627  assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
3628  "constructors by walking all the "
3629  "lexical members of the context.");
3630  assert(ConversionNameSet.empty() && "Failed to find all of the visible "
3631  "conversion functions by walking all "
3632  "the lexical members of the context.");
3633  }
3634 
3635  // Next we need to do a lookup with each name into this decl context to fully
3636  // populate any results from external sources. We don't actually use the
3637  // results of these lookups because we only want to use the results after all
3638  // results have been loaded and the pointers into them will be stable.
3639  for (auto &Name : Names)
3640  DC->lookup(Name);
3641 
3642  // Now we need to insert the results for each name into the hash table. For
3643  // constructor names and conversion function names, we actually need to merge
3644  // all of the results for them into one list of results each and insert
3645  // those.
3646  SmallVector<NamedDecl *, 8> ConstructorDecls;
3647  SmallVector<NamedDecl *, 8> ConversionDecls;
3648 
3649  // Now loop over the names, either inserting them or appending for the two
3650  // special cases.
3651  for (auto &Name : Names) {
3652  DeclContext::lookup_result Result = DC->noload_lookup(Name);
3653 
3654  switch (Name.getNameKind()) {
3655  default:
3656  Generator.insert(Name, Trait.getData(Result), Trait);
3657  break;
3658 
3660  ConstructorDecls.append(Result.begin(), Result.end());
3661  break;
3662 
3664  ConversionDecls.append(Result.begin(), Result.end());
3665  break;
3666  }
3667  }
3668 
3669  // Handle our two special cases if we ended up having any. We arbitrarily use
3670  // the first declaration's name here because the name itself isn't part of
3671  // the key, only the kind of name is used.
3672  if (!ConstructorDecls.empty())
3673  Generator.insert(ConstructorDecls.front()->getDeclName(),
3674  Trait.getData(ConstructorDecls), Trait);
3675  if (!ConversionDecls.empty())
3676  Generator.insert(ConversionDecls.front()->getDeclName(),
3677  Trait.getData(ConversionDecls), Trait);
3678 
3679  // Create the on-disk hash table. Also emit the existing imported and
3680  // merged table if there is one.
3681  auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr;
3682  Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr);
3683 }
3684 
3685 /// \brief Write the block containing all of the declaration IDs
3686 /// visible from the given DeclContext.
3687 ///
3688 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
3689 /// bitstream, or 0 if no block was written.
3690 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
3691  DeclContext *DC) {
3692  // If we imported a key declaration of this namespace, write the visible
3693  // lookup results as an update record for it rather than including them
3694  // on this declaration. We will only look at key declarations on reload.
3695  if (isa<NamespaceDecl>(DC) && Chain &&
3696  Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) {
3697  // Only do this once, for the first local declaration of the namespace.
3698  for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
3699  Prev = Prev->getPreviousDecl())
3700  if (!Prev->isFromASTFile())
3701  return 0;
3702 
3703  // Note that we need to emit an update record for the primary context.
3704  UpdatedDeclContexts.insert(DC->getPrimaryContext());
3705 
3706  // Make sure all visible decls are written. They will be recorded later. We
3707  // do this using a side data structure so we can sort the names into
3708  // a deterministic order.
3711  LookupResults;
3712  if (Map) {
3713  LookupResults.reserve(Map->size());
3714  for (auto &Entry : *Map)
3715  LookupResults.push_back(
3716  std::make_pair(Entry.first, Entry.second.getLookupResult()));
3717  }
3718 
3719  std::sort(LookupResults.begin(), LookupResults.end(), llvm::less_first());
3720  for (auto &NameAndResult : LookupResults) {
3721  DeclarationName Name = NameAndResult.first;
3722  DeclContext::lookup_result Result = NameAndResult.second;
3725  // We have to work around a name lookup bug here where negative lookup
3726  // results for these names get cached in namespace lookup tables (these
3727  // names should never be looked up in a namespace).
3728  assert(Result.empty() && "Cannot have a constructor or conversion "
3729  "function name in a namespace!");
3730  continue;
3731  }
3732 
3733  for (NamedDecl *ND : Result)
3734  if (!ND->isFromASTFile())
3735  GetDeclRef(ND);
3736  }
3737 
3738  return 0;
3739  }
3740 
3741  if (DC->getPrimaryContext() != DC)
3742  return 0;
3743 
3744  // Skip contexts which don't support name lookup.
3745  if (!DC->isLookupContext())
3746  return 0;
3747 
3748  // If not in C++, we perform name lookup for the translation unit via the
3749  // IdentifierInfo chains, don't bother to build a visible-declarations table.
3750  if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
3751  return 0;
3752 
3753  // Serialize the contents of the mapping used for lookup. Note that,
3754  // although we have two very different code paths, the serialized
3755  // representation is the same for both cases: a declaration name,
3756  // followed by a size, followed by references to the visible
3757  // declarations that have that name.
3758  uint64_t Offset = Stream.GetCurrentBitNo();
3759  StoredDeclsMap *Map = DC->buildLookup();
3760  if (!Map || Map->empty())
3761  return 0;
3762 
3763  // Create the on-disk hash table in a buffer.
3764  SmallString<4096> LookupTable;
3765  GenerateNameLookupTable(DC, LookupTable);
3766 
3767  // Write the lookup table
3768  RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
3769  Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
3770  LookupTable);
3771  ++NumVisibleDeclContexts;
3772  return Offset;
3773 }
3774 
3775 /// \brief Write an UPDATE_VISIBLE block for the given context.
3776 ///
3777 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
3778 /// DeclContext in a dependent AST file. As such, they only exist for the TU
3779 /// (in C++), for namespaces, and for classes with forward-declared unscoped
3780 /// enumeration members (in C++11).
3781 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
3782  StoredDeclsMap *Map = DC->getLookupPtr();
3783  if (!Map || Map->empty())
3784  return;
3785 
3786  // Create the on-disk hash table in a buffer.
3787  SmallString<4096> LookupTable;
3788  GenerateNameLookupTable(DC, LookupTable);
3789 
3790  // If we're updating a namespace, select a key declaration as the key for the
3791  // update record; those are the only ones that will be checked on reload.
3792  if (isa<NamespaceDecl>(DC))
3793  DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
3794 
3795  // Write the lookup table
3796  RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))};
3797  Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
3798 }
3799 
3800 /// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
3801 void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
3802  RecordData::value_type Record[] = {Opts.fp_contract};
3803  Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
3804 }
3805 
3806 /// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
3807 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
3808  if (!SemaRef.Context.getLangOpts().OpenCL)
3809  return;
3810 
3811  const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
3812  RecordData Record;
3813 #define OPENCLEXT(nm) Record.push_back(Opts.nm);
3814 #include "clang/Basic/OpenCLExtensions.def"
3815  Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
3816 }
3817 
3818 void ASTWriter::WriteObjCCategories() {
3819  SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
3820  RecordData Categories;
3821 
3822  for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
3823  unsigned Size = 0;
3824  unsigned StartIndex = Categories.size();
3825 
3826  ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
3827 
3828  // Allocate space for the size.
3829  Categories.push_back(0);
3830 
3831  // Add the categories.
3833  Cat = Class->known_categories_begin(),
3834  CatEnd = Class->known_categories_end();
3835  Cat != CatEnd; ++Cat, ++Size) {
3836  assert(getDeclID(*Cat) != 0 && "Bogus category");
3837  AddDeclRef(*Cat, Categories);
3838  }
3839 
3840  // Update the size.
3841  Categories[StartIndex] = Size;
3842 
3843  // Record this interface -> category map.
3844  ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
3845  CategoriesMap.push_back(CatInfo);
3846  }
3847 
3848  // Sort the categories map by the definition ID, since the reader will be
3849  // performing binary searches on this information.
3850  llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
3851 
3852  // Emit the categories map.
3853  using namespace llvm;
3854 
3855  auto *Abbrev = new BitCodeAbbrev();
3856  Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
3857  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
3858  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3859  unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
3860 
3861  RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
3862  Stream.EmitRecordWithBlob(AbbrevID, Record,
3863  reinterpret_cast<char *>(CategoriesMap.data()),
3864  CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
3865 
3866  // Emit the category lists.
3867  Stream.EmitRecord(OBJC_CATEGORIES, Categories);
3868 }
3869 
3870 void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
3872 
3873  if (LPTMap.empty())
3874  return;
3875 
3876  RecordData Record;
3877  for (auto LPTMapEntry : LPTMap) {
3878  const FunctionDecl *FD = LPTMapEntry.first;
3879  LateParsedTemplate *LPT = LPTMapEntry.second;
3880  AddDeclRef(FD, Record);
3881  AddDeclRef(LPT->D, Record);
3882  Record.push_back(LPT->Toks.size());
3883 
3884  for (const auto &Tok : LPT->Toks) {
3885  AddToken(Tok, Record);
3886  }
3887  }
3888  Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
3889 }
3890 
3891 /// \brief Write the state of 'pragma clang optimize' at the end of the module.
3892 void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
3893  RecordData Record;
3894  SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
3895  AddSourceLocation(PragmaLoc, Record);
3896  Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
3897 }
3898 
3899 void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
3900  ModuleFileExtensionWriter &Writer) {
3901  // Enter the extension block.
3902  Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
3903 
3904  // Emit the metadata record abbreviation.
3905  auto *Abv = new llvm::BitCodeAbbrev();
3906  Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
3907  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3908  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3909  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3910  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
3911  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
3912  unsigned Abbrev = Stream.EmitAbbrev(Abv);
3913 
3914  // Emit the metadata record.
3915  RecordData Record;
3916  auto Metadata = Writer.getExtension()->getExtensionMetadata();
3917  Record.push_back(EXTENSION_METADATA);
3918  Record.push_back(Metadata.MajorVersion);
3919  Record.push_back(Metadata.MinorVersion);
3920  Record.push_back(Metadata.BlockName.size());
3921  Record.push_back(Metadata.UserInfo.size());
3923  Buffer += Metadata.BlockName;
3924  Buffer += Metadata.UserInfo;
3925  Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
3926 
3927  // Emit the contents of the extension block.
3928  Writer.writeExtensionContents(SemaRef, Stream);
3929 
3930  // Exit the extension block.
3931  Stream.ExitBlock();
3932 }
3933 
3934 //===----------------------------------------------------------------------===//
3935 // General Serialization Routines
3936 //===----------------------------------------------------------------------===//
3937 
3938 /// \brief Write a record containing the given attributes.
3939 void ASTWriter::WriteAttributes(ArrayRef<const Attr*> Attrs,
3940  RecordDataImpl &Record) {
3941  Record.push_back(Attrs.size());
3942  for (const auto *A : Attrs) {
3943  Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
3944  AddSourceRange(A->getRange(), Record);
3945 
3946 #include "clang/Serialization/AttrPCHWrite.inc"
3947 
3948  }
3949 }
3950 
3951 void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
3952  AddSourceLocation(Tok.getLocation(), Record);
3953  Record.push_back(Tok.getLength());
3954 
3955  // FIXME: When reading literal tokens, reconstruct the literal pointer
3956  // if it is needed.
3957  AddIdentifierRef(Tok.getIdentifierInfo(), Record);
3958  // FIXME: Should translate token kind to a stable encoding.
3959  Record.push_back(Tok.getKind());
3960  // FIXME: Should translate token flags to a stable encoding.
3961  Record.push_back(Tok.getFlags());
3962 }
3963 
3964 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
3965  Record.push_back(Str.size());
3966  Record.insert(Record.end(), Str.begin(), Str.end());
3967 }
3968 
3970  assert(Context && "should have context when outputting path");
3971 
3972  bool Changed =
3974 
3975  // Remove a prefix to make the path relative, if relevant.
3976  const char *PathBegin = Path.data();
3977  const char *PathPtr =
3978  adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
3979  if (PathPtr != PathBegin) {
3980  Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
3981  Changed = true;
3982  }
3983 
3984  return Changed;
3985 }
3986 
3987 void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
3988  SmallString<128> FilePath(Path);
3989  PreparePathForOutput(FilePath);
3990  AddString(FilePath, Record);
3991 }
3992 
3993 void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
3994  StringRef Path) {
3995  SmallString<128> FilePath(Path);
3996  PreparePathForOutput(FilePath);
3997  Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
3998 }
3999 
4001  RecordDataImpl &Record) {
4002  Record.push_back(Version.getMajor());
4003  if (Optional<unsigned> Minor = Version.getMinor())
4004  Record.push_back(*Minor + 1);
4005  else
4006  Record.push_back(0);
4007  if (Optional<unsigned> Subminor = Version.getSubminor())
4008  Record.push_back(*Subminor + 1);
4009  else
4010  Record.push_back(0);
4011 }
4012 
4013 /// \brief Note that the identifier II occurs at the given offset
4014 /// within the identifier table.
4015 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
4016  IdentID ID = IdentifierIDs[II];
4017  // Only store offsets new to this AST file. Other identifier names are looked
4018  // up earlier in the chain and thus don't need an offset.
4019  if (ID >= FirstIdentID)
4020  IdentifierOffsets[ID - FirstIdentID] = Offset;
4021 }
4022 
4023 /// \brief Note that the selector Sel occurs at the given offset
4024 /// within the method pool/selector table.
4025 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
4026  unsigned ID = SelectorIDs[Sel];
4027  assert(ID && "Unknown selector");
4028  // Don't record offsets for selectors that are also available in a different
4029  // file.
4030  if (ID < FirstSelectorID)
4031  return;
4032  SelectorOffsets[ID - FirstSelectorID] = Offset;
4033 }
4034 
4036  llvm::BitstreamWriter &Stream,
4038  bool IncludeTimestamps)
4039  : Stream(Stream), Context(nullptr), PP(nullptr), Chain(nullptr),
4040  WritingModule(nullptr), IncludeTimestamps(IncludeTimestamps),
4041  WritingAST(false), DoneWritingDeclsAndTypes(false),
4042  ASTHasCompilerErrors(false), FirstDeclID(NUM_PREDEF_DECL_IDS),
4043  NextDeclID(FirstDeclID), FirstTypeID(NUM_PREDEF_TYPE_IDS),
4044  NextTypeID(FirstTypeID), FirstIdentID(NUM_PREDEF_IDENT_IDS),
4045  NextIdentID(FirstIdentID), FirstMacroID(NUM_PREDEF_MACRO_IDS),
4046  NextMacroID(FirstMacroID), FirstSubmoduleID(NUM_PREDEF_SUBMODULE_IDS),
4047  NextSubmoduleID(FirstSubmoduleID),
4048  FirstSelectorID(NUM_PREDEF_SELECTOR_IDS), NextSelectorID(FirstSelectorID),
4049  CollectedStmts(&StmtsToEmit), NumStatements(0), NumMacros(0),
4050  NumLexicalDeclContexts(0), NumVisibleDeclContexts(0),
4051  NextCXXBaseSpecifiersID(1), NextCXXCtorInitializersID(1),
4052  TypeExtQualAbbrev(0), TypeFunctionProtoAbbrev(0), DeclParmVarAbbrev(0),
4053  DeclContextLexicalAbbrev(0), DeclContextVisibleLookupAbbrev(0),
4054  UpdateVisibleAbbrev(0), DeclRecordAbbrev(0), DeclTypedefAbbrev(0),
4055  DeclVarAbbrev(0), DeclFieldAbbrev(0), DeclEnumAbbrev(0),
4056  DeclObjCIvarAbbrev(0), DeclCXXMethodAbbrev(0), DeclRefExprAbbrev(0),
4057  CharacterLiteralAbbrev(0), IntegerLiteralAbbrev(0),
4058  ExprImplicitCastAbbrev(0) {
4059  for (const auto &Ext : Extensions) {
4060  if (auto Writer = Ext->createExtensionWriter(*this))
4061  ModuleFileExtensionWriters.push_back(std::move(Writer));
4062  }
4063 }
4064 
4066  llvm::DeleteContainerSeconds(FileDeclIDs);
4067 }
4068 
4070  assert(WritingAST && "can't determine lang opts when not writing AST");
4071  return Context->getLangOpts();
4072 }
4073 
4075  return IncludeTimestamps ? E->getModificationTime() : 0;
4076 }
4077 
4078 uint64_t ASTWriter::WriteAST(Sema &SemaRef, const std::string &OutputFile,
4079  Module *WritingModule, StringRef isysroot,
4080  bool hasErrors) {
4081  WritingAST = true;
4082 
4083  ASTHasCompilerErrors = hasErrors;
4084 
4085  // Emit the file header.
4086  Stream.Emit((unsigned)'C', 8);
4087  Stream.Emit((unsigned)'P', 8);
4088  Stream.Emit((unsigned)'C', 8);
4089  Stream.Emit((unsigned)'H', 8);
4090 
4091  WriteBlockInfoBlock();
4092 
4093  Context = &SemaRef.Context;
4094  PP = &SemaRef.PP;
4095  this->WritingModule = WritingModule;
4096  ASTFileSignature Signature =
4097  WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
4098  Context = nullptr;
4099  PP = nullptr;
4100  this->WritingModule = nullptr;
4101  this->BaseDirectory.clear();
4102 
4103  WritingAST = false;
4104  return Signature;
4105 }
4106 
4107 template<typename Vector>
4108 static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4109  ASTWriter::RecordData &Record) {
4110  for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4111  I != E; ++I) {
4112  Writer.AddDeclRef(*I, Record);
4113  }
4114 }
4115 
4116 uint64_t ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
4117  const std::string &OutputFile,
4118  Module *WritingModule) {
4119  using namespace llvm;
4120 
4121  bool isModule = WritingModule != nullptr;
4122 
4123  // Make sure that the AST reader knows to finalize itself.
4124  if (Chain)
4125  Chain->finalizeForWriting();
4126 
4127  ASTContext &Context = SemaRef.Context;
4128  Preprocessor &PP = SemaRef.PP;
4129 
4130  // Set up predefined declaration IDs.
4131  auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
4132  if (D) {
4133  assert(D->isCanonicalDecl() && "predefined decl is not canonical");
4134  DeclIDs[D] = ID;
4135  }
4136  };
4137  RegisterPredefDecl(Context.getTranslationUnitDecl(),
4139  RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
4140  RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
4141  RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
4142  RegisterPredefDecl(Context.ObjCProtocolClassDecl,
4144  RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
4145  RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
4146  RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
4148  RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
4149  RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
4150  RegisterPredefDecl(Context.BuiltinMSVaListDecl,
4152  RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
4153  RegisterPredefDecl(Context.MakeIntegerSeqDecl,
4155 
4156  // Build a record containing all of the tentative definitions in this file, in
4157  // TentativeDefinitions order. Generally, this record will be empty for
4158  // headers.
4159  RecordData TentativeDefinitions;
4160  AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
4161 
4162  // Build a record containing all of the file scoped decls in this file.
4163  RecordData UnusedFileScopedDecls;
4164  if (!isModule)
4166  UnusedFileScopedDecls);
4167 
4168  // Build a record containing all of the delegating constructors we still need
4169  // to resolve.
4170  RecordData DelegatingCtorDecls;
4171  if (!isModule)
4172  AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
4173 
4174  // Write the set of weak, undeclared identifiers. We always write the
4175  // entire table, since later PCH files in a PCH chain are only interested in
4176  // the results at the end of the chain.
4177  RecordData WeakUndeclaredIdentifiers;
4178  for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) {
4179  IdentifierInfo *II = WeakUndeclaredIdentifier.first;
4180  WeakInfo &WI = WeakUndeclaredIdentifier.second;
4181  AddIdentifierRef(II, WeakUndeclaredIdentifiers);
4182  AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
4183  AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
4184  WeakUndeclaredIdentifiers.push_back(WI.getUsed());
4185  }
4186 
4187  // Build a record containing all of the ext_vector declarations.
4188  RecordData ExtVectorDecls;
4189  AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
4190 
4191  // Build a record containing all of the VTable uses information.
4192  RecordData VTableUses;
4193  if (!SemaRef.VTableUses.empty()) {
4194  for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4195  AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4196  AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4197  VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4198  }
4199  }
4200 
4201  // Build a record containing all of the UnusedLocalTypedefNameCandidates.
4202  RecordData UnusedLocalTypedefNameCandidates;
4203  for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4204  AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
4205 
4206  // Build a record containing all of pending implicit instantiations.
4207  RecordData PendingInstantiations;
4208  for (const auto &I : SemaRef.PendingInstantiations) {
4209  AddDeclRef(I.first, PendingInstantiations);
4210  AddSourceLocation(I.second, PendingInstantiations);
4211  }
4212  assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4213  "There are local ones at end of translation unit!");
4214 
4215  // Build a record containing some declaration references.
4216  RecordData SemaDeclRefs;
4217  if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
4218  AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4219  AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
4220  }
4221 
4222  RecordData CUDASpecialDeclRefs;
4223  if (Context.getcudaConfigureCallDecl()) {
4224  AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4225  }
4226 
4227  // Build a record containing all of the known namespaces.
4228  RecordData KnownNamespaces;
4229  for (const auto &I : SemaRef.KnownNamespaces) {
4230  if (!I.second)
4231  AddDeclRef(I.first, KnownNamespaces);
4232  }
4233 
4234  // Build a record of all used, undefined objects that require definitions.
4235  RecordData UndefinedButUsed;
4236 
4238  SemaRef.getUndefinedButUsed(Undefined);
4239  for (const auto &I : Undefined) {
4240  AddDeclRef(I.first, UndefinedButUsed);
4241  AddSourceLocation(I.second, UndefinedButUsed);
4242  }
4243 
4244  // Build a record containing all delete-expressions that we would like to
4245  // analyze later in AST.
4246  RecordData DeleteExprsToAnalyze;
4247 
4248  for (const auto &DeleteExprsInfo :
4249  SemaRef.getMismatchingDeleteExpressions()) {
4250  AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
4251  DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
4252  for (const auto &DeleteLoc : DeleteExprsInfo.second) {
4253  AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
4254  DeleteExprsToAnalyze.push_back(DeleteLoc.second);
4255  }
4256  }
4257 
4258  // Write the control block
4259  uint64_t Signature = WriteControlBlock(PP, Context, isysroot, OutputFile);
4260 
4261  // Write the remaining AST contents.
4262  Stream.EnterSubblock(AST_BLOCK_ID, 5);
4263 
4264  // This is so that older clang versions, before the introduction
4265  // of the control block, can read and reject the newer PCH format.
4266  {
4267  RecordData Record = {VERSION_MAJOR};
4268  Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4269  }
4270 
4271  // Create a lexical update block containing all of the declarations in the
4272  // translation unit that do not come from other AST files.
4273  const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
4274  SmallVector<uint32_t, 128> NewGlobalKindDeclPairs;
4275  for (const auto *D : TU->noload_decls()) {
4276  if (!D->isFromASTFile()) {
4277  NewGlobalKindDeclPairs.push_back(D->getKind());
4278  NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
4279  }
4280  }
4281 
4282  auto *Abv = new llvm::BitCodeAbbrev();
4283  Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4284  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4285  unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv);
4286  {
4287  RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
4288  Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4289  bytes(NewGlobalKindDeclPairs));
4290  }
4291 
4292  // And a visible updates block for the translation unit.
4293  Abv = new llvm::BitCodeAbbrev();
4294  Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4295  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4296  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4297  UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv);
4298  WriteDeclContextVisibleUpdate(TU);
4299 
4300  // If we have any extern "C" names, write out a visible update for them.
4301  if (Context.ExternCContext)
4302  WriteDeclContextVisibleUpdate(Context.ExternCContext);
4303 
4304  // If the translation unit has an anonymous namespace, and we don't already
4305  // have an update block for it, write it as an update block.
4306  // FIXME: Why do we not do this if there's already an update block?
4307  if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4308  ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
4309  if (Record.empty())
4310  Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
4311  }
4312 
4313  // Add update records for all mangling numbers and static local numbers.
4314  // These aren't really update records, but this is a convenient way of
4315  // tagging this rare extra data onto the declarations.
4316  for (const auto &Number : Context.MangleNumbers)
4317  if (!Number.first->isFromASTFile())
4318  DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4319  Number.second));
4320  for (const auto &Number : Context.StaticLocalNumbers)
4321  if (!Number.first->isFromASTFile())
4322  DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4323  Number.second));
4324 
4325  // Make sure visible decls, added to DeclContexts previously loaded from
4326  // an AST file, are registered for serialization.
4327  for (const auto *I : UpdatingVisibleDecls) {
4328  GetDeclRef(I);
4329  }
4330 
4331  // Make sure all decls associated with an identifier are registered for
4332  // serialization, if we're storing decls with identifiers.
4333  if (!WritingModule || !getLangOpts().CPlusPlus) {
4335  for (const auto &ID : PP.getIdentifierTable()) {
4336  const IdentifierInfo *II = ID.second;
4337  if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
4338  IIs.push_back(II);
4339  }
4340  // Sort the identifiers to visit based on their name.
4341  std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
4342  for (const IdentifierInfo *II : IIs) {
4343  for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4344  DEnd = SemaRef.IdResolver.end();
4345  D != DEnd; ++D) {
4346  GetDeclRef(*D);
4347  }
4348  }
4349  }
4350 
4351  // Form the record of special types.
4352  RecordData SpecialTypes;
4353  AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
4354  AddTypeRef(Context.getFILEType(), SpecialTypes);
4355  AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4356  AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4357  AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4358  AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
4359  AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
4360  AddTypeRef(Context.getucontext_tType(), SpecialTypes);
4361 
4362  if (Chain) {
4363  // Write the mapping information describing our module dependencies and how
4364  // each of those modules were mapped into our own offset/ID space, so that
4365  // the reader can build the appropriate mapping to its own offset/ID space.
4366  // The map consists solely of a blob with the following format:
4367  // *(module-name-len:i16 module-name:len*i8
4368  // source-location-offset:i32
4369  // identifier-id:i32
4370  // preprocessed-entity-id:i32
4371  // macro-definition-id:i32
4372  // submodule-id:i32
4373  // selector-id:i32
4374  // declaration-id:i32
4375  // c++-base-specifiers-id:i32
4376  // type-id:i32)
4377  //
4378  auto *Abbrev = new BitCodeAbbrev();
4379  Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4380  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4381  unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(Abbrev);
4383  {
4384  llvm::raw_svector_ostream Out(Buffer);
4385  for (ModuleFile *M : Chain->ModuleMgr) {
4386  using namespace llvm::support;
4387  endian::Writer<little> LE(Out);
4388  StringRef FileName = M->FileName;
4389  LE.write<uint16_t>(FileName.size());
4390  Out.write(FileName.data(), FileName.size());
4391 
4392  // Note: if a base ID was uint max, it would not be possible to load
4393  // another module after it or have more than one entity inside it.
4394  uint32_t None = std::numeric_limits<uint32_t>::max();
4395 
4396  auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) {
4397  assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
4398  if (ShouldWrite)
4399  LE.write<uint32_t>(BaseID);
4400  else
4401  LE.write<uint32_t>(None);
4402  };
4403 
4404  // These values should be unique within a chain, since they will be read
4405  // as keys into ContinuousRangeMaps.
4406  writeBaseIDOrNone(M->SLocEntryBaseOffset, M->LocalNumSLocEntries);
4407  writeBaseIDOrNone(M->BaseIdentifierID, M->LocalNumIdentifiers);
4408  writeBaseIDOrNone(M->BaseMacroID, M->LocalNumMacros);
4409  writeBaseIDOrNone(M->BasePreprocessedEntityID,
4411  writeBaseIDOrNone(M->BaseSubmoduleID, M->LocalNumSubmodules);
4412  writeBaseIDOrNone(M->BaseSelectorID, M->LocalNumSelectors);
4413  writeBaseIDOrNone(M->BaseDeclID, M->LocalNumDecls);
4414  writeBaseIDOrNone(M->BaseTypeIndex, M->LocalNumTypes);
4415  }
4416  }
4417  RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
4418  Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4419  Buffer.data(), Buffer.size());
4420  }
4421 
4422  RecordData DeclUpdatesOffsetsRecord;
4423 
4424  // Keep writing types, declarations, and declaration update records
4425  // until we've emitted all of them.
4426  Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
4427  WriteTypeAbbrevs();
4428  WriteDeclAbbrevs();
4429  do {
4430  WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
4431  while (!DeclTypesToEmit.empty()) {
4432  DeclOrType DOT = DeclTypesToEmit.front();
4433  DeclTypesToEmit.pop();
4434  if (DOT.isType())
4435  WriteType(DOT.getType());
4436  else
4437  WriteDecl(Context, DOT.getDecl());
4438  }
4439  } while (!DeclUpdates.empty());
4440  Stream.ExitBlock();
4441 
4442  DoneWritingDeclsAndTypes = true;
4443 
4444  // These things can only be done once we've written out decls and types.
4445  WriteTypeDeclOffsets();
4446  if (!DeclUpdatesOffsetsRecord.empty())
4447  Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
4448  WriteCXXBaseSpecifiersOffsets();
4449  WriteCXXCtorInitializersOffsets();
4450  WriteFileDeclIDsMap();
4451  WriteSourceManagerBlock(Context.getSourceManager(), PP);
4452  WriteComments();
4453  WritePreprocessor(PP, isModule);
4454  WriteHeaderSearch(PP.getHeaderSearchInfo());
4455  WriteSelectors(SemaRef);
4456  WriteReferencedSelectorsPool(SemaRef);
4457  WriteLateParsedTemplates(SemaRef);
4458  WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
4459  WriteFPPragmaOptions(SemaRef.getFPOptions());
4460  WriteOpenCLExtensions(SemaRef);
4461  WritePragmaDiagnosticMappings(Context.getDiagnostics(), isModule);
4462 
4463  // If we're emitting a module, write out the submodule information.
4464  if (WritingModule)
4465  WriteSubmodules(WritingModule);
4466 
4467  Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
4468 
4469  // Write the record containing external, unnamed definitions.
4470  if (!EagerlyDeserializedDecls.empty())
4471  Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
4472 
4473  // Write the record containing tentative definitions.
4474  if (!TentativeDefinitions.empty())
4475  Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
4476 
4477  // Write the record containing unused file scoped decls.
4478  if (!UnusedFileScopedDecls.empty())
4479  Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
4480 
4481  // Write the record containing weak undeclared identifiers.
4482  if (!WeakUndeclaredIdentifiers.empty())
4483  Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
4484  WeakUndeclaredIdentifiers);
4485 
4486  // Write the record containing ext_vector type names.
4487  if (!ExtVectorDecls.empty())
4488  Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
4489 
4490  // Write the record containing VTable uses information.
4491  if (!VTableUses.empty())
4492  Stream.EmitRecord(VTABLE_USES, VTableUses);
4493 
4494  // Write the record containing potentially unused local typedefs.
4495  if (!UnusedLocalTypedefNameCandidates.empty())
4496  Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
4497  UnusedLocalTypedefNameCandidates);
4498 
4499  // Write the record containing pending implicit instantiations.
4500  if (!PendingInstantiations.empty())
4501  Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
4502 
4503  // Write the record containing declaration references of Sema.
4504  if (!SemaDeclRefs.empty())
4505  Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
4506 
4507  // Write the record containing CUDA-specific declaration references.
4508  if (!CUDASpecialDeclRefs.empty())
4509  Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
4510 
4511  // Write the delegating constructors.
4512  if (!DelegatingCtorDecls.empty())
4513  Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
4514 
4515  // Write the known namespaces.
4516  if (!KnownNamespaces.empty())
4517  Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
4518 
4519  // Write the undefined internal functions and variables, and inline functions.
4520  if (!UndefinedButUsed.empty())
4521  Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
4522 
4523  if (!DeleteExprsToAnalyze.empty())
4524  Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
4525 
4526  // Write the visible updates to DeclContexts.
4527  for (auto *DC : UpdatedDeclContexts)
4528  WriteDeclContextVisibleUpdate(DC);
4529 
4530  if (!WritingModule) {
4531  // Write the submodules that were imported, if any.
4532  struct ModuleInfo {
4533  uint64_t ID;
4534  Module *M;
4535  ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
4536  };
4538  for (const auto *I : Context.local_imports()) {
4539  assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
4540  Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
4541  I->getImportedModule()));
4542  }
4543 
4544  if (!Imports.empty()) {
4545  auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
4546  return A.ID < B.ID;
4547  };
4548  auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
4549  return A.ID == B.ID;
4550  };
4551 
4552  // Sort and deduplicate module IDs.
4553  std::sort(Imports.begin(), Imports.end(), Cmp);
4554  Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
4555  Imports.end());
4556 
4557  RecordData ImportedModules;
4558  for (const auto &Import : Imports) {
4559  ImportedModules.push_back(Import.ID);
4560  // FIXME: If the module has macros imported then later has declarations
4561  // imported, this location won't be the right one as a location for the
4562  // declaration imports.
4563  AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
4564  }
4565 
4566  Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
4567  }
4568  }
4569 
4570  WriteDeclReplacementsBlock();
4571  WriteObjCCategories();
4572  if(!WritingModule)
4573  WriteOptimizePragmaOptions(SemaRef);
4574 
4575  // Some simple statistics
4576  RecordData::value_type Record[] = {
4577  NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts};
4578  Stream.EmitRecord(STATISTICS, Record);
4579  Stream.ExitBlock();
4580 
4581  // Write the module file extension blocks.
4582  for (const auto &ExtWriter : ModuleFileExtensionWriters)
4583  WriteModuleFileExtension(SemaRef, *ExtWriter);
4584 
4585  return Signature;
4586 }
4587 
4588 void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
4589  if (DeclUpdates.empty())
4590  return;
4591 
4592  DeclUpdateMap LocalUpdates;
4593  LocalUpdates.swap(DeclUpdates);
4594 
4595  for (auto &DeclUpdate : LocalUpdates) {
4596  const Decl *D = DeclUpdate.first;
4597 
4598  bool HasUpdatedBody = false;
4599  RecordData Record;
4600  for (auto &Update : DeclUpdate.second) {
4601  DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
4602 
4603  Record.push_back(Kind);
4604  switch (Kind) {
4608  assert(Update.getDecl() && "no decl to add?");
4609  Record.push_back(GetDeclRef(Update.getDecl()));
4610  break;
4611 
4613  // An updated body is emitted last, so that the reader doesn't need
4614  // to skip over the lazy body to reach statements for other records.
4615  Record.pop_back();
4616  HasUpdatedBody = true;
4617  break;
4618 
4620  AddSourceLocation(Update.getLoc(), Record);
4621  break;
4622 
4624  AddStmt(const_cast<Expr*>(
4625  cast<ParmVarDecl>(Update.getDecl())->getDefaultArg()));
4626  break;
4627 
4629  auto *RD = cast<CXXRecordDecl>(D);
4630  UpdatedDeclContexts.insert(RD->getPrimaryContext());
4631  AddCXXDefinitionData(RD, Record);
4632  Record.push_back(WriteDeclContextLexicalBlock(
4633  *Context, const_cast<CXXRecordDecl *>(RD)));
4634 
4635  // This state is sometimes updated by template instantiation, when we
4636  // switch from the specialization referring to the template declaration
4637  // to it referring to the template definition.
4638  if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
4639  Record.push_back(MSInfo->getTemplateSpecializationKind());
4640  AddSourceLocation(MSInfo->getPointOfInstantiation(), Record);
4641  } else {
4642  auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
4643  Record.push_back(Spec->getTemplateSpecializationKind());
4644  AddSourceLocation(Spec->getPointOfInstantiation(), Record);
4645 
4646  // The instantiation might have been resolved to a partial
4647  // specialization. If so, record which one.
4648  auto From = Spec->getInstantiatedFrom();
4649  if (auto PartialSpec =
4650  From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
4651  Record.push_back(true);
4652  AddDeclRef(PartialSpec, Record);
4653  AddTemplateArgumentList(&Spec->getTemplateInstantiationArgs(),
4654  Record);
4655  } else {
4656  Record.push_back(false);
4657  }
4658  }
4659  Record.push_back(RD->getTagKind());
4660  AddSourceLocation(RD->getLocation(), Record);
4661  AddSourceLocation(RD->getLocStart(), Record);
4662  AddSourceLocation(RD->getRBraceLoc(), Record);
4663 
4664  // Instantiation may change attributes; write them all out afresh.
4665  Record.push_back(D->hasAttrs());
4666  if (Record.back())
4667  WriteAttributes(llvm::makeArrayRef(D->getAttrs().begin(),
4668  D->getAttrs().size()), Record);
4669 
4670  // FIXME: Ensure we don't get here for explicit instantiations.
4671  break;
4672  }
4673 
4675  AddDeclRef(Update.getDecl(), Record);
4676  break;
4677 
4680  *this,
4681  cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>(),
4682  Record);
4683  break;
4684 
4686  Record.push_back(GetOrCreateTypeID(Update.getType()));
4687  break;
4688 
4689  case UPD_DECL_MARKED_USED:
4690  break;
4691 
4692  case UPD_MANGLING_NUMBER:
4694  Record.push_back(Update.getNumber());
4695  break;
4696 
4698  AddSourceRange(D->getAttr<OMPThreadPrivateDeclAttr>()->getRange(),
4699  Record);
4700  break;
4701 
4702  case UPD_DECL_EXPORTED:
4703  Record.push_back(getSubmoduleID(Update.getModule()));
4704  break;
4705 
4707  WriteAttributes(llvm::makeArrayRef(Update.getAttr()), Record);
4708  break;
4709  }
4710  }
4711 
4712  if (HasUpdatedBody) {
4713  const auto *Def = cast<FunctionDecl>(D);
4714  Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
4715  Record.push_back(Def->isInlined());
4716  AddSourceLocation(Def->getInnerLocStart(), Record);
4717  AddFunctionDefinition(Def, Record);
4718  }
4719 
4720  OffsetsRecord.push_back(GetDeclRef(D));
4721  OffsetsRecord.push_back(Stream.GetCurrentBitNo());
4722 
4723  Stream.EmitRecord(DECL_UPDATES, Record);
4724 
4726  }
4727 }
4728 
4729 void ASTWriter::WriteDeclReplacementsBlock() {
4730  if (ReplacedDecls.empty())
4731  return;
4732 
4733  RecordData Record;
4734  for (const auto &I : ReplacedDecls) {
4735  Record.push_back(I.ID);
4736  Record.push_back(I.Offset);
4737  Record.push_back(I.Loc);
4738  }
4739  Stream.EmitRecord(DECL_REPLACEMENTS, Record);
4740 }
4741 
4743  Record.push_back(Loc.getRawEncoding());
4744 }
4745 
4747  AddSourceLocation(Range.getBegin(), Record);
4748  AddSourceLocation(Range.getEnd(), Record);
4749 }
4750 
4751 void ASTWriter::AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record) {
4752  Record.push_back(Value.getBitWidth());
4753  const uint64_t *Words = Value.getRawData();
4754  Record.append(Words, Words + Value.getNumWords());
4755 }
4756 
4757 void ASTWriter::AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record) {
4758  Record.push_back(Value.isUnsigned());
4759  AddAPInt(Value, Record);
4760 }
4761 
4762 void ASTWriter::AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record) {
4763  AddAPInt(Value.bitcastToAPInt(), Record);
4764 }
4765 
4767  Record.push_back(getIdentifierRef(II));
4768 }
4769 
4771  if (!II)
4772  return 0;
4773 
4774  IdentID &ID = IdentifierIDs[II];
4775  if (ID == 0)
4776  ID = NextIdentID++;
4777  return ID;
4778 }
4779 
4781  // Don't emit builtin macros like __LINE__ to the AST file unless they
4782  // have been redefined by the header (in which case they are not
4783  // isBuiltinMacro).
4784  if (!MI || MI->isBuiltinMacro())
4785  return 0;
4786 
4787  MacroID &ID = MacroIDs[MI];
4788  if (ID == 0) {
4789  ID = NextMacroID++;
4790  MacroInfoToEmitData Info = { Name, MI, ID };
4791  MacroInfosToEmit.push_back(Info);
4792  }
4793  return ID;
4794 }
4795 
4797  if (!MI || MI->isBuiltinMacro())
4798  return 0;
4799 
4800  assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
4801  return MacroIDs[MI];
4802 }
4803 
4805  return IdentMacroDirectivesOffsetMap.lookup(Name);
4806 }
4807 
4809  Record.push_back(getSelectorRef(SelRef));
4810 }
4811 
4813  if (Sel.getAsOpaquePtr() == nullptr) {
4814  return 0;
4815  }
4816 
4817  SelectorID SID = SelectorIDs[Sel];
4818  if (SID == 0 && Chain) {
4819  // This might trigger a ReadSelector callback, which will set the ID for
4820  // this selector.
4821  Chain->LoadSelector(Sel);
4822  SID = SelectorIDs[Sel];
4823  }
4824  if (SID == 0) {
4825  SID = NextSelectorID++;
4826  SelectorIDs[Sel] = SID;
4827  }
4828  return SID;
4829 }
4830 
4832  AddDeclRef(Temp->getDestructor(), Record);
4833 }
4834 
4836  RecordDataImpl &Record) {
4837  assert(!Inits.empty() && "Empty ctor initializer sets are not recorded");
4838  CXXCtorInitializersToWrite.push_back(
4839  QueuedCXXCtorInitializers(NextCXXCtorInitializersID, Inits));
4840  Record.push_back(NextCXXCtorInitializersID++);
4841 }
4842 
4844  CXXBaseSpecifier const *BasesEnd,
4845  RecordDataImpl &Record) {
4846  assert(Bases != BasesEnd && "Empty base-specifier sets are not recorded");
4847  CXXBaseSpecifiersToWrite.push_back(
4848  QueuedCXXBaseSpecifiers(NextCXXBaseSpecifiersID,
4849  Bases, BasesEnd));
4850  Record.push_back(NextCXXBaseSpecifiersID++);
4851 }
4852 
4854  const TemplateArgumentLocInfo &Arg,
4855  RecordDataImpl &Record) {
4856  switch (Kind) {
4858  AddStmt(Arg.getAsExpr());
4859  break;
4861  AddTypeSourceInfo(Arg.getAsTypeSourceInfo(), Record);
4862  break;
4865  AddSourceLocation(Arg.getTemplateNameLoc(), Record);
4866  break;
4869  AddSourceLocation(Arg.getTemplateNameLoc(), Record);
4871  break;
4877  // FIXME: Is this right?
4878  break;
4879  }
4880 }
4881 
4883  RecordDataImpl &Record) {
4884  AddTemplateArgument(Arg.getArgument(), Record);
4885 
4887  bool InfoHasSameExpr
4888  = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
4889  Record.push_back(InfoHasSameExpr);
4890  if (InfoHasSameExpr)
4891  return; // Avoid storing the same expr twice.
4892  }
4894  Record);
4895 }
4896 
4898  RecordDataImpl &Record) {
4899  if (!TInfo) {
4900  AddTypeRef(QualType(), Record);
4901  return;
4902  }
4903 
4904  AddTypeLoc(TInfo->getTypeLoc(), Record);
4905 }
4906 
4908  AddTypeRef(TL.getType(), Record);
4909 
4910  TypeLocWriter TLW(*this, Record);
4911  for (; !TL.isNull(); TL = TL.getNextTypeLoc())
4912  TLW.Visit(TL);
4913 }
4914 
4916  Record.push_back(GetOrCreateTypeID(T));
4917 }
4918 
4920  assert(Context);
4921  return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
4922  if (T.isNull())
4923  return TypeIdx();
4924  assert(!T.getLocalFastQualifiers());
4925 
4926  TypeIdx &Idx = TypeIdxs[T];
4927  if (Idx.getIndex() == 0) {
4928  if (DoneWritingDeclsAndTypes) {
4929  assert(0 && "New type seen after serializing all the types to emit!");
4930  return TypeIdx();
4931  }
4932 
4933  // We haven't seen this type before. Assign it a new ID and put it
4934  // into the queue of types to emit.
4935  Idx = TypeIdx(NextTypeID++);
4936  DeclTypesToEmit.push(T);
4937  }
4938  return Idx;
4939  });
4940 }
4941 
4943  assert(Context);
4944  return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
4945  if (T.isNull())
4946  return TypeIdx();
4947  assert(!T.getLocalFastQualifiers());
4948 
4949  TypeIdxMap::const_iterator I = TypeIdxs.find(T);
4950  assert(I != TypeIdxs.end() && "Type not emitted!");
4951  return I->second;
4952  });
4953 }
4954 
4955 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
4956  Record.push_back(GetDeclRef(D));
4957 }
4958 
4960  assert(WritingAST && "Cannot request a declaration ID before AST writing");
4961 
4962  if (!D) {
4963  return 0;
4964  }
4965 
4966  // If D comes from an AST file, its declaration ID is already known and
4967  // fixed.
4968  if (D->isFromASTFile())
4969  return D->getGlobalID();
4970 
4971  assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
4972  DeclID &ID = DeclIDs[D];
4973  if (ID == 0) {
4974  if (DoneWritingDeclsAndTypes) {
4975  assert(0 && "New decl seen after serializing all the decls to emit!");
4976  return 0;
4977  }
4978 
4979  // We haven't seen this declaration before. Give it a new ID and
4980  // enqueue it in the list of declarations to emit.
4981  ID = NextDeclID++;
4982  DeclTypesToEmit.push(const_cast<Decl *>(D));
4983  }
4984 
4985  return ID;
4986 }
4987 
4989  if (!D)
4990  return 0;
4991 
4992  // If D comes from an AST file, its declaration ID is already known and
4993  // fixed.
4994  if (D->isFromASTFile())
4995  return D->getGlobalID();
4996 
4997  assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
4998  return DeclIDs[D];
4999 }
5000 
5001 void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
5002  assert(ID);
5003  assert(D);
5004 
5005  SourceLocation Loc = D->getLocation();
5006  if (Loc.isInvalid())
5007  return;
5008 
5009  // We only keep track of the file-level declarations of each file.
5010  if (!D->getLexicalDeclContext()->isFileContext())
5011  return;
5012  // FIXME: ParmVarDecls that are part of a function type of a parameter of
5013  // a function/objc method, should not have TU as lexical context.
5014  if (isa<ParmVarDecl>(D))
5015  return;
5016 
5017  SourceManager &SM = Context->getSourceManager();
5018  SourceLocation FileLoc = SM.getFileLoc(Loc);
5019  assert(SM.isLocalSourceLocation(FileLoc));
5020  FileID FID;
5021  unsigned Offset;
5022  std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
5023  if (FID.isInvalid())
5024  return;
5025  assert(SM.getSLocEntry(FID).isFile());
5026 
5027  DeclIDInFileInfo *&Info = FileDeclIDs[FID];
5028  if (!Info)
5029  Info = new DeclIDInFileInfo();
5030 
5031  std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
5032  LocDeclIDsTy &Decls = Info->DeclIDs;
5033 
5034  if (Decls.empty() || Decls.back().first <= Offset) {
5035  Decls.push_back(LocDecl);
5036  return;
5037  }
5038 
5040  std::upper_bound(Decls.begin(), Decls.end(), LocDecl, llvm::less_first());
5041 
5042  Decls.insert(I, LocDecl);
5043 }
5044 
5046  // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
5047  Record.push_back(Name.getNameKind());
5048  switch (Name.getNameKind()) {
5050  AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
5051  break;
5052 
5056  AddSelectorRef(Name.getObjCSelector(), Record);
5057  break;
5058 
5062  AddTypeRef(Name.getCXXNameType(), Record);
5063  break;
5064 
5066  Record.push_back(Name.getCXXOverloadedOperator());
5067  break;
5068 
5070  AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record);
5071  break;
5072 
5074  // No extra data to emit
5075  break;
5076  }
5077 }
5078 
5080  assert(needsAnonymousDeclarationNumber(D) &&
5081  "expected an anonymous declaration");
5082 
5083  // Number the anonymous declarations within this context, if we've not
5084  // already done so.
5085  auto It = AnonymousDeclarationNumbers.find(D);
5086  if (It == AnonymousDeclarationNumbers.end()) {
5087  auto *DC = D->getLexicalDeclContext();
5088  numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
5089  AnonymousDeclarationNumbers[ND] = Number;
5090  });
5091 
5092  It = AnonymousDeclarationNumbers.find(D);
5093  assert(It != AnonymousDeclarationNumbers.end() &&
5094  "declaration not found within its lexical context");
5095  }
5096 
5097  return It->second;
5098 }
5099 
5101  DeclarationName Name, RecordDataImpl &Record) {
5102  switch (Name.getNameKind()) {
5106  AddTypeSourceInfo(DNLoc.NamedType.TInfo, Record);
5107  break;
5108 
5112  Record);
5115  Record);
5116  break;
5117 
5121  Record);
5122  break;
5123 
5129  break;
5130  }
5131 }
5132 
5134  RecordDataImpl &Record) {
5135  AddDeclarationName(NameInfo.getName(), Record);
5136  AddSourceLocation(NameInfo.getLoc(), Record);
5137  AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName(), Record);
5138 }
5139 
5141  RecordDataImpl &Record) {
5143  Record.push_back(Info.NumTemplParamLists);
5144  for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i)
5145  AddTemplateParameterList(Info.TemplParamLists[i], Record);
5146 }
5147 
5149  RecordDataImpl &Record) {
5150  // Nested name specifiers usually aren't too long. I think that 8 would
5151  // typically accommodate the vast majority.
5153 
5154  // Push each of the NNS's onto a stack for serialization in reverse order.
5155  while (NNS) {
5156  NestedNames.push_back(NNS);
5157  NNS = NNS->getPrefix();
5158  }
5159 
5160  Record.push_back(NestedNames.size());
5161  while(!NestedNames.empty()) {
5162  NNS = NestedNames.pop_back_val();
5164  Record.push_back(Kind);
5165  switch (Kind) {
5167  AddIdentifierRef(NNS->getAsIdentifier(), Record);
5168  break;
5169 
5171  AddDeclRef(NNS->getAsNamespace(), Record);
5172  break;
5173 
5175  AddDeclRef(NNS->getAsNamespaceAlias(), Record);
5176  break;
5177 
5180  AddTypeRef(QualType(NNS->getAsType(), 0), Record);
5181  Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5182  break;
5183 
5185  // Don't need to write an associated value.
5186  break;
5187 
5189  AddDeclRef(NNS->getAsRecordDecl(), Record);
5190  break;
5191  }
5192  }
5193 }
5194 
5196  RecordDataImpl &Record) {
5197  // Nested name specifiers usually aren't too long. I think that 8 would
5198  // typically accommodate the vast majority.
5200 
5201  // Push each of the nested-name-specifiers's onto a stack for
5202  // serialization in reverse order.
5203  while (NNS) {
5204  NestedNames.push_back(NNS);
5205  NNS = NNS.getPrefix();
5206  }
5207 
5208  Record.push_back(NestedNames.size());
5209  while(!NestedNames.empty()) {
5210  NNS = NestedNames.pop_back_val();
5212  = NNS.getNestedNameSpecifier()->getKind();
5213  Record.push_back(Kind);
5214  switch (Kind) {
5217  AddSourceRange(NNS.getLocalSourceRange(), Record);
5218  break;
5219 
5222  AddSourceRange(NNS.getLocalSourceRange(), Record);
5223  break;
5224 
5227  AddSourceRange(NNS.getLocalSourceRange(), Record);
5228  break;
5229 
5232  Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5233  AddTypeLoc(NNS.getTypeLoc(), Record);
5234  AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
5235  break;
5236 
5238  AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
5239  break;
5240 
5243  AddSourceRange(NNS.getLocalSourceRange(), Record);
5244  break;
5245  }
5246  }
5247 }
5248 
5250  TemplateName::NameKind Kind = Name.getKind();
5251  Record.push_back(Kind);
5252  switch (Kind) {
5254  AddDeclRef(Name.getAsTemplateDecl(), Record);
5255  break;
5256 
5259  Record.push_back(OvT->size());
5260  for (const auto &I : *OvT)
5261  AddDeclRef(I, Record);
5262  break;
5263  }
5264 
5267  AddNestedNameSpecifier(QualT->getQualifier(), Record);
5268  Record.push_back(QualT->hasTemplateKeyword());
5269  AddDeclRef(QualT->getTemplateDecl(), Record);
5270  break;
5271  }
5272 
5275  AddNestedNameSpecifier(DepT->getQualifier(), Record);
5276  Record.push_back(DepT->isIdentifier());
5277  if (DepT->isIdentifier())
5278  AddIdentifierRef(DepT->getIdentifier(), Record);
5279  else
5280  Record.push_back(DepT->getOperator());
5281  break;
5282  }
5283 
5287  AddDeclRef(subst->getParameter(), Record);
5288  AddTemplateName(subst->getReplacement(), Record);
5289  break;
5290  }
5291 
5295  AddDeclRef(SubstPack->getParameterPack(), Record);
5296  AddTemplateArgument(SubstPack->getArgumentPack(), Record);
5297  break;
5298  }
5299  }
5300 }
5301 
5303  RecordDataImpl &Record) {
5304  Record.push_back(Arg.getKind());
5305  switch (Arg.getKind()) {
5307  break;
5309  AddTypeRef(Arg.getAsType(), Record);
5310  break;
5312  AddDeclRef(Arg.getAsDecl(), Record);
5313  AddTypeRef(Arg.getParamTypeForDecl(), Record);
5314  break;
5316  AddTypeRef(Arg.getNullPtrType(), Record);
5317  break;
5319  AddAPSInt(Arg.getAsIntegral(), Record);
5320  AddTypeRef(Arg.getIntegralType(), Record);
5321  break;
5324  break;
5327  if (Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
5328  Record.push_back(*NumExpansions + 1);
5329  else
5330  Record.push_back(0);
5331  break;
5333  AddStmt(Arg.getAsExpr());
5334  break;
5336  Record.push_back(Arg.pack_size());
5337  for (const auto &P : Arg.pack_elements())
5338  AddTemplateArgument(P, Record);
5339  break;
5340  }
5341 }
5342 
5343 void
5345  RecordDataImpl &Record) {
5346  assert(TemplateParams && "No TemplateParams!");
5347  AddSourceLocation(TemplateParams->getTemplateLoc(), Record);
5348  AddSourceLocation(TemplateParams->getLAngleLoc(), Record);
5349  AddSourceLocation(TemplateParams->getRAngleLoc(), Record);
5350  Record.push_back(TemplateParams->size());
5351  for (const auto &P : *TemplateParams)
5352  AddDeclRef(P, Record);
5353 }
5354 
5355 /// \brief Emit a template argument list.
5356 void
5358  RecordDataImpl &Record) {
5359  assert(TemplateArgs && "No TemplateArgs!");
5360  Record.push_back(TemplateArgs->size());
5361  for (int i=0, e = TemplateArgs->size(); i != e; ++i)
5362  AddTemplateArgument(TemplateArgs->get(i), Record);
5363 }
5364 
5365 void
5367 (const ASTTemplateArgumentListInfo *ASTTemplArgList, RecordDataImpl &Record) {
5368  assert(ASTTemplArgList && "No ASTTemplArgList!");
5369  AddSourceLocation(ASTTemplArgList->LAngleLoc, Record);
5370  AddSourceLocation(ASTTemplArgList->RAngleLoc, Record);
5371  Record.push_back(ASTTemplArgList->NumTemplateArgs);
5372  const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
5373  for (int i=0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
5374  AddTemplateArgumentLoc(TemplArgs[i], Record);
5375 }
5376 
5377 void
5379  Record.push_back(Set.size());
5381  I = Set.begin(), E = Set.end(); I != E; ++I) {
5382  AddDeclRef(I.getDecl(), Record);
5383  Record.push_back(I.getAccess());
5384  }
5385 }
5386 
5388  RecordDataImpl &Record) {
5389  Record.push_back(Base.isVirtual());
5390  Record.push_back(Base.isBaseOfClass());
5391  Record.push_back(Base.getAccessSpecifierAsWritten());
5392  Record.push_back(Base.getInheritConstructors());
5393  AddTypeSourceInfo(Base.getTypeSourceInfo(), Record);
5394  AddSourceRange(Base.getSourceRange(), Record);
5396  : SourceLocation(),
5397  Record);
5398 }
5399 
5401  RecordData Record;
5402  unsigned N = CXXBaseSpecifiersToWrite.size();
5403  for (unsigned I = 0; I != N; ++I) {
5404  Record.clear();
5405 
5406  // Record the offset of this base-specifier set.
5407  unsigned Index = CXXBaseSpecifiersToWrite[I].ID - 1;
5408  if (Index == CXXBaseSpecifiersOffsets.size())
5409  CXXBaseSpecifiersOffsets.push_back(Stream.GetCurrentBitNo());
5410  else {
5411  if (Index > CXXBaseSpecifiersOffsets.size())
5412  CXXBaseSpecifiersOffsets.resize(Index + 1);
5413  CXXBaseSpecifiersOffsets[Index] = Stream.GetCurrentBitNo();
5414  }
5415 
5416  const CXXBaseSpecifier *B = CXXBaseSpecifiersToWrite[I].Bases,
5417  *BEnd = CXXBaseSpecifiersToWrite[I].BasesEnd;
5418  Record.push_back(BEnd - B);
5419  for (; B != BEnd; ++B)
5420  AddCXXBaseSpecifier(*B, Record);
5421  Stream.EmitRecord(serialization::DECL_CXX_BASE_SPECIFIERS, Record);
5422 
5423  // Flush any expressions that were written as part of the base specifiers.
5424  FlushStmts();
5425  }
5426 
5427  assert(N == CXXBaseSpecifiersToWrite.size() &&
5428  "added more base specifiers while writing base specifiers");
5429  CXXBaseSpecifiersToWrite.clear();
5430 }
5431 
5433  const CXXCtorInitializer * const *CtorInitializers,
5434  unsigned NumCtorInitializers,
5435  RecordDataImpl &Record) {
5436  Record.push_back(NumCtorInitializers);
5437  for (unsigned i=0; i != NumCtorInitializers; ++i) {
5438  const CXXCtorInitializer *Init = CtorInitializers[i];
5439 
5440  if (Init->isBaseInitializer()) {
5441  Record.push_back(CTOR_INITIALIZER_BASE);
5442  AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
5443  Record.push_back(Init->isBaseVirtual());
5444  } else if (Init->isDelegatingInitializer()) {
5445  Record.push_back(CTOR_INITIALIZER_DELEGATING);
5446  AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
5447  } else if (Init->isMemberInitializer()){
5448  Record.push_back(CTOR_INITIALIZER_MEMBER);
5449  AddDeclRef(Init->getMember(), Record);
5450  } else {
5451  Record.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
5452  AddDeclRef(Init->getIndirectMember(), Record);
5453  }
5454 
5455  AddSourceLocation(Init->getMemberLocation(), Record);
5456  AddStmt(Init->getInit());
5457  AddSourceLocation(Init->getLParenLoc(), Record);
5458  AddSourceLocation(Init->getRParenLoc(), Record);
5459  Record.push_back(Init->isWritten());
5460  if (Init->isWritten()) {
5461  Record.push_back(Init->getSourceOrder());
5462  } else {
5463  Record.push_back(Init->getNumArrayIndices());
5464  for (unsigned i=0, e=Init->getNumArrayIndices(); i != e; ++i)
5465  AddDeclRef(Init->getArrayIndex(i), Record);
5466  }
5467  }
5468 }
5469 
5471  RecordData Record;
5472 
5473  unsigned N = CXXCtorInitializersToWrite.size();
5474  (void)N; // Silence unused warning in non-assert builds.
5475  for (auto &Init : CXXCtorInitializersToWrite) {
5476  Record.clear();
5477 
5478  // Record the offset of this mem-initializer list.
5479  unsigned Index = Init.ID - 1;
5480  if (Index == CXXCtorInitializersOffsets.size())
5481  CXXCtorInitializersOffsets.push_back(Stream.GetCurrentBitNo());
5482  else {
5483  if (Index > CXXCtorInitializersOffsets.size())
5484  CXXCtorInitializersOffsets.resize(Index + 1);
5485  CXXCtorInitializersOffsets[Index] = Stream.GetCurrentBitNo();
5486  }
5487 
5488  AddCXXCtorInitializers(Init.Inits.data(), Init.Inits.size(), Record);
5489  Stream.EmitRecord(serialization::DECL_CXX_CTOR_INITIALIZERS, Record);
5490 
5491  // Flush any expressions that were written as part of the initializers.
5492  FlushStmts();
5493  }
5494 
5495  assert(N == CXXCtorInitializersToWrite.size() &&
5496  "added more ctor initializers while writing ctor initializers");
5497  CXXCtorInitializersToWrite.clear();
5498 }
5499 
5501  auto &Data = D->data();
5502  Record.push_back(Data.IsLambda);
5503  Record.push_back(Data.UserDeclaredConstructor);
5504  Record.push_back(Data.UserDeclaredSpecialMembers);
5505  Record.push_back(Data.Aggregate);
5506  Record.push_back(Data.PlainOldData);
5507  Record.push_back(Data.Empty);
5508  Record.push_back(Data.Polymorphic);
5509  Record.push_back(Data.Abstract);
5510  Record.push_back(Data.IsStandardLayout);
5511  Record.push_back(Data.HasNoNonEmptyBases);
5512  Record.push_back(Data.HasPrivateFields);
5513  Record.push_back(Data.HasProtectedFields);
5514  Record.push_back(Data.HasPublicFields);
5515  Record.push_back(Data.HasMutableFields);
5516  Record.push_back(Data.HasVariantMembers);
5517  Record.push_back(Data.HasOnlyCMembers);
5518  Record.push_back(Data.HasInClassInitializer);
5519  Record.push_back(Data.HasUninitializedReferenceMember);
5520  Record.push_back(Data.NeedOverloadResolutionForMoveConstructor);
5521  Record.push_back(Data.NeedOverloadResolutionForMoveAssignment);
5522  Record.push_back(Data.NeedOverloadResolutionForDestructor);
5523  Record.push_back(Data.DefaultedMoveConstructorIsDeleted);
5524  Record.push_back(Data.DefaultedMoveAssignmentIsDeleted);
5525  Record.push_back(Data.DefaultedDestructorIsDeleted);
5526  Record.push_back(Data.HasTrivialSpecialMembers);
5527  Record.push_back(Data.DeclaredNonTrivialSpecialMembers);
5528  Record.push_back(Data.HasIrrelevantDestructor);
5529  Record.push_back(Data.HasConstexprNonCopyMoveConstructor);
5530  Record.push_back(Data.DefaultedDefaultConstructorIsConstexpr);
5531  Record.push_back(Data.HasConstexprDefaultConstructor);
5532  Record.push_back(Data.HasNonLiteralTypeFieldsOrBases);
5533  Record.push_back(Data.ComputedVisibleConversions);
5534  Record.push_back(Data.UserProvidedDefaultConstructor);
5535  Record.push_back(Data.DeclaredSpecialMembers);
5536  Record.push_back(Data.ImplicitCopyConstructorHasConstParam);
5537  Record.push_back(Data.ImplicitCopyAssignmentHasConstParam);
5538  Record.push_back(Data.HasDeclaredCopyConstructorWithConstParam);
5539  Record.push_back(Data.HasDeclaredCopyAssignmentWithConstParam);
5540  // IsLambda bit is already saved.
5541 
5542  Record.push_back(Data.NumBases);
5543  if (Data.NumBases > 0)
5544  AddCXXBaseSpecifiersRef(Data.getBases(), Data.getBases() + Data.NumBases,
5545  Record);
5546 
5547  // FIXME: Make VBases lazily computed when needed to avoid storing them.
5548  Record.push_back(Data.NumVBases);
5549  if (Data.NumVBases > 0)
5550  AddCXXBaseSpecifiersRef(Data.getVBases(), Data.getVBases() + Data.NumVBases,
5551  Record);
5552 
5553  AddUnresolvedSet(Data.Conversions.get(*Context), Record);
5554  AddUnresolvedSet(Data.VisibleConversions.get(*Context), Record);
5555  // Data.Definition is the owning decl, no need to write it.
5556  AddDeclRef(D->getFirstFriend(), Record);
5557 
5558  // Add lambda-specific data.
5559  if (Data.IsLambda) {
5560  auto &Lambda = D->getLambdaData();
5561  Record.push_back(Lambda.Dependent);
5562  Record.push_back(Lambda.IsGenericLambda);
5563  Record.push_back(Lambda.CaptureDefault);
5564  Record.push_back(Lambda.NumCaptures);
5565  Record.push_back(Lambda.NumExplicitCaptures);
5566  Record.push_back(Lambda.ManglingNumber);
5567  AddDeclRef(Lambda.ContextDecl, Record);
5568  AddTypeSourceInfo(Lambda.MethodTyInfo, Record);
5569  for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
5570  const LambdaCapture &Capture = Lambda.Captures[I];
5571  AddSourceLocation(Capture.getLocation(), Record);
5572  Record.push_back(Capture.isImplicit());
5573  Record.push_back(Capture.getCaptureKind());
5574  switch (Capture.getCaptureKind()) {
5575  case LCK_This:
5576  case LCK_VLAType:
5577  break;
5578  case LCK_ByCopy:
5579  case LCK_ByRef:
5580  VarDecl *Var =
5581  Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
5582  AddDeclRef(Var, Record);
5583  AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
5584  : SourceLocation(),
5585  Record);
5586  break;
5587  }
5588  }
5589  }
5590 }
5591 
5593  assert(Reader && "Cannot remove chain");
5594  assert((!Chain || Chain == Reader) && "Cannot replace chain");
5595  assert(FirstDeclID == NextDeclID &&
5596  FirstTypeID == NextTypeID &&
5597  FirstIdentID == NextIdentID &&
5598  FirstMacroID == NextMacroID &&
5599  FirstSubmoduleID == NextSubmoduleID &&
5600  FirstSelectorID == NextSelectorID &&
5601  "Setting chain after writing has started.");
5602 
5603  Chain = Reader;
5604 
5605  // Note, this will get called multiple times, once one the reader starts up
5606  // and again each time it's done reading a PCH or module.
5607  FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
5608  FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
5609  FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
5610  FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
5611  FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
5612  FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
5613  NextDeclID = FirstDeclID;
5614  NextTypeID = FirstTypeID;
5615  NextIdentID = FirstIdentID;
5616  NextMacroID = FirstMacroID;
5617  NextSelectorID = FirstSelectorID;
5618  NextSubmoduleID = FirstSubmoduleID;
5619 }
5620 
5622  // Always keep the highest ID. See \p TypeRead() for more information.
5623  IdentID &StoredID = IdentifierIDs[II];
5624  if (ID > StoredID)
5625  StoredID = ID;
5626 }
5627 
5629  // Always keep the highest ID. See \p TypeRead() for more information.
5630  MacroID &StoredID = MacroIDs[MI];
5631  if (ID > StoredID)
5632  StoredID = ID;
5633 }
5634 
5636  // Always take the highest-numbered type index. This copes with an interesting
5637  // case for chained AST writing where we schedule writing the type and then,
5638  // later, deserialize the type from another AST. In this case, we want to
5639  // keep the higher-numbered entry so that we can properly write it out to
5640  // the AST file.
5641  TypeIdx &StoredIdx = TypeIdxs[T];
5642  if (Idx.getIndex() >= StoredIdx.getIndex())
5643  StoredIdx = Idx;
5644 }
5645 
5647  // Always keep the highest ID. See \p TypeRead() for more information.
5648  SelectorID &StoredID = SelectorIDs[S];
5649  if (ID > StoredID)
5650  StoredID = ID;
5651 }
5652 
5654  MacroDefinitionRecord *MD) {
5655  assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
5656  MacroDefinitions[MD] = ID;
5657 }
5658 
5660  assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
5661  SubmoduleIDs[Mod] = ID;
5662 }
5663 
5665  assert(D->isCompleteDefinition());
5666  assert(!WritingAST && "Already writing the AST!");
5667  if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
5668  // We are interested when a PCH decl is modified.
5669  if (RD->isFromASTFile()) {
5670  // A forward reference was mutated into a definition. Rewrite it.
5671  // FIXME: This happens during template instantiation, should we
5672  // have created a new definition decl instead ?
5673  assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
5674  "completed a tag from another module but not by instantiation?");
5675  DeclUpdates[RD].push_back(
5677  }
5678  }
5679 }
5680 
5681 static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) {
5682  if (D->isFromASTFile())
5683  return true;
5684 
5685  // If we've not loaded any modules, this can't be imported.
5686  if (!Chain || !Chain->getModuleManager().size())
5687  return false;
5688 
5689  // The predefined __va_list_tag struct is imported if we imported any decls.
5690  // FIXME: This is a gross hack.
5691  return D == D->getASTContext().getVaListTagDecl();
5692 }
5693 
5694 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
5695  // TU and namespaces are handled elsewhere.
5696  if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC))
5697  return;
5698 
5699  // We're only interested in cases where a local declaration is added to an
5700  // imported context.
5701  if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC)))
5702  return;
5703 
5704  assert(DC == DC->getPrimaryContext() && "added to non-primary context");
5705  assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
5706  assert(!WritingAST && "Already writing the AST!");
5707  if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) {
5708  // We're adding a visible declaration to a predefined decl context. Ensure
5709  // that we write out all of its lookup results so we don't get a nasty
5710  // surprise when we try to emit its lookup table.
5711  for (auto *Child : DC->decls())
5712  UpdatingVisibleDecls.push_back(Child);
5713  }
5714  UpdatingVisibleDecls.push_back(D);
5715 }
5716 
5718  assert(D->isImplicit());
5719 
5720  // We're only interested in cases where a local declaration is added to an
5721  // imported context.
5722  if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD))
5723  return;
5724 
5725  if (!isa<CXXMethodDecl>(D))
5726  return;
5727 
5728  // A decl coming from PCH was modified.
5729  assert(RD->isCompleteDefinition());
5730  assert(!WritingAST && "Already writing the AST!");
5731  DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
5732 }
5733 
5735  assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
5736  if (!Chain) return;
5737  Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
5738  // If we don't already know the exception specification for this redecl
5739  // chain, add an update record for it.
5740  if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
5741  ->getType()
5742  ->castAs<FunctionProtoType>()
5743  ->getExceptionSpecType()))
5744  DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
5745  });
5746 }
5747 
5749  assert(!WritingAST && "Already writing the AST!");
5750  if (!Chain) return;
5751  Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
5752  DeclUpdates[D].push_back(
5753  DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
5754  });
5755 }
5756 
5758  const FunctionDecl *Delete) {
5759  assert(!WritingAST && "Already writing the AST!");
5760  assert(Delete && "Not given an operator delete");
5761  if (!Chain) return;
5762  Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
5763  DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete));
5764  });
5765 }
5766 
5768  assert(!WritingAST && "Already writing the AST!");
5769  if (!D->isFromASTFile())
5770  return; // Declaration not imported from PCH.
5771 
5772  // Implicit function decl from a PCH was defined.
5773  DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
5774 }
5775 
5777  assert(!WritingAST && "Already writing the AST!");
5778  if (!D->isFromASTFile())
5779  return;
5780 
5781  DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
5782 }
5783 
5785  assert(!WritingAST && "Already writing the AST!");
5786  if (!D->isFromASTFile())
5787  return;
5788 
5789  // Since the actual instantiation is delayed, this really means that we need
5790  // to update the instantiation location.
5791  DeclUpdates[D].push_back(
5794 }
5795 
5797  assert(!WritingAST && "Already writing the AST!");
5798  if (!D->isFromASTFile())
5799  return;
5800 
5801  DeclUpdates[D].push_back(
5802  DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D));
5803 }
5804 
5806  const ObjCInterfaceDecl *IFD) {
5807  assert(!WritingAST && "Already writing the AST!");
5808  if (!IFD->isFromASTFile())
5809  return; // Declaration not imported from PCH.
5810 
5811  assert(IFD->getDefinition() && "Category on a class without a definition?");
5812  ObjCClassesWithCategories.insert(
5813  const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
5814 }
5815 
5817  assert(!WritingAST && "Already writing the AST!");
5818  if (!D->isFromASTFile())
5819  return;
5820 
5821  DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
5822 }
5823 
5825  assert(!WritingAST && "Already writing the AST!");
5826  if (!D->isFromASTFile())
5827  return;
5828 
5829  DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE));
5830 }
5831 
5833  assert(!WritingAST && "Already writing the AST!");
5834  assert(D->isHidden() && "expected a hidden declaration");
5835  DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M));
5836 }
5837 
5839  const RecordDecl *Record) {
5840  assert(!WritingAST && "Already writing the AST!");
5841  if (!Record->isFromASTFile())
5842  return;
5843  DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr));
5844 }
void AddTemplateArgument(const TemplateArgument &Arg, RecordDataImpl &Record)
Emit a template argument.
Definition: ASTWriter.cpp:5302
bool hasLineDirectives() const
Return true if this FileID has #line directives in it.
A PredefinedExpr record.
Definition: ASTBitCodes.h:1215
unsigned getNumElements() const
Definition: Type.h:2749
TypeSourceInfo * getUnderlyingTInfo() const
Definition: TypeLoc.h:1646
SourceManager & getSourceManager() const
Definition: Preprocessor.h:687
bool isPoisoned() const
Return true if this token has been poisoned.
SourceLocation getOptimizeOffPragmaLocation() const
Get the location for the currently active "\#pragma clang optimize off". If this location is invalid...
Definition: Sema.h:7714
A FriendTemplateDecl record.
Definition: ASTBitCodes.h:1109
Defines the clang::ASTContext interface.
unsigned getNumArrayIndices() const
Determine the number of implicit array indices used while described an array member initialization...
Definition: DeclCXX.h:2094
A CompoundLiteralExpr record.
Definition: ASTBitCodes.h:1255
A NonTypeTemplateParmDecl record.
Definition: ASTBitCodes.h:1127
QualType getExceptionType(unsigned i) const
Definition: Type.h:3221
Represents a type that was referred to using an elaborated type keyword, e.g., struct S...
Definition: Type.h:4262
SourceLocation getEnd() const
QualType getUnderlyingType() const
Definition: Type.h:3458
UnusedFileScopedDeclsType UnusedFileScopedDecls
The set of file scoped decls seen so far that have not been used and must warn if not used...
Definition: Sema.h:493
Record code for the preprocessor options table.
Definition: ASTBitCodes.h:313
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:5108
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition: Type.h:4778
unsigned getAnonymousDeclarationNumber(const NamedDecl *D)
Definition: ASTWriter.cpp:5079
uint64_t getMacroDirectivesOffset(const IdentifierInfo *Name)
Definition: ASTWriter.cpp:4804
void AddedVisibleDecl(const DeclContext *DC, const Decl *D) override
A new declaration with name has been added to a DeclContext.
Definition: ASTWriter.cpp:5694
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1483
llvm::SmallSetVector< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition: Sema.h:455
bool isVariadic() const
Definition: Type.h:3255
std::string Name
The name of this module.
Definition: Basic/Module.h:50
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
ExtVectorDeclsType ExtVectorDecls
ExtVectorDecls - This is a list all the extended vector types.
Definition: Sema.h:443
IdentifierInfo * getIdentifier() const
Definition: ASTBitCodes.h:1559
iterator begin() const
Definition: DeclBase.h:1090
Source range/offset of a preprocessed entity.
Definition: ASTBitCodes.h:166
Header getUmbrellaHeader() const
Retrieve the header that serves as the umbrella header for this module.
Definition: Basic/Module.h:401
SourceLocation getElaboratedKeywordLoc() const
Definition: TypeLoc.h:1840
unsigned getDepth() const
Definition: Type.h:3779
Record code for the signature that identifiers this AST file.
Definition: ASTBitCodes.h:283
no exception specification
void AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo, RecordDataImpl &Record)
Definition: ASTWriter.cpp:5133
Record code for potentially unused local typedef names.
Definition: ASTBitCodes.h:571
Smart pointer class that efficiently represents Objective-C method names.
Record code for map of Objective-C class definition IDs to the ObjC categories in a module that are a...
Definition: ASTBitCodes.h:529
This is a discriminated union of FileInfo and ExpansionInfo.
An IndirectGotoStmt record.
Definition: ASTBitCodes.h:1199
llvm::iterator_range< pack_iterator > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
Definition: TemplateBase.h:329
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2147
Represents the dependent type named by a dependently-scoped typename using declaration, e.g.
Definition: Type.h:3332
A (possibly-)qualified type.
Definition: Type.h:575
static void EmitBlockID(unsigned ID, const char *Name, llvm::BitstreamWriter &Stream, ASTWriter::RecordDataImpl &Record)
Definition: ASTWriter.cpp:723
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition: DeclCXX.h:206
A PointerType record.
Definition: ASTBitCodes.h:834
#define BLOCK(X)
void FunctionDefinitionInstantiated(const FunctionDecl *D) override
A function template's definition was instantiated.
Definition: ASTWriter.cpp:5776
An AddrLabelExpr record.
Definition: ASTBitCodes.h:1271
bool isBaseOfClass() const
Determine whether this base class is a base of a class declared with the 'class' keyword (vs...
Definition: DeclCXX.h:210
The macro directives history for a particular identifier.
Definition: ASTBitCodes.h:618
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition: Type.h:1527
Represents a version number in the form major[.minor[.subminor[.build]]].
Definition: VersionTuple.h:26
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
Definition: TemplateBase.h:282
Implements support for file system lookup, file system caching, and directory search management...
Definition: FileManager.h:115
SourceLocation getNameLoc() const
Definition: TypeLoc.h:1804
void AddToken(const Token &Tok, RecordDataImpl &Record)
Emit a token.
Definition: ASTWriter.cpp:3951
unsigned local_sloc_entry_size() const
Get the number of local SLocEntries we have.
LateParsedTemplateMapT LateParsedTemplateMap
Definition: Sema.h:521
ArrayRef< const IdentifierInfo * > args() const
Definition: MacroInfo.h:180
FunctionDecl * getExceptionSpecDecl() const
If this function type has an exception specification which hasn't been determined yet (either because...
Definition: Type.h:3235
OpenCL volatile options.
Definition: LangOptions.h:166
A CXXStaticCastExpr record.
Definition: ASTBitCodes.h:1357
Defines the clang::FileManager interface and associated types.
Record code for the source manager line table information, which stores information about #line direc...
Definition: ASTBitCodes.h:525
An AttributedStmt record.
Definition: ASTBitCodes.h:1185
void AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record)
Emit an integral value.
Definition: ASTWriter.cpp:4751
DeclarationName getCXXConstructorName(CanQualType Ty)
getCXXConstructorName - Returns the name of a C++ constructor for the given Type. ...
A CXXReinterpretCastExpr record.
Definition: ASTBitCodes.h:1361
QualType getBaseType() const
Definition: Type.h:3512
bool isKindOfTypeAsWritten() const
Whether this is a "__kindof" type as written.
Definition: Type.h:4688
A ObjCBoolLiteralExpr record.
Definition: ASTBitCodes.h:1337
void getUndefinedButUsed(SmallVectorImpl< std::pair< NamedDecl *, SourceLocation > > &Undefined)
Obtain a sorted list of functions that are undefined but ODR-used.
Definition: Sema.cpp:474
submodule_iterator submodule_begin()
Definition: Basic/Module.h:474
ArrayRef< RawComment * > getComments() const
unsigned getHash() const
Compute a fingerprint of this key for use in on-disk hash table.
Definition: ASTReader.cpp:887
const unsigned NUM_PREDEF_TYPE_IDS
The number of predefined type IDs that are reserved for the PREDEF_TYPE_* constants.
Definition: ASTBitCodes.h:820
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:1439
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:2847
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known...
void MacroDefinitionRead(serialization::PreprocessedEntityID ID, MacroDefinitionRecord *MD) override
A macro definition was read from the AST file.
Definition: ASTWriter.cpp:5653
unsigned IsExternC
Whether this is an 'extern "C"' module (which implicitly puts all headers in it within an 'extern "...
Definition: Basic/Module.h:178
IdentifierInfo * getCXXLiteralIdentifier() const
getCXXLiteralIdentifier - If this name is the name of a literal operator, retrieve the identifier ass...
OverloadedOperatorKind getOperator() const
Return the overloaded operator to which this template name refers.
Definition: TemplateName.h:483
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition: Basic/Module.h:368
C Language Family Type Representation.
Defines the SourceManager interface.
uint32_t IdentID
An ID number that refers to an identifier in an AST file.
Definition: ASTBitCodes.h:123
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in...
static bool isImportedDeclContext(ASTReader *Chain, const Decl *D)
Definition: ASTWriter.cpp:5681
const LangOptions & getLangOpts() const
Definition: ASTWriter.cpp:4069
Represents a qualified type name for which the type name is dependent.
Definition: Type.h:4328
The template argument is an expression, and we've not resolved it to one of the other forms yet...
Definition: TemplateBase.h:69
CXXRecordDecl * getDecl() const
Definition: Type.cpp:3060
RawCommentList Comments
All comments in this translation unit.
Definition: ASTContext.h:609
NestedNameSpecifierLoc getPrefix() const
Return the prefix of this nested-name-specifier.
An ImplicitValueInitExpr record.
Definition: ASTBitCodes.h:1265
unsigned getNextLocalOffset() const
unsigned size() const
Number of modules loaded.
const unsigned int NUM_PREDEF_SELECTOR_IDS
The number of predefined selector IDs.
Definition: ASTBitCodes.h:145
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:77
An ImplicitCastExpr record.
Definition: ASTBitCodes.h:1251
Defines the FileSystemStatCache interface.
void CompletedTagDefinition(const TagDecl *D) override
A new TagDecl definition was completed.
Definition: ASTWriter.cpp:5664
const SrcMgr::SLocEntry & getSLocEntry(FileID FID, bool *Invalid=nullptr) const
A VarTemplatePartialSpecializationDecl record.
Definition: ASTBitCodes.h:1121
bool isObjectLike() const
Definition: MacroInfo.h:197
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed...
Definition: Sema.h:6906
unsigned IsFramework
Whether this is a framework module.
Definition: Basic/Module.h:166
bool hasCommaPasting() const
Definition: MacroInfo.h:214
Kind getKind() const
Definition: MacroInfo.h:334
Defines the C++ template declaration subclasses.
Describes a source location entry (SLocEntry) for a macro expansion.
Definition: ASTBitCodes.h:596
Represents a C++11 auto or C++14 decltype(auto) type.
Definition: Type.h:3918
static NamedDecl * getDeclForLocalLookup(const LangOptions &LangOpts, NamedDecl *D)
Determine the declaration that should be put into the name lookup table to represent the given declar...
Definition: ASTWriter.cpp:3098
An LValueReferenceType record.
Definition: ASTBitCodes.h:838
static unsigned getNumberOfModules(Module *Mod)
Compute the number of modules within the given tree (including the given module). ...
Definition: ASTWriter.cpp:2377
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration, or NULL if there is no previous declaration.
Definition: DeclBase.h:834
Defines the clang::MacroInfo and clang::MacroDirective classes.
A CXXOperatorCallExpr record.
Definition: ASTBitCodes.h:1349
Optional< unsigned > getMinor() const
Retrieve the minor version number, if provided.
Definition: VersionTuple.h:72
Specifies the submodules that are imported by this submodule.
Definition: ASTBitCodes.h:656
A record that stores the set of declarations that are lexically stored within a given DeclContext...
Definition: ASTBitCodes.h:1066
TemplateSpecializationType(TemplateName T, const TemplateArgument *Args, unsigned NumArgs, QualType Canon, QualType Aliased)
Definition: Type.cpp:3118
void ReaderInitialized(ASTReader *Reader) override
The ASTReader was initialized.
Definition: ASTWriter.cpp:5592
QualType getPointeeType() const
Definition: Type.h:2388
IdentifierInfo * getAsIdentifierInfo() const
getAsIdentifierInfo - Retrieve the IdentifierInfo * stored in this declaration name, or NULL if this declaration name isn't a simple identifier.
Specifies an umbrella directory.
Definition: ASTBitCodes.h:653
A CXXTemporaryObjectExpr record.
Definition: ASTBitCodes.h:1355
CXXRecordDecl * getAsRecordDecl() const
Retrieve the record declaration stored in this nested name specifier.
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition: Sema.h:6946
uint32_t DeclID
An ID number that refers to a declaration in an AST file.
Definition: ASTBitCodes.h:63
SourceLocation getLocalRangeBegin() const
Definition: TypeLoc.h:1260
Each ExpansionInfo encodes the expansion location - where the token was ultimately expanded...
DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, unsigned NumArgs, const TemplateArgument *Args, QualType Canon)
Definition: Type.cpp:2454
const ExpansionInfo & getExpansion() const
unsigned getLength() const
Efficiently return the length of this identifier info.
A SubstTemplateTypeParmType record.
Definition: ASTBitCodes.h:876
QualType getRecordType(const RecordDecl *Decl) const
std::unique_ptr< llvm::MemoryBuffer > Buffer
void AddTypeSourceInfo(TypeSourceInfo *TInfo, RecordDataImpl &Record)
Emits a reference to a declarator info.
Definition: ASTWriter.cpp:4897
Class that performs name lookup into a DeclContext stored in an AST file.
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2424
SourceLocation getRParenLoc() const
Definition: DeclCXX.h:2090
TemplateTemplateParmDecl * getParameterPack() const
Retrieve the template template parameter pack being substituted.
Definition: TemplateName.h:132
The template argument is a declaration that was provided for a pointer, reference, or pointer to member non-type template parameter.
Definition: TemplateBase.h:51
NamespaceDecl - Represent a C++ namespace.
Definition: Decl.h:402
A ObjCPropertyDecl record.
Definition: ASTBitCodes.h:1039
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
StoredDeclsMap * getLookupPtr() const
Retrieve the internal representation of the lookup structure.
Definition: DeclBase.h:1735
Wrapper for source info for typedefs.
Definition: TypeLoc.h:620
void AddTemplateName(TemplateName Name, RecordDataImpl &Record)
Emit a template name.
Definition: ASTWriter.cpp:5249
bool hasBaseTypeAsWritten() const
Definition: TypeLoc.h:933
serialization::DeclID GetDeclRef(const Decl *D)
Force a declaration to be emitted and get its ID.
Definition: ASTWriter.cpp:4959
A container of type source information.
Definition: Decl.h:61
void AddCXXCtorInitializersRef(ArrayRef< CXXCtorInitializer * > Inits, RecordDataImpl &Record)
Emit the ID for a CXXCtorInitializer array and register the array for later serialization.
Definition: ASTWriter.cpp:4835
unsigned getIndex() const
Definition: Type.h:3780
Record code for enabled OpenCL extensions.
Definition: ASTBitCodes.h:508
Record code for the module build directory.
Definition: ASTBitCodes.h:286
Floating point control options.
Definition: LangOptions.h:155
void * getAsOpaquePtr() const
An ElaboratedType record.
Definition: ASTBitCodes.h:874
void AddTypeRef(QualType T, RecordDataImpl &Record)
Emit a reference to a type.
Definition: ASTWriter.cpp:4915
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:305
serialization::SelectorID BaseSelectorID
Base selector ID for selectors local to this module.
An UnresolvedUsingType record.
Definition: ASTBitCodes.h:878
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
unsigned fp_contract
Definition: LangOptions.h:157
static void AddStmtsExprs(llvm::BitstreamWriter &Stream, ASTWriter::RecordDataImpl &Record)
Definition: ASTWriter.cpp:749
const TemplateArgument & get(unsigned Idx) const
Retrieve the template argument at a given index.
Definition: DeclTemplate.h:217
unsigned getRawEncoding() const
When a SourceLocation itself cannot be used, this returns an (opaque) 32-bit integer encoding for it...
Wrapper for source info for pointers decayed from arrays and functions.
Definition: TypeLoc.h:1095
bool hasAttrEnumOperand() const
Definition: TypeLoc.h:738
Describes the capture of a variable or of this, or of a C++1y init-capture.
Definition: LambdaCapture.h:26
SourceRange getAttrOperandParensRange() const
The location of the parentheses around the operand, if there is an operand.
Definition: TypeLoc.h:797
bool isSpelledAsLValue() const
Definition: Type.h:2304
An IncompleteArrayType record.
Definition: ASTBitCodes.h:846
A template template parameter that has been substituted for some other template name.
Definition: TemplateName.h:200
Specifies a header that is part of the module but must be textually included.
Definition: ASTBitCodes.h:675
const llvm::APInt & getSize() const
Definition: Type.h:2495
static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream)
Create an abbreviation for the SLocEntry that refers to a buffer's blob.
Definition: ASTWriter.cpp:1634
A ClassTemplateDecl record.
Definition: ASTBitCodes.h:1111
SourceLocation getIncludeLoc() const
CharacteristicKind getFileCharacteristic() const
Return whether this is a system header or not.
An UnresolvedUsingTypenameDecl record.
Definition: ASTBitCodes.h:1090
unsigned getCounterValue() const
An identifier, stored as an IdentifierInfo*.
The internal '__builtin_va_list' typedef.
Definition: ASTBitCodes.h:977
Manages the set of modules loaded by an AST reader.
Definition: ModuleManager.h:32
serialization::MacroID getMacroRef(MacroInfo *MI, const IdentifierInfo *Name)
Get the unique number used to refer to the given macro.
Definition: ASTWriter.cpp:4780
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:699
Expr * getInit() const
Get the initializer.
Definition: DeclCXX.h:2119
bool decls_empty() const
Definition: DeclBase.cpp:1173
Wrapper for source info for member pointers.
Definition: TypeLoc.h:1163
Options for controlling the target.
Definition: TargetOptions.h:24
Wrapper of type source information for a type with non-trivial direct qualifiers. ...
Definition: TypeLoc.h:247
bool hasAttrExprOperand() const
Definition: TypeLoc.h:733
A UsingShadowDecl record.
Definition: ASTBitCodes.h:1084
SourceLocation getDefinitionLoc() const
Return the location that the macro was defined at.
Definition: MacroInfo.h:120
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:46
AutoTypeKeyword getKeyword() const
Definition: Type.h:3936
void DeclarationMarkedOpenMPThreadPrivate(const Decl *D) override
A declaration is marked as OpenMP threadprivate which was not previously marked as threadprivate...
Definition: ASTWriter.cpp:5824
serialization::SubmoduleID BaseSubmoduleID
Base submodule ID for submodules local to this module.
const unsigned int NUM_PREDEF_DECL_IDS
The number of declaration IDs that are predefined.
Definition: ASTBitCodes.h:996
static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream)
Create an abbreviation for the SLocEntry that refers to a file.
Definition: ASTWriter.cpp:1600
QualType getucontext_tType() const
Retrieve the C ucontext_t type.
Definition: ASTContext.h:1517
The value of the next COUNTER to dispense.
Definition: ASTBitCodes.h:424
const DeclContext * getDefinitiveDeclContext(const DeclContext *DC)
Retrieve the "definitive" declaration that provides all of the visible entries for the given declarat...
Definition: ASTCommon.cpp:207
TemplateTypeParmDecl * getDecl() const
Definition: Type.h:3783
Specifies the umbrella header used to create this module, if any.
Definition: ASTBitCodes.h:647
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
Definition: TemplateBase.h:566
A namespace, stored as a NamespaceDecl*.
void AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record)
Emit a CXXTemporary.
Definition: ASTWriter.cpp:4831
QualType getOriginalType() const
Definition: Type.h:2211
iterator local_end()
End iterator for local, non-loaded, preprocessed entities.
unsigned isCompilingModuleHeader
Whether this header is part of the module that we are building.
Definition: HeaderSearch.h:60
ModuleMap & getModuleMap()
Retrieve the module map.
Definition: HeaderSearch.h:591
Record code for header search information.
Definition: ASTBitCodes.h:502
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:48
Describes a source location entry (SLocEntry) for a buffer.
Definition: ASTBitCodes.h:588
Used to hold and unique data used to represent #line information.
llvm::MapVector< Selector, SourceLocation > ReferencedSelectors
Method selectors used in a @selector expression.
Definition: Sema.h:966
A CXXConstructExpr record.
Definition: ASTBitCodes.h:1353
Record code for the target options table.
Definition: ASTBitCodes.h:301
serialization::IdentID getIdentifierRef(const IdentifierInfo *II)
Get the unique number used to refer to the given identifier.
Definition: ASTWriter.cpp:4770
static StringRef bytes(const std::vector< T, Allocator > &v)
Definition: ASTWriter.cpp:68
bool hasAttrOperand() const
Definition: TypeLoc.h:743
A TemplateTemplateParmDecl record.
Definition: ASTBitCodes.h:1129
Record code for the array of eagerly deserialized decls.
Definition: ASTBitCodes.h:395
TemplateTemplateParmDecl * getParameter() const
Definition: TemplateName.h:326
ParmVarDecl - Represents a parameter to a function.
Definition: Decl.h:1299
Represents the result of substituting a type for a template type parameter.
Definition: Type.h:3817
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:1042
Defines the clang::Expr interface and subclasses for C++ expressions.
FPOptions & getFPOptions()
Definition: Sema.h:1043
A ObjCInterfaceDecl record.
Definition: ASTBitCodes.h:1023
QualType getRawCFConstantStringType() const
Get the structure type used to representation CFStrings, or NULL if it hasn't yet been built...
Definition: ASTContext.h:1382
QualType getUnderlyingType() const
Definition: Type.h:3511
SourceLocation getAmpAmpLoc() const
Definition: TypeLoc.h:1238
void AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record)
Emit a reference to an identifier.
Definition: ASTWriter.cpp:4766
bool isBaseInitializer() const
Determine whether this initializer is initializing a base class.
Definition: DeclCXX.h:1965
The collection of all-type qualifiers we support.
Definition: Type.h:116
A ShuffleVectorExpr record.
Definition: ASTBitCodes.h:1279
Record code for the diagnostic options table.
Definition: ASTBitCodes.h:304
PipeType - OpenCL20.
Definition: Type.h:5020
iterator begin(DeclarationName Name)
begin - Returns an iterator for decls with the name 'Name'.
const IdentifierInfo * getIdentifier() const
Returns the identifier to which this template name refers.
Definition: TemplateName.h:473
known_categories_iterator known_categories_begin() const
Retrieve an iterator to the beginning of the known-categories list.
Definition: DeclObjC.h:1362
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:40
unsigned getNumParams() const
Definition: Type.h:3160
RecordDecl - Represents a struct/union/class.
Definition: Decl.h:3166
const unsigned VERSION_MAJOR
AST file major version number supported by this version of Clang.
Definition: ASTBitCodes.h:39
void AddQualifierInfo(const QualifierInfo &Info, RecordDataImpl &Record)
Definition: ASTWriter.cpp:5140
SourceRange getLocalSourceRange() const
Retrieve the source range covering just the last part of this nested-name-specifier, not including the prefix.
const IdentifierInfo * getIdentifier() const
Retrieve the type named by the typename specifier as an identifier.
Definition: Type.h:4355
DeclarationName getName() const
getName - Returns the embedded declaration name.
const StringRef FilePath
One of these records is kept for each identifier that is lexed.
unsigned getIndexTypeCVRQualifiers() const
Definition: Type.h:2465
A macro directive exported by a module.
Definition: ASTBitCodes.h:622
An ObjCAtThrowStmt record.
Definition: ASTBitCodes.h:1333
time_t getTimestampForOutput(const FileEntry *E) const
Get a timestamp for output into the AST file.
Definition: ASTWriter.cpp:4074
Specifies a top-level header that falls into this (sub)module.
Definition: ASTBitCodes.h:651
The block containing comments.
Definition: ASTBitCodes.h:225
OverloadedTemplateStorage * getAsOverloadedTemplate() const
Retrieve the underlying, overloaded function template.
A DesignatedInitExpr record.
Definition: ASTBitCodes.h:1261
StringRef getModuleCachePath() const
Retrieve the path to the module cache.
Definition: HeaderSearch.h:324
class LLVM_ALIGNAS(8) DependentTemplateSpecializationType const IdentifierInfo * Name
Represents a template specialization type whose template cannot be resolved, e.g. ...
Definition: Type.h:4381
bool isNull() const
Definition: TypeLoc.h:95
Represents a class type in Objective C.
Definition: Type.h:4557
bool isFromAST() const
Return true if the identifier in its current state was loaded from an AST file.
Iteration over the preprocessed entities.
Expr * getSizeExpr() const
Definition: Type.h:2591
void AddTypeLoc(TypeLoc TL, RecordDataImpl &Record)
Emits a type with source-location information.
Definition: ASTWriter.cpp:4907
IdentifierInfo * getIdentifierInfoForSlot(unsigned argIndex) const
Retrieve the identifier at a given position in the selector.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:91
A C++ nested-name-specifier augmented with source location information.
Record the location of a macro definition.
Represents a dependent template name that cannot be resolved prior to template instantiation.
Definition: TemplateName.h:411
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1054
bool isIdentifier() const
Determine whether this template name refers to an identifier.
Definition: TemplateName.h:470
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:57
void RedefinedHiddenDefinition(const NamedDecl *D, Module *M) override
A definition has been made visible by being redefined locally.
Definition: ASTWriter.cpp:5832
Specifies a header that has been explicitly excluded from this submodule.
Definition: ASTBitCodes.h:664
static SourceLocation getFromRawEncoding(unsigned Encoding)
Turn a raw encoding of a SourceLocation object into a real SourceLocation.
SmallVector< Requirement, 2 > Requirements
The set of language features required to use this module.
Definition: Basic/Module.h:148
TypeSourceInfo * getTypeArgTInfo(unsigned i) const
Definition: TypeLoc.h:886
SourceLocation getLocalRangeEnd() const
Definition: TypeLoc.h:1267
SourceLocation getEllipsisLoc() const
Retrieve the location of the ellipsis for a capture that is a pack expansion.
bool isCompleteDefinition() const
isCompleteDefinition - Return true if this decl has its body fully specified.
Definition: Decl.h:2788
SourceLocation getTypeArgsRAngleLoc() const
Definition: TypeLoc.h:875
bool isMemberInitializer() const
Determine whether this initializer is initializing a non-static data member.
Definition: DeclCXX.h:1971
The unsigned 128-bit integer type.
Definition: ASTBitCodes.h:971
Record code for the module map file that was used to build this AST file.
Definition: ASTBitCodes.h:280
void ResolvedOperatorDelete(const CXXDestructorDecl *DD, const FunctionDecl *Delete) override
A virtual destructor's operator delete has been resolved.
Definition: ASTWriter.cpp:5757
NameKind getKind() const
An ExtVectorType record.
Definition: ASTBitCodes.h:852
Delete expressions that will be analyzed later.
Definition: ASTBitCodes.h:578
bool isBeingDefined() const
Determines whether this type is in the process of being defined.
Definition: Type.cpp:2965
llvm::MapVector< const FunctionDecl *, LateParsedTemplate * > LateParsedTemplateMapT
Definition: Sema.h:520
ParmVarDecl * getParam(unsigned i) const
Definition: TypeLoc.h:1306
SourceLocation getLParenLoc() const
Definition: TypeLoc.h:1679
unsigned size() const
bool isTranslationUnit() const
Definition: DeclBase.h:1269
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Definition: DeclTemplate.h:232
NestedNameSpecifier * getQualifier() const
Retrieve the qualification on this type.
Definition: Type.h:4348
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:28
const LangOptions & getLangOpts() const
Definition: Preprocessor.h:683
CachedTokens Toks
Definition: Sema.h:9272
Represents the result of substituting a set of types for a template type parameter pack...
Definition: Type.h:3872
Token - This structure provides full information about a lexed token.
Definition: Token.h:37
static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream)
Create an abbreviation for the SLocEntry that refers to a macro expansion.
Definition: ASTWriter.cpp:1645
unsigned getNumProtocols() const
Definition: TypeLoc.h:910
Wrapper for source info for unresolved typename using decls.
Definition: TypeLoc.h:642
bool makeAbsolutePath(SmallVectorImpl< char > &Path) const
Makes Path absolute taking into account FileSystemOptions and the working directory option...
SourceLocation getBuiltinLoc() const
Definition: TypeLoc.h:522
unsigned size() const
Definition: DeclTemplate.h:91
An AttributedType record.
Definition: ASTBitCodes.h:898
unsigned getAsOpaqueValue() const
Definition: Type.h:225
An object-like macro definition.
Definition: ASTBitCodes.h:606
~ASTWriter() override
Definition: ASTWriter.cpp:4065
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:48
unsigned getRegParm() const
Definition: Type.h:2916
qual_range quals() const
Definition: Type.h:4666
Describes one token.
Definition: ASTBitCodes.h:615
An AdjustedType record.
Definition: ASTBitCodes.h:910
Describes a module or submodule.
Definition: Basic/Module.h:47
QualType getUnderlyingType() const
Definition: Type.h:3437
Expr * getUnderlyingExpr() const
Definition: Type.h:3457
A IndirectFieldDecl record.
Definition: ASTBitCodes.h:1139
FileManager & getFileManager() const
Definition: Preprocessor.h:686
Record code for the set of ext_vector type names.
Definition: ASTBitCodes.h:439
iterator end()
end - Returns an iterator that has 'finished'.
serialization::MacroID getMacroID(MacroInfo *MI)
Determine the ID of an already-emitted macro.
Definition: ASTWriter.cpp:4796
T * getAttr() const
Definition: DeclBase.h:495
Specifies the submodules that are re-exported from this submodule.
Definition: ASTBitCodes.h:659
TemplateParameterList ** TemplParamLists
TemplParamLists - A new-allocated array of size NumTemplParamLists, containing pointers to the "outer...
Definition: Decl.h:558
serialization::MacroID BaseMacroID
Base macro ID for macros local to this module.
TemplateArgument getArgumentPack() const
Definition: Type.cpp:3078
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2351
uint32_t SubmoduleID
An ID number that refers to a submodule in a module file.
Definition: ASTBitCodes.h:160
SourceLocation getLAngleLoc() const
Definition: DeclTemplate.h:131
SmallVector< uint64_t, 64 > RecordData
Definition: ASTWriter.h:87
unsigned InferExportWildcard
Whether, when inferring submodules, the inferr submodules should export all modules they import (e...
Definition: Basic/Module.h:195
A qualified template name, where the qualification is kept to describe the source code as written...
Definition: TemplateName.h:194
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:580
const LangOptions & getLangOpts() const
Definition: ASTContext.h:596
Wrapper for source info for injected class names of class templates.
Definition: TypeLoc.h:631
A record of the steps taken while preprocessing a source file, including the various preprocessing di...
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:514
Capturing by copy (a.k.a., by value)
Definition: Lambda.h:36
IndirectFieldDecl * getIndirectMember() const
Definition: DeclCXX.h:2045
An AccessSpecDecl record.
Definition: ASTBitCodes.h:1104
SourceLocation getRAngleLoc() const
Definition: TypeLoc.h:1462
uint32_t Offset
Definition: CacheTokens.cpp:44
Describes a blob that contains the data for a buffer entry.
Definition: ASTBitCodes.h:593
QualType getBaseType() const
Gets the base type of this object type.
Definition: Type.h:4612
Record code for the language options table.
Definition: ASTBitCodes.h:298
ModuleManager & getModuleManager()
Retrieve the module manager.
Definition: ASTReader.h:1473
QualType getReturnType() const
Definition: Type.h:2977
Wrapper for source info for functions.
Definition: TypeLoc.h:1255
Specifies a conflict with another module.
Definition: ASTBitCodes.h:670
The signed 128-bit integer type.
Definition: ASTBitCodes.h:968
StoredDeclsMap * buildLookup()
Ensure the lookup structure is fully-built and return it.
Definition: DeclBase.cpp:1306
bool isUsedForHeaderGuard() const
Determine whether this macro was used for a header guard.
Definition: MacroInfo.h:272
SourceLocation getEllipsisLoc() const
For a pack expansion, determine the location of the ellipsis.
Definition: DeclCXX.h:224
A UnaryTransformType record.
Definition: ASTBitCodes.h:904
UnresolvedUsingTypenameDecl * getDecl() const
Definition: Type.h:3342
A reference to a previously [de]serialized Stmt record.
Definition: ASTBitCodes.h:1173
NestedNameSpecifierLoc getQualifierLoc() const
Definition: TypeLoc.h:1792
A UsingDirecitveDecl record.
Definition: ASTBitCodes.h:1086
An ObjCObjectType record.
Definition: ASTBitCodes.h:882
void IdentifierRead(serialization::IdentID ID, IdentifierInfo *II) override
An identifier was deserialized from the AST file.
Definition: ASTWriter.cpp:5621
A ConstantArrayType record.
Definition: ASTBitCodes.h:844
TemplateArgument getArgumentPack() const
Retrieve the template template argument pack with which this parameter was substituted.
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:704
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:135
Represents a typeof (or typeof) expression (a GCC extension).
Definition: Type.h:3384
Record code for #pragma optimize options.
Definition: ASTBitCodes.h:568
GlobalMethodPool MethodPool
Method Pool - allows efficient lookup when typechecking messages to "id".
Definition: Sema.h:962
HeaderSearch & getHeaderSearchInfo() const
Definition: Preprocessor.h:688
void AddSourceRange(SourceRange Range, RecordDataImpl &Record)
Emit a source range.
Definition: ASTWriter.cpp:4746
Specifies a header that is private to this submodule but must be textually included.
Definition: ASTBitCodes.h:678
Expr * getNoexceptExpr() const
Definition: Type.h:3225
TypeSourceInfo * getClassTInfo() const
Definition: TypeLoc.h:1177
Record code for pending implicit instantiations.
Definition: ASTBitCodes.h:469
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:697
SourceLocation RAngleLoc
The source location of the right angle bracket ('>').
Definition: TemplateBase.h:579
The internal '__make_integer_seq' template.
Definition: ASTBitCodes.h:989
QualifiedTemplateName * getAsQualifiedTemplateName() const
Retrieve the underlying qualified template name structure, if any.
bool needsExtraLocalData() const
Definition: TypeLoc.h:538
Decl * getVaListTagDecl() const
Retrieve the C type declaration corresponding to the predefined __va_list_tag type used to help defin...
Record code for #pragma diagnostic mappings.
Definition: ASTBitCodes.h:496
Module * Parent
The parent of this module.
Definition: Basic/Module.h:57
An ExtQualType record.
Definition: ASTBitCodes.h:830
void AddTemplateParameterList(const TemplateParameterList *TemplateParams, RecordDataImpl &Record)
Emit a template parameter list.
Definition: ASTWriter.cpp:5344
Record code for floating point #pragma options.
Definition: ASTBitCodes.h:505
void AddSelectorRef(Selector, RecordDataImpl &Record)
Emit a Selector (which is a smart pointer reference).
Definition: ASTWriter.cpp:4808
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition: Sema.h:687
TemplateDecl * getTemplateDecl() const
The template declaration to which this qualified name refers.
Definition: TemplateName.h:389
SourceLocation getRParenLoc() const
Definition: TypeLoc.h:1601
Wrapper for source info for ObjC interfaces.
Definition: TypeLoc.h:981
Record code for the set of known namespaces, which are used for typo correction.
Definition: ASTBitCodes.h:515
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:651
SourceLocation getFileLoc(SourceLocation Loc) const
Given Loc, if it is a macro location return the expansion location or the spelling location...
TypeID MakeTypeID(ASTContext &Context, QualType T, IdxForTypeTy IdxForType)
Definition: ASTCommon.h:47
Record code for an array of all of the (sub)modules that were imported by the AST file...
Definition: ASTBitCodes.h:536
submodule_iterator submodule_end()
Definition: Basic/Module.h:476
bool isDelegatingInitializer() const
Determine whether this initializer is creating a delegating constructor.
Definition: DeclCXX.h:1993
serialization::DeclID BaseDeclID
Base declaration ID for declarations local to this module.
QualType getsigjmp_bufType() const
Retrieve the C sigjmp_buf type.
Definition: ASTContext.h:1505
NestedNameSpecifier * getQualifier() const
Retrieve the qualification on this type.
Definition: Type.h:4289
TypeClass getTypeClass() const
Definition: Type.h:1501
void AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg, RecordDataImpl &Record)
Emits a template argument location.
Definition: ASTWriter.cpp:4882
VarDecl * getCapturedVar() const
Retrieve the declaration of the local variable being captured.
Definition: LambdaCapture.h:93
A marker record that indicates that we are at the end of an expression.
Definition: ASTBitCodes.h:1169
A ClassTemplateSpecializationDecl record.
Definition: ASTBitCodes.h:1113
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC)...
Definition: DeclBase.h:708
tok::TokenKind getKind() const
Definition: Token.h:90
A BlockPointerType record.
Definition: ASTBitCodes.h:836
NestedNameSpecifier * getQualifier() const
Return the nested name specifier that qualifies this name.
Definition: TemplateName.h:467
void StaticDataMemberInstantiated(const VarDecl *D) override
A static data member was implicitly instantiated.
Definition: ASTWriter.cpp:5784
Preprocessor & PP
Definition: Sema.h:294
A MemberPointerType record.
Definition: ASTBitCodes.h:842
Represents an ObjC class declaration.
Definition: DeclObjC.h:853
bool isWritten() const
Determine whether this initializer is explicitly written in the source code.
Definition: DeclCXX.h:2063
ObjCMethodDecl * getMethod() const
SourceLocation getTypeofLoc() const
Definition: TypeLoc.h:1587
detail::InMemoryDirectory::const_iterator I
SourceLocation getTypeArgsLAngleLoc() const
Definition: TypeLoc.h:868
unsigned getNumParams() const
Definition: TypeLoc.h:1301
void AddDeclarationName(DeclarationName Name, RecordDataImpl &Record)
Emit a declaration name.
Definition: ASTWriter.cpp:5045
serialization::TypeID getTypeID(QualType T) const
Determine the type ID of an already-emitted type.
Definition: ASTWriter.cpp:4942
The preprocessor keeps track of this information for each file that is #included. ...
Definition: HeaderSearch.h:39
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
QualType getCanonicalTypeInternal() const
Definition: Type.h:1973
Record code for the table of offsets into the block of source-location information.
Definition: ASTBitCodes.h:428
bool isInvalid() const
serialization::SubmoduleID inferSubmoduleIDFromLocation(SourceLocation Loc)
Infer the submodule ID that contains an entity at the given source location.
Definition: ASTWriter.cpp:2605
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:753
bool hasModeAttr() const
Definition: TypeLoc.h:595
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:2686
const TemplateTypeParmType * getReplacedParameter() const
Gets the template parameter that was substituted for.
Definition: Type.h:3893
A SubstTemplateTypeParmPackType record.
Definition: ASTBitCodes.h:900
TypeCode
Record codes for each kind of type.
Definition: ASTBitCodes.h:828
DiagnosticsEngine & getDiagnostics() const
Iterator that walks over the list of categories, filtering out those that do not meet specific criter...
Definition: DeclObjC.h:1265
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
unsigned getObjCOrBuiltinID() const
Encapsulates the information needed to find the file referenced by a #include or #include_next, (sub-)framework lookup, etc.
Definition: HeaderSearch.h:137
IdentifierInfo * getAlias() const
Definition: Weak.h:34
SourceLocation getKWLoc() const
Definition: TypeLoc.h:2047
AnnotatingParser & P
Represents a K&R-style 'int foo()' function, which has no information available about its arguments...
Definition: Type.h:3007
unsigned IsSystem
Whether this is a "system" module (which assumes that all headers in it are system headers)...
Definition: Basic/Module.h:173
The block containing information about the source manager.
Definition: ASTBitCodes.h:208
bool isCPlusPlusOperatorKeyword() const
void AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD, const ObjCInterfaceDecl *IFD) override
A new objc category class was added for an interface.
Definition: ASTWriter.cpp:5805
const TemplateArgumentLoc * getTemplateArgs() const
Retrieve the template arguments.
Definition: TemplateBase.h:585
void AddedAttributeToRecord(const Attr *Attr, const RecordDecl *Record) override
An attribute was added to a RecordDecl.
Definition: ASTWriter.cpp:5838
void SelectorRead(serialization::SelectorID ID, Selector Sel) override
A selector was read from the AST file.
Definition: ASTWriter.cpp:5646
TypeLoc getNextTypeLoc() const
Get the next TypeLoc pointed by this TypeLoc, e.g for "int*" the TypeLoc is a PointerLoc and next Typ...
Definition: TypeLoc.h:145
A VariableArrayType record.
Definition: ASTBitCodes.h:848
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:5003
void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, RecordDataImpl &Record)
Emit a nested name specifier with source-location information.
Definition: ASTWriter.cpp:5195
Optional< unsigned > getNumTemplateExpansions() const
Retrieve the number of expansions that a template template argument expansion will produce...
QualType getInjectedSpecializationType() const
Definition: Type.h:4158
void ModuleRead(serialization::SubmoduleID ID, Module *Mod) override
A module definition was read from the AST file.
Definition: ASTWriter.cpp:5659
ExtInfo getExtInfo() const
Definition: Type.h:2986
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:259
const unsigned int NUM_PREDEF_PP_ENTITY_IDS
The number of predefined preprocessed entity IDs.
Definition: ASTBitCodes.h:197
TypeLoc getTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
unsigned NumTemplParamLists
NumTemplParamLists - The number of "outer" template parameter lists.
Definition: Decl.h:551
QualType getParamType(unsigned i) const
Definition: Type.h:3161
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3041
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:3193
TentativeDefinitionsType TentativeDefinitions
All the tentative definitions encountered in the TU.
Definition: Sema.h:485
Defines the major attributes of a submodule, including its name and parent.
Definition: ASTBitCodes.h:644
const llvm::MapVector< FieldDecl *, DeleteLocs > & getMismatchingDeleteExpressions() const
Retrieves list of suspicious delete-expressions that will be checked at the end of translation unit...
Definition: Sema.cpp:1525
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
SourceLocation getAttrEnumOperandLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition: TypeLoc.h:784
llvm::SmallSetVector< Module *, 2 > Imports
The set of modules imported by this module, and on which this module depends.
Definition: Basic/Module.h:221
StringRef Filename
Definition: Format.cpp:1723
A dependent template name that has not been resolved to a template (or set of templates).
Definition: TemplateName.h:197
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:454
SourceLocation getLBracketLoc() const
Definition: TypeLoc.h:1363
unsigned getOwningModuleID() const
Retrieve the global ID of the module that owns this particular declaration.
Definition: DeclBase.h:647
ASTContext * Context
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization, retrieves the member specialization information.
Definition: Decl.cpp:2291
unsigned LocalNumSLocEntries
The number of source location entries in this AST file.
A StaticAssertDecl record.
Definition: ASTBitCodes.h:1133
Captures information about a #pragma weak directive.
Definition: Weak.h:25
void AddPath(StringRef Path, RecordDataImpl &Record)
Add a path to the given record.
Definition: ASTWriter.cpp:3987
ID
Defines the set of possible language-specific address spaces.
Definition: AddressSpaces.h:27
A VarTemplateSpecializationDecl record.
Definition: ASTBitCodes.h:1119
Record code for the table of offsets of each macro ID.
Definition: ASTBitCodes.h:553
SourceManager & SM
NameKind getNameKind() const
getNameKind - Determine what kind of name this is.
static const char * adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir)
Adjusts the given filename to only write out the portion of the filename that is not part of the syst...
Definition: ASTWriter.cpp:1137
Exposes information about the current target.
A record containing CXXBaseSpecifiers.
Definition: ASTBitCodes.h:1135
unsigned IgnoreSysRoot
IgnoreSysRoot - This is false if an absolute path should be treated relative to the sysroot...
Represents an array type in C++ whose size is a value-dependent expression.
Definition: Type.h:2627
void AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs, RecordDataImpl &Record)
Emit a template argument list.
Definition: ASTWriter.cpp:5357
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
SourceLocation getElaboratedKeywordLoc() const
Definition: TypeLoc.h:1727
void FlushCXXBaseSpecifiers()
Flush all of the C++ base specifier sets that have been added via AddCXXBaseSpecifiersRef().
Definition: ASTWriter.cpp:5400
bool isImplicit() const
Determine whether this was an implicit capture (not written between the square brackets introducing t...
An ObjCObjectPointerType record.
Definition: ASTBitCodes.h:870
An TemplateSpecializationType record.
Definition: ASTBitCodes.h:886
Type source information for an attributed type.
Definition: TypeLoc.h:724
An ObjCInterfaceType record.
Definition: ASTBitCodes.h:868
SourceLocation getRBracketLoc() const
Definition: TypeLoc.h:1370
QualType getPointeeType() const
Definition: Type.h:2268
Expr - This represents one expression.
Definition: Expr.h:104
HeaderSearchOptions & getHeaderSearchOpts() const
Retrieve the header-search options with which this header search was initialized. ...
Definition: HeaderSearch.h:260
A ObjCCategoryImplDecl record.
Definition: ASTBitCodes.h:1033
StringRef getName() const
Return the actual identifier string.
Record code for the array of VTable uses.
Definition: ASTBitCodes.h:449
static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II, bool IsModule)
Whether the given identifier is "interesting".
Definition: ASTReader.cpp:749
bool isLookupContext() const
Test whether the context supports looking up names.
Definition: DeclBase.h:1261
SourceLocation getLParenLoc() const
Definition: DeclCXX.h:2089
The directory that the PCH was originally created in.
Definition: ASTBitCodes.h:265
unsigned getNumArgs() const
A ObjCPropertyImplDecl record.
Definition: ASTBitCodes.h:1041
TypeSpecifierWidth getWrittenWidthSpec() const
Definition: TypeLoc.h:572
unsigned LocalNumIdentifiers
The number of identifiers in this AST file.
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
Definition: TemplateBase.h:582
Implements an efficient mapping from strings to IdentifierInfo nodes.
bool hasLineTable() const
Determine if the source manager has a line table.
Defines implementation details of the clang::SourceManager class.
SourceManager & SourceMgr
Definition: Format.cpp:1352
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:54
FileManager & getFileManager() const
unsigned getNumArgs() const
Definition: MacroInfo.h:179
Inits[]
Definition: OpenMPClause.h:310
unsigned ConfigMacrosExhaustive
Whether the set of configuration macros is exhaustive.
Definition: Basic/Module.h:202
Record code for the table of offsets to entries in the preprocessing record.
Definition: ASTBitCodes.h:446
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2345
LazyDeclPtr StdNamespace
The C++ "std" namespace, where the standard library resides.
Definition: Sema.h:683
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:875
A CXXConstructorDecl record.
Definition: ASTBitCodes.h:1098
Defines version macros and version-related utility functions for Clang.
Expr * getUnderlyingExpr() const
Definition: Type.h:3391
Defines the clang::Preprocessor interface.
ArgKind
The kind of template argument we're storing.
Definition: TemplateBase.h:43
const SrcMgr::SLocEntry & getLocalSLocEntry(unsigned Index, bool *Invalid=nullptr) const
Get a local SLocEntry. This is exposed for indexing.
The block containing the detailed preprocessing record.
Definition: ASTBitCodes.h:219
AccessSpecifier getAccessSpecifierAsWritten() const
Retrieves the access specifier as written in the source code (which may mean that no access specifier...
Definition: DeclCXX.h:245
QualType getNamedType() const
Retrieve the type named by the qualified-id.
Definition: Type.h:4292
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:216
bool getNoReturn() const
Definition: Type.h:2913
llvm::MapVector< IdentifierInfo *, WeakInfo > WeakUndeclaredIdentifiers
WeakUndeclaredIdentifiers - Identifiers contained in #pragma weak before declared.
Definition: Sema.h:656
serialization::TypeID GetOrCreateTypeID(QualType T)
Force a type to be emitted and get its ID.
Definition: ASTWriter.cpp:4919
SourceLocation getLParenLoc() const
Definition: TypeLoc.h:2003
SourceLocation getLocation() const
Retrieve the source location of the capture.
A structure for storing the information associated with a substituted template template parameter...
Definition: TemplateName.h:313
lookup_result noload_lookup(DeclarationName Name)
Find the declarations with the given name that are visible within this context; don't attempt to retr...
Definition: DeclBase.cpp:1430
unsigned LocalNumMacros
The number of macros in this AST file.
A CXXStdInitializerListExpr record.
Definition: ASTBitCodes.h:1369
A record containing CXXCtorInitializers.
Definition: ASTBitCodes.h:1137
ArrayRef< const FileEntry * > getTopHeaders(FileManager &FileMgr)
The top-level headers associated with this module.
A VarTemplateDecl record.
Definition: ASTBitCodes.h:1117
IdentifierResolver - Keeps track of shadowed decls on enclosing scopes.
SubstTemplateTemplateParmPackStorage * getAsSubstTemplateTemplateParmPack() const
Retrieve the substituted template template parameter pack, if known.
Record code for the original file that was used to generate the AST file, including both its file ID ...
Definition: ASTBitCodes.h:262
An ArraySubscriptExpr record.
Definition: ASTBitCodes.h:1239
Represents a C++ template name within the type system.
Definition: TemplateName.h:175
llvm::SmallVector< LinkLibrary, 2 > LinkLibraries
The set of libraries or frameworks to link against when an entity from this module is used...
Definition: Basic/Module.h:275
Represents the type decltype(expr) (C++11).
Definition: Type.h:3449
Information about a module that has been loaded by the ASTReader.
A namespace alias, stored as a NamespaceAliasDecl*.
void AddString(StringRef Str, RecordDataImpl &Record)
Add a string to the given record.
Definition: ASTWriter.cpp:3964
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file. ...
Definition: Token.h:124
A CXXDestructorDecl record.
Definition: ASTBitCodes.h:1100
unsigned getLocalOrImportedSubmoduleID(Module *Mod)
Retrieve or create a submodule ID for this module, or return 0 if the submodule is neither local (a s...
Definition: ASTWriter.cpp:2351
SourceLocation getMemberLocation() const
Definition: DeclCXX.h:2051
bool isSubModuleOf(const Module *Other) const
Determine whether this module is a submodule of the given other module.
Kind getAttrKind() const
Definition: Type.h:3661
void AddCXXBaseSpecifier(const CXXBaseSpecifier &Base, RecordDataImpl &Record)
Emit a C++ base specifier.
Definition: ASTWriter.cpp:5387
A FunctionProtoType record.
Definition: ASTBitCodes.h:856
A NonTypeTemplateParmDecl record that stores an expanded non-type template parameter pack...
Definition: ASTBitCodes.h:1142
SourceLocation getTemplateNameLoc() const
Definition: TypeLoc.h:1483
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition: TypeLoc.h:107
QualType getFILEType() const
Retrieve the C FILE type.
Definition: ASTContext.h:1481
Describes a source location entry (SLocEntry) for a file.
Definition: ASTBitCodes.h:585
SmallVector< VTableUse, 16 > VTableUses
The list of vtables that are required but have not yet been materialized.
Definition: Sema.h:5252
void FlushPendingAfterDecl()
Flush all pending records that are tacked onto the end of decl and decl update records.
Definition: ASTWriter.h:816
Wrapper for source info for enum types.
Definition: TypeLoc.h:680
A unary type transform, which is a type constructed from another.
Definition: Type.h:3490
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:1751
A block containing a module file extension.
Definition: ASTBitCodes.h:246
unsigned getNumTokens() const
Return the number of tokens that this macro expands to.
Definition: MacroInfo.h:231
bool hasTrailingReturn() const
Definition: Type.h:3265
std::string FileName
The file name of the module file.
A NamespaceAliasDecl record.
Definition: ASTBitCodes.h:1080
QualType getCXXNameType() const
getCXXNameType - If this name is one of the C++ names (of a constructor, destructor, or conversion function), return the type associated with that name.
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition: DeclBase.h:635
Record code for an update to a decl context's lookup table.
Definition: ASTBitCodes.h:481
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion, return the pattern as a template name.
Definition: TemplateBase.h:269
const unsigned VERSION_MINOR
AST file minor version number supported by this version of Clang.
Definition: ASTBitCodes.h:49
SourceLocation getModuleImportLoc(Module *M) const
A DesignatedInitUpdateExpr record.
Definition: ASTBitCodes.h:1263
unsigned header_file_size() const
Definition: HeaderSearch.h:596
Represents a GCC generic vector type.
Definition: Type.h:2724
struct CXXOpName CXXOperatorName
a DecltypeType record.
Definition: ASTBitCodes.h:872
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2334
CXXRecordDecl * getStdBadAlloc() const
An ImplicitParamDecl record.
Definition: ASTBitCodes.h:1049
DirectoryName getUmbrellaDir() const
Retrieve the directory for which this module serves as the umbrella.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
SourceLocation getExpansionLocEnd() const
QualType getElementType() const
Definition: Type.h:2748
void MacroRead(serialization::MacroID ID, MacroInfo *MI) override
A macro was read from the AST file.
Definition: ASTWriter.cpp:5628
unsigned SLocEntryBaseOffset
The base offset in the source manager's view of this module.
An EnumConstantDecl record.
Definition: ASTBitCodes.h:1017
Record code for the table of offsets of each identifier ID.
Definition: ASTBitCodes.h:366
Record code for undefined but used functions and variables that need a definition in this TU...
Definition: ASTBitCodes.h:562
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:162
A DependentNameType record.
Definition: ASTBitCodes.h:888
do v
Definition: arm_acle.h:77
Abstract base class that writes a module file extension block into a module file. ...
A ObjCCategoryDecl record.
Definition: ASTBitCodes.h:1031
QualType getReplacementType() const
Gets the type that was substituted for the template parameter.
Definition: Type.h:3838
bool isC99Varargs() const
Definition: MacroInfo.h:202
LambdaCaptureKind getCaptureKind() const
Determine the kind of capture.
Definition: ExprCXX.cpp:910
An ObjCForCollectionStmt record.
Definition: ASTBitCodes.h:1323
Record code for the identifier table.
Definition: ASTBitCodes.h:385
const HeaderFileInfo * getExistingFileInfo(const FileEntry *FE, bool WantExternal=true) const
Return the HeaderFileInfo structure for the specified FileEntry, if it has ever been filled in...
Decl * VaListTagDecl
Definition: ASTContext.h:916
A ObjCCompatibleAliasDecl record.
Definition: ASTBitCodes.h:1037
AttrVec & getAttrs()
Definition: DeclBase.h:443
SourceLocation getProtocolRAngleLoc() const
Definition: TypeLoc.h:903
SmallVector< ExportDecl, 2 > Exports
The set of export declarations.
Definition: Basic/Module.h:230
SourceLocation getTemplateNameLoc() const
Definition: TemplateBase.h:410
SourceRange getBracketsRange() const
Definition: Type.h:2652
DelegatingCtorDeclsType DelegatingCtorDecls
All the delegating constructors seen so far in the file, used for cycle detection at the end of the T...
Definition: Sema.h:501
A MS-style AsmStmt record.
Definition: ASTBitCodes.h:1213
void AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record)
Emit a source location.
Definition: ASTWriter.cpp:4742
unsigned getLocalFastQualifiers() const
Definition: Type.h:605
const unsigned int NUM_PREDEF_IDENT_IDS
The number of predefined identifier IDs.
Definition: ASTBitCodes.h:126
const TemplateTypeParmType * getReplacedParameter() const
Gets the template parameter that was substituted for.
Definition: Type.h:3832
SpecifierKind
The kind of specifier that completes this nested name specifier.
SourceLocation getKWLoc() const
Definition: TypeLoc.h:1676
NamespaceDecl * getAsNamespace() const
Retrieve the namespace stored in this nested name specifier.
NestedNameSpecifierLoc getTemplateQualifierLoc() const
Definition: TemplateBase.h:405
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition: TypeLoc.h:1910
A template template parameter pack that has been substituted for a template template argument pack...
Definition: TemplateName.h:204
Wrapper for source info for arrays.
Definition: TypeLoc.h:1358
Record code for the set of source location entries that need to be preloaded by the AST reader...
Definition: ASTBitCodes.h:436
QualifierInfo - A struct with extended info about a syntactic name qualifier, to be used for the case...
Definition: Decl.h:544
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition: TypeLoc.h:1479
Information about a FileID, basically just the logical file that it represents and include stack info...
The list of delegating constructor declarations.
Definition: ASTBitCodes.h:511
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:215
DeclContext::lookup_result getLookupResult()
getLookupResult - Return an array of all the decls that this list represents.
unsigned isModuleHeader
Whether this header is part of a module.
Definition: HeaderSearch.h:57
Encapsulates changes to the "macros namespace" (the location where the macro name became active...
Definition: MacroInfo.h:307
SourceLocation getTemplateKeywordLoc() const
Definition: TypeLoc.h:1448
SourceLocation getRParenLoc() const
Definition: TypeLoc.h:1028
An UnresolvedUsingValueDecl record.
Definition: ASTBitCodes.h:1088
#define false
Definition: stdbool.h:33
serialization::TypeID BaseTypeIndex
Base type ID for types local to this module as represented in the global type ID space.
Kind
void AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record)
Emit a signed integral value.
Definition: ASTWriter.cpp:4757
bool hasRevertedBuiltin() const
True if setNotBuiltin() was called.
bool hasChangedSinceDeserialization() const
Determine whether this identifier has changed since it was loaded from an AST file.
serialization::IdentID BaseIdentifierID
Base identifier ID for identifiers local to this module.
const char * getName() const
Definition: FileManager.h:84
Encodes a location in the source.
Sugar for parentheses used when specifying types.
Definition: Type.h:2116
const char * getNameStart() const
Return the beginning of the actual null-terminated string for this identifier.
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:3570
void AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg, RecordDataImpl &Record)
Emits a template argument location info.
Definition: ASTWriter.cpp:4853
const TemplateArgument * iterator
Definition: Type.h:4070
QualType getElementType() const
Definition: Type.h:2099
FileSystemOptions & getFileSystemOpts()
Returns the current file system options.
Definition: FileManager.h:221
A record that stores the set of declarations that are visible from a given DeclContext.
Definition: ASTBitCodes.h:1074
Specifies a library or framework to link against.
Definition: ASTBitCodes.h:666
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this function type.
Definition: Type.h:3271
Record code for file ID of the file or buffer that was used to generate the AST file.
Definition: ASTBitCodes.h:269
Represents a C++ temporary.
Definition: ExprCXX.h:1075
Represents typeof(type), a GCC extension.
Definition: Type.h:3425
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:4766
Specifies a header that falls into this (sub)module.
Definition: ASTBitCodes.h:649
Record code for the table of offsets to CXXBaseSpecifier sets.
Definition: ASTBitCodes.h:493
A structure for storing an already-substituted template template parameter pack.
Definition: TemplateName.h:118
A ComplexType record.
Definition: ASTBitCodes.h:832
Record code for special CUDA declarations.
Definition: ASTBitCodes.h:499
OverloadedOperatorKind getCXXOverloadedOperator() const
getCXXOverloadedOperator - If this name is the name of an overloadable operator in C++ (e...
Options for controlling the compiler diagnostics engine.
A list of "interesting" identifiers.
Definition: ASTBitCodes.h:558
SourceLocation getLParenLoc() const
Definition: TypeLoc.h:1274
The block of configuration options, used to check that a module is being used in a configuration comp...
Definition: ASTBitCodes.h:243
TagDecl - Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:2644
void DefaultArgumentInstantiated(const ParmVarDecl *D) override
A default argument was instantiated.
Definition: ASTWriter.cpp:5796
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:311
unsigned getOffset() const
bool isPackExpansion() const
Determine whether this base specifier is a pack expansion.
Definition: DeclCXX.h:213
virtual void writeExtensionContents(Sema &SemaRef, llvm::BitstreamWriter &Stream)=0
Write the contents of the extension block into the given bitstream.
This is so that older clang versions, before the introduction of the control block, can read and reject the newer PCH format.
Definition: ASTBitCodes.h:371
IdentifierTable & getIdentifierTable()
Definition: Preprocessor.h:690
VectorKind getVectorKind() const
Definition: Type.h:2757
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3527
Cached information about one file (either on disk or in the virtual file system). ...
Definition: FileManager.h:53
Metadata describing this particular extension.
Definition: ASTBitCodes.h:319
static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule, const Preprocessor &PP)
Definition: ASTWriter.cpp:2046
FileManager & getFileMgr() const
Definition: HeaderSearch.h:262
SmallVector< Header, 2 > Headers[5]
The headers that are part of this module.
Definition: Basic/Module.h:126
A CXXFunctionalCastExpr record.
Definition: ASTBitCodes.h:1365
Record code for the offsets of each decl.
Definition: ASTBitCodes.h:358
SourceLocation getTemplateEllipsisLoc() const
Definition: TemplateBase.h:414
SourceLocation getNameLoc() const
Definition: TypeLoc.h:493
Metadata for submodules as a whole.
Definition: ASTBitCodes.h:641
SourceLocation getDefinitionEndLoc() const
Return the location of the last token in the macro.
Definition: MacroInfo.h:126
An ObjCEncodeExpr record.
Definition: ASTBitCodes.h:1302
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
A TypeOfExprType record.
Definition: ASTBitCodes.h:860
std::string getClangFullRepositoryVersion()
Retrieves the full repository version that is an amalgamation of the information in getClangRepositor...
Definition: Version.cpp:90
Record code for late parsed template functions.
Definition: ASTBitCodes.h:565
bool isBaseVirtual() const
Returns whether the base is virtual or not.
Definition: DeclCXX.h:2018
Defines the clang::TargetOptions class.
A TemplateTypeParmDecl record.
Definition: ASTBitCodes.h:1125
frontend::IncludeDirGroup Group
unsigned LocalNumDecls
The number of declarations in this AST file.
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:1931
unsigned getMajor() const
Retrieve the major version number.
Definition: VersionTuple.h:69
The internal 'instancetype' typedef.
Definition: ASTBitCodes.h:974
unsigned getNumTypeArgs() const
Definition: TypeLoc.h:882
FunctionDecl * getExceptionSpecTemplate() const
If this function type has an uninstantiated exception specification, this is the function whose excep...
Definition: Type.h:3245
void CompletedImplicitDefinition(const FunctionDecl *D) override
An implicit member got a definition.
Definition: ASTWriter.cpp:5767
SourceLocation getRParenLoc() const
Definition: TypeLoc.h:2010
Describes the categories of an Objective-C class.
Definition: ASTBitCodes.h:1514
static ASTFileSignature getSignature()
Definition: ASTWriter.cpp:1173
uint32_t MacroID
An ID number that refers to a macro in an AST file.
Definition: ASTBitCodes.h:129
const FileInfo & getFile() const
void AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record)
Definition: ASTWriter.cpp:5500
The AST block, which acts as a container around the full AST block.
Definition: ASTBitCodes.h:204
TypedefNameDecl * getDecl() const
Definition: Type.h:3375
DiagnosticOptions & getDiagnosticOptions() const
Retrieve the diagnostic options.
Definition: Diagnostic.h:358
TypeSpecifierType getWrittenTypeSpec() const
Definition: TypeLoc.cpp:289
unsigned getNumProtocols() const
Return the number of qualifying protocols in this interface type, or 0 if there are none...
Definition: Type.h:4674
SubstTemplateTemplateParmStorage * getAsSubstTemplateTemplateParm() const
Retrieve the substituted template template parameter, if known.
NamespaceAliasDecl * getAsNamespaceAlias() const
Retrieve the namespace alias stored in this nested name specifier.
SourceLocation getBegin() const
void AddVersionTuple(const VersionTuple &Version, RecordDataImpl &Record)
Add a version tuple to the given record.
Definition: ASTWriter.cpp:4000
ModuleFileExtension * getExtension() const
Retrieve the module file extension with which this writer is associated.
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1368
void AddNestedNameSpecifier(NestedNameSpecifier *NNS, RecordDataImpl &Record)
Emit a nested name specifier.
Definition: ASTWriter.cpp:5148
const Token & getReplacementToken(unsigned Tok) const
Definition: MacroInfo.h:233
void AddDeclRef(const Decl *D, RecordDataImpl &Record)
Emit a reference to a declaration.
Definition: ASTWriter.cpp:4955
An InjectedClassNameType record.
Definition: ASTBitCodes.h:880
FileID getMainFileID() const
Returns the FileID of the main source file.
bool getInheritConstructors() const
Determine whether this base class's constructors get inherited.
Definition: DeclCXX.h:216
bool isFileContext() const
Definition: DeclBase.h:1265
Record code for the extra statistics we gather while generating an AST file.
Definition: ASTBitCodes.h:408
FunctionDecl * getcudaConfigureCallDecl()
Definition: ASTContext.h:1093
A NamespaceDecl record.
Definition: ASTBitCodes.h:1078
int getSourceOrder() const
Return the source position of the initializer, counting from 0.
Definition: DeclCXX.h:2067
SourceLocation getKWLoc() const
Definition: TypeLoc.h:1996
static void addExceptionSpec(ASTWriter &Writer, const FunctionProtoType *T, ASTWriter::RecordDataImpl &Record)
Definition: ASTWriter.cpp:211
An array of decls optimized for the common case of only containing one entry.
bool PreparePathForOutput(SmallVectorImpl< char > &Path)
Convert a path from this build process into one that is appropriate for emission in the module file...
Definition: ASTWriter.cpp:3969
UTTKind getUTTKind() const
Definition: Type.h:3514
unsigned LocalNumSubmodules
The number of submodules in this module.
unsigned ComputeHash(Selector Sel)
Definition: ASTCommon.cpp:195
void AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases, CXXBaseSpecifier const *BasesEnd, RecordDataImpl &Record)
Emit a set of C++ base specifiers to the record.
Definition: ASTWriter.cpp:4843
DiagnosticsEngine & getDiagnostics() const
Definition: Preprocessor.h:680
Record code for referenced selector pool.
Definition: ASTBitCodes.h:454
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:245
bool isLocalSourceLocation(SourceLocation Loc) const
Returns true if Loc did not come from a PCH/Module.
SourceLocation getNameLoc() const
Definition: TypeLoc.h:990
Represents a pointer type decayed from an array or function type.
Definition: Type.h:2231
FileID getPredefinesFileID() const
Returns the FileID for the preprocessor predefines.
Definition: Preprocessor.h:770
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:4128
QualType getPointeeType() const
Definition: Type.h:2161
Record code for the set of non-builtin, special types.
Definition: ASTBitCodes.h:404
A ObjCProtocolDecl record.
Definition: ASTBitCodes.h:1025
Represents a pack expansion of types.
Definition: Type.h:4471
SmallVectorImpl< uint64_t > RecordDataImpl
Definition: ASTWriter.h:88
ArrayRef< QualType > getTypeArgsAsWritten() const
Retrieve the type arguments of this object type as they were written.
Definition: Type.h:4658
DeclarationNameLoc - Additional source/type location info for a declaration name. ...
Expr * getSizeExpr() const
Definition: Type.h:2647
unsigned getFlags() const
Return the internal represtation of the flags.
Definition: Token.h:247
SourceLocation getLocation() const
Definition: Weak.h:35
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:2526
void SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset)
Note that the identifier II occurs at the given offset within the identifier table.
Definition: ASTWriter.cpp:4015
unsigned LocalNumSelectors
The number of selectors new to this file.
Record code for a decl replacement block.
Definition: ASTBitCodes.h:476
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T-> getSizeExpr()))
void AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc, DeclarationName Name, RecordDataImpl &Record)
Definition: ASTWriter.cpp:5100
Represents a template argument.
Definition: TemplateBase.h:40
Record code for the list of other AST files imported by this AST file.
Definition: ASTBitCodes.h:257
A CXXConversionDecl record.
Definition: ASTBitCodes.h:1102
Describes a macro definition within the preprocessing record.
Definition: ASTBitCodes.h:631
void DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) override
A function's return type has been deduced.
Definition: ASTWriter.cpp:5748
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons...
Definition: Type.h:2195
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:238
Represents a template name that was expressed as a qualified name.
Definition: TemplateName.h:354
TypeSourceInfo * getTypeSourceInfo() const
Returns the declarator information for a base class or delegating initializer.
Definition: DeclCXX.h:2026
Record code for the module name.
Definition: ASTBitCodes.h:276
Selector getObjCSelector() const
getObjCSelector - Get the Objective-C selector stored in this declaration name.
Describes an inclusion directive within the preprocessing record.
Definition: ASTBitCodes.h:635
An InitListExpr record.
Definition: ASTBitCodes.h:1259
The internal '__builtin_ms_va_list' typedef.
Definition: ASTBitCodes.h:983
bool hasTemplateKeyword() const
Whether the template name was prefixed by the "template" keyword.
Definition: TemplateName.h:381
not evaluated yet, for special member function
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1121
Record code for a file sorted array of DeclIDs in a module.
Definition: ASTBitCodes.h:532
A CXXBoolLiteralExpr record.
Definition: ASTBitCodes.h:1371
Record code for the array of Objective-C categories (including extensions).
Definition: ASTBitCodes.h:546
Specifies a configuration macro for this module.
Definition: ASTBitCodes.h:668
void AddASTTemplateArgumentListInfo(const ASTTemplateArgumentListInfo *ASTTemplArgList, RecordDataImpl &Record)
Emits an AST template argument list info.
Definition: ASTWriter.cpp:5367
virtual ModuleFileExtensionMetadata getExtensionMetadata() const =0
Retrieves the metadata for this module file extension.
Module * inferModuleFromLocation(FullSourceLoc Loc)
Infers the (sub)module based on the given source location and source manager.
Definition: ModuleMap.cpp:919
SourceLocation getEllipsisLoc() const
Definition: TypeLoc.h:1956
bool hasLocalNonFastQualifiers() const
Determine whether this particular QualType instance has any "non-fast" qualifiers, e.g., those that are stored in an ExtQualType instance.
Definition: Type.h:689
An ExtVectorElementExpr record.
Definition: ASTBitCodes.h:1257
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:63
Record code for the array of unused file scoped decls.
Definition: ASTBitCodes.h:442
llvm::iterator_range< submodule_iterator > submodules()
Definition: Basic/Module.h:479
A FunctionNoProtoType record.
Definition: ASTBitCodes.h:854
Reads an AST files chain containing the contents of a translation unit.
Definition: ASTReader.h:311
bool getProducesResult() const
Definition: Type.h:2914
QualType getEquivalentType() const
Definition: Type.h:3666
A ClassTemplatePartialSpecializationDecl record.
Definition: ASTBitCodes.h:1115
#define RECORD(X)
SourceLocation getStarLoc() const
Definition: TypeLoc.h:1202
ObjCInterfaceDecl * getDefinition()
Retrieve the definition of this class, or NULL if this class has been forward-declared (with @class) ...
Definition: DeclObjC.h:1216
IdentifierInfo * getAsIdentifier() const
Retrieve the identifier stored in this nested name specifier.
SourceLocation getTemplateKeywordLoc() const
Definition: TypeLoc.h:1871
bool isGNUVarargs() const
Definition: MacroInfo.h:203
bool isParameterPack() const
Definition: Type.h:3781
const ContentCache * getContentCache() const
void AddUnresolvedSet(const ASTUnresolvedSet &Set, RecordDataImpl &Record)
Emit a UnresolvedSet structure.
Definition: ASTWriter.cpp:5378
DeclarationName - The name of a declaration.
Record code for the Objective-C method pool,.
Definition: ASTBitCodes.h:420
const MacroInfo * getMacroInfo() const
Definition: MacroInfo.h:403
Record of updates for a declaration that was modified after being deserialized.
Definition: ASTBitCodes.h:489
static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream)
Create an abbreviation for the SLocEntry that refers to a buffer.
Definition: ASTWriter.cpp:1619
CallingConv getCC() const
Definition: Type.h:2922
SourceLocation getCaretLoc() const
Definition: TypeLoc.h:1150
Specifies a header that is private to this submodule.
Definition: ASTBitCodes.h:672
Expr * getSizeExpr() const
Definition: TypeLoc.h:1381
A LinkageSpecDecl record.
Definition: ASTBitCodes.h:1092
Describes a macro expansion within the preprocessing record.
Definition: ASTBitCodes.h:628
A CXXDynamicCastExpr record.
Definition: ASTBitCodes.h:1359
SourceLocation LAngleLoc
The source location of the left angle bracket ('<').
Definition: TemplateBase.h:576
bool hasAttrs() const
Definition: DeclBase.h:439
An EnumType record.
Definition: ASTBitCodes.h:866
detail::InMemoryDirectory::const_iterator E
SourceLocation getElaboratedKeywordLoc() const
Definition: TypeLoc.h:1785
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2369
QualType getModifiedType() const
Definition: Type.h:3665
PreprocessingRecord * getPreprocessingRecord() const
Retrieve the preprocessing record, or NULL if there is no preprocessing record.
Definition: Preprocessor.h:982
IdentifierResolver IdResolver
Definition: Sema.h:675
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:1946
FieldDecl * getMember() const
If this is a member initializer, returns the declaration of the non-static data member being initiali...
Definition: DeclCXX.h:2032
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
SourceLocation getExpansionLocStart() const
An RValueReferenceType record.
Definition: ASTBitCodes.h:840
A type that was preceded by the 'template' keyword, stored as a Type*.
bool isExtensionToken() const
get/setExtension - Initialize information about whether or not this language token is an extension...
unsigned Map[Count]
The type of a lookup table which maps from language-specific address spaces to target-specific ones...
Definition: AddressSpaces.h:45
An AtomicType record.
Definition: ASTBitCodes.h:906
An ObjCAtFinallyStmt record.
Definition: ASTBitCodes.h:1327
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:4836
Represents a pointer to an Objective C object.
Definition: Type.h:4821
Encapsulates the data about a macro definition (e.g.
Definition: MacroInfo.h:34
Pointer to a block type.
Definition: Type.h:2254
Capturing variable-length array type.
Definition: Lambda.h:38
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition: Type.h:808
time_t getModificationTime() const
Definition: FileManager.h:90
struct CXXLitOpName CXXLiteralOperatorName
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:3544
TypeSpecifierSign getWrittenSignSpec() const
Definition: TypeLoc.h:558
Complex values, per C99 6.2.5p11.
Definition: Type.h:2087
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:421
std::vector< Conflict > Conflicts
The list of conflicts.
Definition: Basic/Module.h:304
Record code for the table of offsets into the Objective-C method pool.
Definition: ASTBitCodes.h:417
unsigned getTypeQuals() const
Definition: Type.h:3267
bool getUsed()
Definition: Weak.h:37
Represents a C++ base or member initializer.
Definition: DeclCXX.h:1885
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
Definition: DeclTemplate.h:532
A DependentSizedArrayType record.
Definition: ASTBitCodes.h:892
Record code for the remapping information used to relate loaded modules to the various offsets and ID...
Definition: ASTBitCodes.h:521
An ObjCAtSynchronizedStmt record.
Definition: ASTBitCodes.h:1331
A key used when looking up entities by DeclarationName.
Definition: ASTBitCodes.h:1544
MacroDirective * getLocalMacroDirectiveHistory(const IdentifierInfo *II) const
Given an identifier, return the latest non-imported macro directive for that identifier.
An UnresolvedSet-like class which uses the ASTContext's allocator.
Record code for declarations that Sema keeps references of.
Definition: ASTBitCodes.h:463
QualType getIntegralType() const
Retrieve the type of the integral value.
Definition: TemplateBase.h:294
const unsigned int NUM_PREDEF_MACRO_IDS
The number of predefined macro IDs.
Definition: ASTBitCodes.h:139
Offsets into the input-files block where input files reside.
Definition: ASTBitCodes.h:273
A CXXMemberCallExpr record.
Definition: ASTBitCodes.h:1351
ExtVectorType - Extended vector type.
Definition: Type.h:2784
QualType getInnerType() const
Definition: Type.h:2130
void ResolvedExceptionSpec(const FunctionDecl *FD) override
A function's exception specification has been evaluated or instantiated.
Definition: ASTWriter.cpp:5734
const DeclarationNameLoc & getInfo() const
void FlushCXXCtorInitializers()
Flush all of the C++ constructor initializer lists that have been added via AddCXXCtorInitializersRef...
Definition: ASTWriter.cpp:5470
bool isBuiltinMacro() const
Return true if this macro requires processing before expansion.
Definition: MacroInfo.h:212
The block containing the submodule structure.
Definition: ASTBitCodes.h:222
Wrapper for source info for record types.
Definition: TypeLoc.h:672
TypeSourceInfo * getTypeSourceInfo() const
Retrieves the type and source location of the base class.
Definition: DeclCXX.h:257
ObjCInterfaceDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this Objective-C class.
Definition: DeclObjC.h:1575
The template argument is a type.
Definition: TemplateBase.h:48
Wraps an ObjCPointerType with source location information.
Definition: TypeLoc.h:1198
import_range local_imports() const
Definition: ASTContext.h:846
Optional< unsigned > getSubminor() const
Retrieve the subminor version number, if provided.
Definition: VersionTuple.h:79
serialization::SelectorID getSelectorRef(Selector Sel)
Get the unique number used to refer to the given selector.
Definition: ASTWriter.cpp:4812
The template argument is actually a parameter pack.
Definition: TemplateBase.h:72
serialization::PreprocessedEntityID BasePreprocessedEntityID
Base preprocessed entity ID for preprocessed entities local to this module.
Capturing the this pointer.
Definition: Lambda.h:35
void EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record, StringRef Path)
Emit the current record with the given path as a blob.
Definition: ASTWriter.cpp:3993
Represents a base class of a C++ class.
Definition: DeclCXX.h:157
SourceLocation getProtocolLAngleLoc() const
Definition: TypeLoc.h:896
SourceManager & getSourceManager()
Definition: ASTContext.h:553
Keeps track of options that affect how file operations are performed.
NestedNameSpecifierLoc getQualifierLoc() const
Definition: TypeLoc.h:1847
The type-property cache.
Definition: Type.cpp:3238
A TypedefType record.
Definition: ASTBitCodes.h:858
A template argument list.
Definition: DeclTemplate.h:172
TemplateArgumentLocInfo getLocInfo() const
Definition: TemplateBase.h:468
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
const Type * getClass() const
Definition: Type.h:2402
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
Definition: TemplateBase.h:256
NestedNameSpecifierLoc QualifierLoc
Definition: Decl.h:545
PreprocessorOptions & getPreprocessorOpts() const
Retrieve the preprocessor options used to initialize this preprocessor.
Definition: Preprocessor.h:678
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:3598
bool hasRevertedTokenIDToIdentifier() const
True if revertTokenIDToIdentifier() was called.
uint32_t PreprocessedEntityID
An ID number that refers to an entity in the detailed preprocessing record.
Definition: ASTBitCodes.h:157
SourceLocation getProtocolLoc(unsigned i) const
Definition: TypeLoc.h:914
unsigned pack_size() const
The number of template arguments in the given template argument pack.
Definition: TemplateBase.h:335
known_categories_iterator known_categories_end() const
Retrieve an iterator to the end of the known-categories list.
Definition: DeclObjC.h:1367
void AddStmt(Stmt *S)
Add the given statement or expression to the queue of statements to emit.
Definition: ASTWriter.h:798
bool isPackExpansion() const
Determine whether this capture is a pack expansion, which captures a function parameter pack...
A GCC-style AsmStmt record.
Definition: ASTBitCodes.h:1211
void SetSelectorOffset(Selector Sel, uint32_t Offset)
Note that the selector Sel occurs at the given offset within the method pool/selector table...
Definition: ASTWriter.cpp:4025
unsigned InferSubmodules
Whether we should infer submodules for this module based on the headers.
Definition: Basic/Module.h:187
Represents a C++ struct/union/class.
Definition: DeclCXX.h:285
void FlushStmts()
Flush all of the statements and expressions that have been added to the queue via AddStmt()...
uint32_t SelectorID
An ID number that refers to an ObjC selector in an AST file.
Definition: ASTBitCodes.h:142
An TemplateTypeParmType record.
Definition: ASTBitCodes.h:884
void DeclarationMarkedUsed(const Decl *D) override
A declaration is marked used which was not previously marked used.
Definition: ASTWriter.cpp:5816
Decl * D
The template function declaration to be late parsed.
Definition: Sema.h:9274
The template argument is a template name that was provided for a template template parameter...
Definition: TemplateBase.h:60
Represents a C array with an unspecified size.
Definition: Type.h:2530
Record code for the filesystem options table.
Definition: ASTBitCodes.h:307
SourceLocation getTemplateNameLoc() const
Definition: TypeLoc.h:1878
static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec, ASTWriter::RecordData &Record)
Definition: ASTWriter.cpp:4108
An ObjCAtCatchStmt record.
Definition: ASTBitCodes.h:1325
static bool cleanPathForOutput(FileManager &FileMgr, SmallVectorImpl< char > &Path)
Prepares a path for being written to an AST file by converting it to an absolute path and removing ne...
Definition: ASTWriter.cpp:1120
bool needsAnonymousDeclarationNumber(const NamedDecl *D)
Determine whether the given declaration needs an anonymous declaration number.
Definition: ASTCommon.cpp:346
A ObjCImplementationDecl record.
Definition: ASTBitCodes.h:1035
NestedNameSpecifier * getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
ArraySizeModifier getSizeModifier() const
Definition: Type.h:2459
ElaboratedTypeKeyword getKeyword() const
Definition: Type.h:4223
A structure for storing the information associated with an overloaded template name.
Definition: TemplateName.h:92
Capturing by reference.
Definition: Lambda.h:37
SourceLocation getRParenLoc() const
Definition: TypeLoc.h:1281
Location information for a TemplateArgument.
Definition: TemplateBase.h:362
A ObjCAtDefsFieldDecl record.
Definition: ASTBitCodes.h:1029
Record code for the offsets of each type.
Definition: ASTBitCodes.h:346
The block containing the definitions of all of the types and decls used within the AST file...
Definition: ASTBitCodes.h:216
The internal '__va_list_tag' struct, if any.
Definition: ASTBitCodes.h:980
This class is used for builtin types like 'int'.
Definition: Type.h:2011
Writes an AST file containing the contents of a translation unit.
Definition: ASTWriter.h:84
Record code for the table of offsets to CXXCtorInitializers lists.
Definition: ASTBitCodes.h:575
SourceLocation getLBracketLoc() const
Definition: Type.h:2597
serialization::DeclID getDeclID(const Decl *D)
Determine the declaration ID of an already-emitted declaration.
Definition: ASTWriter.cpp:4988
QualType getAdjustedType() const
Definition: Type.h:2212
const unsigned int LOCAL_REDECLARATIONS
Record code for a list of local redeclarations of a declaration.
Definition: ASTBitCodes.h:999
A TypeAliasDecl record.
Definition: ASTBitCodes.h:1011
LineTableInfo & getLineTable()
Retrieve the stored line table.
QualType getParamTypeForDecl() const
Definition: TemplateBase.h:250
NestedNameSpecifier * getQualifier() const
Return the nested name specifier that qualifies this name.
Definition: TemplateName.h:377
uint64_t WriteAST(Sema &SemaRef, const std::string &OutputFile, Module *WritingModule, StringRef isysroot, bool hasErrors=false)
Write a precompiled header for the given semantic analysis.
Definition: ASTWriter.cpp:4078
Defines the clang::TargetInfo interface.
MacroDefinitionRecord * findMacroDefinition(const MacroInfo *MI)
Retrieve the macro definition that corresponds to the given MacroInfo.
A SourceLocation and its associated SourceManager.
QualType getPattern() const
Retrieve the pattern of this pack expansion, which is the type that will be repeatedly instantiated w...
Definition: Type.h:4498
Defines the clang::VersionTuple class, which represents a version in the form major[.minor[.subminor]].
ArrayRef< ModuleMacro * > getLeafModuleMacros(const IdentifierInfo *II) const
Get the list of leaf (non-overridden) module macros for a name.
Definition: Preprocessor.h:891
a linked list of methods with the same selector name but different signatures.
Specifies a required feature.
Definition: ASTBitCodes.h:661
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
QualType getPointeeTypeAsWritten() const
Definition: Type.h:2307
std::vector< std::string > ConfigMacros
The set of "configuration macros", which are macros that (intentionally) change how this module is bu...
Definition: Basic/Module.h:279
bool getHasRegParm() const
Definition: Type.h:2915
TypeSourceInfo * getAsTypeSourceInfo() const
Definition: TemplateBase.h:397
uint32_t getIndex() const
Definition: ASTBitCodes.h:89
TagDecl * getDecl() const
Definition: Type.cpp:2961
SourceLocation getRParenLoc() const
Definition: TypeLoc.h:1682
SourceLocation getRBracketLoc() const
Definition: Type.h:2598
Record for offsets of DECL_UPDATES records for declarations that were modified after being deserializ...
Definition: ASTBitCodes.h:485
unsigned ModuleMapFileHomeIsCwd
Set the 'home directory' of a module map file to the current working directory (or the home directory...
TranslationUnitDecl - The top declaration context.
Definition: Decl.h:79
VarDecl * getArrayIndex(unsigned I)
Retrieve a particular array index variable used to describe an array member initialization.
Definition: DeclCXX.h:2100
NamespaceDecl * getAnonymousNamespace() const
Retrieve the anonymous namespace nested inside this namespace, if any.
Definition: Decl.h:479
QualType getjmp_bufType() const
Retrieve the C jmp_buf type.
Definition: ASTContext.h:1493
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:132
unsigned getLength() const
Definition: Token.h:127
QualType getElementType() const
Definition: Type.h:5033
QualType getElementType() const
Definition: Type.h:2458
SourceLocation getStarLoc() const
Definition: TypeLoc.h:1137
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:953
A FunctionTemplateDecl record.
Definition: ASTBitCodes.h:1123
llvm::DenseMap< CXXRecordDecl *, bool > VTablesUsed
The set of classes whose vtables have been used within this translation unit, and a bit that will be ...
Definition: Sema.h:5258
void AddCXXCtorInitializers(const CXXCtorInitializer *const *CtorInitializers, unsigned NumCtorInitializers, RecordDataImpl &Record)
Emit a CXXCtorInitializer array.
Definition: ASTWriter.cpp:5432
Contains a late templated function.
Definition: Sema.h:9271
OverloadedOperatorKind getOperatorKind() const
Definition: ASTBitCodes.h:1570
Record code for weak undeclared identifiers.
Definition: ASTBitCodes.h:466
The block containing information about the preprocessor.
Definition: ASTBitCodes.h:212
A DecayedType record.
Definition: ASTBitCodes.h:908
SourceLocation getAmpLoc() const
Definition: TypeLoc.h:1225
SourceLocation getLAngleLoc() const
Definition: TypeLoc.h:1455
uint32_t TypeID
An ID number that refers to a type in an AST file.
Definition: ASTBitCodes.h:80
unsigned getGlobalID() const
Retrieve the global declaration ID associated with this declaration, which specifies where in the...
Definition: DeclBase.h:639
Wrapper for source info for builtin types.
Definition: TypeLoc.h:517
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
A set of overloaded template declarations.
Definition: TemplateName.h:191
Wrapper for template type parameters.
Definition: TypeLoc.h:688
Record code for the headers search options table.
Definition: ASTBitCodes.h:310
A trivial tuple used to represent a source range.
SourceLocation getLocation() const
Definition: DeclBase.h:384
ASTContext & Context
Definition: Sema.h:295
NamedDecl - This represents a decl with a name.
Definition: Decl.h:145
AST file metadata, including the AST file version number and information about the compiler used to b...
Definition: ASTBitCodes.h:253
static void EmitRecordID(unsigned ID, const char *Name, llvm::BitstreamWriter &Stream, ASTWriter::RecordDataImpl &Record)
Definition: ASTWriter.cpp:739
The block of input files, which were used as inputs to create this AST file.
Definition: ASTBitCodes.h:236
ObjCMethodList * getNext() const
unsigned IsExplicit
Whether this is an explicit submodule.
Definition: Basic/Module.h:169
NestedNameSpecifierLoc getQualifierLoc() const
Definition: TypeLoc.h:1734
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:2575
void numberAnonymousDeclsWithin(const DeclContext *DC, Fn Visit)
Visit each declaration within DC that needs an anonymous declaration number and call Visit with the d...
Definition: ASTCommon.h:93
unsigned LocalNumTypes
The number of types in this AST file.
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
SourceRange getSourceRange() const LLVM_READONLY
Retrieves the source range that contains the entire base specifier.
Definition: DeclCXX.h:201
A function-like macro definition.
Definition: ASTBitCodes.h:611
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:642
The Objective-C 'Protocol' type.
Definition: ASTBitCodes.h:965
The global specifier '::'. There is no stored value.
T * getFETokenInfo() const
getFETokenInfo/setFETokenInfo - The language front-end is allowed to associate arbitrary metadata wit...
NamespaceDecl * getStdNamespace() const
The control block, which contains all of the information that needs to be validated prior to committi...
Definition: ASTBitCodes.h:230
const TemplateArgument & getArgument() const
Definition: TemplateBase.h:464
Wrapper for source info for pointers.
Definition: TypeLoc.h:1134
Wrapper for source info for block pointers.
Definition: TypeLoc.h:1147
void AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) override
An implicit member was added after the definition was completed.
Definition: ASTWriter.cpp:5717
Optional< unsigned > getNumExpansions() const
Retrieve the number of expansions that this pack expansion will generate, if known.
Definition: Type.h:4502
This class handles loading and caching of source files into memory.
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2480
const CXXDestructorDecl * getDestructor() const
Definition: ExprCXX.h:1086
PredefinedDeclIDs
Predefined declaration IDs.
Definition: ASTBitCodes.h:948
iterator - Iterate over the decls of a specified declaration name.
Record code for an update to the TU's lexically contained declarations.
Definition: ASTBitCodes.h:458
TypeSourceInfo * getUnderlyingTInfo() const
Definition: TypeLoc.h:1685
A class which abstracts out some details necessary for making a call.
Definition: Type.h:2872
A GenericSelectionExpr record.
Definition: ASTBitCodes.h:1285
A type index; the type ID with the qualifier bits removed.
Definition: ASTBitCodes.h:83
Attr - This represents one attribute.
Definition: Attr.h:44
void TypeRead(serialization::TypeIdx Idx, QualType T) override
A type was deserialized from the AST file.
Definition: ASTWriter.cpp:5635
const MacroDirective * getPrevious() const
Get previous definition of the macro with the same name.
Definition: MacroInfo.h:342
bool SawDateOrTime() const
Returns true if the preprocessor has seen a use of DATE or TIME in the file so far.
A PackExpansionType record.
Definition: ASTBitCodes.h:896
ASTWriter(llvm::BitstreamWriter &Stream, ArrayRef< llvm::IntrusiveRefCntPtr< ModuleFileExtension >> Extensions, bool IncludeTimestamps=true)
Create a new precompiled header writer that outputs to the given bitstream.
Definition: ASTWriter.cpp:4035
A single template declaration.
Definition: TemplateName.h:189
const unsigned int NUM_PREDEF_SUBMODULE_IDS
The number of predefined submodule IDs.
Definition: ASTBitCodes.h:163
SourceLocation getLocation() const
Definition: MacroInfo.h:336
SourceLocation getStarLoc() const
Definition: TypeLoc.h:1167
unsigned InferExplicitSubmodules
Whether, when inferring submodules, the inferred submodules should be explicit.
Definition: Basic/Module.h:191
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:96
void GetUniqueIDMapping(SmallVectorImpl< const FileEntry * > &UIDToFiles) const
Produce an array mapping from the unique IDs assigned to each file to the corresponding FileEntry poi...
A DependentTemplateSpecializationType record.
Definition: ASTBitCodes.h:890
bool isUsed() const
Return false if this macro is defined in the main file and has not yet been used. ...
Definition: MacroInfo.h:219
void AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record)
Emit a floating-point value.
Definition: ASTWriter.cpp:4762
SourceLocation getSpellingLoc() const
bool capturesVariable() const
Determine whether this capture handles a variable.
Definition: LambdaCapture.h:77
bool isHidden() const
Determine whether this declaration is hidden from name lookup.
Definition: Decl.h:237
SourceLocation getLParenLoc() const
Definition: TypeLoc.h:1594
Record code for the array of tentative definitions.
Definition: ASTBitCodes.h:411
unsigned getNumExceptions() const
Definition: Type.h:3220
SourceLocation getLParenLoc() const
Definition: TypeLoc.h:1025
iterator local_begin()
Begin iterator for local, non-loaded, preprocessed entities.
IdentifierInfo * getIdentifierInfo() const
Definition: Token.h:177
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:130
QualType getDeducedType() const
Get the type deduced for this auto type, or null if it's either not been deduced or was deduced to a ...
Definition: Type.h:3945