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