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