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