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