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