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