]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/clang/lib/Serialization/ASTReader.cpp
Merge ^/vendor/lvm-project/release-10.x up to its last change (upstream
[FreeBSD/FreeBSD.git] / contrib / llvm-project / clang / lib / Serialization / ASTReader.cpp
1 //===- ASTReader.cpp - AST File Reader ------------------------------------===//
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 ASTReader class, which reads AST files.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "clang/Basic/OpenMPKinds.h"
14 #include "clang/Serialization/ASTRecordReader.h"
15 #include "ASTCommon.h"
16 #include "ASTReaderInternals.h"
17 #include "clang/AST/AbstractTypeReader.h"
18 #include "clang/AST/ASTConsumer.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/ASTMutationListener.h"
21 #include "clang/AST/ASTUnresolvedSet.h"
22 #include "clang/AST/Decl.h"
23 #include "clang/AST/DeclBase.h"
24 #include "clang/AST/DeclCXX.h"
25 #include "clang/AST/DeclFriend.h"
26 #include "clang/AST/DeclGroup.h"
27 #include "clang/AST/DeclObjC.h"
28 #include "clang/AST/DeclTemplate.h"
29 #include "clang/AST/DeclarationName.h"
30 #include "clang/AST/Expr.h"
31 #include "clang/AST/ExprCXX.h"
32 #include "clang/AST/ExternalASTSource.h"
33 #include "clang/AST/NestedNameSpecifier.h"
34 #include "clang/AST/OpenMPClause.h"
35 #include "clang/AST/ODRHash.h"
36 #include "clang/AST/RawCommentList.h"
37 #include "clang/AST/TemplateBase.h"
38 #include "clang/AST/TemplateName.h"
39 #include "clang/AST/Type.h"
40 #include "clang/AST/TypeLoc.h"
41 #include "clang/AST/TypeLocVisitor.h"
42 #include "clang/AST/UnresolvedSet.h"
43 #include "clang/Basic/CommentOptions.h"
44 #include "clang/Basic/Diagnostic.h"
45 #include "clang/Basic/DiagnosticOptions.h"
46 #include "clang/Basic/ExceptionSpecificationType.h"
47 #include "clang/Basic/FileManager.h"
48 #include "clang/Basic/FileSystemOptions.h"
49 #include "clang/Basic/IdentifierTable.h"
50 #include "clang/Basic/LLVM.h"
51 #include "clang/Basic/LangOptions.h"
52 #include "clang/Basic/Module.h"
53 #include "clang/Basic/ObjCRuntime.h"
54 #include "clang/Basic/OperatorKinds.h"
55 #include "clang/Basic/PragmaKinds.h"
56 #include "clang/Basic/Sanitizers.h"
57 #include "clang/Basic/SourceLocation.h"
58 #include "clang/Basic/SourceManager.h"
59 #include "clang/Basic/SourceManagerInternals.h"
60 #include "clang/Basic/Specifiers.h"
61 #include "clang/Basic/TargetInfo.h"
62 #include "clang/Basic/TargetOptions.h"
63 #include "clang/Basic/TokenKinds.h"
64 #include "clang/Basic/Version.h"
65 #include "clang/Lex/HeaderSearch.h"
66 #include "clang/Lex/HeaderSearchOptions.h"
67 #include "clang/Lex/MacroInfo.h"
68 #include "clang/Lex/ModuleMap.h"
69 #include "clang/Lex/PreprocessingRecord.h"
70 #include "clang/Lex/Preprocessor.h"
71 #include "clang/Lex/PreprocessorOptions.h"
72 #include "clang/Lex/Token.h"
73 #include "clang/Sema/ObjCMethodList.h"
74 #include "clang/Sema/Scope.h"
75 #include "clang/Sema/Sema.h"
76 #include "clang/Sema/Weak.h"
77 #include "clang/Serialization/ASTBitCodes.h"
78 #include "clang/Serialization/ASTDeserializationListener.h"
79 #include "clang/Serialization/ContinuousRangeMap.h"
80 #include "clang/Serialization/GlobalModuleIndex.h"
81 #include "clang/Serialization/InMemoryModuleCache.h"
82 #include "clang/Serialization/ModuleFile.h"
83 #include "clang/Serialization/ModuleFileExtension.h"
84 #include "clang/Serialization/ModuleManager.h"
85 #include "clang/Serialization/PCHContainerOperations.h"
86 #include "clang/Serialization/SerializationDiagnostic.h"
87 #include "llvm/ADT/APFloat.h"
88 #include "llvm/ADT/APInt.h"
89 #include "llvm/ADT/APSInt.h"
90 #include "llvm/ADT/ArrayRef.h"
91 #include "llvm/ADT/DenseMap.h"
92 #include "llvm/ADT/FoldingSet.h"
93 #include "llvm/ADT/Hashing.h"
94 #include "llvm/ADT/IntrusiveRefCntPtr.h"
95 #include "llvm/ADT/None.h"
96 #include "llvm/ADT/Optional.h"
97 #include "llvm/ADT/STLExtras.h"
98 #include "llvm/ADT/ScopeExit.h"
99 #include "llvm/ADT/SmallPtrSet.h"
100 #include "llvm/ADT/SmallString.h"
101 #include "llvm/ADT/SmallVector.h"
102 #include "llvm/ADT/StringExtras.h"
103 #include "llvm/ADT/StringMap.h"
104 #include "llvm/ADT/StringRef.h"
105 #include "llvm/ADT/Triple.h"
106 #include "llvm/ADT/iterator_range.h"
107 #include "llvm/Bitstream/BitstreamReader.h"
108 #include "llvm/Support/Casting.h"
109 #include "llvm/Support/Compiler.h"
110 #include "llvm/Support/Compression.h"
111 #include "llvm/Support/DJB.h"
112 #include "llvm/Support/Endian.h"
113 #include "llvm/Support/Error.h"
114 #include "llvm/Support/ErrorHandling.h"
115 #include "llvm/Support/FileSystem.h"
116 #include "llvm/Support/MemoryBuffer.h"
117 #include "llvm/Support/Path.h"
118 #include "llvm/Support/SaveAndRestore.h"
119 #include "llvm/Support/Timer.h"
120 #include "llvm/Support/VersionTuple.h"
121 #include "llvm/Support/raw_ostream.h"
122 #include <algorithm>
123 #include <cassert>
124 #include <cstddef>
125 #include <cstdint>
126 #include <cstdio>
127 #include <ctime>
128 #include <iterator>
129 #include <limits>
130 #include <map>
131 #include <memory>
132 #include <string>
133 #include <system_error>
134 #include <tuple>
135 #include <utility>
136 #include <vector>
137
138 using namespace clang;
139 using namespace clang::serialization;
140 using namespace clang::serialization::reader;
141 using llvm::BitstreamCursor;
142
143 //===----------------------------------------------------------------------===//
144 // ChainedASTReaderListener implementation
145 //===----------------------------------------------------------------------===//
146
147 bool
148 ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
149   return First->ReadFullVersionInformation(FullVersion) ||
150          Second->ReadFullVersionInformation(FullVersion);
151 }
152
153 void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
154   First->ReadModuleName(ModuleName);
155   Second->ReadModuleName(ModuleName);
156 }
157
158 void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
159   First->ReadModuleMapFile(ModuleMapPath);
160   Second->ReadModuleMapFile(ModuleMapPath);
161 }
162
163 bool
164 ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
165                                               bool Complain,
166                                               bool AllowCompatibleDifferences) {
167   return First->ReadLanguageOptions(LangOpts, Complain,
168                                     AllowCompatibleDifferences) ||
169          Second->ReadLanguageOptions(LangOpts, Complain,
170                                      AllowCompatibleDifferences);
171 }
172
173 bool ChainedASTReaderListener::ReadTargetOptions(
174     const TargetOptions &TargetOpts, bool Complain,
175     bool AllowCompatibleDifferences) {
176   return First->ReadTargetOptions(TargetOpts, Complain,
177                                   AllowCompatibleDifferences) ||
178          Second->ReadTargetOptions(TargetOpts, Complain,
179                                    AllowCompatibleDifferences);
180 }
181
182 bool ChainedASTReaderListener::ReadDiagnosticOptions(
183     IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
184   return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
185          Second->ReadDiagnosticOptions(DiagOpts, Complain);
186 }
187
188 bool
189 ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
190                                                 bool Complain) {
191   return First->ReadFileSystemOptions(FSOpts, Complain) ||
192          Second->ReadFileSystemOptions(FSOpts, Complain);
193 }
194
195 bool ChainedASTReaderListener::ReadHeaderSearchOptions(
196     const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
197     bool Complain) {
198   return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
199                                         Complain) ||
200          Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
201                                          Complain);
202 }
203
204 bool ChainedASTReaderListener::ReadPreprocessorOptions(
205     const PreprocessorOptions &PPOpts, bool Complain,
206     std::string &SuggestedPredefines) {
207   return First->ReadPreprocessorOptions(PPOpts, Complain,
208                                         SuggestedPredefines) ||
209          Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
210 }
211
212 void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
213                                            unsigned Value) {
214   First->ReadCounter(M, Value);
215   Second->ReadCounter(M, Value);
216 }
217
218 bool ChainedASTReaderListener::needsInputFileVisitation() {
219   return First->needsInputFileVisitation() ||
220          Second->needsInputFileVisitation();
221 }
222
223 bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
224   return First->needsSystemInputFileVisitation() ||
225   Second->needsSystemInputFileVisitation();
226 }
227
228 void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
229                                                ModuleKind Kind) {
230   First->visitModuleFile(Filename, Kind);
231   Second->visitModuleFile(Filename, Kind);
232 }
233
234 bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
235                                               bool isSystem,
236                                               bool isOverridden,
237                                               bool isExplicitModule) {
238   bool Continue = false;
239   if (First->needsInputFileVisitation() &&
240       (!isSystem || First->needsSystemInputFileVisitation()))
241     Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
242                                       isExplicitModule);
243   if (Second->needsInputFileVisitation() &&
244       (!isSystem || Second->needsSystemInputFileVisitation()))
245     Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
246                                        isExplicitModule);
247   return Continue;
248 }
249
250 void ChainedASTReaderListener::readModuleFileExtension(
251        const ModuleFileExtensionMetadata &Metadata) {
252   First->readModuleFileExtension(Metadata);
253   Second->readModuleFileExtension(Metadata);
254 }
255
256 //===----------------------------------------------------------------------===//
257 // PCH validator implementation
258 //===----------------------------------------------------------------------===//
259
260 ASTReaderListener::~ASTReaderListener() = default;
261
262 /// Compare the given set of language options against an existing set of
263 /// language options.
264 ///
265 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
266 /// \param AllowCompatibleDifferences If true, differences between compatible
267 ///        language options will be permitted.
268 ///
269 /// \returns true if the languagae options mis-match, false otherwise.
270 static bool checkLanguageOptions(const LangOptions &LangOpts,
271                                  const LangOptions &ExistingLangOpts,
272                                  DiagnosticsEngine *Diags,
273                                  bool AllowCompatibleDifferences = true) {
274 #define LANGOPT(Name, Bits, Default, Description)                 \
275   if (ExistingLangOpts.Name != LangOpts.Name) {                   \
276     if (Diags)                                                    \
277       Diags->Report(diag::err_pch_langopt_mismatch)               \
278         << Description << LangOpts.Name << ExistingLangOpts.Name; \
279     return true;                                                  \
280   }
281
282 #define VALUE_LANGOPT(Name, Bits, Default, Description)   \
283   if (ExistingLangOpts.Name != LangOpts.Name) {           \
284     if (Diags)                                            \
285       Diags->Report(diag::err_pch_langopt_value_mismatch) \
286         << Description;                                   \
287     return true;                                          \
288   }
289
290 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description)   \
291   if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) {  \
292     if (Diags)                                                 \
293       Diags->Report(diag::err_pch_langopt_value_mismatch)      \
294         << Description;                                        \
295     return true;                                               \
296   }
297
298 #define COMPATIBLE_LANGOPT(Name, Bits, Default, Description)  \
299   if (!AllowCompatibleDifferences)                            \
300     LANGOPT(Name, Bits, Default, Description)
301
302 #define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description)  \
303   if (!AllowCompatibleDifferences)                                 \
304     ENUM_LANGOPT(Name, Bits, Default, Description)
305
306 #define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
307   if (!AllowCompatibleDifferences)                                 \
308     VALUE_LANGOPT(Name, Bits, Default, Description)
309
310 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
311 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
312 #define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
313 #include "clang/Basic/LangOptions.def"
314
315   if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
316     if (Diags)
317       Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
318     return true;
319   }
320
321   if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
322     if (Diags)
323       Diags->Report(diag::err_pch_langopt_value_mismatch)
324       << "target Objective-C runtime";
325     return true;
326   }
327
328   if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
329       LangOpts.CommentOpts.BlockCommandNames) {
330     if (Diags)
331       Diags->Report(diag::err_pch_langopt_value_mismatch)
332         << "block command names";
333     return true;
334   }
335
336   // Sanitizer feature mismatches are treated as compatible differences. If
337   // compatible differences aren't allowed, we still only want to check for
338   // mismatches of non-modular sanitizers (the only ones which can affect AST
339   // generation).
340   if (!AllowCompatibleDifferences) {
341     SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
342     SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
343     SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
344     ExistingSanitizers.clear(ModularSanitizers);
345     ImportedSanitizers.clear(ModularSanitizers);
346     if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
347       const std::string Flag = "-fsanitize=";
348       if (Diags) {
349 #define SANITIZER(NAME, ID)                                                    \
350   {                                                                            \
351     bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID);         \
352     bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID);         \
353     if (InExistingModule != InImportedModule)                                  \
354       Diags->Report(diag::err_pch_targetopt_feature_mismatch)                  \
355           << InExistingModule << (Flag + NAME);                                \
356   }
357 #include "clang/Basic/Sanitizers.def"
358       }
359       return true;
360     }
361   }
362
363   return false;
364 }
365
366 /// Compare the given set of target options against an existing set of
367 /// target options.
368 ///
369 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
370 ///
371 /// \returns true if the target options mis-match, false otherwise.
372 static bool checkTargetOptions(const TargetOptions &TargetOpts,
373                                const TargetOptions &ExistingTargetOpts,
374                                DiagnosticsEngine *Diags,
375                                bool AllowCompatibleDifferences = true) {
376 #define CHECK_TARGET_OPT(Field, Name)                             \
377   if (TargetOpts.Field != ExistingTargetOpts.Field) {             \
378     if (Diags)                                                    \
379       Diags->Report(diag::err_pch_targetopt_mismatch)             \
380         << Name << TargetOpts.Field << ExistingTargetOpts.Field;  \
381     return true;                                                  \
382   }
383
384   // The triple and ABI must match exactly.
385   CHECK_TARGET_OPT(Triple, "target");
386   CHECK_TARGET_OPT(ABI, "target ABI");
387
388   // We can tolerate different CPUs in many cases, notably when one CPU
389   // supports a strict superset of another. When allowing compatible
390   // differences skip this check.
391   if (!AllowCompatibleDifferences)
392     CHECK_TARGET_OPT(CPU, "target CPU");
393
394 #undef CHECK_TARGET_OPT
395
396   // Compare feature sets.
397   SmallVector<StringRef, 4> ExistingFeatures(
398                                              ExistingTargetOpts.FeaturesAsWritten.begin(),
399                                              ExistingTargetOpts.FeaturesAsWritten.end());
400   SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
401                                          TargetOpts.FeaturesAsWritten.end());
402   llvm::sort(ExistingFeatures);
403   llvm::sort(ReadFeatures);
404
405   // We compute the set difference in both directions explicitly so that we can
406   // diagnose the differences differently.
407   SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
408   std::set_difference(
409       ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
410       ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
411   std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
412                       ExistingFeatures.begin(), ExistingFeatures.end(),
413                       std::back_inserter(UnmatchedReadFeatures));
414
415   // If we are allowing compatible differences and the read feature set is
416   // a strict subset of the existing feature set, there is nothing to diagnose.
417   if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
418     return false;
419
420   if (Diags) {
421     for (StringRef Feature : UnmatchedReadFeatures)
422       Diags->Report(diag::err_pch_targetopt_feature_mismatch)
423           << /* is-existing-feature */ false << Feature;
424     for (StringRef Feature : UnmatchedExistingFeatures)
425       Diags->Report(diag::err_pch_targetopt_feature_mismatch)
426           << /* is-existing-feature */ true << Feature;
427   }
428
429   return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
430 }
431
432 bool
433 PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
434                                   bool Complain,
435                                   bool AllowCompatibleDifferences) {
436   const LangOptions &ExistingLangOpts = PP.getLangOpts();
437   return checkLanguageOptions(LangOpts, ExistingLangOpts,
438                               Complain ? &Reader.Diags : nullptr,
439                               AllowCompatibleDifferences);
440 }
441
442 bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
443                                      bool Complain,
444                                      bool AllowCompatibleDifferences) {
445   const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
446   return checkTargetOptions(TargetOpts, ExistingTargetOpts,
447                             Complain ? &Reader.Diags : nullptr,
448                             AllowCompatibleDifferences);
449 }
450
451 namespace {
452
453 using MacroDefinitionsMap =
454     llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
455 using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>;
456
457 } // namespace
458
459 static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
460                                          DiagnosticsEngine &Diags,
461                                          bool Complain) {
462   using Level = DiagnosticsEngine::Level;
463
464   // Check current mappings for new -Werror mappings, and the stored mappings
465   // for cases that were explicitly mapped to *not* be errors that are now
466   // errors because of options like -Werror.
467   DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
468
469   for (DiagnosticsEngine *MappingSource : MappingSources) {
470     for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
471       diag::kind DiagID = DiagIDMappingPair.first;
472       Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
473       if (CurLevel < DiagnosticsEngine::Error)
474         continue; // not significant
475       Level StoredLevel =
476           StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
477       if (StoredLevel < DiagnosticsEngine::Error) {
478         if (Complain)
479           Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
480               Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
481         return true;
482       }
483     }
484   }
485
486   return false;
487 }
488
489 static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
490   diag::Severity Ext = Diags.getExtensionHandlingBehavior();
491   if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
492     return true;
493   return Ext >= diag::Severity::Error;
494 }
495
496 static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
497                                     DiagnosticsEngine &Diags,
498                                     bool IsSystem, bool Complain) {
499   // Top-level options
500   if (IsSystem) {
501     if (Diags.getSuppressSystemWarnings())
502       return false;
503     // If -Wsystem-headers was not enabled before, be conservative
504     if (StoredDiags.getSuppressSystemWarnings()) {
505       if (Complain)
506         Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
507       return true;
508     }
509   }
510
511   if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
512     if (Complain)
513       Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
514     return true;
515   }
516
517   if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
518       !StoredDiags.getEnableAllWarnings()) {
519     if (Complain)
520       Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
521     return true;
522   }
523
524   if (isExtHandlingFromDiagsError(Diags) &&
525       !isExtHandlingFromDiagsError(StoredDiags)) {
526     if (Complain)
527       Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
528     return true;
529   }
530
531   return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
532 }
533
534 /// Return the top import module if it is implicit, nullptr otherwise.
535 static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
536                                           Preprocessor &PP) {
537   // If the original import came from a file explicitly generated by the user,
538   // don't check the diagnostic mappings.
539   // FIXME: currently this is approximated by checking whether this is not a
540   // module import of an implicitly-loaded module file.
541   // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
542   // the transitive closure of its imports, since unrelated modules cannot be
543   // imported until after this module finishes validation.
544   ModuleFile *TopImport = &*ModuleMgr.rbegin();
545   while (!TopImport->ImportedBy.empty())
546     TopImport = TopImport->ImportedBy[0];
547   if (TopImport->Kind != MK_ImplicitModule)
548     return nullptr;
549
550   StringRef ModuleName = TopImport->ModuleName;
551   assert(!ModuleName.empty() && "diagnostic options read before module name");
552
553   Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
554   assert(M && "missing module");
555   return M;
556 }
557
558 bool PCHValidator::ReadDiagnosticOptions(
559     IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
560   DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
561   IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
562   IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
563       new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
564   // This should never fail, because we would have processed these options
565   // before writing them to an ASTFile.
566   ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
567
568   ModuleManager &ModuleMgr = Reader.getModuleManager();
569   assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
570
571   Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
572   if (!TopM)
573     return false;
574
575   // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
576   // contains the union of their flags.
577   return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
578                                  Complain);
579 }
580
581 /// Collect the macro definitions provided by the given preprocessor
582 /// options.
583 static void
584 collectMacroDefinitions(const PreprocessorOptions &PPOpts,
585                         MacroDefinitionsMap &Macros,
586                         SmallVectorImpl<StringRef> *MacroNames = nullptr) {
587   for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
588     StringRef Macro = PPOpts.Macros[I].first;
589     bool IsUndef = PPOpts.Macros[I].second;
590
591     std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
592     StringRef MacroName = MacroPair.first;
593     StringRef MacroBody = MacroPair.second;
594
595     // For an #undef'd macro, we only care about the name.
596     if (IsUndef) {
597       if (MacroNames && !Macros.count(MacroName))
598         MacroNames->push_back(MacroName);
599
600       Macros[MacroName] = std::make_pair("", true);
601       continue;
602     }
603
604     // For a #define'd macro, figure out the actual definition.
605     if (MacroName.size() == Macro.size())
606       MacroBody = "1";
607     else {
608       // Note: GCC drops anything following an end-of-line character.
609       StringRef::size_type End = MacroBody.find_first_of("\n\r");
610       MacroBody = MacroBody.substr(0, End);
611     }
612
613     if (MacroNames && !Macros.count(MacroName))
614       MacroNames->push_back(MacroName);
615     Macros[MacroName] = std::make_pair(MacroBody, false);
616   }
617 }
618
619 /// Check the preprocessor options deserialized from the control block
620 /// against the preprocessor options in an existing preprocessor.
621 ///
622 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
623 /// \param Validate If true, validate preprocessor options. If false, allow
624 ///        macros defined by \p ExistingPPOpts to override those defined by
625 ///        \p PPOpts in SuggestedPredefines.
626 static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
627                                      const PreprocessorOptions &ExistingPPOpts,
628                                      DiagnosticsEngine *Diags,
629                                      FileManager &FileMgr,
630                                      std::string &SuggestedPredefines,
631                                      const LangOptions &LangOpts,
632                                      bool Validate = true) {
633   // Check macro definitions.
634   MacroDefinitionsMap ASTFileMacros;
635   collectMacroDefinitions(PPOpts, ASTFileMacros);
636   MacroDefinitionsMap ExistingMacros;
637   SmallVector<StringRef, 4> ExistingMacroNames;
638   collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
639
640   for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
641     // Dig out the macro definition in the existing preprocessor options.
642     StringRef MacroName = ExistingMacroNames[I];
643     std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
644
645     // Check whether we know anything about this macro name or not.
646     llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
647         ASTFileMacros.find(MacroName);
648     if (!Validate || Known == ASTFileMacros.end()) {
649       // FIXME: Check whether this identifier was referenced anywhere in the
650       // AST file. If so, we should reject the AST file. Unfortunately, this
651       // information isn't in the control block. What shall we do about it?
652
653       if (Existing.second) {
654         SuggestedPredefines += "#undef ";
655         SuggestedPredefines += MacroName.str();
656         SuggestedPredefines += '\n';
657       } else {
658         SuggestedPredefines += "#define ";
659         SuggestedPredefines += MacroName.str();
660         SuggestedPredefines += ' ';
661         SuggestedPredefines += Existing.first.str();
662         SuggestedPredefines += '\n';
663       }
664       continue;
665     }
666
667     // If the macro was defined in one but undef'd in the other, we have a
668     // conflict.
669     if (Existing.second != Known->second.second) {
670       if (Diags) {
671         Diags->Report(diag::err_pch_macro_def_undef)
672           << MacroName << Known->second.second;
673       }
674       return true;
675     }
676
677     // If the macro was #undef'd in both, or if the macro bodies are identical,
678     // it's fine.
679     if (Existing.second || Existing.first == Known->second.first)
680       continue;
681
682     // The macro bodies differ; complain.
683     if (Diags) {
684       Diags->Report(diag::err_pch_macro_def_conflict)
685         << MacroName << Known->second.first << Existing.first;
686     }
687     return true;
688   }
689
690   // Check whether we're using predefines.
691   if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) {
692     if (Diags) {
693       Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
694     }
695     return true;
696   }
697
698   // Detailed record is important since it is used for the module cache hash.
699   if (LangOpts.Modules &&
700       PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) {
701     if (Diags) {
702       Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
703     }
704     return true;
705   }
706
707   // Compute the #include and #include_macros lines we need.
708   for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
709     StringRef File = ExistingPPOpts.Includes[I];
710
711     if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&
712         !ExistingPPOpts.PCHThroughHeader.empty()) {
713       // In case the through header is an include, we must add all the includes
714       // to the predefines so the start point can be determined.
715       SuggestedPredefines += "#include \"";
716       SuggestedPredefines += File;
717       SuggestedPredefines += "\"\n";
718       continue;
719     }
720
721     if (File == ExistingPPOpts.ImplicitPCHInclude)
722       continue;
723
724     if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
725           != PPOpts.Includes.end())
726       continue;
727
728     SuggestedPredefines += "#include \"";
729     SuggestedPredefines += File;
730     SuggestedPredefines += "\"\n";
731   }
732
733   for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
734     StringRef File = ExistingPPOpts.MacroIncludes[I];
735     if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
736                   File)
737         != PPOpts.MacroIncludes.end())
738       continue;
739
740     SuggestedPredefines += "#__include_macros \"";
741     SuggestedPredefines += File;
742     SuggestedPredefines += "\"\n##\n";
743   }
744
745   return false;
746 }
747
748 bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
749                                            bool Complain,
750                                            std::string &SuggestedPredefines) {
751   const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
752
753   return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
754                                   Complain? &Reader.Diags : nullptr,
755                                   PP.getFileManager(),
756                                   SuggestedPredefines,
757                                   PP.getLangOpts());
758 }
759
760 bool SimpleASTReaderListener::ReadPreprocessorOptions(
761                                   const PreprocessorOptions &PPOpts,
762                                   bool Complain,
763                                   std::string &SuggestedPredefines) {
764   return checkPreprocessorOptions(PPOpts,
765                                   PP.getPreprocessorOpts(),
766                                   nullptr,
767                                   PP.getFileManager(),
768                                   SuggestedPredefines,
769                                   PP.getLangOpts(),
770                                   false);
771 }
772
773 /// Check the header search options deserialized from the control block
774 /// against the header search options in an existing preprocessor.
775 ///
776 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
777 static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
778                                      StringRef SpecificModuleCachePath,
779                                      StringRef ExistingModuleCachePath,
780                                      DiagnosticsEngine *Diags,
781                                      const LangOptions &LangOpts) {
782   if (LangOpts.Modules) {
783     if (SpecificModuleCachePath != ExistingModuleCachePath) {
784       if (Diags)
785         Diags->Report(diag::err_pch_modulecache_mismatch)
786           << SpecificModuleCachePath << ExistingModuleCachePath;
787       return true;
788     }
789   }
790
791   return false;
792 }
793
794 bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
795                                            StringRef SpecificModuleCachePath,
796                                            bool Complain) {
797   return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
798                                   PP.getHeaderSearchInfo().getModuleCachePath(),
799                                   Complain ? &Reader.Diags : nullptr,
800                                   PP.getLangOpts());
801 }
802
803 void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
804   PP.setCounterValue(Value);
805 }
806
807 //===----------------------------------------------------------------------===//
808 // AST reader implementation
809 //===----------------------------------------------------------------------===//
810
811 void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
812                                            bool TakeOwnership) {
813   DeserializationListener = Listener;
814   OwnsDeserializationListener = TakeOwnership;
815 }
816
817 unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
818   return serialization::ComputeHash(Sel);
819 }
820
821 std::pair<unsigned, unsigned>
822 ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
823   using namespace llvm::support;
824
825   unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
826   unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
827   return std::make_pair(KeyLen, DataLen);
828 }
829
830 ASTSelectorLookupTrait::internal_key_type
831 ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
832   using namespace llvm::support;
833
834   SelectorTable &SelTable = Reader.getContext().Selectors;
835   unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
836   IdentifierInfo *FirstII = Reader.getLocalIdentifier(
837       F, endian::readNext<uint32_t, little, unaligned>(d));
838   if (N == 0)
839     return SelTable.getNullarySelector(FirstII);
840   else if (N == 1)
841     return SelTable.getUnarySelector(FirstII);
842
843   SmallVector<IdentifierInfo *, 16> Args;
844   Args.push_back(FirstII);
845   for (unsigned I = 1; I != N; ++I)
846     Args.push_back(Reader.getLocalIdentifier(
847         F, endian::readNext<uint32_t, little, unaligned>(d)));
848
849   return SelTable.getSelector(N, Args.data());
850 }
851
852 ASTSelectorLookupTrait::data_type
853 ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
854                                  unsigned DataLen) {
855   using namespace llvm::support;
856
857   data_type Result;
858
859   Result.ID = Reader.getGlobalSelectorID(
860       F, endian::readNext<uint32_t, little, unaligned>(d));
861   unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
862   unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
863   Result.InstanceBits = FullInstanceBits & 0x3;
864   Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
865   Result.FactoryBits = FullFactoryBits & 0x3;
866   Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
867   unsigned NumInstanceMethods = FullInstanceBits >> 3;
868   unsigned NumFactoryMethods = FullFactoryBits >> 3;
869
870   // Load instance methods
871   for (unsigned I = 0; I != NumInstanceMethods; ++I) {
872     if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
873             F, endian::readNext<uint32_t, little, unaligned>(d)))
874       Result.Instance.push_back(Method);
875   }
876
877   // Load factory methods
878   for (unsigned I = 0; I != NumFactoryMethods; ++I) {
879     if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
880             F, endian::readNext<uint32_t, little, unaligned>(d)))
881       Result.Factory.push_back(Method);
882   }
883
884   return Result;
885 }
886
887 unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
888   return llvm::djbHash(a);
889 }
890
891 std::pair<unsigned, unsigned>
892 ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
893   using namespace llvm::support;
894
895   unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
896   unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
897   return std::make_pair(KeyLen, DataLen);
898 }
899
900 ASTIdentifierLookupTraitBase::internal_key_type
901 ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
902   assert(n >= 2 && d[n-1] == '\0');
903   return StringRef((const char*) d, n-1);
904 }
905
906 /// Whether the given identifier is "interesting".
907 static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
908                                     bool IsModule) {
909   return II.hadMacroDefinition() ||
910          II.isPoisoned() ||
911          (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
912          II.hasRevertedTokenIDToIdentifier() ||
913          (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
914           II.getFETokenInfo());
915 }
916
917 static bool readBit(unsigned &Bits) {
918   bool Value = Bits & 0x1;
919   Bits >>= 1;
920   return Value;
921 }
922
923 IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
924   using namespace llvm::support;
925
926   unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
927   return Reader.getGlobalIdentifierID(F, RawID >> 1);
928 }
929
930 static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
931   if (!II.isFromAST()) {
932     II.setIsFromAST();
933     bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
934     if (isInterestingIdentifier(Reader, II, IsModule))
935       II.setChangedSinceDeserialization();
936   }
937 }
938
939 IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
940                                                    const unsigned char* d,
941                                                    unsigned DataLen) {
942   using namespace llvm::support;
943
944   unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
945   bool IsInteresting = RawID & 0x01;
946
947   // Wipe out the "is interesting" bit.
948   RawID = RawID >> 1;
949
950   // Build the IdentifierInfo and link the identifier ID with it.
951   IdentifierInfo *II = KnownII;
952   if (!II) {
953     II = &Reader.getIdentifierTable().getOwn(k);
954     KnownII = II;
955   }
956   markIdentifierFromAST(Reader, *II);
957   Reader.markIdentifierUpToDate(II);
958
959   IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
960   if (!IsInteresting) {
961     // For uninteresting identifiers, there's nothing else to do. Just notify
962     // the reader that we've finished loading this identifier.
963     Reader.SetIdentifierInfo(ID, II);
964     return II;
965   }
966
967   unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
968   unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
969   bool CPlusPlusOperatorKeyword = readBit(Bits);
970   bool HasRevertedTokenIDToIdentifier = readBit(Bits);
971   bool HasRevertedBuiltin = readBit(Bits);
972   bool Poisoned = readBit(Bits);
973   bool ExtensionToken = readBit(Bits);
974   bool HadMacroDefinition = readBit(Bits);
975
976   assert(Bits == 0 && "Extra bits in the identifier?");
977   DataLen -= 8;
978
979   // Set or check the various bits in the IdentifierInfo structure.
980   // Token IDs are read-only.
981   if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
982     II->revertTokenIDToIdentifier();
983   if (!F.isModule())
984     II->setObjCOrBuiltinID(ObjCOrBuiltinID);
985   else if (HasRevertedBuiltin && II->getBuiltinID()) {
986     II->revertBuiltin();
987     assert((II->hasRevertedBuiltin() ||
988             II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
989            "Incorrect ObjC keyword or builtin ID");
990   }
991   assert(II->isExtensionToken() == ExtensionToken &&
992          "Incorrect extension token flag");
993   (void)ExtensionToken;
994   if (Poisoned)
995     II->setIsPoisoned(true);
996   assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
997          "Incorrect C++ operator keyword flag");
998   (void)CPlusPlusOperatorKeyword;
999
1000   // If this identifier is a macro, deserialize the macro
1001   // definition.
1002   if (HadMacroDefinition) {
1003     uint32_t MacroDirectivesOffset =
1004         endian::readNext<uint32_t, little, unaligned>(d);
1005     DataLen -= 4;
1006
1007     Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
1008   }
1009
1010   Reader.SetIdentifierInfo(ID, II);
1011
1012   // Read all of the declarations visible at global scope with this
1013   // name.
1014   if (DataLen > 0) {
1015     SmallVector<uint32_t, 4> DeclIDs;
1016     for (; DataLen > 0; DataLen -= 4)
1017       DeclIDs.push_back(Reader.getGlobalDeclID(
1018           F, endian::readNext<uint32_t, little, unaligned>(d)));
1019     Reader.SetGloballyVisibleDecls(II, DeclIDs);
1020   }
1021
1022   return II;
1023 }
1024
1025 DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
1026     : Kind(Name.getNameKind()) {
1027   switch (Kind) {
1028   case DeclarationName::Identifier:
1029     Data = (uint64_t)Name.getAsIdentifierInfo();
1030     break;
1031   case DeclarationName::ObjCZeroArgSelector:
1032   case DeclarationName::ObjCOneArgSelector:
1033   case DeclarationName::ObjCMultiArgSelector:
1034     Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
1035     break;
1036   case DeclarationName::CXXOperatorName:
1037     Data = Name.getCXXOverloadedOperator();
1038     break;
1039   case DeclarationName::CXXLiteralOperatorName:
1040     Data = (uint64_t)Name.getCXXLiteralIdentifier();
1041     break;
1042   case DeclarationName::CXXDeductionGuideName:
1043     Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1044                ->getDeclName().getAsIdentifierInfo();
1045     break;
1046   case DeclarationName::CXXConstructorName:
1047   case DeclarationName::CXXDestructorName:
1048   case DeclarationName::CXXConversionFunctionName:
1049   case DeclarationName::CXXUsingDirective:
1050     Data = 0;
1051     break;
1052   }
1053 }
1054
1055 unsigned DeclarationNameKey::getHash() const {
1056   llvm::FoldingSetNodeID ID;
1057   ID.AddInteger(Kind);
1058
1059   switch (Kind) {
1060   case DeclarationName::Identifier:
1061   case DeclarationName::CXXLiteralOperatorName:
1062   case DeclarationName::CXXDeductionGuideName:
1063     ID.AddString(((IdentifierInfo*)Data)->getName());
1064     break;
1065   case DeclarationName::ObjCZeroArgSelector:
1066   case DeclarationName::ObjCOneArgSelector:
1067   case DeclarationName::ObjCMultiArgSelector:
1068     ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1069     break;
1070   case DeclarationName::CXXOperatorName:
1071     ID.AddInteger((OverloadedOperatorKind)Data);
1072     break;
1073   case DeclarationName::CXXConstructorName:
1074   case DeclarationName::CXXDestructorName:
1075   case DeclarationName::CXXConversionFunctionName:
1076   case DeclarationName::CXXUsingDirective:
1077     break;
1078   }
1079
1080   return ID.ComputeHash();
1081 }
1082
1083 ModuleFile *
1084 ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
1085   using namespace llvm::support;
1086
1087   uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
1088   return Reader.getLocalModuleFile(F, ModuleFileID);
1089 }
1090
1091 std::pair<unsigned, unsigned>
1092 ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
1093   using namespace llvm::support;
1094
1095   unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
1096   unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
1097   return std::make_pair(KeyLen, DataLen);
1098 }
1099
1100 ASTDeclContextNameLookupTrait::internal_key_type
1101 ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1102   using namespace llvm::support;
1103
1104   auto Kind = (DeclarationName::NameKind)*d++;
1105   uint64_t Data;
1106   switch (Kind) {
1107   case DeclarationName::Identifier:
1108   case DeclarationName::CXXLiteralOperatorName:
1109   case DeclarationName::CXXDeductionGuideName:
1110     Data = (uint64_t)Reader.getLocalIdentifier(
1111         F, endian::readNext<uint32_t, little, unaligned>(d));
1112     break;
1113   case DeclarationName::ObjCZeroArgSelector:
1114   case DeclarationName::ObjCOneArgSelector:
1115   case DeclarationName::ObjCMultiArgSelector:
1116     Data =
1117         (uint64_t)Reader.getLocalSelector(
1118                              F, endian::readNext<uint32_t, little, unaligned>(
1119                                     d)).getAsOpaquePtr();
1120     break;
1121   case DeclarationName::CXXOperatorName:
1122     Data = *d++; // OverloadedOperatorKind
1123     break;
1124   case DeclarationName::CXXConstructorName:
1125   case DeclarationName::CXXDestructorName:
1126   case DeclarationName::CXXConversionFunctionName:
1127   case DeclarationName::CXXUsingDirective:
1128     Data = 0;
1129     break;
1130   }
1131
1132   return DeclarationNameKey(Kind, Data);
1133 }
1134
1135 void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1136                                                  const unsigned char *d,
1137                                                  unsigned DataLen,
1138                                                  data_type_builder &Val) {
1139   using namespace llvm::support;
1140
1141   for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1142     uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1143     Val.insert(Reader.getGlobalDeclID(F, LocalID));
1144   }
1145 }
1146
1147 bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1148                                               BitstreamCursor &Cursor,
1149                                               uint64_t Offset,
1150                                               DeclContext *DC) {
1151   assert(Offset != 0);
1152
1153   SavedStreamPosition SavedPosition(Cursor);
1154   if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1155     Error(std::move(Err));
1156     return true;
1157   }
1158
1159   RecordData Record;
1160   StringRef Blob;
1161   Expected<unsigned> MaybeCode = Cursor.ReadCode();
1162   if (!MaybeCode) {
1163     Error(MaybeCode.takeError());
1164     return true;
1165   }
1166   unsigned Code = MaybeCode.get();
1167
1168   Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1169   if (!MaybeRecCode) {
1170     Error(MaybeRecCode.takeError());
1171     return true;
1172   }
1173   unsigned RecCode = MaybeRecCode.get();
1174   if (RecCode != DECL_CONTEXT_LEXICAL) {
1175     Error("Expected lexical block");
1176     return true;
1177   }
1178
1179   assert(!isa<TranslationUnitDecl>(DC) &&
1180          "expected a TU_UPDATE_LEXICAL record for TU");
1181   // If we are handling a C++ class template instantiation, we can see multiple
1182   // lexical updates for the same record. It's important that we select only one
1183   // of them, so that field numbering works properly. Just pick the first one we
1184   // see.
1185   auto &Lex = LexicalDecls[DC];
1186   if (!Lex.first) {
1187     Lex = std::make_pair(
1188         &M, llvm::makeArrayRef(
1189                 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1190                     Blob.data()),
1191                 Blob.size() / 4));
1192   }
1193   DC->setHasExternalLexicalStorage(true);
1194   return false;
1195 }
1196
1197 bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1198                                               BitstreamCursor &Cursor,
1199                                               uint64_t Offset,
1200                                               DeclID ID) {
1201   assert(Offset != 0);
1202
1203   SavedStreamPosition SavedPosition(Cursor);
1204   if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1205     Error(std::move(Err));
1206     return true;
1207   }
1208
1209   RecordData Record;
1210   StringRef Blob;
1211   Expected<unsigned> MaybeCode = Cursor.ReadCode();
1212   if (!MaybeCode) {
1213     Error(MaybeCode.takeError());
1214     return true;
1215   }
1216   unsigned Code = MaybeCode.get();
1217
1218   Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1219   if (!MaybeRecCode) {
1220     Error(MaybeRecCode.takeError());
1221     return true;
1222   }
1223   unsigned RecCode = MaybeRecCode.get();
1224   if (RecCode != DECL_CONTEXT_VISIBLE) {
1225     Error("Expected visible lookup table block");
1226     return true;
1227   }
1228
1229   // We can't safely determine the primary context yet, so delay attaching the
1230   // lookup table until we're done with recursive deserialization.
1231   auto *Data = (const unsigned char*)Blob.data();
1232   PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
1233   return false;
1234 }
1235
1236 void ASTReader::Error(StringRef Msg) const {
1237   Error(diag::err_fe_pch_malformed, Msg);
1238   if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1239       !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
1240     Diag(diag::note_module_cache_path)
1241       << PP.getHeaderSearchInfo().getModuleCachePath();
1242   }
1243 }
1244
1245 void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1246                       StringRef Arg3) const {
1247   if (Diags.isDiagnosticInFlight())
1248     Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2, Arg3);
1249   else
1250     Diag(DiagID) << Arg1 << Arg2 << Arg3;
1251 }
1252
1253 void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1254                       unsigned Select) const {
1255   if (!Diags.isDiagnosticInFlight())
1256     Diag(DiagID) << Arg1 << Arg2 << Select;
1257 }
1258
1259 void ASTReader::Error(llvm::Error &&Err) const {
1260   Error(toString(std::move(Err)));
1261 }
1262
1263 //===----------------------------------------------------------------------===//
1264 // Source Manager Deserialization
1265 //===----------------------------------------------------------------------===//
1266
1267 /// Read the line table in the source manager block.
1268 /// \returns true if there was an error.
1269 bool ASTReader::ParseLineTable(ModuleFile &F,
1270                                const RecordData &Record) {
1271   unsigned Idx = 0;
1272   LineTableInfo &LineTable = SourceMgr.getLineTable();
1273
1274   // Parse the file names
1275   std::map<int, int> FileIDs;
1276   FileIDs[-1] = -1; // For unspecified filenames.
1277   for (unsigned I = 0; Record[Idx]; ++I) {
1278     // Extract the file name
1279     auto Filename = ReadPath(F, Record, Idx);
1280     FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1281   }
1282   ++Idx;
1283
1284   // Parse the line entries
1285   std::vector<LineEntry> Entries;
1286   while (Idx < Record.size()) {
1287     int FID = Record[Idx++];
1288     assert(FID >= 0 && "Serialized line entries for non-local file.");
1289     // Remap FileID from 1-based old view.
1290     FID += F.SLocEntryBaseID - 1;
1291
1292     // Extract the line entries
1293     unsigned NumEntries = Record[Idx++];
1294     assert(NumEntries && "no line entries for file ID");
1295     Entries.clear();
1296     Entries.reserve(NumEntries);
1297     for (unsigned I = 0; I != NumEntries; ++I) {
1298       unsigned FileOffset = Record[Idx++];
1299       unsigned LineNo = Record[Idx++];
1300       int FilenameID = FileIDs[Record[Idx++]];
1301       SrcMgr::CharacteristicKind FileKind
1302         = (SrcMgr::CharacteristicKind)Record[Idx++];
1303       unsigned IncludeOffset = Record[Idx++];
1304       Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1305                                        FileKind, IncludeOffset));
1306     }
1307     LineTable.AddEntry(FileID::get(FID), Entries);
1308   }
1309
1310   return false;
1311 }
1312
1313 /// Read a source manager block
1314 bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1315   using namespace SrcMgr;
1316
1317   BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1318
1319   // Set the source-location entry cursor to the current position in
1320   // the stream. This cursor will be used to read the contents of the
1321   // source manager block initially, and then lazily read
1322   // source-location entries as needed.
1323   SLocEntryCursor = F.Stream;
1324
1325   // The stream itself is going to skip over the source manager block.
1326   if (llvm::Error Err = F.Stream.SkipBlock()) {
1327     Error(std::move(Err));
1328     return true;
1329   }
1330
1331   // Enter the source manager block.
1332   if (llvm::Error Err =
1333           SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1334     Error(std::move(Err));
1335     return true;
1336   }
1337
1338   RecordData Record;
1339   while (true) {
1340     Expected<llvm::BitstreamEntry> MaybeE =
1341         SLocEntryCursor.advanceSkippingSubblocks();
1342     if (!MaybeE) {
1343       Error(MaybeE.takeError());
1344       return true;
1345     }
1346     llvm::BitstreamEntry E = MaybeE.get();
1347
1348     switch (E.Kind) {
1349     case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1350     case llvm::BitstreamEntry::Error:
1351       Error("malformed block record in AST file");
1352       return true;
1353     case llvm::BitstreamEntry::EndBlock:
1354       return false;
1355     case llvm::BitstreamEntry::Record:
1356       // The interesting case.
1357       break;
1358     }
1359
1360     // Read a record.
1361     Record.clear();
1362     StringRef Blob;
1363     Expected<unsigned> MaybeRecord =
1364         SLocEntryCursor.readRecord(E.ID, Record, &Blob);
1365     if (!MaybeRecord) {
1366       Error(MaybeRecord.takeError());
1367       return true;
1368     }
1369     switch (MaybeRecord.get()) {
1370     default:  // Default behavior: ignore.
1371       break;
1372
1373     case SM_SLOC_FILE_ENTRY:
1374     case SM_SLOC_BUFFER_ENTRY:
1375     case SM_SLOC_EXPANSION_ENTRY:
1376       // Once we hit one of the source location entries, we're done.
1377       return false;
1378     }
1379   }
1380 }
1381
1382 /// If a header file is not found at the path that we expect it to be
1383 /// and the PCH file was moved from its original location, try to resolve the
1384 /// file by assuming that header+PCH were moved together and the header is in
1385 /// the same place relative to the PCH.
1386 static std::string
1387 resolveFileRelativeToOriginalDir(const std::string &Filename,
1388                                  const std::string &OriginalDir,
1389                                  const std::string &CurrDir) {
1390   assert(OriginalDir != CurrDir &&
1391          "No point trying to resolve the file if the PCH dir didn't change");
1392
1393   using namespace llvm::sys;
1394
1395   SmallString<128> filePath(Filename);
1396   fs::make_absolute(filePath);
1397   assert(path::is_absolute(OriginalDir));
1398   SmallString<128> currPCHPath(CurrDir);
1399
1400   path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1401                        fileDirE = path::end(path::parent_path(filePath));
1402   path::const_iterator origDirI = path::begin(OriginalDir),
1403                        origDirE = path::end(OriginalDir);
1404   // Skip the common path components from filePath and OriginalDir.
1405   while (fileDirI != fileDirE && origDirI != origDirE &&
1406          *fileDirI == *origDirI) {
1407     ++fileDirI;
1408     ++origDirI;
1409   }
1410   for (; origDirI != origDirE; ++origDirI)
1411     path::append(currPCHPath, "..");
1412   path::append(currPCHPath, fileDirI, fileDirE);
1413   path::append(currPCHPath, path::filename(Filename));
1414   return currPCHPath.str();
1415 }
1416
1417 bool ASTReader::ReadSLocEntry(int ID) {
1418   if (ID == 0)
1419     return false;
1420
1421   if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1422     Error("source location entry ID out-of-range for AST file");
1423     return true;
1424   }
1425
1426   // Local helper to read the (possibly-compressed) buffer data following the
1427   // entry record.
1428   auto ReadBuffer = [this](
1429       BitstreamCursor &SLocEntryCursor,
1430       StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1431     RecordData Record;
1432     StringRef Blob;
1433     Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();
1434     if (!MaybeCode) {
1435       Error(MaybeCode.takeError());
1436       return nullptr;
1437     }
1438     unsigned Code = MaybeCode.get();
1439
1440     Expected<unsigned> MaybeRecCode =
1441         SLocEntryCursor.readRecord(Code, Record, &Blob);
1442     if (!MaybeRecCode) {
1443       Error(MaybeRecCode.takeError());
1444       return nullptr;
1445     }
1446     unsigned RecCode = MaybeRecCode.get();
1447
1448     if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1449       if (!llvm::zlib::isAvailable()) {
1450         Error("zlib is not available");
1451         return nullptr;
1452       }
1453       SmallString<0> Uncompressed;
1454       if (llvm::Error E =
1455               llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
1456         Error("could not decompress embedded file contents: " +
1457               llvm::toString(std::move(E)));
1458         return nullptr;
1459       }
1460       return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1461     } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1462       return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1463     } else {
1464       Error("AST record has invalid code");
1465       return nullptr;
1466     }
1467   };
1468
1469   ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1470   if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(
1471           F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {
1472     Error(std::move(Err));
1473     return true;
1474   }
1475
1476   BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1477   unsigned BaseOffset = F->SLocEntryBaseOffset;
1478
1479   ++NumSLocEntriesRead;
1480   Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();
1481   if (!MaybeEntry) {
1482     Error(MaybeEntry.takeError());
1483     return true;
1484   }
1485   llvm::BitstreamEntry Entry = MaybeEntry.get();
1486
1487   if (Entry.Kind != llvm::BitstreamEntry::Record) {
1488     Error("incorrectly-formatted source location entry in AST file");
1489     return true;
1490   }
1491
1492   RecordData Record;
1493   StringRef Blob;
1494   Expected<unsigned> MaybeSLOC =
1495       SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);
1496   if (!MaybeSLOC) {
1497     Error(MaybeSLOC.takeError());
1498     return true;
1499   }
1500   switch (MaybeSLOC.get()) {
1501   default:
1502     Error("incorrectly-formatted source location entry in AST file");
1503     return true;
1504
1505   case SM_SLOC_FILE_ENTRY: {
1506     // We will detect whether a file changed and return 'Failure' for it, but
1507     // we will also try to fail gracefully by setting up the SLocEntry.
1508     unsigned InputID = Record[4];
1509     InputFile IF = getInputFile(*F, InputID);
1510     const FileEntry *File = IF.getFile();
1511     bool OverriddenBuffer = IF.isOverridden();
1512
1513     // Note that we only check if a File was returned. If it was out-of-date
1514     // we have complained but we will continue creating a FileID to recover
1515     // gracefully.
1516     if (!File)
1517       return true;
1518
1519     SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1520     if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1521       // This is the module's main file.
1522       IncludeLoc = getImportLocation(F);
1523     }
1524     SrcMgr::CharacteristicKind
1525       FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1526     // FIXME: The FileID should be created from the FileEntryRef.
1527     FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1528                                         ID, BaseOffset + Record[0]);
1529     SrcMgr::FileInfo &FileInfo =
1530           const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1531     FileInfo.NumCreatedFIDs = Record[5];
1532     if (Record[3])
1533       FileInfo.setHasLineDirectives();
1534
1535     unsigned NumFileDecls = Record[7];
1536     if (NumFileDecls && ContextObj) {
1537       const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1538       assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1539       FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1540                                                              NumFileDecls));
1541     }
1542
1543     const SrcMgr::ContentCache *ContentCache
1544       = SourceMgr.getOrCreateContentCache(File, isSystem(FileCharacter));
1545     if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1546         ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1547         !ContentCache->getRawBuffer()) {
1548       auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1549       if (!Buffer)
1550         return true;
1551       SourceMgr.overrideFileContents(File, std::move(Buffer));
1552     }
1553
1554     break;
1555   }
1556
1557   case SM_SLOC_BUFFER_ENTRY: {
1558     const char *Name = Blob.data();
1559     unsigned Offset = Record[0];
1560     SrcMgr::CharacteristicKind
1561       FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1562     SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1563     if (IncludeLoc.isInvalid() && F->isModule()) {
1564       IncludeLoc = getImportLocation(F);
1565     }
1566
1567     auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1568     if (!Buffer)
1569       return true;
1570     SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
1571                            BaseOffset + Offset, IncludeLoc);
1572     break;
1573   }
1574
1575   case SM_SLOC_EXPANSION_ENTRY: {
1576     SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1577     SourceMgr.createExpansionLoc(SpellingLoc,
1578                                      ReadSourceLocation(*F, Record[2]),
1579                                      ReadSourceLocation(*F, Record[3]),
1580                                      Record[5],
1581                                      Record[4],
1582                                      ID,
1583                                      BaseOffset + Record[0]);
1584     break;
1585   }
1586   }
1587
1588   return false;
1589 }
1590
1591 std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1592   if (ID == 0)
1593     return std::make_pair(SourceLocation(), "");
1594
1595   if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1596     Error("source location entry ID out-of-range for AST file");
1597     return std::make_pair(SourceLocation(), "");
1598   }
1599
1600   // Find which module file this entry lands in.
1601   ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1602   if (!M->isModule())
1603     return std::make_pair(SourceLocation(), "");
1604
1605   // FIXME: Can we map this down to a particular submodule? That would be
1606   // ideal.
1607   return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
1608 }
1609
1610 /// Find the location where the module F is imported.
1611 SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1612   if (F->ImportLoc.isValid())
1613     return F->ImportLoc;
1614
1615   // Otherwise we have a PCH. It's considered to be "imported" at the first
1616   // location of its includer.
1617   if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1618     // Main file is the importer.
1619     assert(SourceMgr.getMainFileID().isValid() && "missing main file");
1620     return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
1621   }
1622   return F->ImportedBy[0]->FirstLoc;
1623 }
1624
1625 /// Enter a subblock of the specified BlockID with the specified cursor. Read
1626 /// the abbreviations that are at the top of the block and then leave the cursor
1627 /// pointing into the block.
1628 bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
1629   if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
1630     // FIXME this drops errors on the floor.
1631     consumeError(std::move(Err));
1632     return true;
1633   }
1634
1635   while (true) {
1636     uint64_t Offset = Cursor.GetCurrentBitNo();
1637     Expected<unsigned> MaybeCode = Cursor.ReadCode();
1638     if (!MaybeCode) {
1639       // FIXME this drops errors on the floor.
1640       consumeError(MaybeCode.takeError());
1641       return true;
1642     }
1643     unsigned Code = MaybeCode.get();
1644
1645     // We expect all abbrevs to be at the start of the block.
1646     if (Code != llvm::bitc::DEFINE_ABBREV) {
1647       if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1648         // FIXME this drops errors on the floor.
1649         consumeError(std::move(Err));
1650         return true;
1651       }
1652       return false;
1653     }
1654     if (llvm::Error Err = Cursor.ReadAbbrevRecord()) {
1655       // FIXME this drops errors on the floor.
1656       consumeError(std::move(Err));
1657       return true;
1658     }
1659   }
1660 }
1661
1662 Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
1663                            unsigned &Idx) {
1664   Token Tok;
1665   Tok.startToken();
1666   Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1667   Tok.setLength(Record[Idx++]);
1668   if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1669     Tok.setIdentifierInfo(II);
1670   Tok.setKind((tok::TokenKind)Record[Idx++]);
1671   Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1672   return Tok;
1673 }
1674
1675 MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
1676   BitstreamCursor &Stream = F.MacroCursor;
1677
1678   // Keep track of where we are in the stream, then jump back there
1679   // after reading this macro.
1680   SavedStreamPosition SavedPosition(Stream);
1681
1682   if (llvm::Error Err = Stream.JumpToBit(Offset)) {
1683     // FIXME this drops errors on the floor.
1684     consumeError(std::move(Err));
1685     return nullptr;
1686   }
1687   RecordData Record;
1688   SmallVector<IdentifierInfo*, 16> MacroParams;
1689   MacroInfo *Macro = nullptr;
1690
1691   while (true) {
1692     // Advance to the next record, but if we get to the end of the block, don't
1693     // pop it (removing all the abbreviations from the cursor) since we want to
1694     // be able to reseek within the block and read entries.
1695     unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
1696     Expected<llvm::BitstreamEntry> MaybeEntry =
1697         Stream.advanceSkippingSubblocks(Flags);
1698     if (!MaybeEntry) {
1699       Error(MaybeEntry.takeError());
1700       return Macro;
1701     }
1702     llvm::BitstreamEntry Entry = MaybeEntry.get();
1703
1704     switch (Entry.Kind) {
1705     case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1706     case llvm::BitstreamEntry::Error:
1707       Error("malformed block record in AST file");
1708       return Macro;
1709     case llvm::BitstreamEntry::EndBlock:
1710       return Macro;
1711     case llvm::BitstreamEntry::Record:
1712       // The interesting case.
1713       break;
1714     }
1715
1716     // Read a record.
1717     Record.clear();
1718     PreprocessorRecordTypes RecType;
1719     if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
1720       RecType = (PreprocessorRecordTypes)MaybeRecType.get();
1721     else {
1722       Error(MaybeRecType.takeError());
1723       return Macro;
1724     }
1725     switch (RecType) {
1726     case PP_MODULE_MACRO:
1727     case PP_MACRO_DIRECTIVE_HISTORY:
1728       return Macro;
1729
1730     case PP_MACRO_OBJECT_LIKE:
1731     case PP_MACRO_FUNCTION_LIKE: {
1732       // If we already have a macro, that means that we've hit the end
1733       // of the definition of the macro we were looking for. We're
1734       // done.
1735       if (Macro)
1736         return Macro;
1737
1738       unsigned NextIndex = 1; // Skip identifier ID.
1739       SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
1740       MacroInfo *MI = PP.AllocateMacroInfo(Loc);
1741       MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
1742       MI->setIsUsed(Record[NextIndex++]);
1743       MI->setUsedForHeaderGuard(Record[NextIndex++]);
1744
1745       if (RecType == PP_MACRO_FUNCTION_LIKE) {
1746         // Decode function-like macro info.
1747         bool isC99VarArgs = Record[NextIndex++];
1748         bool isGNUVarArgs = Record[NextIndex++];
1749         bool hasCommaPasting = Record[NextIndex++];
1750         MacroParams.clear();
1751         unsigned NumArgs = Record[NextIndex++];
1752         for (unsigned i = 0; i != NumArgs; ++i)
1753           MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1754
1755         // Install function-like macro info.
1756         MI->setIsFunctionLike();
1757         if (isC99VarArgs) MI->setIsC99Varargs();
1758         if (isGNUVarArgs) MI->setIsGNUVarargs();
1759         if (hasCommaPasting) MI->setHasCommaPasting();
1760         MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
1761       }
1762
1763       // Remember that we saw this macro last so that we add the tokens that
1764       // form its body to it.
1765       Macro = MI;
1766
1767       if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1768           Record[NextIndex]) {
1769         // We have a macro definition. Register the association
1770         PreprocessedEntityID
1771             GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1772         PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
1773         PreprocessingRecord::PPEntityID PPID =
1774             PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1775         MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1776             PPRec.getPreprocessedEntity(PPID));
1777         if (PPDef)
1778           PPRec.RegisterMacroDefinition(Macro, PPDef);
1779       }
1780
1781       ++NumMacrosRead;
1782       break;
1783     }
1784
1785     case PP_TOKEN: {
1786       // If we see a TOKEN before a PP_MACRO_*, then the file is
1787       // erroneous, just pretend we didn't see this.
1788       if (!Macro) break;
1789
1790       unsigned Idx = 0;
1791       Token Tok = ReadToken(F, Record, Idx);
1792       Macro->AddTokenToBody(Tok);
1793       break;
1794     }
1795     }
1796   }
1797 }
1798
1799 PreprocessedEntityID
1800 ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
1801                                          unsigned LocalID) const {
1802   if (!M.ModuleOffsetMap.empty())
1803     ReadModuleOffsetMap(M);
1804
1805   ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1806     I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1807   assert(I != M.PreprocessedEntityRemap.end()
1808          && "Invalid index into preprocessed entity index remap");
1809
1810   return LocalID + I->second;
1811 }
1812
1813 unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1814   return llvm::hash_combine(ikey.Size, ikey.ModTime);
1815 }
1816
1817 HeaderFileInfoTrait::internal_key_type
1818 HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1819   internal_key_type ikey = {FE->getSize(),
1820                             M.HasTimestamps ? FE->getModificationTime() : 0,
1821                             FE->getName(), /*Imported*/ false};
1822   return ikey;
1823 }
1824
1825 bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1826   if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
1827     return false;
1828
1829   if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
1830     return true;
1831
1832   // Determine whether the actual files are equivalent.
1833   FileManager &FileMgr = Reader.getFileManager();
1834   auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1835     if (!Key.Imported) {
1836       if (auto File = FileMgr.getFile(Key.Filename))
1837         return *File;
1838       return nullptr;
1839     }
1840
1841     std::string Resolved = Key.Filename;
1842     Reader.ResolveImportedPath(M, Resolved);
1843     if (auto File = FileMgr.getFile(Resolved))
1844       return *File;
1845     return nullptr;
1846   };
1847
1848   const FileEntry *FEA = GetFile(a);
1849   const FileEntry *FEB = GetFile(b);
1850   return FEA && FEA == FEB;
1851 }
1852
1853 std::pair<unsigned, unsigned>
1854 HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1855   using namespace llvm::support;
1856
1857   unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
1858   unsigned DataLen = (unsigned) *d++;
1859   return std::make_pair(KeyLen, DataLen);
1860 }
1861
1862 HeaderFileInfoTrait::internal_key_type
1863 HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
1864   using namespace llvm::support;
1865
1866   internal_key_type ikey;
1867   ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1868   ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
1869   ikey.Filename = (const char *)d;
1870   ikey.Imported = true;
1871   return ikey;
1872 }
1873
1874 HeaderFileInfoTrait::data_type
1875 HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
1876                               unsigned DataLen) {
1877   using namespace llvm::support;
1878
1879   const unsigned char *End = d + DataLen;
1880   HeaderFileInfo HFI;
1881   unsigned Flags = *d++;
1882   // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1883   HFI.isImport |= (Flags >> 5) & 0x01;
1884   HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
1885   HFI.DirInfo = (Flags >> 1) & 0x07;
1886   HFI.IndexHeaderMapHeader = Flags & 0x01;
1887   // FIXME: Find a better way to handle this. Maybe just store a
1888   // "has been included" flag?
1889   HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1890                              HFI.NumIncludes);
1891   HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1892       M, endian::readNext<uint32_t, little, unaligned>(d));
1893   if (unsigned FrameworkOffset =
1894           endian::readNext<uint32_t, little, unaligned>(d)) {
1895     // The framework offset is 1 greater than the actual offset,
1896     // since 0 is used as an indicator for "no framework name".
1897     StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1898     HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1899   }
1900
1901   assert((End - d) % 4 == 0 &&
1902          "Wrong data length in HeaderFileInfo deserialization");
1903   while (d != End) {
1904     uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
1905     auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1906     LocalSMID >>= 2;
1907
1908     // This header is part of a module. Associate it with the module to enable
1909     // implicit module import.
1910     SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1911     Module *Mod = Reader.getSubmodule(GlobalSMID);
1912     FileManager &FileMgr = Reader.getFileManager();
1913     ModuleMap &ModMap =
1914         Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1915
1916     std::string Filename = key.Filename;
1917     if (key.Imported)
1918       Reader.ResolveImportedPath(M, Filename);
1919     // FIXME: This is not always the right filename-as-written, but we're not
1920     // going to use this information to rebuild the module, so it doesn't make
1921     // a lot of difference.
1922     Module::Header H = { key.Filename, *FileMgr.getFile(Filename) };
1923     ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1924     HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
1925   }
1926
1927   // This HeaderFileInfo was externally loaded.
1928   HFI.External = true;
1929   HFI.IsValid = true;
1930   return HFI;
1931 }
1932
1933 void ASTReader::addPendingMacro(IdentifierInfo *II,
1934                                 ModuleFile *M,
1935                                 uint64_t MacroDirectivesOffset) {
1936   assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1937   PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
1938 }
1939
1940 void ASTReader::ReadDefinedMacros() {
1941   // Note that we are loading defined macros.
1942   Deserializing Macros(this);
1943
1944   for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
1945     BitstreamCursor &MacroCursor = I.MacroCursor;
1946
1947     // If there was no preprocessor block, skip this file.
1948     if (MacroCursor.getBitcodeBytes().empty())
1949       continue;
1950
1951     BitstreamCursor Cursor = MacroCursor;
1952     if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
1953       Error(std::move(Err));
1954       return;
1955     }
1956
1957     RecordData Record;
1958     while (true) {
1959       Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
1960       if (!MaybeE) {
1961         Error(MaybeE.takeError());
1962         return;
1963       }
1964       llvm::BitstreamEntry E = MaybeE.get();
1965
1966       switch (E.Kind) {
1967       case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1968       case llvm::BitstreamEntry::Error:
1969         Error("malformed block record in AST file");
1970         return;
1971       case llvm::BitstreamEntry::EndBlock:
1972         goto NextCursor;
1973
1974       case llvm::BitstreamEntry::Record: {
1975         Record.clear();
1976         Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
1977         if (!MaybeRecord) {
1978           Error(MaybeRecord.takeError());
1979           return;
1980         }
1981         switch (MaybeRecord.get()) {
1982         default:  // Default behavior: ignore.
1983           break;
1984
1985         case PP_MACRO_OBJECT_LIKE:
1986         case PP_MACRO_FUNCTION_LIKE: {
1987           IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
1988           if (II->isOutOfDate())
1989             updateOutOfDateIdentifier(*II);
1990           break;
1991         }
1992
1993         case PP_TOKEN:
1994           // Ignore tokens.
1995           break;
1996         }
1997         break;
1998       }
1999       }
2000     }
2001     NextCursor:  ;
2002   }
2003 }
2004
2005 namespace {
2006
2007   /// Visitor class used to look up identifirs in an AST file.
2008   class IdentifierLookupVisitor {
2009     StringRef Name;
2010     unsigned NameHash;
2011     unsigned PriorGeneration;
2012     unsigned &NumIdentifierLookups;
2013     unsigned &NumIdentifierLookupHits;
2014     IdentifierInfo *Found = nullptr;
2015
2016   public:
2017     IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
2018                             unsigned &NumIdentifierLookups,
2019                             unsigned &NumIdentifierLookupHits)
2020       : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
2021         PriorGeneration(PriorGeneration),
2022         NumIdentifierLookups(NumIdentifierLookups),
2023         NumIdentifierLookupHits(NumIdentifierLookupHits) {}
2024
2025     bool operator()(ModuleFile &M) {
2026       // If we've already searched this module file, skip it now.
2027       if (M.Generation <= PriorGeneration)
2028         return true;
2029
2030       ASTIdentifierLookupTable *IdTable
2031         = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
2032       if (!IdTable)
2033         return false;
2034
2035       ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
2036                                      Found);
2037       ++NumIdentifierLookups;
2038       ASTIdentifierLookupTable::iterator Pos =
2039           IdTable->find_hashed(Name, NameHash, &Trait);
2040       if (Pos == IdTable->end())
2041         return false;
2042
2043       // Dereferencing the iterator has the effect of building the
2044       // IdentifierInfo node and populating it with the various
2045       // declarations it needs.
2046       ++NumIdentifierLookupHits;
2047       Found = *Pos;
2048       return true;
2049     }
2050
2051     // Retrieve the identifier info found within the module
2052     // files.
2053     IdentifierInfo *getIdentifierInfo() const { return Found; }
2054   };
2055
2056 } // namespace
2057
2058 void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
2059   // Note that we are loading an identifier.
2060   Deserializing AnIdentifier(this);
2061
2062   unsigned PriorGeneration = 0;
2063   if (getContext().getLangOpts().Modules)
2064     PriorGeneration = IdentifierGeneration[&II];
2065
2066   // If there is a global index, look there first to determine which modules
2067   // provably do not have any results for this identifier.
2068   GlobalModuleIndex::HitSet Hits;
2069   GlobalModuleIndex::HitSet *HitsPtr = nullptr;
2070   if (!loadGlobalIndex()) {
2071     if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
2072       HitsPtr = &Hits;
2073     }
2074   }
2075
2076   IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
2077                                   NumIdentifierLookups,
2078                                   NumIdentifierLookupHits);
2079   ModuleMgr.visit(Visitor, HitsPtr);
2080   markIdentifierUpToDate(&II);
2081 }
2082
2083 void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
2084   if (!II)
2085     return;
2086
2087   II->setOutOfDate(false);
2088
2089   // Update the generation for this identifier.
2090   if (getContext().getLangOpts().Modules)
2091     IdentifierGeneration[II] = getGeneration();
2092 }
2093
2094 void ASTReader::resolvePendingMacro(IdentifierInfo *II,
2095                                     const PendingMacroInfo &PMInfo) {
2096   ModuleFile &M = *PMInfo.M;
2097
2098   BitstreamCursor &Cursor = M.MacroCursor;
2099   SavedStreamPosition SavedPosition(Cursor);
2100   if (llvm::Error Err = Cursor.JumpToBit(PMInfo.MacroDirectivesOffset)) {
2101     Error(std::move(Err));
2102     return;
2103   }
2104
2105   struct ModuleMacroRecord {
2106     SubmoduleID SubModID;
2107     MacroInfo *MI;
2108     SmallVector<SubmoduleID, 8> Overrides;
2109   };
2110   llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
2111
2112   // We expect to see a sequence of PP_MODULE_MACRO records listing exported
2113   // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
2114   // macro histroy.
2115   RecordData Record;
2116   while (true) {
2117     Expected<llvm::BitstreamEntry> MaybeEntry =
2118         Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
2119     if (!MaybeEntry) {
2120       Error(MaybeEntry.takeError());
2121       return;
2122     }
2123     llvm::BitstreamEntry Entry = MaybeEntry.get();
2124
2125     if (Entry.Kind != llvm::BitstreamEntry::Record) {
2126       Error("malformed block record in AST file");
2127       return;
2128     }
2129
2130     Record.clear();
2131     Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
2132     if (!MaybePP) {
2133       Error(MaybePP.takeError());
2134       return;
2135     }
2136     switch ((PreprocessorRecordTypes)MaybePP.get()) {
2137     case PP_MACRO_DIRECTIVE_HISTORY:
2138       break;
2139
2140     case PP_MODULE_MACRO: {
2141       ModuleMacros.push_back(ModuleMacroRecord());
2142       auto &Info = ModuleMacros.back();
2143       Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
2144       Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
2145       for (int I = 2, N = Record.size(); I != N; ++I)
2146         Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
2147       continue;
2148     }
2149
2150     default:
2151       Error("malformed block record in AST file");
2152       return;
2153     }
2154
2155     // We found the macro directive history; that's the last record
2156     // for this macro.
2157     break;
2158   }
2159
2160   // Module macros are listed in reverse dependency order.
2161   {
2162     std::reverse(ModuleMacros.begin(), ModuleMacros.end());
2163     llvm::SmallVector<ModuleMacro*, 8> Overrides;
2164     for (auto &MMR : ModuleMacros) {
2165       Overrides.clear();
2166       for (unsigned ModID : MMR.Overrides) {
2167         Module *Mod = getSubmodule(ModID);
2168         auto *Macro = PP.getModuleMacro(Mod, II);
2169         assert(Macro && "missing definition for overridden macro");
2170         Overrides.push_back(Macro);
2171       }
2172
2173       bool Inserted = false;
2174       Module *Owner = getSubmodule(MMR.SubModID);
2175       PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
2176     }
2177   }
2178
2179   // Don't read the directive history for a module; we don't have anywhere
2180   // to put it.
2181   if (M.isModule())
2182     return;
2183
2184   // Deserialize the macro directives history in reverse source-order.
2185   MacroDirective *Latest = nullptr, *Earliest = nullptr;
2186   unsigned Idx = 0, N = Record.size();
2187   while (Idx < N) {
2188     MacroDirective *MD = nullptr;
2189     SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
2190     MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
2191     switch (K) {
2192     case MacroDirective::MD_Define: {
2193       MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
2194       MD = PP.AllocateDefMacroDirective(MI, Loc);
2195       break;
2196     }
2197     case MacroDirective::MD_Undefine:
2198       MD = PP.AllocateUndefMacroDirective(Loc);
2199       break;
2200     case MacroDirective::MD_Visibility:
2201       bool isPublic = Record[Idx++];
2202       MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2203       break;
2204     }
2205
2206     if (!Latest)
2207       Latest = MD;
2208     if (Earliest)
2209       Earliest->setPrevious(MD);
2210     Earliest = MD;
2211   }
2212
2213   if (Latest)
2214     PP.setLoadedMacroDirective(II, Earliest, Latest);
2215 }
2216
2217 ASTReader::InputFileInfo
2218 ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
2219   // Go find this input file.
2220   BitstreamCursor &Cursor = F.InputFilesCursor;
2221   SavedStreamPosition SavedPosition(Cursor);
2222   if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
2223     // FIXME this drops errors on the floor.
2224     consumeError(std::move(Err));
2225   }
2226
2227   Expected<unsigned> MaybeCode = Cursor.ReadCode();
2228   if (!MaybeCode) {
2229     // FIXME this drops errors on the floor.
2230     consumeError(MaybeCode.takeError());
2231   }
2232   unsigned Code = MaybeCode.get();
2233   RecordData Record;
2234   StringRef Blob;
2235
2236   if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
2237     assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
2238            "invalid record type for input file");
2239   else {
2240     // FIXME this drops errors on the floor.
2241     consumeError(Maybe.takeError());
2242   }
2243
2244   assert(Record[0] == ID && "Bogus stored ID or offset");
2245   InputFileInfo R;
2246   R.StoredSize = static_cast<off_t>(Record[1]);
2247   R.StoredTime = static_cast<time_t>(Record[2]);
2248   R.Overridden = static_cast<bool>(Record[3]);
2249   R.Transient = static_cast<bool>(Record[4]);
2250   R.TopLevelModuleMap = static_cast<bool>(Record[5]);
2251   R.Filename = Blob;
2252   ResolveImportedPath(F, R.Filename);
2253
2254   Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
2255   if (!MaybeEntry) // FIXME this drops errors on the floor.
2256     consumeError(MaybeEntry.takeError());
2257   llvm::BitstreamEntry Entry = MaybeEntry.get();
2258   assert(Entry.Kind == llvm::BitstreamEntry::Record &&
2259          "expected record type for input file hash");
2260
2261   Record.clear();
2262   if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record))
2263     assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH &&
2264            "invalid record type for input file hash");
2265   else {
2266     // FIXME this drops errors on the floor.
2267     consumeError(Maybe.takeError());
2268   }
2269   R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) |
2270                   static_cast<uint64_t>(Record[0]);
2271   return R;
2272 }
2273
2274 static unsigned moduleKindForDiagnostic(ModuleKind Kind);
2275 InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
2276   // If this ID is bogus, just return an empty input file.
2277   if (ID == 0 || ID > F.InputFilesLoaded.size())
2278     return InputFile();
2279
2280   // If we've already loaded this input file, return it.
2281   if (F.InputFilesLoaded[ID-1].getFile())
2282     return F.InputFilesLoaded[ID-1];
2283
2284   if (F.InputFilesLoaded[ID-1].isNotFound())
2285     return InputFile();
2286
2287   // Go find this input file.
2288   BitstreamCursor &Cursor = F.InputFilesCursor;
2289   SavedStreamPosition SavedPosition(Cursor);
2290   if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
2291     // FIXME this drops errors on the floor.
2292     consumeError(std::move(Err));
2293   }
2294
2295   InputFileInfo FI = readInputFileInfo(F, ID);
2296   off_t StoredSize = FI.StoredSize;
2297   time_t StoredTime = FI.StoredTime;
2298   bool Overridden = FI.Overridden;
2299   bool Transient = FI.Transient;
2300   StringRef Filename = FI.Filename;
2301   uint64_t StoredContentHash = FI.ContentHash;
2302
2303   const FileEntry *File = nullptr;
2304   if (auto FE = FileMgr.getFile(Filename, /*OpenFile=*/false))
2305     File = *FE;
2306
2307   // If we didn't find the file, resolve it relative to the
2308   // original directory from which this AST file was created.
2309   if (File == nullptr && !F.OriginalDir.empty() && !F.BaseDirectory.empty() &&
2310       F.OriginalDir != F.BaseDirectory) {
2311     std::string Resolved = resolveFileRelativeToOriginalDir(
2312         Filename, F.OriginalDir, F.BaseDirectory);
2313     if (!Resolved.empty())
2314       if (auto FE = FileMgr.getFile(Resolved))
2315         File = *FE;
2316   }
2317
2318   // For an overridden file, create a virtual file with the stored
2319   // size/timestamp.
2320   if ((Overridden || Transient) && File == nullptr)
2321     File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
2322
2323   if (File == nullptr) {
2324     if (Complain) {
2325       std::string ErrorStr = "could not find file '";
2326       ErrorStr += Filename;
2327       ErrorStr += "' referenced by AST file '";
2328       ErrorStr += F.FileName;
2329       ErrorStr += "'";
2330       Error(ErrorStr);
2331     }
2332     // Record that we didn't find the file.
2333     F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2334     return InputFile();
2335   }
2336
2337   // Check if there was a request to override the contents of the file
2338   // that was part of the precompiled header. Overriding such a file
2339   // can lead to problems when lexing using the source locations from the
2340   // PCH.
2341   SourceManager &SM = getSourceManager();
2342   // FIXME: Reject if the overrides are different.
2343   if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
2344     if (Complain)
2345       Error(diag::err_fe_pch_file_overridden, Filename);
2346
2347     // After emitting the diagnostic, bypass the overriding file to recover
2348     // (this creates a separate FileEntry).
2349     File = SM.bypassFileContentsOverride(*File);
2350     if (!File) {
2351       F.InputFilesLoaded[ID - 1] = InputFile::getNotFound();
2352       return InputFile();
2353     }
2354   }
2355
2356   enum ModificationType {
2357     Size,
2358     ModTime,
2359     Content,
2360     None,
2361   };
2362   auto HasInputFileChanged = [&]() {
2363     if (StoredSize != File->getSize())
2364       return ModificationType::Size;
2365     if (!DisableValidation && StoredTime &&
2366         StoredTime != File->getModificationTime()) {
2367       // In case the modification time changes but not the content,
2368       // accept the cached file as legit.
2369       if (ValidateASTInputFilesContent &&
2370           StoredContentHash != static_cast<uint64_t>(llvm::hash_code(-1))) {
2371         auto MemBuffOrError = FileMgr.getBufferForFile(File);
2372         if (!MemBuffOrError) {
2373           if (!Complain)
2374             return ModificationType::ModTime;
2375           std::string ErrorStr = "could not get buffer for file '";
2376           ErrorStr += File->getName();
2377           ErrorStr += "'";
2378           Error(ErrorStr);
2379           return ModificationType::ModTime;
2380         }
2381
2382         auto ContentHash = hash_value(MemBuffOrError.get()->getBuffer());
2383         if (StoredContentHash == static_cast<uint64_t>(ContentHash))
2384           return ModificationType::None;
2385         return ModificationType::Content;
2386       }
2387       return ModificationType::ModTime;
2388     }
2389     return ModificationType::None;
2390   };
2391
2392   bool IsOutOfDate = false;
2393   auto FileChange = HasInputFileChanged();
2394   // For an overridden file, there is nothing to validate.
2395   if (!Overridden && FileChange != ModificationType::None) {
2396     if (Complain) {
2397       // Build a list of the PCH imports that got us here (in reverse).
2398       SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2399       while (!ImportStack.back()->ImportedBy.empty())
2400         ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
2401
2402       // The top-level PCH is stale.
2403       StringRef TopLevelPCHName(ImportStack.back()->FileName);
2404       unsigned DiagnosticKind =
2405           moduleKindForDiagnostic(ImportStack.back()->Kind);
2406       if (DiagnosticKind == 0)
2407         Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName,
2408               (unsigned)FileChange);
2409       else if (DiagnosticKind == 1)
2410         Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName,
2411               (unsigned)FileChange);
2412       else
2413         Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName,
2414               (unsigned)FileChange);
2415
2416       // Print the import stack.
2417       if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2418         Diag(diag::note_pch_required_by)
2419           << Filename << ImportStack[0]->FileName;
2420         for (unsigned I = 1; I < ImportStack.size(); ++I)
2421           Diag(diag::note_pch_required_by)
2422             << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
2423       }
2424
2425       if (!Diags.isDiagnosticInFlight())
2426         Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
2427     }
2428
2429     IsOutOfDate = true;
2430   }
2431   // FIXME: If the file is overridden and we've already opened it,
2432   // issue an error (or split it into a separate FileEntry).
2433
2434   InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
2435
2436   // Note that we've loaded this input file.
2437   F.InputFilesLoaded[ID-1] = IF;
2438   return IF;
2439 }
2440
2441 /// If we are loading a relocatable PCH or module file, and the filename
2442 /// is not an absolute path, add the system or module root to the beginning of
2443 /// the file name.
2444 void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2445   // Resolve relative to the base directory, if we have one.
2446   if (!M.BaseDirectory.empty())
2447     return ResolveImportedPath(Filename, M.BaseDirectory);
2448 }
2449
2450 void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
2451   if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2452     return;
2453
2454   SmallString<128> Buffer;
2455   llvm::sys::path::append(Buffer, Prefix, Filename);
2456   Filename.assign(Buffer.begin(), Buffer.end());
2457 }
2458
2459 static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2460   switch (ARR) {
2461   case ASTReader::Failure: return true;
2462   case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2463   case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2464   case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2465   case ASTReader::ConfigurationMismatch:
2466     return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2467   case ASTReader::HadErrors: return true;
2468   case ASTReader::Success: return false;
2469   }
2470
2471   llvm_unreachable("unknown ASTReadResult");
2472 }
2473
2474 ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2475     BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2476     bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
2477     std::string &SuggestedPredefines) {
2478   if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
2479     // FIXME this drops errors on the floor.
2480     consumeError(std::move(Err));
2481     return Failure;
2482   }
2483
2484   // Read all of the records in the options block.
2485   RecordData Record;
2486   ASTReadResult Result = Success;
2487   while (true) {
2488     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2489     if (!MaybeEntry) {
2490       // FIXME this drops errors on the floor.
2491       consumeError(MaybeEntry.takeError());
2492       return Failure;
2493     }
2494     llvm::BitstreamEntry Entry = MaybeEntry.get();
2495
2496     switch (Entry.Kind) {
2497     case llvm::BitstreamEntry::Error:
2498     case llvm::BitstreamEntry::SubBlock:
2499       return Failure;
2500
2501     case llvm::BitstreamEntry::EndBlock:
2502       return Result;
2503
2504     case llvm::BitstreamEntry::Record:
2505       // The interesting case.
2506       break;
2507     }
2508
2509     // Read and process a record.
2510     Record.clear();
2511     Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
2512     if (!MaybeRecordType) {
2513       // FIXME this drops errors on the floor.
2514       consumeError(MaybeRecordType.takeError());
2515       return Failure;
2516     }
2517     switch ((OptionsRecordTypes)MaybeRecordType.get()) {
2518     case LANGUAGE_OPTIONS: {
2519       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2520       if (ParseLanguageOptions(Record, Complain, Listener,
2521                                AllowCompatibleConfigurationMismatch))
2522         Result = ConfigurationMismatch;
2523       break;
2524     }
2525
2526     case TARGET_OPTIONS: {
2527       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2528       if (ParseTargetOptions(Record, Complain, Listener,
2529                              AllowCompatibleConfigurationMismatch))
2530         Result = ConfigurationMismatch;
2531       break;
2532     }
2533
2534     case FILE_SYSTEM_OPTIONS: {
2535       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2536       if (!AllowCompatibleConfigurationMismatch &&
2537           ParseFileSystemOptions(Record, Complain, Listener))
2538         Result = ConfigurationMismatch;
2539       break;
2540     }
2541
2542     case HEADER_SEARCH_OPTIONS: {
2543       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2544       if (!AllowCompatibleConfigurationMismatch &&
2545           ParseHeaderSearchOptions(Record, Complain, Listener))
2546         Result = ConfigurationMismatch;
2547       break;
2548     }
2549
2550     case PREPROCESSOR_OPTIONS:
2551       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2552       if (!AllowCompatibleConfigurationMismatch &&
2553           ParsePreprocessorOptions(Record, Complain, Listener,
2554                                    SuggestedPredefines))
2555         Result = ConfigurationMismatch;
2556       break;
2557     }
2558   }
2559 }
2560
2561 ASTReader::ASTReadResult
2562 ASTReader::ReadControlBlock(ModuleFile &F,
2563                             SmallVectorImpl<ImportedModule> &Loaded,
2564                             const ModuleFile *ImportedBy,
2565                             unsigned ClientLoadCapabilities) {
2566   BitstreamCursor &Stream = F.Stream;
2567
2568   if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2569     Error(std::move(Err));
2570     return Failure;
2571   }
2572
2573   // Lambda to read the unhashed control block the first time it's called.
2574   //
2575   // For PCM files, the unhashed control block cannot be read until after the
2576   // MODULE_NAME record.  However, PCH files have no MODULE_NAME, and yet still
2577   // need to look ahead before reading the IMPORTS record.  For consistency,
2578   // this block is always read somehow (see BitstreamEntry::EndBlock).
2579   bool HasReadUnhashedControlBlock = false;
2580   auto readUnhashedControlBlockOnce = [&]() {
2581     if (!HasReadUnhashedControlBlock) {
2582       HasReadUnhashedControlBlock = true;
2583       if (ASTReadResult Result =
2584               readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2585         return Result;
2586     }
2587     return Success;
2588   };
2589
2590   // Read all of the records and blocks in the control block.
2591   RecordData Record;
2592   unsigned NumInputs = 0;
2593   unsigned NumUserInputs = 0;
2594   StringRef BaseDirectoryAsWritten;
2595   while (true) {
2596     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2597     if (!MaybeEntry) {
2598       Error(MaybeEntry.takeError());
2599       return Failure;
2600     }
2601     llvm::BitstreamEntry Entry = MaybeEntry.get();
2602
2603     switch (Entry.Kind) {
2604     case llvm::BitstreamEntry::Error:
2605       Error("malformed block record in AST file");
2606       return Failure;
2607     case llvm::BitstreamEntry::EndBlock: {
2608       // Validate the module before returning.  This call catches an AST with
2609       // no module name and no imports.
2610       if (ASTReadResult Result = readUnhashedControlBlockOnce())
2611         return Result;
2612
2613       // Validate input files.
2614       const HeaderSearchOptions &HSOpts =
2615           PP.getHeaderSearchInfo().getHeaderSearchOpts();
2616
2617       // All user input files reside at the index range [0, NumUserInputs), and
2618       // system input files reside at [NumUserInputs, NumInputs). For explicitly
2619       // loaded module files, ignore missing inputs.
2620       if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2621           F.Kind != MK_PrebuiltModule) {
2622         bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2623
2624         // If we are reading a module, we will create a verification timestamp,
2625         // so we verify all input files.  Otherwise, verify only user input
2626         // files.
2627
2628         unsigned N = NumUserInputs;
2629         if (ValidateSystemInputs ||
2630             (HSOpts.ModulesValidateOncePerBuildSession &&
2631              F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
2632              F.Kind == MK_ImplicitModule))
2633           N = NumInputs;
2634
2635         for (unsigned I = 0; I < N; ++I) {
2636           InputFile IF = getInputFile(F, I+1, Complain);
2637           if (!IF.getFile() || IF.isOutOfDate())
2638             return OutOfDate;
2639         }
2640       }
2641
2642       if (Listener)
2643         Listener->visitModuleFile(F.FileName, F.Kind);
2644
2645       if (Listener && Listener->needsInputFileVisitation()) {
2646         unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2647                                                                 : NumUserInputs;
2648         for (unsigned I = 0; I < N; ++I) {
2649           bool IsSystem = I >= NumUserInputs;
2650           InputFileInfo FI = readInputFileInfo(F, I+1);
2651           Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
2652                                    F.Kind == MK_ExplicitModule ||
2653                                    F.Kind == MK_PrebuiltModule);
2654         }
2655       }
2656
2657       return Success;
2658     }
2659
2660     case llvm::BitstreamEntry::SubBlock:
2661       switch (Entry.ID) {
2662       case INPUT_FILES_BLOCK_ID:
2663         F.InputFilesCursor = Stream;
2664         if (llvm::Error Err = Stream.SkipBlock()) {
2665           Error(std::move(Err));
2666           return Failure;
2667         }
2668         if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2669           Error("malformed block record in AST file");
2670           return Failure;
2671         }
2672         continue;
2673
2674       case OPTIONS_BLOCK_ID:
2675         // If we're reading the first module for this group, check its options
2676         // are compatible with ours. For modules it imports, no further checking
2677         // is required, because we checked them when we built it.
2678         if (Listener && !ImportedBy) {
2679           // Should we allow the configuration of the module file to differ from
2680           // the configuration of the current translation unit in a compatible
2681           // way?
2682           //
2683           // FIXME: Allow this for files explicitly specified with -include-pch.
2684           bool AllowCompatibleConfigurationMismatch =
2685               F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
2686
2687           ASTReadResult Result =
2688               ReadOptionsBlock(Stream, ClientLoadCapabilities,
2689                                AllowCompatibleConfigurationMismatch, *Listener,
2690                                SuggestedPredefines);
2691           if (Result == Failure) {
2692             Error("malformed block record in AST file");
2693             return Result;
2694           }
2695
2696           if (DisableValidation ||
2697               (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2698             Result = Success;
2699
2700           // If we can't load the module, exit early since we likely
2701           // will rebuild the module anyway. The stream may be in the
2702           // middle of a block.
2703           if (Result != Success)
2704             return Result;
2705         } else if (llvm::Error Err = Stream.SkipBlock()) {
2706           Error(std::move(Err));
2707           return Failure;
2708         }
2709         continue;
2710
2711       default:
2712         if (llvm::Error Err = Stream.SkipBlock()) {
2713           Error(std::move(Err));
2714           return Failure;
2715         }
2716         continue;
2717       }
2718
2719     case llvm::BitstreamEntry::Record:
2720       // The interesting case.
2721       break;
2722     }
2723
2724     // Read and process a record.
2725     Record.clear();
2726     StringRef Blob;
2727     Expected<unsigned> MaybeRecordType =
2728         Stream.readRecord(Entry.ID, Record, &Blob);
2729     if (!MaybeRecordType) {
2730       Error(MaybeRecordType.takeError());
2731       return Failure;
2732     }
2733     switch ((ControlRecordTypes)MaybeRecordType.get()) {
2734     case METADATA: {
2735       if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2736         if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2737           Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2738                                         : diag::err_pch_version_too_new);
2739         return VersionMismatch;
2740       }
2741
2742       bool hasErrors = Record[7];
2743       if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2744         Diag(diag::err_pch_with_compiler_errors);
2745         return HadErrors;
2746       }
2747       if (hasErrors) {
2748         Diags.ErrorOccurred = true;
2749         Diags.UncompilableErrorOccurred = true;
2750         Diags.UnrecoverableErrorOccurred = true;
2751       }
2752
2753       F.RelocatablePCH = Record[4];
2754       // Relative paths in a relocatable PCH are relative to our sysroot.
2755       if (F.RelocatablePCH)
2756         F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
2757
2758       F.HasTimestamps = Record[5];
2759
2760       F.PCHHasObjectFile = Record[6];
2761
2762       const std::string &CurBranch = getClangFullRepositoryVersion();
2763       StringRef ASTBranch = Blob;
2764       if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2765         if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2766           Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
2767         return VersionMismatch;
2768       }
2769       break;
2770     }
2771
2772     case IMPORTS: {
2773       // Validate the AST before processing any imports (otherwise, untangling
2774       // them can be error-prone and expensive).  A module will have a name and
2775       // will already have been validated, but this catches the PCH case.
2776       if (ASTReadResult Result = readUnhashedControlBlockOnce())
2777         return Result;
2778
2779       // Load each of the imported PCH files.
2780       unsigned Idx = 0, N = Record.size();
2781       while (Idx < N) {
2782         // Read information about the AST file.
2783         ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2784         // The import location will be the local one for now; we will adjust
2785         // all import locations of module imports after the global source
2786         // location info are setup, in ReadAST.
2787         SourceLocation ImportLoc =
2788             ReadUntranslatedSourceLocation(Record[Idx++]);
2789         off_t StoredSize = (off_t)Record[Idx++];
2790         time_t StoredModTime = (time_t)Record[Idx++];
2791         ASTFileSignature StoredSignature = {
2792             {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2793               (uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2794               (uint32_t)Record[Idx++]}}};
2795
2796         std::string ImportedName = ReadString(Record, Idx);
2797         std::string ImportedFile;
2798
2799         // For prebuilt and explicit modules first consult the file map for
2800         // an override. Note that here we don't search prebuilt module
2801         // directories, only the explicit name to file mappings. Also, we will
2802         // still verify the size/signature making sure it is essentially the
2803         // same file but perhaps in a different location.
2804         if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
2805           ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
2806             ImportedName, /*FileMapOnly*/ true);
2807
2808         if (ImportedFile.empty())
2809           // Use BaseDirectoryAsWritten to ensure we use the same path in the
2810           // ModuleCache as when writing.
2811           ImportedFile = ReadPath(BaseDirectoryAsWritten, Record, Idx);
2812         else
2813           SkipPath(Record, Idx);
2814
2815         // If our client can't cope with us being out of date, we can't cope with
2816         // our dependency being missing.
2817         unsigned Capabilities = ClientLoadCapabilities;
2818         if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2819           Capabilities &= ~ARR_Missing;
2820
2821         // Load the AST file.
2822         auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2823                                   Loaded, StoredSize, StoredModTime,
2824                                   StoredSignature, Capabilities);
2825
2826         // If we diagnosed a problem, produce a backtrace.
2827         if (isDiagnosedResult(Result, Capabilities))
2828           Diag(diag::note_module_file_imported_by)
2829               << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2830
2831         switch (Result) {
2832         case Failure: return Failure;
2833           // If we have to ignore the dependency, we'll have to ignore this too.
2834         case Missing:
2835         case OutOfDate: return OutOfDate;
2836         case VersionMismatch: return VersionMismatch;
2837         case ConfigurationMismatch: return ConfigurationMismatch;
2838         case HadErrors: return HadErrors;
2839         case Success: break;
2840         }
2841       }
2842       break;
2843     }
2844
2845     case ORIGINAL_FILE:
2846       F.OriginalSourceFileID = FileID::get(Record[0]);
2847       F.ActualOriginalSourceFileName = Blob;
2848       F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2849       ResolveImportedPath(F, F.OriginalSourceFileName);
2850       break;
2851
2852     case ORIGINAL_FILE_ID:
2853       F.OriginalSourceFileID = FileID::get(Record[0]);
2854       break;
2855
2856     case ORIGINAL_PCH_DIR:
2857       F.OriginalDir = Blob;
2858       break;
2859
2860     case MODULE_NAME:
2861       F.ModuleName = Blob;
2862       Diag(diag::remark_module_import)
2863           << F.ModuleName << F.FileName << (ImportedBy ? true : false)
2864           << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
2865       if (Listener)
2866         Listener->ReadModuleName(F.ModuleName);
2867
2868       // Validate the AST as soon as we have a name so we can exit early on
2869       // failure.
2870       if (ASTReadResult Result = readUnhashedControlBlockOnce())
2871         return Result;
2872
2873       break;
2874
2875     case MODULE_DIRECTORY: {
2876       // Save the BaseDirectory as written in the PCM for computing the module
2877       // filename for the ModuleCache.
2878       BaseDirectoryAsWritten = Blob;
2879       assert(!F.ModuleName.empty() &&
2880              "MODULE_DIRECTORY found before MODULE_NAME");
2881       // If we've already loaded a module map file covering this module, we may
2882       // have a better path for it (relative to the current build).
2883       Module *M = PP.getHeaderSearchInfo().lookupModule(
2884           F.ModuleName, /*AllowSearch*/ true,
2885           /*AllowExtraModuleMapSearch*/ true);
2886       if (M && M->Directory) {
2887         // If we're implicitly loading a module, the base directory can't
2888         // change between the build and use.
2889         // Don't emit module relocation error if we have -fno-validate-pch
2890         if (!PP.getPreprocessorOpts().DisablePCHValidation &&
2891             F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
2892           auto BuildDir = PP.getFileManager().getDirectory(Blob);
2893           if (!BuildDir || *BuildDir != M->Directory) {
2894             if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2895               Diag(diag::err_imported_module_relocated)
2896                   << F.ModuleName << Blob << M->Directory->getName();
2897             return OutOfDate;
2898           }
2899         }
2900         F.BaseDirectory = M->Directory->getName();
2901       } else {
2902         F.BaseDirectory = Blob;
2903       }
2904       break;
2905     }
2906
2907     case MODULE_MAP_FILE:
2908       if (ASTReadResult Result =
2909               ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2910         return Result;
2911       break;
2912
2913     case INPUT_FILE_OFFSETS:
2914       NumInputs = Record[0];
2915       NumUserInputs = Record[1];
2916       F.InputFileOffsets =
2917           (const llvm::support::unaligned_uint64_t *)Blob.data();
2918       F.InputFilesLoaded.resize(NumInputs);
2919       F.NumUserInputFiles = NumUserInputs;
2920       break;
2921     }
2922   }
2923 }
2924
2925 ASTReader::ASTReadResult
2926 ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
2927   BitstreamCursor &Stream = F.Stream;
2928
2929   if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID)) {
2930     Error(std::move(Err));
2931     return Failure;
2932   }
2933
2934   // Read all of the records and blocks for the AST file.
2935   RecordData Record;
2936   while (true) {
2937     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2938     if (!MaybeEntry) {
2939       Error(MaybeEntry.takeError());
2940       return Failure;
2941     }
2942     llvm::BitstreamEntry Entry = MaybeEntry.get();
2943
2944     switch (Entry.Kind) {
2945     case llvm::BitstreamEntry::Error:
2946       Error("error at end of module block in AST file");
2947       return Failure;
2948     case llvm::BitstreamEntry::EndBlock:
2949       // Outside of C++, we do not store a lookup map for the translation unit.
2950       // Instead, mark it as needing a lookup map to be built if this module
2951       // contains any declarations lexically within it (which it always does!).
2952       // This usually has no cost, since we very rarely need the lookup map for
2953       // the translation unit outside C++.
2954       if (ASTContext *Ctx = ContextObj) {
2955         DeclContext *DC = Ctx->getTranslationUnitDecl();
2956         if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
2957           DC->setMustBuildLookupTable();
2958       }
2959
2960       return Success;
2961     case llvm::BitstreamEntry::SubBlock:
2962       switch (Entry.ID) {
2963       case DECLTYPES_BLOCK_ID:
2964         // We lazily load the decls block, but we want to set up the
2965         // DeclsCursor cursor to point into it.  Clone our current bitcode
2966         // cursor to it, enter the block and read the abbrevs in that block.
2967         // With the main cursor, we just skip over it.
2968         F.DeclsCursor = Stream;
2969         if (llvm::Error Err = Stream.SkipBlock()) {
2970           Error(std::move(Err));
2971           return Failure;
2972         }
2973         if (ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2974           Error("malformed block record in AST file");
2975           return Failure;
2976         }
2977         break;
2978
2979       case PREPROCESSOR_BLOCK_ID:
2980         F.MacroCursor = Stream;
2981         if (!PP.getExternalSource())
2982           PP.setExternalSource(this);
2983
2984         if (llvm::Error Err = Stream.SkipBlock()) {
2985           Error(std::move(Err));
2986           return Failure;
2987         }
2988         if (ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2989           Error("malformed block record in AST file");
2990           return Failure;
2991         }
2992         F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2993         break;
2994
2995       case PREPROCESSOR_DETAIL_BLOCK_ID:
2996         F.PreprocessorDetailCursor = Stream;
2997
2998         if (llvm::Error Err = Stream.SkipBlock()) {
2999           Error(std::move(Err));
3000           return Failure;
3001         }
3002         if (ReadBlockAbbrevs(F.PreprocessorDetailCursor,
3003                              PREPROCESSOR_DETAIL_BLOCK_ID)) {
3004           Error("malformed preprocessor detail record in AST file");
3005           return Failure;
3006         }
3007         F.PreprocessorDetailStartOffset
3008         = F.PreprocessorDetailCursor.GetCurrentBitNo();
3009
3010         if (!PP.getPreprocessingRecord())
3011           PP.createPreprocessingRecord();
3012         if (!PP.getPreprocessingRecord()->getExternalSource())
3013           PP.getPreprocessingRecord()->SetExternalSource(*this);
3014         break;
3015
3016       case SOURCE_MANAGER_BLOCK_ID:
3017         if (ReadSourceManagerBlock(F))
3018           return Failure;
3019         break;
3020
3021       case SUBMODULE_BLOCK_ID:
3022         if (ASTReadResult Result =
3023                 ReadSubmoduleBlock(F, ClientLoadCapabilities))
3024           return Result;
3025         break;
3026
3027       case COMMENTS_BLOCK_ID: {
3028         BitstreamCursor C = Stream;
3029
3030         if (llvm::Error Err = Stream.SkipBlock()) {
3031           Error(std::move(Err));
3032           return Failure;
3033         }
3034         if (ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
3035           Error("malformed comments block in AST file");
3036           return Failure;
3037         }
3038         CommentsCursors.push_back(std::make_pair(C, &F));
3039         break;
3040       }
3041
3042       default:
3043         if (llvm::Error Err = Stream.SkipBlock()) {
3044           Error(std::move(Err));
3045           return Failure;
3046         }
3047         break;
3048       }
3049       continue;
3050
3051     case llvm::BitstreamEntry::Record:
3052       // The interesting case.
3053       break;
3054     }
3055
3056     // Read and process a record.
3057     Record.clear();
3058     StringRef Blob;
3059     Expected<unsigned> MaybeRecordType =
3060         Stream.readRecord(Entry.ID, Record, &Blob);
3061     if (!MaybeRecordType) {
3062       Error(MaybeRecordType.takeError());
3063       return Failure;
3064     }
3065     ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
3066
3067     // If we're not loading an AST context, we don't care about most records.
3068     if (!ContextObj) {
3069       switch (RecordType) {
3070       case IDENTIFIER_TABLE:
3071       case IDENTIFIER_OFFSET:
3072       case INTERESTING_IDENTIFIERS:
3073       case STATISTICS:
3074       case PP_CONDITIONAL_STACK:
3075       case PP_COUNTER_VALUE:
3076       case SOURCE_LOCATION_OFFSETS:
3077       case MODULE_OFFSET_MAP:
3078       case SOURCE_MANAGER_LINE_TABLE:
3079       case SOURCE_LOCATION_PRELOADS:
3080       case PPD_ENTITIES_OFFSETS:
3081       case HEADER_SEARCH_TABLE:
3082       case IMPORTED_MODULES:
3083       case MACRO_OFFSET:
3084         break;
3085       default:
3086         continue;
3087       }
3088     }
3089
3090     switch (RecordType) {
3091     default:  // Default behavior: ignore.
3092       break;
3093
3094     case TYPE_OFFSET: {
3095       if (F.LocalNumTypes != 0) {
3096         Error("duplicate TYPE_OFFSET record in AST file");
3097         return Failure;
3098       }
3099       F.TypeOffsets = (const uint32_t *)Blob.data();
3100       F.LocalNumTypes = Record[0];
3101       unsigned LocalBaseTypeIndex = Record[1];
3102       F.BaseTypeIndex = getTotalNumTypes();
3103
3104       if (F.LocalNumTypes > 0) {
3105         // Introduce the global -> local mapping for types within this module.
3106         GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
3107
3108         // Introduce the local -> global mapping for types within this module.
3109         F.TypeRemap.insertOrReplace(
3110           std::make_pair(LocalBaseTypeIndex,
3111                          F.BaseTypeIndex - LocalBaseTypeIndex));
3112
3113         TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
3114       }
3115       break;
3116     }
3117
3118     case DECL_OFFSET: {
3119       if (F.LocalNumDecls != 0) {
3120         Error("duplicate DECL_OFFSET record in AST file");
3121         return Failure;
3122       }
3123       F.DeclOffsets = (const DeclOffset *)Blob.data();
3124       F.LocalNumDecls = Record[0];
3125       unsigned LocalBaseDeclID = Record[1];
3126       F.BaseDeclID = getTotalNumDecls();
3127
3128       if (F.LocalNumDecls > 0) {
3129         // Introduce the global -> local mapping for declarations within this
3130         // module.
3131         GlobalDeclMap.insert(
3132           std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
3133
3134         // Introduce the local -> global mapping for declarations within this
3135         // module.
3136         F.DeclRemap.insertOrReplace(
3137           std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
3138
3139         // Introduce the global -> local mapping for declarations within this
3140         // module.
3141         F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
3142
3143         DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
3144       }
3145       break;
3146     }
3147
3148     case TU_UPDATE_LEXICAL: {
3149       DeclContext *TU = ContextObj->getTranslationUnitDecl();
3150       LexicalContents Contents(
3151           reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
3152               Blob.data()),
3153           static_cast<unsigned int>(Blob.size() / 4));
3154       TULexicalDecls.push_back(std::make_pair(&F, Contents));
3155       TU->setHasExternalLexicalStorage(true);
3156       break;
3157     }
3158
3159     case UPDATE_VISIBLE: {
3160       unsigned Idx = 0;
3161       serialization::DeclID ID = ReadDeclID(F, Record, Idx);
3162       auto *Data = (const unsigned char*)Blob.data();
3163       PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
3164       // If we've already loaded the decl, perform the updates when we finish
3165       // loading this block.
3166       if (Decl *D = GetExistingDecl(ID))
3167         PendingUpdateRecords.push_back(
3168             PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3169       break;
3170     }
3171
3172     case IDENTIFIER_TABLE:
3173       F.IdentifierTableData = Blob.data();
3174       if (Record[0]) {
3175         F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
3176             (const unsigned char *)F.IdentifierTableData + Record[0],
3177             (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
3178             (const unsigned char *)F.IdentifierTableData,
3179             ASTIdentifierLookupTrait(*this, F));
3180
3181         PP.getIdentifierTable().setExternalIdentifierLookup(this);
3182       }
3183       break;
3184
3185     case IDENTIFIER_OFFSET: {
3186       if (F.LocalNumIdentifiers != 0) {
3187         Error("duplicate IDENTIFIER_OFFSET record in AST file");
3188         return Failure;
3189       }
3190       F.IdentifierOffsets = (const uint32_t *)Blob.data();
3191       F.LocalNumIdentifiers = Record[0];
3192       unsigned LocalBaseIdentifierID = Record[1];
3193       F.BaseIdentifierID = getTotalNumIdentifiers();
3194
3195       if (F.LocalNumIdentifiers > 0) {
3196         // Introduce the global -> local mapping for identifiers within this
3197         // module.
3198         GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
3199                                                   &F));
3200
3201         // Introduce the local -> global mapping for identifiers within this
3202         // module.
3203         F.IdentifierRemap.insertOrReplace(
3204           std::make_pair(LocalBaseIdentifierID,
3205                          F.BaseIdentifierID - LocalBaseIdentifierID));
3206
3207         IdentifiersLoaded.resize(IdentifiersLoaded.size()
3208                                  + F.LocalNumIdentifiers);
3209       }
3210       break;
3211     }
3212
3213     case INTERESTING_IDENTIFIERS:
3214       F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
3215       break;
3216
3217     case EAGERLY_DESERIALIZED_DECLS:
3218       // FIXME: Skip reading this record if our ASTConsumer doesn't care
3219       // about "interesting" decls (for instance, if we're building a module).
3220       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3221         EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
3222       break;
3223
3224     case MODULAR_CODEGEN_DECLS:
3225       // FIXME: Skip reading this record if our ASTConsumer doesn't care about
3226       // them (ie: if we're not codegenerating this module).
3227       if (F.Kind == MK_MainFile ||
3228           getContext().getLangOpts().BuildingPCHWithObjectFile)
3229         for (unsigned I = 0, N = Record.size(); I != N; ++I)
3230           EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
3231       break;
3232
3233     case SPECIAL_TYPES:
3234       if (SpecialTypes.empty()) {
3235         for (unsigned I = 0, N = Record.size(); I != N; ++I)
3236           SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
3237         break;
3238       }
3239
3240       if (SpecialTypes.size() != Record.size()) {
3241         Error("invalid special-types record");
3242         return Failure;
3243       }
3244
3245       for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3246         serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
3247         if (!SpecialTypes[I])
3248           SpecialTypes[I] = ID;
3249         // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
3250         // merge step?
3251       }
3252       break;
3253
3254     case STATISTICS:
3255       TotalNumStatements += Record[0];
3256       TotalNumMacros += Record[1];
3257       TotalLexicalDeclContexts += Record[2];
3258       TotalVisibleDeclContexts += Record[3];
3259       break;
3260
3261     case UNUSED_FILESCOPED_DECLS:
3262       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3263         UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
3264       break;
3265
3266     case DELEGATING_CTORS:
3267       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3268         DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
3269       break;
3270
3271     case WEAK_UNDECLARED_IDENTIFIERS:
3272       if (Record.size() % 4 != 0) {
3273         Error("invalid weak identifiers record");
3274         return Failure;
3275       }
3276
3277       // FIXME: Ignore weak undeclared identifiers from non-original PCH
3278       // files. This isn't the way to do it :)
3279       WeakUndeclaredIdentifiers.clear();
3280
3281       // Translate the weak, undeclared identifiers into global IDs.
3282       for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
3283         WeakUndeclaredIdentifiers.push_back(
3284           getGlobalIdentifierID(F, Record[I++]));
3285         WeakUndeclaredIdentifiers.push_back(
3286           getGlobalIdentifierID(F, Record[I++]));
3287         WeakUndeclaredIdentifiers.push_back(
3288           ReadSourceLocation(F, Record, I).getRawEncoding());
3289         WeakUndeclaredIdentifiers.push_back(Record[I++]);
3290       }
3291       break;
3292
3293     case SELECTOR_OFFSETS: {
3294       F.SelectorOffsets = (const uint32_t *)Blob.data();
3295       F.LocalNumSelectors = Record[0];
3296       unsigned LocalBaseSelectorID = Record[1];
3297       F.BaseSelectorID = getTotalNumSelectors();
3298
3299       if (F.LocalNumSelectors > 0) {
3300         // Introduce the global -> local mapping for selectors within this
3301         // module.
3302         GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
3303
3304         // Introduce the local -> global mapping for selectors within this
3305         // module.
3306         F.SelectorRemap.insertOrReplace(
3307           std::make_pair(LocalBaseSelectorID,
3308                          F.BaseSelectorID - LocalBaseSelectorID));
3309
3310         SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
3311       }
3312       break;
3313     }
3314
3315     case METHOD_POOL:
3316       F.SelectorLookupTableData = (const unsigned char *)Blob.data();
3317       if (Record[0])
3318         F.SelectorLookupTable
3319           = ASTSelectorLookupTable::Create(
3320                         F.SelectorLookupTableData + Record[0],
3321                         F.SelectorLookupTableData,
3322                         ASTSelectorLookupTrait(*this, F));
3323       TotalNumMethodPoolEntries += Record[1];
3324       break;
3325
3326     case REFERENCED_SELECTOR_POOL:
3327       if (!Record.empty()) {
3328         for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
3329           ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
3330                                                                 Record[Idx++]));
3331           ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
3332                                               getRawEncoding());
3333         }
3334       }
3335       break;
3336
3337     case PP_CONDITIONAL_STACK:
3338       if (!Record.empty()) {
3339         unsigned Idx = 0, End = Record.size() - 1;
3340         bool ReachedEOFWhileSkipping = Record[Idx++];
3341         llvm::Optional<Preprocessor::PreambleSkipInfo> SkipInfo;
3342         if (ReachedEOFWhileSkipping) {
3343           SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
3344           SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
3345           bool FoundNonSkipPortion = Record[Idx++];
3346           bool FoundElse = Record[Idx++];
3347           SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
3348           SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
3349                            FoundElse, ElseLoc);
3350         }
3351         SmallVector<PPConditionalInfo, 4> ConditionalStack;
3352         while (Idx < End) {
3353           auto Loc = ReadSourceLocation(F, Record, Idx);
3354           bool WasSkipping = Record[Idx++];
3355           bool FoundNonSkip = Record[Idx++];
3356           bool FoundElse = Record[Idx++];
3357           ConditionalStack.push_back(
3358               {Loc, WasSkipping, FoundNonSkip, FoundElse});
3359         }
3360         PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
3361       }
3362       break;
3363
3364     case PP_COUNTER_VALUE:
3365       if (!Record.empty() && Listener)
3366         Listener->ReadCounter(F, Record[0]);
3367       break;
3368
3369     case FILE_SORTED_DECLS:
3370       F.FileSortedDecls = (const DeclID *)Blob.data();
3371       F.NumFileSortedDecls = Record[0];
3372       break;
3373
3374     case SOURCE_LOCATION_OFFSETS: {
3375       F.SLocEntryOffsets = (const uint32_t *)Blob.data();
3376       F.LocalNumSLocEntries = Record[0];
3377       unsigned SLocSpaceSize = Record[1];
3378       std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
3379           SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
3380                                               SLocSpaceSize);
3381       if (!F.SLocEntryBaseID) {
3382         Error("ran out of source locations");
3383         break;
3384       }
3385       // Make our entry in the range map. BaseID is negative and growing, so
3386       // we invert it. Because we invert it, though, we need the other end of
3387       // the range.
3388       unsigned RangeStart =
3389           unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
3390       GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
3391       F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
3392
3393       // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3394       assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
3395       GlobalSLocOffsetMap.insert(
3396           std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
3397                            - SLocSpaceSize,&F));
3398
3399       // Initialize the remapping table.
3400       // Invalid stays invalid.
3401       F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
3402       // This module. Base was 2 when being compiled.
3403       F.SLocRemap.insertOrReplace(std::make_pair(2U,
3404                                   static_cast<int>(F.SLocEntryBaseOffset - 2)));
3405
3406       TotalNumSLocEntries += F.LocalNumSLocEntries;
3407       break;
3408     }
3409
3410     case MODULE_OFFSET_MAP:
3411       F.ModuleOffsetMap = Blob;
3412       break;
3413
3414     case SOURCE_MANAGER_LINE_TABLE:
3415       if (ParseLineTable(F, Record)) {
3416         Error("malformed SOURCE_MANAGER_LINE_TABLE in AST file");
3417         return Failure;
3418       }
3419       break;
3420
3421     case SOURCE_LOCATION_PRELOADS: {
3422       // Need to transform from the local view (1-based IDs) to the global view,
3423       // which is based off F.SLocEntryBaseID.
3424       if (!F.PreloadSLocEntries.empty()) {
3425         Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
3426         return Failure;
3427       }
3428
3429       F.PreloadSLocEntries.swap(Record);
3430       break;
3431     }
3432
3433     case EXT_VECTOR_DECLS:
3434       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3435         ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3436       break;
3437
3438     case VTABLE_USES:
3439       if (Record.size() % 3 != 0) {
3440         Error("Invalid VTABLE_USES record");
3441         return Failure;
3442       }
3443
3444       // Later tables overwrite earlier ones.
3445       // FIXME: Modules will have some trouble with this. This is clearly not
3446       // the right way to do this.
3447       VTableUses.clear();
3448
3449       for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3450         VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3451         VTableUses.push_back(
3452           ReadSourceLocation(F, Record, Idx).getRawEncoding());
3453         VTableUses.push_back(Record[Idx++]);
3454       }
3455       break;
3456
3457     case PENDING_IMPLICIT_INSTANTIATIONS:
3458       if (PendingInstantiations.size() % 2 != 0) {
3459         Error("Invalid existing PendingInstantiations");
3460         return Failure;
3461       }
3462
3463       if (Record.size() % 2 != 0) {
3464         Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
3465         return Failure;
3466       }
3467
3468       for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3469         PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3470         PendingInstantiations.push_back(
3471           ReadSourceLocation(F, Record, I).getRawEncoding());
3472       }
3473       break;
3474
3475     case SEMA_DECL_REFS:
3476       if (Record.size() != 3) {
3477         Error("Invalid SEMA_DECL_REFS block");
3478         return Failure;
3479       }
3480       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3481         SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3482       break;
3483
3484     case PPD_ENTITIES_OFFSETS: {
3485       F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3486       assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3487       F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
3488
3489       unsigned LocalBasePreprocessedEntityID = Record[0];
3490
3491       unsigned StartingID;
3492       if (!PP.getPreprocessingRecord())
3493         PP.createPreprocessingRecord();
3494       if (!PP.getPreprocessingRecord()->getExternalSource())
3495         PP.getPreprocessingRecord()->SetExternalSource(*this);
3496       StartingID
3497         = PP.getPreprocessingRecord()
3498             ->allocateLoadedEntities(F.NumPreprocessedEntities);
3499       F.BasePreprocessedEntityID = StartingID;
3500
3501       if (F.NumPreprocessedEntities > 0) {
3502         // Introduce the global -> local mapping for preprocessed entities in
3503         // this module.
3504         GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3505
3506         // Introduce the local -> global mapping for preprocessed entities in
3507         // this module.
3508         F.PreprocessedEntityRemap.insertOrReplace(
3509           std::make_pair(LocalBasePreprocessedEntityID,
3510             F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3511       }
3512
3513       break;
3514     }
3515
3516     case PPD_SKIPPED_RANGES: {
3517       F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
3518       assert(Blob.size() % sizeof(PPSkippedRange) == 0);
3519       F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
3520
3521       if (!PP.getPreprocessingRecord())
3522         PP.createPreprocessingRecord();
3523       if (!PP.getPreprocessingRecord()->getExternalSource())
3524         PP.getPreprocessingRecord()->SetExternalSource(*this);
3525       F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
3526           ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
3527
3528       if (F.NumPreprocessedSkippedRanges > 0)
3529         GlobalSkippedRangeMap.insert(
3530             std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
3531       break;
3532     }
3533
3534     case DECL_UPDATE_OFFSETS:
3535       if (Record.size() % 2 != 0) {
3536         Error("invalid DECL_UPDATE_OFFSETS block in AST file");
3537         return Failure;
3538       }
3539       for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3540         GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3541         DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3542
3543         // If we've already loaded the decl, perform the updates when we finish
3544         // loading this block.
3545         if (Decl *D = GetExistingDecl(ID))
3546           PendingUpdateRecords.push_back(
3547               PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3548       }
3549       break;
3550
3551     case OBJC_CATEGORIES_MAP:
3552       if (F.LocalNumObjCCategoriesInMap != 0) {
3553         Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
3554         return Failure;
3555       }
3556
3557       F.LocalNumObjCCategoriesInMap = Record[0];
3558       F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
3559       break;
3560
3561     case OBJC_CATEGORIES:
3562       F.ObjCCategories.swap(Record);
3563       break;
3564
3565     case CUDA_SPECIAL_DECL_REFS:
3566       // Later tables overwrite earlier ones.
3567       // FIXME: Modules will have trouble with this.
3568       CUDASpecialDeclRefs.clear();
3569       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3570         CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3571       break;
3572
3573     case HEADER_SEARCH_TABLE:
3574       F.HeaderFileInfoTableData = Blob.data();
3575       F.LocalNumHeaderFileInfos = Record[1];
3576       if (Record[0]) {
3577         F.HeaderFileInfoTable
3578           = HeaderFileInfoLookupTable::Create(
3579                    (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3580                    (const unsigned char *)F.HeaderFileInfoTableData,
3581                    HeaderFileInfoTrait(*this, F,
3582                                        &PP.getHeaderSearchInfo(),
3583                                        Blob.data() + Record[2]));
3584
3585         PP.getHeaderSearchInfo().SetExternalSource(this);
3586         if (!PP.getHeaderSearchInfo().getExternalLookup())
3587           PP.getHeaderSearchInfo().SetExternalLookup(this);
3588       }
3589       break;
3590
3591     case FP_PRAGMA_OPTIONS:
3592       // Later tables overwrite earlier ones.
3593       FPPragmaOptions.swap(Record);
3594       break;
3595
3596     case OPENCL_EXTENSIONS:
3597       for (unsigned I = 0, E = Record.size(); I != E; ) {
3598         auto Name = ReadString(Record, I);
3599         auto &Opt = OpenCLExtensions.OptMap[Name];
3600         Opt.Supported = Record[I++] != 0;
3601         Opt.Enabled = Record[I++] != 0;
3602         Opt.Avail = Record[I++];
3603         Opt.Core = Record[I++];
3604       }
3605       break;
3606
3607     case OPENCL_EXTENSION_TYPES:
3608       for (unsigned I = 0, E = Record.size(); I != E;) {
3609         auto TypeID = static_cast<::TypeID>(Record[I++]);
3610         auto *Type = GetType(TypeID).getTypePtr();
3611         auto NumExt = static_cast<unsigned>(Record[I++]);
3612         for (unsigned II = 0; II != NumExt; ++II) {
3613           auto Ext = ReadString(Record, I);
3614           OpenCLTypeExtMap[Type].insert(Ext);
3615         }
3616       }
3617       break;
3618
3619     case OPENCL_EXTENSION_DECLS:
3620       for (unsigned I = 0, E = Record.size(); I != E;) {
3621         auto DeclID = static_cast<::DeclID>(Record[I++]);
3622         auto *Decl = GetDecl(DeclID);
3623         auto NumExt = static_cast<unsigned>(Record[I++]);
3624         for (unsigned II = 0; II != NumExt; ++II) {
3625           auto Ext = ReadString(Record, I);
3626           OpenCLDeclExtMap[Decl].insert(Ext);
3627         }
3628       }
3629       break;
3630
3631     case TENTATIVE_DEFINITIONS:
3632       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3633         TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3634       break;
3635
3636     case KNOWN_NAMESPACES:
3637       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3638         KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3639       break;
3640
3641     case UNDEFINED_BUT_USED:
3642       if (UndefinedButUsed.size() % 2 != 0) {
3643         Error("Invalid existing UndefinedButUsed");
3644         return Failure;
3645       }
3646
3647       if (Record.size() % 2 != 0) {
3648         Error("invalid undefined-but-used record");
3649         return Failure;
3650       }
3651       for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3652         UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3653         UndefinedButUsed.push_back(
3654             ReadSourceLocation(F, Record, I).getRawEncoding());
3655       }
3656       break;
3657
3658     case DELETE_EXPRS_TO_ANALYZE:
3659       for (unsigned I = 0, N = Record.size(); I != N;) {
3660         DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3661         const uint64_t Count = Record[I++];
3662         DelayedDeleteExprs.push_back(Count);
3663         for (uint64_t C = 0; C < Count; ++C) {
3664           DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3665           bool IsArrayForm = Record[I++] == 1;
3666           DelayedDeleteExprs.push_back(IsArrayForm);
3667         }
3668       }
3669       break;
3670
3671     case IMPORTED_MODULES:
3672       if (!F.isModule()) {
3673         // If we aren't loading a module (which has its own exports), make
3674         // all of the imported modules visible.
3675         // FIXME: Deal with macros-only imports.
3676         for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3677           unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3678           SourceLocation Loc = ReadSourceLocation(F, Record, I);
3679           if (GlobalID) {
3680             ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
3681             if (DeserializationListener)
3682               DeserializationListener->ModuleImportRead(GlobalID, Loc);
3683           }
3684         }
3685       }
3686       break;
3687
3688     case MACRO_OFFSET: {
3689       if (F.LocalNumMacros != 0) {
3690         Error("duplicate MACRO_OFFSET record in AST file");
3691         return Failure;
3692       }
3693       F.MacroOffsets = (const uint32_t *)Blob.data();
3694       F.LocalNumMacros = Record[0];
3695       unsigned LocalBaseMacroID = Record[1];
3696       F.BaseMacroID = getTotalNumMacros();
3697
3698       if (F.LocalNumMacros > 0) {
3699         // Introduce the global -> local mapping for macros within this module.
3700         GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3701
3702         // Introduce the local -> global mapping for macros within this module.
3703         F.MacroRemap.insertOrReplace(
3704           std::make_pair(LocalBaseMacroID,
3705                          F.BaseMacroID - LocalBaseMacroID));
3706
3707         MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3708       }
3709       break;
3710     }
3711
3712     case LATE_PARSED_TEMPLATE:
3713       LateParsedTemplates.append(Record.begin(), Record.end());
3714       break;
3715
3716     case OPTIMIZE_PRAGMA_OPTIONS:
3717       if (Record.size() != 1) {
3718         Error("invalid pragma optimize record");
3719         return Failure;
3720       }
3721       OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3722       break;
3723
3724     case MSSTRUCT_PRAGMA_OPTIONS:
3725       if (Record.size() != 1) {
3726         Error("invalid pragma ms_struct record");
3727         return Failure;
3728       }
3729       PragmaMSStructState = Record[0];
3730       break;
3731
3732     case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3733       if (Record.size() != 2) {
3734         Error("invalid pragma ms_struct record");
3735         return Failure;
3736       }
3737       PragmaMSPointersToMembersState = Record[0];
3738       PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3739       break;
3740
3741     case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3742       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3743         UnusedLocalTypedefNameCandidates.push_back(
3744             getGlobalDeclID(F, Record[I]));
3745       break;
3746
3747     case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3748       if (Record.size() != 1) {
3749         Error("invalid cuda pragma options record");
3750         return Failure;
3751       }
3752       ForceCUDAHostDeviceDepth = Record[0];
3753       break;
3754
3755     case PACK_PRAGMA_OPTIONS: {
3756       if (Record.size() < 3) {
3757         Error("invalid pragma pack record");
3758         return Failure;
3759       }
3760       PragmaPackCurrentValue = Record[0];
3761       PragmaPackCurrentLocation = ReadSourceLocation(F, Record[1]);
3762       unsigned NumStackEntries = Record[2];
3763       unsigned Idx = 3;
3764       // Reset the stack when importing a new module.
3765       PragmaPackStack.clear();
3766       for (unsigned I = 0; I < NumStackEntries; ++I) {
3767         PragmaPackStackEntry Entry;
3768         Entry.Value = Record[Idx++];
3769         Entry.Location = ReadSourceLocation(F, Record[Idx++]);
3770         Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
3771         PragmaPackStrings.push_back(ReadString(Record, Idx));
3772         Entry.SlotLabel = PragmaPackStrings.back();
3773         PragmaPackStack.push_back(Entry);
3774       }
3775       break;
3776     }
3777     }
3778   }
3779 }
3780
3781 void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3782   assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3783
3784   // Additional remapping information.
3785   const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
3786   const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3787   F.ModuleOffsetMap = StringRef();
3788
3789   // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3790   if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3791     F.SLocRemap.insert(std::make_pair(0U, 0));
3792     F.SLocRemap.insert(std::make_pair(2U, 1));
3793   }
3794
3795   // Continuous range maps we may be updating in our module.
3796   using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder;
3797   RemapBuilder SLocRemap(F.SLocRemap);
3798   RemapBuilder IdentifierRemap(F.IdentifierRemap);
3799   RemapBuilder MacroRemap(F.MacroRemap);
3800   RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3801   RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3802   RemapBuilder SelectorRemap(F.SelectorRemap);
3803   RemapBuilder DeclRemap(F.DeclRemap);
3804   RemapBuilder TypeRemap(F.TypeRemap);
3805
3806   while (Data < DataEnd) {
3807     // FIXME: Looking up dependency modules by filename is horrible. Let's
3808     // start fixing this with prebuilt and explicit modules and see how it
3809     // goes...
3810     using namespace llvm::support;
3811     ModuleKind Kind = static_cast<ModuleKind>(
3812       endian::readNext<uint8_t, little, unaligned>(Data));
3813     uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3814     StringRef Name = StringRef((const char*)Data, Len);
3815     Data += Len;
3816     ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule
3817                       ? ModuleMgr.lookupByModuleName(Name)
3818                       : ModuleMgr.lookupByFileName(Name));
3819     if (!OM) {
3820       std::string Msg =
3821           "SourceLocation remap refers to unknown module, cannot find ";
3822       Msg.append(Name);
3823       Error(Msg);
3824       return;
3825     }
3826
3827     uint32_t SLocOffset =
3828         endian::readNext<uint32_t, little, unaligned>(Data);
3829     uint32_t IdentifierIDOffset =
3830         endian::readNext<uint32_t, little, unaligned>(Data);
3831     uint32_t MacroIDOffset =
3832         endian::readNext<uint32_t, little, unaligned>(Data);
3833     uint32_t PreprocessedEntityIDOffset =
3834         endian::readNext<uint32_t, little, unaligned>(Data);
3835     uint32_t SubmoduleIDOffset =
3836         endian::readNext<uint32_t, little, unaligned>(Data);
3837     uint32_t SelectorIDOffset =
3838         endian::readNext<uint32_t, little, unaligned>(Data);
3839     uint32_t DeclIDOffset =
3840         endian::readNext<uint32_t, little, unaligned>(Data);
3841     uint32_t TypeIndexOffset =
3842         endian::readNext<uint32_t, little, unaligned>(Data);
3843
3844     uint32_t None = std::numeric_limits<uint32_t>::max();
3845
3846     auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3847                          RemapBuilder &Remap) {
3848       if (Offset != None)
3849         Remap.insert(std::make_pair(Offset,
3850                                     static_cast<int>(BaseOffset - Offset)));
3851     };
3852     mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3853     mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3854     mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3855     mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3856               PreprocessedEntityRemap);
3857     mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3858     mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3859     mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3860     mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3861
3862     // Global -> local mappings.
3863     F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3864   }
3865 }
3866
3867 ASTReader::ASTReadResult
3868 ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3869                                   const ModuleFile *ImportedBy,
3870                                   unsigned ClientLoadCapabilities) {
3871   unsigned Idx = 0;
3872   F.ModuleMapPath = ReadPath(F, Record, Idx);
3873
3874   // Try to resolve ModuleName in the current header search context and
3875   // verify that it is found in the same module map file as we saved. If the
3876   // top-level AST file is a main file, skip this check because there is no
3877   // usable header search context.
3878   assert(!F.ModuleName.empty() &&
3879          "MODULE_NAME should come before MODULE_MAP_FILE");
3880   if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
3881     // An implicitly-loaded module file should have its module listed in some
3882     // module map file that we've already loaded.
3883     Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
3884     auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3885     const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3886     // Don't emit module relocation error if we have -fno-validate-pch
3887     if (!PP.getPreprocessorOpts().DisablePCHValidation && !ModMap) {
3888       if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3889         if (auto *ASTFE = M ? M->getASTFile() : nullptr) {
3890           // This module was defined by an imported (explicit) module.
3891           Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3892                                                << ASTFE->getName();
3893         } else {
3894           // This module was built with a different module map.
3895           Diag(diag::err_imported_module_not_found)
3896               << F.ModuleName << F.FileName
3897               << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath
3898               << !ImportedBy;
3899           // In case it was imported by a PCH, there's a chance the user is
3900           // just missing to include the search path to the directory containing
3901           // the modulemap.
3902           if (ImportedBy && ImportedBy->Kind == MK_PCH)
3903             Diag(diag::note_imported_by_pch_module_not_found)
3904                 << llvm::sys::path::parent_path(F.ModuleMapPath);
3905         }
3906       }
3907       return OutOfDate;
3908     }
3909
3910     assert(M->Name == F.ModuleName && "found module with different name");
3911
3912     // Check the primary module map file.
3913     auto StoredModMap = FileMgr.getFile(F.ModuleMapPath);
3914     if (!StoredModMap || *StoredModMap != ModMap) {
3915       assert(ModMap && "found module is missing module map file");
3916       assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
3917              "top-level import should be verified");
3918       bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
3919       if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3920         Diag(diag::err_imported_module_modmap_changed)
3921             << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
3922             << ModMap->getName() << F.ModuleMapPath << NotImported;
3923       return OutOfDate;
3924     }
3925
3926     llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3927     for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3928       // FIXME: we should use input files rather than storing names.
3929       std::string Filename = ReadPath(F, Record, Idx);
3930       auto F = FileMgr.getFile(Filename, false, false);
3931       if (!F) {
3932         if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3933           Error("could not find file '" + Filename +"' referenced by AST file");
3934         return OutOfDate;
3935       }
3936       AdditionalStoredMaps.insert(*F);
3937     }
3938
3939     // Check any additional module map files (e.g. module.private.modulemap)
3940     // that are not in the pcm.
3941     if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3942       for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3943         // Remove files that match
3944         // Note: SmallPtrSet::erase is really remove
3945         if (!AdditionalStoredMaps.erase(ModMap)) {
3946           if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3947             Diag(diag::err_module_different_modmap)
3948               << F.ModuleName << /*new*/0 << ModMap->getName();
3949           return OutOfDate;
3950         }
3951       }
3952     }
3953
3954     // Check any additional module map files that are in the pcm, but not
3955     // found in header search. Cases that match are already removed.
3956     for (const FileEntry *ModMap : AdditionalStoredMaps) {
3957       if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3958         Diag(diag::err_module_different_modmap)
3959           << F.ModuleName << /*not new*/1 << ModMap->getName();
3960       return OutOfDate;
3961     }
3962   }
3963
3964   if (Listener)
3965     Listener->ReadModuleMapFile(F.ModuleMapPath);
3966   return Success;
3967 }
3968
3969 /// Move the given method to the back of the global list of methods.
3970 static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3971   // Find the entry for this selector in the method pool.
3972   Sema::GlobalMethodPool::iterator Known
3973     = S.MethodPool.find(Method->getSelector());
3974   if (Known == S.MethodPool.end())
3975     return;
3976
3977   // Retrieve the appropriate method list.
3978   ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3979                                                     : Known->second.second;
3980   bool Found = false;
3981   for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
3982     if (!Found) {
3983       if (List->getMethod() == Method) {
3984         Found = true;
3985       } else {
3986         // Keep searching.
3987         continue;
3988       }
3989     }
3990
3991     if (List->getNext())
3992       List->setMethod(List->getNext()->getMethod());
3993     else
3994       List->setMethod(Method);
3995   }
3996 }
3997
3998 void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
3999   assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
4000   for (Decl *D : Names) {
4001     bool wasHidden = D->isHidden();
4002     D->setVisibleDespiteOwningModule();
4003
4004     if (wasHidden && SemaObj) {
4005       if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
4006         moveMethodToBackOfGlobalList(*SemaObj, Method);
4007       }
4008     }
4009   }
4010 }
4011
4012 void ASTReader::makeModuleVisible(Module *Mod,
4013                                   Module::NameVisibilityKind NameVisibility,
4014                                   SourceLocation ImportLoc) {
4015   llvm::SmallPtrSet<Module *, 4> Visited;
4016   SmallVector<Module *, 4> Stack;
4017   Stack.push_back(Mod);
4018   while (!Stack.empty()) {
4019     Mod = Stack.pop_back_val();
4020
4021     if (NameVisibility <= Mod->NameVisibility) {
4022       // This module already has this level of visibility (or greater), so
4023       // there is nothing more to do.
4024       continue;
4025     }
4026
4027     if (!Mod->isAvailable()) {
4028       // Modules that aren't available cannot be made visible.
4029       continue;
4030     }
4031
4032     // Update the module's name visibility.
4033     Mod->NameVisibility = NameVisibility;
4034
4035     // If we've already deserialized any names from this module,
4036     // mark them as visible.
4037     HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
4038     if (Hidden != HiddenNamesMap.end()) {
4039       auto HiddenNames = std::move(*Hidden);
4040       HiddenNamesMap.erase(Hidden);
4041       makeNamesVisible(HiddenNames.second, HiddenNames.first);
4042       assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
4043              "making names visible added hidden names");
4044     }
4045
4046     // Push any exported modules onto the stack to be marked as visible.
4047     SmallVector<Module *, 16> Exports;
4048     Mod->getExportedModules(Exports);
4049     for (SmallVectorImpl<Module *>::iterator
4050            I = Exports.begin(), E = Exports.end(); I != E; ++I) {
4051       Module *Exported = *I;
4052       if (Visited.insert(Exported).second)
4053         Stack.push_back(Exported);
4054     }
4055   }
4056 }
4057
4058 /// We've merged the definition \p MergedDef into the existing definition
4059 /// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
4060 /// visible.
4061 void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
4062                                           NamedDecl *MergedDef) {
4063   if (Def->isHidden()) {
4064     // If MergedDef is visible or becomes visible, make the definition visible.
4065     if (!MergedDef->isHidden())
4066       Def->setVisibleDespiteOwningModule();
4067     else {
4068       getContext().mergeDefinitionIntoModule(
4069           Def, MergedDef->getImportedOwningModule(),
4070           /*NotifyListeners*/ false);
4071       PendingMergedDefinitionsToDeduplicate.insert(Def);
4072     }
4073   }
4074 }
4075
4076 bool ASTReader::loadGlobalIndex() {
4077   if (GlobalIndex)
4078     return false;
4079
4080   if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
4081       !PP.getLangOpts().Modules)
4082     return true;
4083
4084   // Try to load the global index.
4085   TriedLoadingGlobalIndex = true;
4086   StringRef ModuleCachePath
4087     = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
4088   std::pair<GlobalModuleIndex *, llvm::Error> Result =
4089       GlobalModuleIndex::readIndex(ModuleCachePath);
4090   if (llvm::Error Err = std::move(Result.second)) {
4091     assert(!Result.first);
4092     consumeError(std::move(Err)); // FIXME this drops errors on the floor.
4093     return true;
4094   }
4095
4096   GlobalIndex.reset(Result.first);
4097   ModuleMgr.setGlobalIndex(GlobalIndex.get());
4098   return false;
4099 }
4100
4101 bool ASTReader::isGlobalIndexUnavailable() const {
4102   return PP.getLangOpts().Modules && UseGlobalIndex &&
4103          !hasGlobalIndex() && TriedLoadingGlobalIndex;
4104 }
4105
4106 static void updateModuleTimestamp(ModuleFile &MF) {
4107   // Overwrite the timestamp file contents so that file's mtime changes.
4108   std::string TimestampFilename = MF.getTimestampFilename();
4109   std::error_code EC;
4110   llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::OF_Text);
4111   if (EC)
4112     return;
4113   OS << "Timestamp file\n";
4114   OS.close();
4115   OS.clear_error(); // Avoid triggering a fatal error.
4116 }
4117
4118 /// Given a cursor at the start of an AST file, scan ahead and drop the
4119 /// cursor into the start of the given block ID, returning false on success and
4120 /// true on failure.
4121 static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
4122   while (true) {
4123     Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
4124     if (!MaybeEntry) {
4125       // FIXME this drops errors on the floor.
4126       consumeError(MaybeEntry.takeError());
4127       return true;
4128     }
4129     llvm::BitstreamEntry Entry = MaybeEntry.get();
4130
4131     switch (Entry.Kind) {
4132     case llvm::BitstreamEntry::Error:
4133     case llvm::BitstreamEntry::EndBlock:
4134       return true;
4135
4136     case llvm::BitstreamEntry::Record:
4137       // Ignore top-level records.
4138       if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
4139         break;
4140       else {
4141         // FIXME this drops errors on the floor.
4142         consumeError(Skipped.takeError());
4143         return true;
4144       }
4145
4146     case llvm::BitstreamEntry::SubBlock:
4147       if (Entry.ID == BlockID) {
4148         if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
4149           // FIXME this drops the error on the floor.
4150           consumeError(std::move(Err));
4151           return true;
4152         }
4153         // Found it!
4154         return false;
4155       }
4156
4157       if (llvm::Error Err = Cursor.SkipBlock()) {
4158         // FIXME this drops the error on the floor.
4159         consumeError(std::move(Err));
4160         return true;
4161       }
4162     }
4163   }
4164 }
4165
4166 ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
4167                                             ModuleKind Type,
4168                                             SourceLocation ImportLoc,
4169                                             unsigned ClientLoadCapabilities,
4170                                             SmallVectorImpl<ImportedSubmodule> *Imported) {
4171   llvm::SaveAndRestore<SourceLocation>
4172     SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
4173
4174   // Defer any pending actions until we get to the end of reading the AST file.
4175   Deserializing AnASTFile(this);
4176
4177   // Bump the generation number.
4178   unsigned PreviousGeneration = 0;
4179   if (ContextObj)
4180     PreviousGeneration = incrementGeneration(*ContextObj);
4181
4182   unsigned NumModules = ModuleMgr.size();
4183   auto removeModulesAndReturn = [&](ASTReadResult ReadResult) {
4184     assert(ReadResult && "expected to return error");
4185     ModuleMgr.removeModules(ModuleMgr.begin() + NumModules,
4186                             PP.getLangOpts().Modules
4187                                 ? &PP.getHeaderSearchInfo().getModuleMap()
4188                                 : nullptr);
4189
4190     // If we find that any modules are unusable, the global index is going
4191     // to be out-of-date. Just remove it.
4192     GlobalIndex.reset();
4193     ModuleMgr.setGlobalIndex(nullptr);
4194     return ReadResult;
4195   };
4196
4197   SmallVector<ImportedModule, 4> Loaded;
4198   switch (ASTReadResult ReadResult =
4199               ReadASTCore(FileName, Type, ImportLoc,
4200                           /*ImportedBy=*/nullptr, Loaded, 0, 0,
4201                           ASTFileSignature(), ClientLoadCapabilities)) {
4202   case Failure:
4203   case Missing:
4204   case OutOfDate:
4205   case VersionMismatch:
4206   case ConfigurationMismatch:
4207   case HadErrors:
4208     return removeModulesAndReturn(ReadResult);
4209   case Success:
4210     break;
4211   }
4212
4213   // Here comes stuff that we only do once the entire chain is loaded.
4214
4215   // Load the AST blocks of all of the modules that we loaded.  We can still
4216   // hit errors parsing the ASTs at this point.
4217   for (ImportedModule &M : Loaded) {
4218     ModuleFile &F = *M.Mod;
4219
4220     // Read the AST block.
4221     if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
4222       return removeModulesAndReturn(Result);
4223
4224     // The AST block should always have a definition for the main module.
4225     if (F.isModule() && !F.DidReadTopLevelSubmodule) {
4226       Error(diag::err_module_file_missing_top_level_submodule, F.FileName);
4227       return removeModulesAndReturn(Failure);
4228     }
4229
4230     // Read the extension blocks.
4231     while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
4232       if (ASTReadResult Result = ReadExtensionBlock(F))
4233         return removeModulesAndReturn(Result);
4234     }
4235
4236     // Once read, set the ModuleFile bit base offset and update the size in
4237     // bits of all files we've seen.
4238     F.GlobalBitOffset = TotalModulesSizeInBits;
4239     TotalModulesSizeInBits += F.SizeInBits;
4240     GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
4241   }
4242
4243   // Preload source locations and interesting indentifiers.
4244   for (ImportedModule &M : Loaded) {
4245     ModuleFile &F = *M.Mod;
4246
4247     // Preload SLocEntries.
4248     for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
4249       int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
4250       // Load it through the SourceManager and don't call ReadSLocEntry()
4251       // directly because the entry may have already been loaded in which case
4252       // calling ReadSLocEntry() directly would trigger an assertion in
4253       // SourceManager.
4254       SourceMgr.getLoadedSLocEntryByID(Index);
4255     }
4256
4257     // Map the original source file ID into the ID space of the current
4258     // compilation.
4259     if (F.OriginalSourceFileID.isValid()) {
4260       F.OriginalSourceFileID = FileID::get(
4261           F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1);
4262     }
4263
4264     // Preload all the pending interesting identifiers by marking them out of
4265     // date.
4266     for (auto Offset : F.PreloadIdentifierOffsets) {
4267       const unsigned char *Data = reinterpret_cast<const unsigned char *>(
4268           F.IdentifierTableData + Offset);
4269
4270       ASTIdentifierLookupTrait Trait(*this, F);
4271       auto KeyDataLen = Trait.ReadKeyDataLength(Data);
4272       auto Key = Trait.ReadKey(Data, KeyDataLen.first);
4273       auto &II = PP.getIdentifierTable().getOwn(Key);
4274       II.setOutOfDate(true);
4275
4276       // Mark this identifier as being from an AST file so that we can track
4277       // whether we need to serialize it.
4278       markIdentifierFromAST(*this, II);
4279
4280       // Associate the ID with the identifier so that the writer can reuse it.
4281       auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
4282       SetIdentifierInfo(ID, &II);
4283     }
4284   }
4285
4286   // Setup the import locations and notify the module manager that we've
4287   // committed to these module files.
4288   for (ImportedModule &M : Loaded) {
4289     ModuleFile &F = *M.Mod;
4290
4291     ModuleMgr.moduleFileAccepted(&F);
4292
4293     // Set the import location.
4294     F.DirectImportLoc = ImportLoc;
4295     // FIXME: We assume that locations from PCH / preamble do not need
4296     // any translation.
4297     if (!M.ImportedBy)
4298       F.ImportLoc = M.ImportLoc;
4299     else
4300       F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
4301   }
4302
4303   if (!PP.getLangOpts().CPlusPlus ||
4304       (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
4305        Type != MK_PrebuiltModule)) {
4306     // Mark all of the identifiers in the identifier table as being out of date,
4307     // so that various accessors know to check the loaded modules when the
4308     // identifier is used.
4309     //
4310     // For C++ modules, we don't need information on many identifiers (just
4311     // those that provide macros or are poisoned), so we mark all of
4312     // the interesting ones via PreloadIdentifierOffsets.
4313     for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
4314                                 IdEnd = PP.getIdentifierTable().end();
4315          Id != IdEnd; ++Id)
4316       Id->second->setOutOfDate(true);
4317   }
4318   // Mark selectors as out of date.
4319   for (auto Sel : SelectorGeneration)
4320     SelectorOutOfDate[Sel.first] = true;
4321
4322   // Resolve any unresolved module exports.
4323   for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4324     UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
4325     SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
4326     Module *ResolvedMod = getSubmodule(GlobalID);
4327
4328     switch (Unresolved.Kind) {
4329     case UnresolvedModuleRef::Conflict:
4330       if (ResolvedMod) {
4331         Module::Conflict Conflict;
4332         Conflict.Other = ResolvedMod;
4333         Conflict.Message = Unresolved.String.str();
4334         Unresolved.Mod->Conflicts.push_back(Conflict);
4335       }
4336       continue;
4337
4338     case UnresolvedModuleRef::Import:
4339       if (ResolvedMod)
4340         Unresolved.Mod->Imports.insert(ResolvedMod);
4341       continue;
4342
4343     case UnresolvedModuleRef::Export:
4344       if (ResolvedMod || Unresolved.IsWildcard)
4345         Unresolved.Mod->Exports.push_back(
4346           Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
4347       continue;
4348     }
4349   }
4350   UnresolvedModuleRefs.clear();
4351
4352   if (Imported)
4353     Imported->append(ImportedModules.begin(),
4354                      ImportedModules.end());
4355
4356   // FIXME: How do we load the 'use'd modules? They may not be submodules.
4357   // Might be unnecessary as use declarations are only used to build the
4358   // module itself.
4359
4360   if (ContextObj)
4361     InitializeContext();
4362
4363   if (SemaObj)
4364     UpdateSema();
4365
4366   if (DeserializationListener)
4367     DeserializationListener->ReaderInitialized(this);
4368
4369   ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
4370   if (PrimaryModule.OriginalSourceFileID.isValid()) {
4371     // If this AST file is a precompiled preamble, then set the
4372     // preamble file ID of the source manager to the file source file
4373     // from which the preamble was built.
4374     if (Type == MK_Preamble) {
4375       SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
4376     } else if (Type == MK_MainFile) {
4377       SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
4378     }
4379   }
4380
4381   // For any Objective-C class definitions we have already loaded, make sure
4382   // that we load any additional categories.
4383   if (ContextObj) {
4384     for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
4385       loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
4386                          ObjCClassesLoaded[I],
4387                          PreviousGeneration);
4388     }
4389   }
4390
4391   if (PP.getHeaderSearchInfo()
4392           .getHeaderSearchOpts()
4393           .ModulesValidateOncePerBuildSession) {
4394     // Now we are certain that the module and all modules it depends on are
4395     // up to date.  Create or update timestamp files for modules that are
4396     // located in the module cache (not for PCH files that could be anywhere
4397     // in the filesystem).
4398     for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
4399       ImportedModule &M = Loaded[I];
4400       if (M.Mod->Kind == MK_ImplicitModule) {
4401         updateModuleTimestamp(*M.Mod);
4402       }
4403     }
4404   }
4405
4406   return Success;
4407 }
4408
4409 static ASTFileSignature readASTFileSignature(StringRef PCH);
4410
4411 /// Whether \p Stream doesn't start with the AST/PCH file magic number 'CPCH'.
4412 static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
4413   // FIXME checking magic headers is done in other places such as
4414   // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
4415   // always done the same. Unify it all with a helper.
4416   if (!Stream.canSkipToPos(4))
4417     return llvm::createStringError(std::errc::illegal_byte_sequence,
4418                                    "file too small to contain AST file magic");
4419   for (unsigned C : {'C', 'P', 'C', 'H'})
4420     if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
4421       if (Res.get() != C)
4422         return llvm::createStringError(
4423             std::errc::illegal_byte_sequence,
4424             "file doesn't start with AST file magic");
4425     } else
4426       return Res.takeError();
4427   return llvm::Error::success();
4428 }
4429
4430 static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
4431   switch (Kind) {
4432   case MK_PCH:
4433     return 0; // PCH
4434   case MK_ImplicitModule:
4435   case MK_ExplicitModule:
4436   case MK_PrebuiltModule:
4437     return 1; // module
4438   case MK_MainFile:
4439   case MK_Preamble:
4440     return 2; // main source file
4441   }
4442   llvm_unreachable("unknown module kind");
4443 }
4444
4445 ASTReader::ASTReadResult
4446 ASTReader::ReadASTCore(StringRef FileName,
4447                        ModuleKind Type,
4448                        SourceLocation ImportLoc,
4449                        ModuleFile *ImportedBy,
4450                        SmallVectorImpl<ImportedModule> &Loaded,
4451                        off_t ExpectedSize, time_t ExpectedModTime,
4452                        ASTFileSignature ExpectedSignature,
4453                        unsigned ClientLoadCapabilities) {
4454   ModuleFile *M;
4455   std::string ErrorStr;
4456   ModuleManager::AddModuleResult AddResult
4457     = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
4458                           getGeneration(), ExpectedSize, ExpectedModTime,
4459                           ExpectedSignature, readASTFileSignature,
4460                           M, ErrorStr);
4461
4462   switch (AddResult) {
4463   case ModuleManager::AlreadyLoaded:
4464     Diag(diag::remark_module_import)
4465         << M->ModuleName << M->FileName << (ImportedBy ? true : false)
4466         << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
4467     return Success;
4468
4469   case ModuleManager::NewlyLoaded:
4470     // Load module file below.
4471     break;
4472
4473   case ModuleManager::Missing:
4474     // The module file was missing; if the client can handle that, return
4475     // it.
4476     if (ClientLoadCapabilities & ARR_Missing)
4477       return Missing;
4478
4479     // Otherwise, return an error.
4480     Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
4481                                           << FileName << !ErrorStr.empty()
4482                                           << ErrorStr;
4483     return Failure;
4484
4485   case ModuleManager::OutOfDate:
4486     // We couldn't load the module file because it is out-of-date. If the
4487     // client can handle out-of-date, return it.
4488     if (ClientLoadCapabilities & ARR_OutOfDate)
4489       return OutOfDate;
4490
4491     // Otherwise, return an error.
4492     Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
4493                                             << FileName << !ErrorStr.empty()
4494                                             << ErrorStr;
4495     return Failure;
4496   }
4497
4498   assert(M && "Missing module file");
4499
4500   bool ShouldFinalizePCM = false;
4501   auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() {
4502     auto &MC = getModuleManager().getModuleCache();
4503     if (ShouldFinalizePCM)
4504       MC.finalizePCM(FileName);
4505     else
4506       MC.tryToDropPCM(FileName);
4507   });
4508   ModuleFile &F = *M;
4509   BitstreamCursor &Stream = F.Stream;
4510   Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
4511   F.SizeInBits = F.Buffer->getBufferSize() * 8;
4512
4513   // Sniff for the signature.
4514   if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4515     Diag(diag::err_module_file_invalid)
4516         << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
4517     return Failure;
4518   }
4519
4520   // This is used for compatibility with older PCH formats.
4521   bool HaveReadControlBlock = false;
4522   while (true) {
4523     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4524     if (!MaybeEntry) {
4525       Error(MaybeEntry.takeError());
4526       return Failure;
4527     }
4528     llvm::BitstreamEntry Entry = MaybeEntry.get();
4529
4530     switch (Entry.Kind) {
4531     case llvm::BitstreamEntry::Error:
4532     case llvm::BitstreamEntry::Record:
4533     case llvm::BitstreamEntry::EndBlock:
4534       Error("invalid record at top-level of AST file");
4535       return Failure;
4536
4537     case llvm::BitstreamEntry::SubBlock:
4538       break;
4539     }
4540
4541     switch (Entry.ID) {
4542     case CONTROL_BLOCK_ID:
4543       HaveReadControlBlock = true;
4544       switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
4545       case Success:
4546         // Check that we didn't try to load a non-module AST file as a module.
4547         //
4548         // FIXME: Should we also perform the converse check? Loading a module as
4549         // a PCH file sort of works, but it's a bit wonky.
4550         if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
4551              Type == MK_PrebuiltModule) &&
4552             F.ModuleName.empty()) {
4553           auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4554           if (Result != OutOfDate ||
4555               (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4556             Diag(diag::err_module_file_not_module) << FileName;
4557           return Result;
4558         }
4559         break;
4560
4561       case Failure: return Failure;
4562       case Missing: return Missing;
4563       case OutOfDate: return OutOfDate;
4564       case VersionMismatch: return VersionMismatch;
4565       case ConfigurationMismatch: return ConfigurationMismatch;
4566       case HadErrors: return HadErrors;
4567       }
4568       break;
4569
4570     case AST_BLOCK_ID:
4571       if (!HaveReadControlBlock) {
4572         if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
4573           Diag(diag::err_pch_version_too_old);
4574         return VersionMismatch;
4575       }
4576
4577       // Record that we've loaded this module.
4578       Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4579       ShouldFinalizePCM = true;
4580       return Success;
4581
4582     case UNHASHED_CONTROL_BLOCK_ID:
4583       // This block is handled using look-ahead during ReadControlBlock.  We
4584       // shouldn't get here!
4585       Error("malformed block record in AST file");
4586       return Failure;
4587
4588     default:
4589       if (llvm::Error Err = Stream.SkipBlock()) {
4590         Error(std::move(Err));
4591         return Failure;
4592       }
4593       break;
4594     }
4595   }
4596
4597   llvm_unreachable("unexpected break; expected return");
4598 }
4599
4600 ASTReader::ASTReadResult
4601 ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4602                                     unsigned ClientLoadCapabilities) {
4603   const HeaderSearchOptions &HSOpts =
4604       PP.getHeaderSearchInfo().getHeaderSearchOpts();
4605   bool AllowCompatibleConfigurationMismatch =
4606       F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4607
4608   ASTReadResult Result = readUnhashedControlBlockImpl(
4609       &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4610       Listener.get(),
4611       WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4612
4613   // If F was directly imported by another module, it's implicitly validated by
4614   // the importing module.
4615   if (DisableValidation || WasImportedBy ||
4616       (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4617     return Success;
4618
4619   if (Result == Failure) {
4620     Error("malformed block record in AST file");
4621     return Failure;
4622   }
4623
4624   if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
4625     // If this module has already been finalized in the ModuleCache, we're stuck
4626     // with it; we can only load a single version of each module.
4627     //
4628     // This can happen when a module is imported in two contexts: in one, as a
4629     // user module; in another, as a system module (due to an import from
4630     // another module marked with the [system] flag).  It usually indicates a
4631     // bug in the module map: this module should also be marked with [system].
4632     //
4633     // If -Wno-system-headers (the default), and the first import is as a
4634     // system module, then validation will fail during the as-user import,
4635     // since -Werror flags won't have been validated.  However, it's reasonable
4636     // to treat this consistently as a system module.
4637     //
4638     // If -Wsystem-headers, the PCM on disk was built with
4639     // -Wno-system-headers, and the first import is as a user module, then
4640     // validation will fail during the as-system import since the PCM on disk
4641     // doesn't guarantee that -Werror was respected.  However, the -Werror
4642     // flags were checked during the initial as-user import.
4643     if (getModuleManager().getModuleCache().isPCMFinal(F.FileName)) {
4644       Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4645       return Success;
4646     }
4647   }
4648
4649   return Result;
4650 }
4651
4652 ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4653     ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4654     bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4655     bool ValidateDiagnosticOptions) {
4656   // Initialize a stream.
4657   BitstreamCursor Stream(StreamData);
4658
4659   // Sniff for the signature.
4660   if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4661     // FIXME this drops the error on the floor.
4662     consumeError(std::move(Err));
4663     return Failure;
4664   }
4665
4666   // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4667   if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4668     return Failure;
4669
4670   // Read all of the records in the options block.
4671   RecordData Record;
4672   ASTReadResult Result = Success;
4673   while (true) {
4674     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4675     if (!MaybeEntry) {
4676       // FIXME this drops the error on the floor.
4677       consumeError(MaybeEntry.takeError());
4678       return Failure;
4679     }
4680     llvm::BitstreamEntry Entry = MaybeEntry.get();
4681
4682     switch (Entry.Kind) {
4683     case llvm::BitstreamEntry::Error:
4684     case llvm::BitstreamEntry::SubBlock:
4685       return Failure;
4686
4687     case llvm::BitstreamEntry::EndBlock:
4688       return Result;
4689
4690     case llvm::BitstreamEntry::Record:
4691       // The interesting case.
4692       break;
4693     }
4694
4695     // Read and process a record.
4696     Record.clear();
4697     Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
4698     if (!MaybeRecordType) {
4699       // FIXME this drops the error.
4700       return Failure;
4701     }
4702     switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
4703     case SIGNATURE:
4704       if (F)
4705         std::copy(Record.begin(), Record.end(), F->Signature.data());
4706       break;
4707     case DIAGNOSTIC_OPTIONS: {
4708       bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4709       if (Listener && ValidateDiagnosticOptions &&
4710           !AllowCompatibleConfigurationMismatch &&
4711           ParseDiagnosticOptions(Record, Complain, *Listener))
4712         Result = OutOfDate; // Don't return early.  Read the signature.
4713       break;
4714     }
4715     case DIAG_PRAGMA_MAPPINGS:
4716       if (!F)
4717         break;
4718       if (F->PragmaDiagMappings.empty())
4719         F->PragmaDiagMappings.swap(Record);
4720       else
4721         F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4722                                      Record.begin(), Record.end());
4723       break;
4724     }
4725   }
4726 }
4727
4728 /// Parse a record and blob containing module file extension metadata.
4729 static bool parseModuleFileExtensionMetadata(
4730               const SmallVectorImpl<uint64_t> &Record,
4731               StringRef Blob,
4732               ModuleFileExtensionMetadata &Metadata) {
4733   if (Record.size() < 4) return true;
4734
4735   Metadata.MajorVersion = Record[0];
4736   Metadata.MinorVersion = Record[1];
4737
4738   unsigned BlockNameLen = Record[2];
4739   unsigned UserInfoLen = Record[3];
4740
4741   if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4742
4743   Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4744   Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4745                                   Blob.data() + BlockNameLen + UserInfoLen);
4746   return false;
4747 }
4748
4749 ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4750   BitstreamCursor &Stream = F.Stream;
4751
4752   RecordData Record;
4753   while (true) {
4754     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4755     if (!MaybeEntry) {
4756       Error(MaybeEntry.takeError());
4757       return Failure;
4758     }
4759     llvm::BitstreamEntry Entry = MaybeEntry.get();
4760
4761     switch (Entry.Kind) {
4762     case llvm::BitstreamEntry::SubBlock:
4763       if (llvm::Error Err = Stream.SkipBlock()) {
4764         Error(std::move(Err));
4765         return Failure;
4766       }
4767       continue;
4768
4769     case llvm::BitstreamEntry::EndBlock:
4770       return Success;
4771
4772     case llvm::BitstreamEntry::Error:
4773       return HadErrors;
4774
4775     case llvm::BitstreamEntry::Record:
4776       break;
4777     }
4778
4779     Record.clear();
4780     StringRef Blob;
4781     Expected<unsigned> MaybeRecCode =
4782         Stream.readRecord(Entry.ID, Record, &Blob);
4783     if (!MaybeRecCode) {
4784       Error(MaybeRecCode.takeError());
4785       return Failure;
4786     }
4787     switch (MaybeRecCode.get()) {
4788     case EXTENSION_METADATA: {
4789       ModuleFileExtensionMetadata Metadata;
4790       if (parseModuleFileExtensionMetadata(Record, Blob, Metadata)) {
4791         Error("malformed EXTENSION_METADATA in AST file");
4792         return Failure;
4793       }
4794
4795       // Find a module file extension with this block name.
4796       auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4797       if (Known == ModuleFileExtensions.end()) break;
4798
4799       // Form a reader.
4800       if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4801                                                              F, Stream)) {
4802         F.ExtensionReaders.push_back(std::move(Reader));
4803       }
4804
4805       break;
4806     }
4807     }
4808   }
4809
4810   return Success;
4811 }
4812
4813 void ASTReader::InitializeContext() {
4814   assert(ContextObj && "no context to initialize");
4815   ASTContext &Context = *ContextObj;
4816
4817   // If there's a listener, notify them that we "read" the translation unit.
4818   if (DeserializationListener)
4819     DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
4820                                       Context.getTranslationUnitDecl());
4821
4822   // FIXME: Find a better way to deal with collisions between these
4823   // built-in types. Right now, we just ignore the problem.
4824
4825   // Load the special types.
4826   if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4827     if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4828       if (!Context.CFConstantStringTypeDecl)
4829         Context.setCFConstantStringType(GetType(String));
4830     }
4831
4832     if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4833       QualType FileType = GetType(File);
4834       if (FileType.isNull()) {
4835         Error("FILE type is NULL");
4836         return;
4837       }
4838
4839       if (!Context.FILEDecl) {
4840         if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
4841           Context.setFILEDecl(Typedef->getDecl());
4842         else {
4843           const TagType *Tag = FileType->getAs<TagType>();
4844           if (!Tag) {
4845             Error("Invalid FILE type in AST file");
4846             return;
4847           }
4848           Context.setFILEDecl(Tag->getDecl());
4849         }
4850       }
4851     }
4852
4853     if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4854       QualType Jmp_bufType = GetType(Jmp_buf);
4855       if (Jmp_bufType.isNull()) {
4856         Error("jmp_buf type is NULL");
4857         return;
4858       }
4859
4860       if (!Context.jmp_bufDecl) {
4861         if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4862           Context.setjmp_bufDecl(Typedef->getDecl());
4863         else {
4864           const TagType *Tag = Jmp_bufType->getAs<TagType>();
4865           if (!Tag) {
4866             Error("Invalid jmp_buf type in AST file");
4867             return;
4868           }
4869           Context.setjmp_bufDecl(Tag->getDecl());
4870         }
4871       }
4872     }
4873
4874     if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4875       QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4876       if (Sigjmp_bufType.isNull()) {
4877         Error("sigjmp_buf type is NULL");
4878         return;
4879       }
4880
4881       if (!Context.sigjmp_bufDecl) {
4882         if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4883           Context.setsigjmp_bufDecl(Typedef->getDecl());
4884         else {
4885           const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4886           assert(Tag && "Invalid sigjmp_buf type in AST file");
4887           Context.setsigjmp_bufDecl(Tag->getDecl());
4888         }
4889       }
4890     }
4891
4892     if (unsigned ObjCIdRedef
4893           = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4894       if (Context.ObjCIdRedefinitionType.isNull())
4895         Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4896     }
4897
4898     if (unsigned ObjCClassRedef
4899           = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4900       if (Context.ObjCClassRedefinitionType.isNull())
4901         Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4902     }
4903
4904     if (unsigned ObjCSelRedef
4905           = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4906       if (Context.ObjCSelRedefinitionType.isNull())
4907         Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4908     }
4909
4910     if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4911       QualType Ucontext_tType = GetType(Ucontext_t);
4912       if (Ucontext_tType.isNull()) {
4913         Error("ucontext_t type is NULL");
4914         return;
4915       }
4916
4917       if (!Context.ucontext_tDecl) {
4918         if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4919           Context.setucontext_tDecl(Typedef->getDecl());
4920         else {
4921           const TagType *Tag = Ucontext_tType->getAs<TagType>();
4922           assert(Tag && "Invalid ucontext_t type in AST file");
4923           Context.setucontext_tDecl(Tag->getDecl());
4924         }
4925       }
4926     }
4927   }
4928
4929   ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4930
4931   // If there were any CUDA special declarations, deserialize them.
4932   if (!CUDASpecialDeclRefs.empty()) {
4933     assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4934     Context.setcudaConfigureCallDecl(
4935                            cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4936   }
4937
4938   // Re-export any modules that were imported by a non-module AST file.
4939   // FIXME: This does not make macro-only imports visible again.
4940   for (auto &Import : ImportedModules) {
4941     if (Module *Imported = getSubmodule(Import.ID)) {
4942       makeModuleVisible(Imported, Module::AllVisible,
4943                         /*ImportLoc=*/Import.ImportLoc);
4944       if (Import.ImportLoc.isValid())
4945         PP.makeModuleVisible(Imported, Import.ImportLoc);
4946       // FIXME: should we tell Sema to make the module visible too?
4947     }
4948   }
4949   ImportedModules.clear();
4950 }
4951
4952 void ASTReader::finalizeForWriting() {
4953   // Nothing to do for now.
4954 }
4955
4956 /// Reads and return the signature record from \p PCH's control block, or
4957 /// else returns 0.
4958 static ASTFileSignature readASTFileSignature(StringRef PCH) {
4959   BitstreamCursor Stream(PCH);
4960   if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4961     // FIXME this drops the error on the floor.
4962     consumeError(std::move(Err));
4963     return ASTFileSignature();
4964   }
4965
4966   // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4967   if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4968     return ASTFileSignature();
4969
4970   // Scan for SIGNATURE inside the diagnostic options block.
4971   ASTReader::RecordData Record;
4972   while (true) {
4973     Expected<llvm::BitstreamEntry> MaybeEntry =
4974         Stream.advanceSkippingSubblocks();
4975     if (!MaybeEntry) {
4976       // FIXME this drops the error on the floor.
4977       consumeError(MaybeEntry.takeError());
4978       return ASTFileSignature();
4979     }
4980     llvm::BitstreamEntry Entry = MaybeEntry.get();
4981
4982     if (Entry.Kind != llvm::BitstreamEntry::Record)
4983       return ASTFileSignature();
4984
4985     Record.clear();
4986     StringRef Blob;
4987     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
4988     if (!MaybeRecord) {
4989       // FIXME this drops the error on the floor.
4990       consumeError(MaybeRecord.takeError());
4991       return ASTFileSignature();
4992     }
4993     if (SIGNATURE == MaybeRecord.get())
4994       return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
4995                 (uint32_t)Record[3], (uint32_t)Record[4]}}};
4996   }
4997 }
4998
4999 /// Retrieve the name of the original source file name
5000 /// directly from the AST file, without actually loading the AST
5001 /// file.
5002 std::string ASTReader::getOriginalSourceFile(
5003     const std::string &ASTFileName, FileManager &FileMgr,
5004     const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
5005   // Open the AST file.
5006   auto Buffer = FileMgr.getBufferForFile(ASTFileName);
5007   if (!Buffer) {
5008     Diags.Report(diag::err_fe_unable_to_read_pch_file)
5009         << ASTFileName << Buffer.getError().message();
5010     return std::string();
5011   }
5012
5013   // Initialize the stream
5014   BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
5015
5016   // Sniff for the signature.
5017   if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5018     Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
5019     return std::string();
5020   }
5021
5022   // Scan for the CONTROL_BLOCK_ID block.
5023   if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
5024     Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5025     return std::string();
5026   }
5027
5028   // Scan for ORIGINAL_FILE inside the control block.
5029   RecordData Record;
5030   while (true) {
5031     Expected<llvm::BitstreamEntry> MaybeEntry =
5032         Stream.advanceSkippingSubblocks();
5033     if (!MaybeEntry) {
5034       // FIXME this drops errors on the floor.
5035       consumeError(MaybeEntry.takeError());
5036       return std::string();
5037     }
5038     llvm::BitstreamEntry Entry = MaybeEntry.get();
5039
5040     if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
5041       return std::string();
5042
5043     if (Entry.Kind != llvm::BitstreamEntry::Record) {
5044       Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
5045       return std::string();
5046     }
5047
5048     Record.clear();
5049     StringRef Blob;
5050     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5051     if (!MaybeRecord) {
5052       // FIXME this drops the errors on the floor.
5053       consumeError(MaybeRecord.takeError());
5054       return std::string();
5055     }
5056     if (ORIGINAL_FILE == MaybeRecord.get())
5057       return Blob.str();
5058   }
5059 }
5060
5061 namespace {
5062
5063   class SimplePCHValidator : public ASTReaderListener {
5064     const LangOptions &ExistingLangOpts;
5065     const TargetOptions &ExistingTargetOpts;
5066     const PreprocessorOptions &ExistingPPOpts;
5067     std::string ExistingModuleCachePath;
5068     FileManager &FileMgr;
5069
5070   public:
5071     SimplePCHValidator(const LangOptions &ExistingLangOpts,
5072                        const TargetOptions &ExistingTargetOpts,
5073                        const PreprocessorOptions &ExistingPPOpts,
5074                        StringRef ExistingModuleCachePath,
5075                        FileManager &FileMgr)
5076       : ExistingLangOpts(ExistingLangOpts),
5077         ExistingTargetOpts(ExistingTargetOpts),
5078         ExistingPPOpts(ExistingPPOpts),
5079         ExistingModuleCachePath(ExistingModuleCachePath),
5080         FileMgr(FileMgr) {}
5081
5082     bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
5083                              bool AllowCompatibleDifferences) override {
5084       return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
5085                                   AllowCompatibleDifferences);
5086     }
5087
5088     bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
5089                            bool AllowCompatibleDifferences) override {
5090       return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
5091                                 AllowCompatibleDifferences);
5092     }
5093
5094     bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
5095                                  StringRef SpecificModuleCachePath,
5096                                  bool Complain) override {
5097       return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5098                                       ExistingModuleCachePath,
5099                                       nullptr, ExistingLangOpts);
5100     }
5101
5102     bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
5103                                  bool Complain,
5104                                  std::string &SuggestedPredefines) override {
5105       return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
5106                                       SuggestedPredefines, ExistingLangOpts);
5107     }
5108   };
5109
5110 } // namespace
5111
5112 bool ASTReader::readASTFileControlBlock(
5113     StringRef Filename, FileManager &FileMgr,
5114     const PCHContainerReader &PCHContainerRdr,
5115     bool FindModuleFileExtensions,
5116     ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
5117   // Open the AST file.
5118   // FIXME: This allows use of the VFS; we do not allow use of the
5119   // VFS when actually loading a module.
5120   auto Buffer = FileMgr.getBufferForFile(Filename);
5121   if (!Buffer) {
5122     return true;
5123   }
5124
5125   // Initialize the stream
5126   StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer);
5127   BitstreamCursor Stream(Bytes);
5128
5129   // Sniff for the signature.
5130   if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5131     consumeError(std::move(Err)); // FIXME this drops errors on the floor.
5132     return true;
5133   }
5134
5135   // Scan for the CONTROL_BLOCK_ID block.
5136   if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
5137     return true;
5138
5139   bool NeedsInputFiles = Listener.needsInputFileVisitation();
5140   bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
5141   bool NeedsImports = Listener.needsImportVisitation();
5142   BitstreamCursor InputFilesCursor;
5143
5144   RecordData Record;
5145   std::string ModuleDir;
5146   bool DoneWithControlBlock = false;
5147   while (!DoneWithControlBlock) {
5148     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5149     if (!MaybeEntry) {
5150       // FIXME this drops the error on the floor.
5151       consumeError(MaybeEntry.takeError());
5152       return true;
5153     }
5154     llvm::BitstreamEntry Entry = MaybeEntry.get();
5155
5156     switch (Entry.Kind) {
5157     case llvm::BitstreamEntry::SubBlock: {
5158       switch (Entry.ID) {
5159       case OPTIONS_BLOCK_ID: {
5160         std::string IgnoredSuggestedPredefines;
5161         if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
5162                              /*AllowCompatibleConfigurationMismatch*/ false,
5163                              Listener, IgnoredSuggestedPredefines) != Success)
5164           return true;
5165         break;
5166       }
5167
5168       case INPUT_FILES_BLOCK_ID:
5169         InputFilesCursor = Stream;
5170         if (llvm::Error Err = Stream.SkipBlock()) {
5171           // FIXME this drops the error on the floor.
5172           consumeError(std::move(Err));
5173           return true;
5174         }
5175         if (NeedsInputFiles &&
5176             ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
5177           return true;
5178         break;
5179
5180       default:
5181         if (llvm::Error Err = Stream.SkipBlock()) {
5182           // FIXME this drops the error on the floor.
5183           consumeError(std::move(Err));
5184           return true;
5185         }
5186         break;
5187       }
5188
5189       continue;
5190     }
5191
5192     case llvm::BitstreamEntry::EndBlock:
5193       DoneWithControlBlock = true;
5194       break;
5195
5196     case llvm::BitstreamEntry::Error:
5197       return true;
5198
5199     case llvm::BitstreamEntry::Record:
5200       break;
5201     }
5202
5203     if (DoneWithControlBlock) break;
5204
5205     Record.clear();
5206     StringRef Blob;
5207     Expected<unsigned> MaybeRecCode =
5208         Stream.readRecord(Entry.ID, Record, &Blob);
5209     if (!MaybeRecCode) {
5210       // FIXME this drops the error.
5211       return Failure;
5212     }
5213     switch ((ControlRecordTypes)MaybeRecCode.get()) {
5214     case METADATA:
5215       if (Record[0] != VERSION_MAJOR)
5216         return true;
5217       if (Listener.ReadFullVersionInformation(Blob))
5218         return true;
5219       break;
5220     case MODULE_NAME:
5221       Listener.ReadModuleName(Blob);
5222       break;
5223     case MODULE_DIRECTORY:
5224       ModuleDir = Blob;
5225       break;
5226     case MODULE_MAP_FILE: {
5227       unsigned Idx = 0;
5228       auto Path = ReadString(Record, Idx);
5229       ResolveImportedPath(Path, ModuleDir);
5230       Listener.ReadModuleMapFile(Path);
5231       break;
5232     }
5233     case INPUT_FILE_OFFSETS: {
5234       if (!NeedsInputFiles)
5235         break;
5236
5237       unsigned NumInputFiles = Record[0];
5238       unsigned NumUserFiles = Record[1];
5239       const llvm::support::unaligned_uint64_t *InputFileOffs =
5240           (const llvm::support::unaligned_uint64_t *)Blob.data();
5241       for (unsigned I = 0; I != NumInputFiles; ++I) {
5242         // Go find this input file.
5243         bool isSystemFile = I >= NumUserFiles;
5244
5245         if (isSystemFile && !NeedsSystemInputFiles)
5246           break; // the rest are system input files
5247
5248         BitstreamCursor &Cursor = InputFilesCursor;
5249         SavedStreamPosition SavedPosition(Cursor);
5250         if (llvm::Error Err = Cursor.JumpToBit(InputFileOffs[I])) {
5251           // FIXME this drops errors on the floor.
5252           consumeError(std::move(Err));
5253         }
5254
5255         Expected<unsigned> MaybeCode = Cursor.ReadCode();
5256         if (!MaybeCode) {
5257           // FIXME this drops errors on the floor.
5258           consumeError(MaybeCode.takeError());
5259         }
5260         unsigned Code = MaybeCode.get();
5261
5262         RecordData Record;
5263         StringRef Blob;
5264         bool shouldContinue = false;
5265         Expected<unsigned> MaybeRecordType =
5266             Cursor.readRecord(Code, Record, &Blob);
5267         if (!MaybeRecordType) {
5268           // FIXME this drops errors on the floor.
5269           consumeError(MaybeRecordType.takeError());
5270         }
5271         switch ((InputFileRecordTypes)MaybeRecordType.get()) {
5272         case INPUT_FILE_HASH:
5273           break;
5274         case INPUT_FILE:
5275           bool Overridden = static_cast<bool>(Record[3]);
5276           std::string Filename = Blob;
5277           ResolveImportedPath(Filename, ModuleDir);
5278           shouldContinue = Listener.visitInputFile(
5279               Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
5280           break;
5281         }
5282         if (!shouldContinue)
5283           break;
5284       }
5285       break;
5286     }
5287
5288     case IMPORTS: {
5289       if (!NeedsImports)
5290         break;
5291
5292       unsigned Idx = 0, N = Record.size();
5293       while (Idx < N) {
5294         // Read information about the AST file.
5295         Idx += 1+1+1+1+5; // Kind, ImportLoc, Size, ModTime, Signature
5296         std::string ModuleName = ReadString(Record, Idx);
5297         std::string Filename = ReadString(Record, Idx);
5298         ResolveImportedPath(Filename, ModuleDir);
5299         Listener.visitImport(ModuleName, Filename);
5300       }
5301       break;
5302     }
5303
5304     default:
5305       // No other validation to perform.
5306       break;
5307     }
5308   }
5309
5310   // Look for module file extension blocks, if requested.
5311   if (FindModuleFileExtensions) {
5312     BitstreamCursor SavedStream = Stream;
5313     while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
5314       bool DoneWithExtensionBlock = false;
5315       while (!DoneWithExtensionBlock) {
5316         Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5317         if (!MaybeEntry) {
5318           // FIXME this drops the error.
5319           return true;
5320         }
5321         llvm::BitstreamEntry Entry = MaybeEntry.get();
5322
5323         switch (Entry.Kind) {
5324         case llvm::BitstreamEntry::SubBlock:
5325           if (llvm::Error Err = Stream.SkipBlock()) {
5326             // FIXME this drops the error on the floor.
5327             consumeError(std::move(Err));
5328             return true;
5329           }
5330           continue;
5331
5332         case llvm::BitstreamEntry::EndBlock:
5333           DoneWithExtensionBlock = true;
5334           continue;
5335
5336         case llvm::BitstreamEntry::Error:
5337           return true;
5338
5339         case llvm::BitstreamEntry::Record:
5340           break;
5341         }
5342
5343        Record.clear();
5344        StringRef Blob;
5345        Expected<unsigned> MaybeRecCode =
5346            Stream.readRecord(Entry.ID, Record, &Blob);
5347        if (!MaybeRecCode) {
5348          // FIXME this drops the error.
5349          return true;
5350        }
5351        switch (MaybeRecCode.get()) {
5352        case EXTENSION_METADATA: {
5353          ModuleFileExtensionMetadata Metadata;
5354          if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5355            return true;
5356
5357          Listener.readModuleFileExtension(Metadata);
5358          break;
5359        }
5360        }
5361       }
5362     }
5363     Stream = SavedStream;
5364   }
5365
5366   // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5367   if (readUnhashedControlBlockImpl(
5368           nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
5369           /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
5370           ValidateDiagnosticOptions) != Success)
5371     return true;
5372
5373   return false;
5374 }
5375
5376 bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
5377                                     const PCHContainerReader &PCHContainerRdr,
5378                                     const LangOptions &LangOpts,
5379                                     const TargetOptions &TargetOpts,
5380                                     const PreprocessorOptions &PPOpts,
5381                                     StringRef ExistingModuleCachePath) {
5382   SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
5383                                ExistingModuleCachePath, FileMgr);
5384   return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
5385                                   /*FindModuleFileExtensions=*/false,
5386                                   validator,
5387                                   /*ValidateDiagnosticOptions=*/true);
5388 }
5389
5390 ASTReader::ASTReadResult
5391 ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
5392   // Enter the submodule block.
5393   if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
5394     Error(std::move(Err));
5395     return Failure;
5396   }
5397
5398   ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
5399   bool First = true;
5400   Module *CurrentModule = nullptr;
5401   RecordData Record;
5402   while (true) {
5403     Expected<llvm::BitstreamEntry> MaybeEntry =
5404         F.Stream.advanceSkippingSubblocks();
5405     if (!MaybeEntry) {
5406       Error(MaybeEntry.takeError());
5407       return Failure;
5408     }
5409     llvm::BitstreamEntry Entry = MaybeEntry.get();
5410
5411     switch (Entry.Kind) {
5412     case llvm::BitstreamEntry::SubBlock: // Handled for us already.
5413     case llvm::BitstreamEntry::Error:
5414       Error("malformed block record in AST file");
5415       return Failure;
5416     case llvm::BitstreamEntry::EndBlock:
5417       return Success;
5418     case llvm::BitstreamEntry::Record:
5419       // The interesting case.
5420       break;
5421     }
5422
5423     // Read a record.
5424     StringRef Blob;
5425     Record.clear();
5426     Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
5427     if (!MaybeKind) {
5428       Error(MaybeKind.takeError());
5429       return Failure;
5430     }
5431     unsigned Kind = MaybeKind.get();
5432
5433     if ((Kind == SUBMODULE_METADATA) != First) {
5434       Error("submodule metadata record should be at beginning of block");
5435       return Failure;
5436     }
5437     First = false;
5438
5439     // Submodule information is only valid if we have a current module.
5440     // FIXME: Should we error on these cases?
5441     if (!CurrentModule && Kind != SUBMODULE_METADATA &&
5442         Kind != SUBMODULE_DEFINITION)
5443       continue;
5444
5445     switch (Kind) {
5446     default:  // Default behavior: ignore.
5447       break;
5448
5449     case SUBMODULE_DEFINITION: {
5450       if (Record.size() < 12) {
5451         Error("malformed module definition");
5452         return Failure;
5453       }
5454
5455       StringRef Name = Blob;
5456       unsigned Idx = 0;
5457       SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
5458       SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
5459       Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++];
5460       bool IsFramework = Record[Idx++];
5461       bool IsExplicit = Record[Idx++];
5462       bool IsSystem = Record[Idx++];
5463       bool IsExternC = Record[Idx++];
5464       bool InferSubmodules = Record[Idx++];
5465       bool InferExplicitSubmodules = Record[Idx++];
5466       bool InferExportWildcard = Record[Idx++];
5467       bool ConfigMacrosExhaustive = Record[Idx++];
5468       bool ModuleMapIsPrivate = Record[Idx++];
5469
5470       Module *ParentModule = nullptr;
5471       if (Parent)
5472         ParentModule = getSubmodule(Parent);
5473
5474       // Retrieve this (sub)module from the module map, creating it if
5475       // necessary.
5476       CurrentModule =
5477           ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
5478               .first;
5479
5480       // FIXME: set the definition loc for CurrentModule, or call
5481       // ModMap.setInferredModuleAllowedBy()
5482
5483       SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
5484       if (GlobalIndex >= SubmodulesLoaded.size() ||
5485           SubmodulesLoaded[GlobalIndex]) {
5486         Error("too many submodules");
5487         return Failure;
5488       }
5489
5490       if (!ParentModule) {
5491         if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
5492           // Don't emit module relocation error if we have -fno-validate-pch
5493           if (!PP.getPreprocessorOpts().DisablePCHValidation &&
5494               CurFile != F.File) {
5495             Error(diag::err_module_file_conflict,
5496                   CurrentModule->getTopLevelModuleName(), CurFile->getName(),
5497                   F.File->getName());
5498             return Failure;
5499           }
5500         }
5501
5502         F.DidReadTopLevelSubmodule = true;
5503         CurrentModule->setASTFile(F.File);
5504         CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
5505       }
5506
5507       CurrentModule->Kind = Kind;
5508       CurrentModule->Signature = F.Signature;
5509       CurrentModule->IsFromModuleFile = true;
5510       CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
5511       CurrentModule->IsExternC = IsExternC;
5512       CurrentModule->InferSubmodules = InferSubmodules;
5513       CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
5514       CurrentModule->InferExportWildcard = InferExportWildcard;
5515       CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
5516       CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
5517       if (DeserializationListener)
5518         DeserializationListener->ModuleRead(GlobalID, CurrentModule);
5519
5520       SubmodulesLoaded[GlobalIndex] = CurrentModule;
5521
5522       // Clear out data that will be replaced by what is in the module file.
5523       CurrentModule->LinkLibraries.clear();
5524       CurrentModule->ConfigMacros.clear();
5525       CurrentModule->UnresolvedConflicts.clear();
5526       CurrentModule->Conflicts.clear();
5527
5528       // The module is available unless it's missing a requirement; relevant
5529       // requirements will be (re-)added by SUBMODULE_REQUIRES records.
5530       // Missing headers that were present when the module was built do not
5531       // make it unavailable -- if we got this far, this must be an explicitly
5532       // imported module file.
5533       CurrentModule->Requirements.clear();
5534       CurrentModule->MissingHeaders.clear();
5535       CurrentModule->IsMissingRequirement =
5536           ParentModule && ParentModule->IsMissingRequirement;
5537       CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
5538       break;
5539     }
5540
5541     case SUBMODULE_UMBRELLA_HEADER: {
5542       std::string Filename = Blob;
5543       ResolveImportedPath(F, Filename);
5544       if (auto Umbrella = PP.getFileManager().getFile(Filename)) {
5545         if (!CurrentModule->getUmbrellaHeader())
5546           ModMap.setUmbrellaHeader(CurrentModule, *Umbrella, Blob);
5547         else if (CurrentModule->getUmbrellaHeader().Entry != *Umbrella) {
5548           if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5549             Error("mismatched umbrella headers in submodule");
5550           return OutOfDate;
5551         }
5552       }
5553       break;
5554     }
5555
5556     case SUBMODULE_HEADER:
5557     case SUBMODULE_EXCLUDED_HEADER:
5558     case SUBMODULE_PRIVATE_HEADER:
5559       // We lazily associate headers with their modules via the HeaderInfo table.
5560       // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
5561       // of complete filenames or remove it entirely.
5562       break;
5563
5564     case SUBMODULE_TEXTUAL_HEADER:
5565     case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
5566       // FIXME: Textual headers are not marked in the HeaderInfo table. Load
5567       // them here.
5568       break;
5569
5570     case SUBMODULE_TOPHEADER:
5571       CurrentModule->addTopHeaderFilename(Blob);
5572       break;
5573
5574     case SUBMODULE_UMBRELLA_DIR: {
5575       std::string Dirname = Blob;
5576       ResolveImportedPath(F, Dirname);
5577       if (auto Umbrella = PP.getFileManager().getDirectory(Dirname)) {
5578         if (!CurrentModule->getUmbrellaDir())
5579           ModMap.setUmbrellaDir(CurrentModule, *Umbrella, Blob);
5580         else if (CurrentModule->getUmbrellaDir().Entry != *Umbrella) {
5581           if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5582             Error("mismatched umbrella directories in submodule");
5583           return OutOfDate;
5584         }
5585       }
5586       break;
5587     }
5588
5589     case SUBMODULE_METADATA: {
5590       F.BaseSubmoduleID = getTotalNumSubmodules();
5591       F.LocalNumSubmodules = Record[0];
5592       unsigned LocalBaseSubmoduleID = Record[1];
5593       if (F.LocalNumSubmodules > 0) {
5594         // Introduce the global -> local mapping for submodules within this
5595         // module.
5596         GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
5597
5598         // Introduce the local -> global mapping for submodules within this
5599         // module.
5600         F.SubmoduleRemap.insertOrReplace(
5601           std::make_pair(LocalBaseSubmoduleID,
5602                          F.BaseSubmoduleID - LocalBaseSubmoduleID));
5603
5604         SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5605       }
5606       break;
5607     }
5608
5609     case SUBMODULE_IMPORTS:
5610       for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
5611         UnresolvedModuleRef Unresolved;
5612         Unresolved.File = &F;
5613         Unresolved.Mod = CurrentModule;
5614         Unresolved.ID = Record[Idx];
5615         Unresolved.Kind = UnresolvedModuleRef::Import;
5616         Unresolved.IsWildcard = false;
5617         UnresolvedModuleRefs.push_back(Unresolved);
5618       }
5619       break;
5620
5621     case SUBMODULE_EXPORTS:
5622       for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
5623         UnresolvedModuleRef Unresolved;
5624         Unresolved.File = &F;
5625         Unresolved.Mod = CurrentModule;
5626         Unresolved.ID = Record[Idx];
5627         Unresolved.Kind = UnresolvedModuleRef::Export;
5628         Unresolved.IsWildcard = Record[Idx + 1];
5629         UnresolvedModuleRefs.push_back(Unresolved);
5630       }
5631
5632       // Once we've loaded the set of exports, there's no reason to keep
5633       // the parsed, unresolved exports around.
5634       CurrentModule->UnresolvedExports.clear();
5635       break;
5636
5637     case SUBMODULE_REQUIRES:
5638       CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
5639                                     PP.getTargetInfo());
5640       break;
5641
5642     case SUBMODULE_LINK_LIBRARY:
5643       ModMap.resolveLinkAsDependencies(CurrentModule);
5644       CurrentModule->LinkLibraries.push_back(
5645                                          Module::LinkLibrary(Blob, Record[0]));
5646       break;
5647
5648     case SUBMODULE_CONFIG_MACRO:
5649       CurrentModule->ConfigMacros.push_back(Blob.str());
5650       break;
5651
5652     case SUBMODULE_CONFLICT: {
5653       UnresolvedModuleRef Unresolved;
5654       Unresolved.File = &F;
5655       Unresolved.Mod = CurrentModule;
5656       Unresolved.ID = Record[0];
5657       Unresolved.Kind = UnresolvedModuleRef::Conflict;
5658       Unresolved.IsWildcard = false;
5659       Unresolved.String = Blob;
5660       UnresolvedModuleRefs.push_back(Unresolved);
5661       break;
5662     }
5663
5664     case SUBMODULE_INITIALIZERS: {
5665       if (!ContextObj)
5666         break;
5667       SmallVector<uint32_t, 16> Inits;
5668       for (auto &ID : Record)
5669         Inits.push_back(getGlobalDeclID(F, ID));
5670       ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
5671       break;
5672     }
5673
5674     case SUBMODULE_EXPORT_AS:
5675       CurrentModule->ExportAsModule = Blob.str();
5676       ModMap.addLinkAsDependency(CurrentModule);
5677       break;
5678     }
5679   }
5680 }
5681
5682 /// Parse the record that corresponds to a LangOptions data
5683 /// structure.
5684 ///
5685 /// This routine parses the language options from the AST file and then gives
5686 /// them to the AST listener if one is set.
5687 ///
5688 /// \returns true if the listener deems the file unacceptable, false otherwise.
5689 bool ASTReader::ParseLanguageOptions(const RecordData &Record,
5690                                      bool Complain,
5691                                      ASTReaderListener &Listener,
5692                                      bool AllowCompatibleDifferences) {
5693   LangOptions LangOpts;
5694   unsigned Idx = 0;
5695 #define LANGOPT(Name, Bits, Default, Description) \
5696   LangOpts.Name = Record[Idx++];
5697 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
5698   LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
5699 #include "clang/Basic/LangOptions.def"
5700 #define SANITIZER(NAME, ID)                                                    \
5701   LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
5702 #include "clang/Basic/Sanitizers.def"
5703
5704   for (unsigned N = Record[Idx++]; N; --N)
5705     LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
5706
5707   ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
5708   VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
5709   LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
5710
5711   LangOpts.CurrentModule = ReadString(Record, Idx);
5712
5713   // Comment options.
5714   for (unsigned N = Record[Idx++]; N; --N) {
5715     LangOpts.CommentOpts.BlockCommandNames.push_back(
5716       ReadString(Record, Idx));
5717   }
5718   LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
5719
5720   // OpenMP offloading options.
5721   for (unsigned N = Record[Idx++]; N; --N) {
5722     LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
5723   }
5724
5725   LangOpts.OMPHostIRFile = ReadString(Record, Idx);
5726
5727   return Listener.ReadLanguageOptions(LangOpts, Complain,
5728                                       AllowCompatibleDifferences);
5729 }
5730
5731 bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
5732                                    ASTReaderListener &Listener,
5733                                    bool AllowCompatibleDifferences) {
5734   unsigned Idx = 0;
5735   TargetOptions TargetOpts;
5736   TargetOpts.Triple = ReadString(Record, Idx);
5737   TargetOpts.CPU = ReadString(Record, Idx);
5738   TargetOpts.ABI = ReadString(Record, Idx);
5739   for (unsigned N = Record[Idx++]; N; --N) {
5740     TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
5741   }
5742   for (unsigned N = Record[Idx++]; N; --N) {
5743     TargetOpts.Features.push_back(ReadString(Record, Idx));
5744   }
5745
5746   return Listener.ReadTargetOptions(TargetOpts, Complain,
5747                                     AllowCompatibleDifferences);
5748 }
5749
5750 bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
5751                                        ASTReaderListener &Listener) {
5752   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
5753   unsigned Idx = 0;
5754 #define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
5755 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
5756   DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
5757 #include "clang/Basic/DiagnosticOptions.def"
5758
5759   for (unsigned N = Record[Idx++]; N; --N)
5760     DiagOpts->Warnings.push_back(ReadString(Record, Idx));
5761   for (unsigned N = Record[Idx++]; N; --N)
5762     DiagOpts->Remarks.push_back(ReadString(Record, Idx));
5763
5764   return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
5765 }
5766
5767 bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
5768                                        ASTReaderListener &Listener) {
5769   FileSystemOptions FSOpts;
5770   unsigned Idx = 0;
5771   FSOpts.WorkingDir = ReadString(Record, Idx);
5772   return Listener.ReadFileSystemOptions(FSOpts, Complain);
5773 }
5774
5775 bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
5776                                          bool Complain,
5777                                          ASTReaderListener &Listener) {
5778   HeaderSearchOptions HSOpts;
5779   unsigned Idx = 0;
5780   HSOpts.Sysroot = ReadString(Record, Idx);
5781
5782   // Include entries.
5783   for (unsigned N = Record[Idx++]; N; --N) {
5784     std::string Path = ReadString(Record, Idx);
5785     frontend::IncludeDirGroup Group
5786       = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
5787     bool IsFramework = Record[Idx++];
5788     bool IgnoreSysRoot = Record[Idx++];
5789     HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
5790                                     IgnoreSysRoot);
5791   }
5792
5793   // System header prefixes.
5794   for (unsigned N = Record[Idx++]; N; --N) {
5795     std::string Prefix = ReadString(Record, Idx);
5796     bool IsSystemHeader = Record[Idx++];
5797     HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
5798   }
5799
5800   HSOpts.ResourceDir = ReadString(Record, Idx);
5801   HSOpts.ModuleCachePath = ReadString(Record, Idx);
5802   HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
5803   HSOpts.DisableModuleHash = Record[Idx++];
5804   HSOpts.ImplicitModuleMaps = Record[Idx++];
5805   HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
5806   HSOpts.UseBuiltinIncludes = Record[Idx++];
5807   HSOpts.UseStandardSystemIncludes = Record[Idx++];
5808   HSOpts.UseStandardCXXIncludes = Record[Idx++];
5809   HSOpts.UseLibcxx = Record[Idx++];
5810   std::string SpecificModuleCachePath = ReadString(Record, Idx);
5811
5812   return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5813                                           Complain);
5814 }
5815
5816 bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5817                                          bool Complain,
5818                                          ASTReaderListener &Listener,
5819                                          std::string &SuggestedPredefines) {
5820   PreprocessorOptions PPOpts;
5821   unsigned Idx = 0;
5822
5823   // Macro definitions/undefs
5824   for (unsigned N = Record[Idx++]; N; --N) {
5825     std::string Macro = ReadString(Record, Idx);
5826     bool IsUndef = Record[Idx++];
5827     PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5828   }
5829
5830   // Includes
5831   for (unsigned N = Record[Idx++]; N; --N) {
5832     PPOpts.Includes.push_back(ReadString(Record, Idx));
5833   }
5834
5835   // Macro Includes
5836   for (unsigned N = Record[Idx++]; N; --N) {
5837     PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5838   }
5839
5840   PPOpts.UsePredefines = Record[Idx++];
5841   PPOpts.DetailedRecord = Record[Idx++];
5842   PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
5843   PPOpts.ObjCXXARCStandardLibrary =
5844     static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5845   SuggestedPredefines.clear();
5846   return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5847                                           SuggestedPredefines);
5848 }
5849
5850 std::pair<ModuleFile *, unsigned>
5851 ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5852   GlobalPreprocessedEntityMapType::iterator
5853   I = GlobalPreprocessedEntityMap.find(GlobalIndex);
5854   assert(I != GlobalPreprocessedEntityMap.end() &&
5855          "Corrupted global preprocessed entity map");
5856   ModuleFile *M = I->second;
5857   unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5858   return std::make_pair(M, LocalIndex);
5859 }
5860
5861 llvm::iterator_range<PreprocessingRecord::iterator>
5862 ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5863   if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5864     return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5865                                              Mod.NumPreprocessedEntities);
5866
5867   return llvm::make_range(PreprocessingRecord::iterator(),
5868                           PreprocessingRecord::iterator());
5869 }
5870
5871 llvm::iterator_range<ASTReader::ModuleDeclIterator>
5872 ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
5873   return llvm::make_range(
5874       ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5875       ModuleDeclIterator(this, &Mod,
5876                          Mod.FileSortedDecls + Mod.NumFileSortedDecls));
5877 }
5878
5879 SourceRange ASTReader::ReadSkippedRange(unsigned GlobalIndex) {
5880   auto I = GlobalSkippedRangeMap.find(GlobalIndex);
5881   assert(I != GlobalSkippedRangeMap.end() &&
5882     "Corrupted global skipped range map");
5883   ModuleFile *M = I->second;
5884   unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
5885   assert(LocalIndex < M->NumPreprocessedSkippedRanges);
5886   PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
5887   SourceRange Range(TranslateSourceLocation(*M, RawRange.getBegin()),
5888                     TranslateSourceLocation(*M, RawRange.getEnd()));
5889   assert(Range.isValid());
5890   return Range;
5891 }
5892
5893 PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5894   PreprocessedEntityID PPID = Index+1;
5895   std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5896   ModuleFile &M = *PPInfo.first;
5897   unsigned LocalIndex = PPInfo.second;
5898   const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5899
5900   if (!PP.getPreprocessingRecord()) {
5901     Error("no preprocessing record");
5902     return nullptr;
5903   }
5904
5905   SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
5906   if (llvm::Error Err =
5907           M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset)) {
5908     Error(std::move(Err));
5909     return nullptr;
5910   }
5911
5912   Expected<llvm::BitstreamEntry> MaybeEntry =
5913       M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5914   if (!MaybeEntry) {
5915     Error(MaybeEntry.takeError());
5916     return nullptr;
5917   }
5918   llvm::BitstreamEntry Entry = MaybeEntry.get();
5919
5920   if (Entry.Kind != llvm::BitstreamEntry::Record)
5921     return nullptr;
5922
5923   // Read the record.
5924   SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5925                     TranslateSourceLocation(M, PPOffs.getEnd()));
5926   PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
5927   StringRef Blob;
5928   RecordData Record;
5929   Expected<unsigned> MaybeRecType =
5930       M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
5931   if (!MaybeRecType) {
5932     Error(MaybeRecType.takeError());
5933     return nullptr;
5934   }
5935   switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
5936   case PPD_MACRO_EXPANSION: {
5937     bool isBuiltin = Record[0];
5938     IdentifierInfo *Name = nullptr;
5939     MacroDefinitionRecord *Def = nullptr;
5940     if (isBuiltin)
5941       Name = getLocalIdentifier(M, Record[1]);
5942     else {
5943       PreprocessedEntityID GlobalID =
5944           getGlobalPreprocessedEntityID(M, Record[1]);
5945       Def = cast<MacroDefinitionRecord>(
5946           PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
5947     }
5948
5949     MacroExpansion *ME;
5950     if (isBuiltin)
5951       ME = new (PPRec) MacroExpansion(Name, Range);
5952     else
5953       ME = new (PPRec) MacroExpansion(Def, Range);
5954
5955     return ME;
5956   }
5957
5958   case PPD_MACRO_DEFINITION: {
5959     // Decode the identifier info and then check again; if the macro is
5960     // still defined and associated with the identifier,
5961     IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
5962     MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
5963
5964     if (DeserializationListener)
5965       DeserializationListener->MacroDefinitionRead(PPID, MD);
5966
5967     return MD;
5968   }
5969
5970   case PPD_INCLUSION_DIRECTIVE: {
5971     const char *FullFileNameStart = Blob.data() + Record[0];
5972     StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
5973     const FileEntry *File = nullptr;
5974     if (!FullFileName.empty())
5975       if (auto FE = PP.getFileManager().getFile(FullFileName))
5976         File = *FE;
5977
5978     // FIXME: Stable encoding
5979     InclusionDirective::InclusionKind Kind
5980       = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5981     InclusionDirective *ID
5982       = new (PPRec) InclusionDirective(PPRec, Kind,
5983                                        StringRef(Blob.data(), Record[0]),
5984                                        Record[1], Record[3],
5985                                        File,
5986                                        Range);
5987     return ID;
5988   }
5989   }
5990
5991   llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5992 }
5993
5994 /// Find the next module that contains entities and return the ID
5995 /// of the first entry.
5996 ///
5997 /// \param SLocMapI points at a chunk of a module that contains no
5998 /// preprocessed entities or the entities it contains are not the ones we are
5999 /// looking for.
6000 PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
6001                        GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
6002   ++SLocMapI;
6003   for (GlobalSLocOffsetMapType::const_iterator
6004          EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
6005     ModuleFile &M = *SLocMapI->second;
6006     if (M.NumPreprocessedEntities)
6007       return M.BasePreprocessedEntityID;
6008   }
6009
6010   return getTotalNumPreprocessedEntities();
6011 }
6012
6013 namespace {
6014
6015 struct PPEntityComp {
6016   const ASTReader &Reader;
6017   ModuleFile &M;
6018
6019   PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
6020
6021   bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
6022     SourceLocation LHS = getLoc(L);
6023     SourceLocation RHS = getLoc(R);
6024     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6025   }
6026
6027   bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
6028     SourceLocation LHS = getLoc(L);
6029     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6030   }
6031
6032   bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
6033     SourceLocation RHS = getLoc(R);
6034     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6035   }
6036
6037   SourceLocation getLoc(const PPEntityOffset &PPE) const {
6038     return Reader.TranslateSourceLocation(M, PPE.getBegin());
6039   }
6040 };
6041
6042 } // namespace
6043
6044 PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
6045                                                        bool EndsAfter) const {
6046   if (SourceMgr.isLocalSourceLocation(Loc))
6047     return getTotalNumPreprocessedEntities();
6048
6049   GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
6050       SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
6051   assert(SLocMapI != GlobalSLocOffsetMap.end() &&
6052          "Corrupted global sloc offset map");
6053
6054   if (SLocMapI->second->NumPreprocessedEntities == 0)
6055     return findNextPreprocessedEntity(SLocMapI);
6056
6057   ModuleFile &M = *SLocMapI->second;
6058
6059   using pp_iterator = const PPEntityOffset *;
6060
6061   pp_iterator pp_begin = M.PreprocessedEntityOffsets;
6062   pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
6063
6064   size_t Count = M.NumPreprocessedEntities;
6065   size_t Half;
6066   pp_iterator First = pp_begin;
6067   pp_iterator PPI;
6068
6069   if (EndsAfter) {
6070     PPI = std::upper_bound(pp_begin, pp_end, Loc,
6071                            PPEntityComp(*this, M));
6072   } else {
6073     // Do a binary search manually instead of using std::lower_bound because
6074     // The end locations of entities may be unordered (when a macro expansion
6075     // is inside another macro argument), but for this case it is not important
6076     // whether we get the first macro expansion or its containing macro.
6077     while (Count > 0) {
6078       Half = Count / 2;
6079       PPI = First;
6080       std::advance(PPI, Half);
6081       if (SourceMgr.isBeforeInTranslationUnit(
6082               TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
6083         First = PPI;
6084         ++First;
6085         Count = Count - Half - 1;
6086       } else
6087         Count = Half;
6088     }
6089   }
6090
6091   if (PPI == pp_end)
6092     return findNextPreprocessedEntity(SLocMapI);
6093
6094   return M.BasePreprocessedEntityID + (PPI - pp_begin);
6095 }
6096
6097 /// Returns a pair of [Begin, End) indices of preallocated
6098 /// preprocessed entities that \arg Range encompasses.
6099 std::pair<unsigned, unsigned>
6100     ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
6101   if (Range.isInvalid())
6102     return std::make_pair(0,0);
6103   assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
6104
6105   PreprocessedEntityID BeginID =
6106       findPreprocessedEntity(Range.getBegin(), false);
6107   PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
6108   return std::make_pair(BeginID, EndID);
6109 }
6110
6111 /// Optionally returns true or false if the preallocated preprocessed
6112 /// entity with index \arg Index came from file \arg FID.
6113 Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
6114                                                              FileID FID) {
6115   if (FID.isInvalid())
6116     return false;
6117
6118   std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6119   ModuleFile &M = *PPInfo.first;
6120   unsigned LocalIndex = PPInfo.second;
6121   const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
6122
6123   SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
6124   if (Loc.isInvalid())
6125     return false;
6126
6127   if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
6128     return true;
6129   else
6130     return false;
6131 }
6132
6133 namespace {
6134
6135   /// Visitor used to search for information about a header file.
6136   class HeaderFileInfoVisitor {
6137     const FileEntry *FE;
6138     Optional<HeaderFileInfo> HFI;
6139
6140   public:
6141     explicit HeaderFileInfoVisitor(const FileEntry *FE) : FE(FE) {}
6142
6143     bool operator()(ModuleFile &M) {
6144       HeaderFileInfoLookupTable *Table
6145         = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
6146       if (!Table)
6147         return false;
6148
6149       // Look in the on-disk hash table for an entry for this file name.
6150       HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
6151       if (Pos == Table->end())
6152         return false;
6153
6154       HFI = *Pos;
6155       return true;
6156     }
6157
6158     Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
6159   };
6160
6161 } // namespace
6162
6163 HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
6164   HeaderFileInfoVisitor Visitor(FE);
6165   ModuleMgr.visit(Visitor);
6166   if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
6167     return *HFI;
6168
6169   return HeaderFileInfo();
6170 }
6171
6172 void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
6173   using DiagState = DiagnosticsEngine::DiagState;
6174   SmallVector<DiagState *, 32> DiagStates;
6175
6176   for (ModuleFile &F : ModuleMgr) {
6177     unsigned Idx = 0;
6178     auto &Record = F.PragmaDiagMappings;
6179     if (Record.empty())
6180       continue;
6181
6182     DiagStates.clear();
6183
6184     auto ReadDiagState =
6185         [&](const DiagState &BasedOn, SourceLocation Loc,
6186             bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
6187       unsigned BackrefID = Record[Idx++];
6188       if (BackrefID != 0)
6189         return DiagStates[BackrefID - 1];
6190
6191       // A new DiagState was created here.
6192       Diag.DiagStates.push_back(BasedOn);
6193       DiagState *NewState = &Diag.DiagStates.back();
6194       DiagStates.push_back(NewState);
6195       unsigned Size = Record[Idx++];
6196       assert(Idx + Size * 2 <= Record.size() &&
6197              "Invalid data, not enough diag/map pairs");
6198       while (Size--) {
6199         unsigned DiagID = Record[Idx++];
6200         DiagnosticMapping NewMapping =
6201             DiagnosticMapping::deserialize(Record[Idx++]);
6202         if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
6203           continue;
6204
6205         DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
6206
6207         // If this mapping was specified as a warning but the severity was
6208         // upgraded due to diagnostic settings, simulate the current diagnostic
6209         // settings (and use a warning).
6210         if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
6211           NewMapping.setSeverity(diag::Severity::Warning);
6212           NewMapping.setUpgradedFromWarning(false);
6213         }
6214
6215         Mapping = NewMapping;
6216       }
6217       return NewState;
6218     };
6219
6220     // Read the first state.
6221     DiagState *FirstState;
6222     if (F.Kind == MK_ImplicitModule) {
6223       // Implicitly-built modules are reused with different diagnostic
6224       // settings.  Use the initial diagnostic state from Diag to simulate this
6225       // compilation's diagnostic settings.
6226       FirstState = Diag.DiagStatesByLoc.FirstDiagState;
6227       DiagStates.push_back(FirstState);
6228
6229       // Skip the initial diagnostic state from the serialized module.
6230       assert(Record[1] == 0 &&
6231              "Invalid data, unexpected backref in initial state");
6232       Idx = 3 + Record[2] * 2;
6233       assert(Idx < Record.size() &&
6234              "Invalid data, not enough state change pairs in initial state");
6235     } else if (F.isModule()) {
6236       // For an explicit module, preserve the flags from the module build
6237       // command line (-w, -Weverything, -Werror, ...) along with any explicit
6238       // -Wblah flags.
6239       unsigned Flags = Record[Idx++];
6240       DiagState Initial;
6241       Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
6242       Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
6243       Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
6244       Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
6245       Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
6246       Initial.ExtBehavior = (diag::Severity)Flags;
6247       FirstState = ReadDiagState(Initial, SourceLocation(), true);
6248
6249       assert(F.OriginalSourceFileID.isValid());
6250
6251       // Set up the root buffer of the module to start with the initial
6252       // diagnostic state of the module itself, to cover files that contain no
6253       // explicit transitions (for which we did not serialize anything).
6254       Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
6255           .StateTransitions.push_back({FirstState, 0});
6256     } else {
6257       // For prefix ASTs, start with whatever the user configured on the
6258       // command line.
6259       Idx++; // Skip flags.
6260       FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState,
6261                                  SourceLocation(), false);
6262     }
6263
6264     // Read the state transitions.
6265     unsigned NumLocations = Record[Idx++];
6266     while (NumLocations--) {
6267       assert(Idx < Record.size() &&
6268              "Invalid data, missing pragma diagnostic states");
6269       SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
6270       auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
6271       assert(IDAndOffset.first.isValid() && "invalid FileID for transition");
6272       assert(IDAndOffset.second == 0 && "not a start location for a FileID");
6273       unsigned Transitions = Record[Idx++];
6274
6275       // Note that we don't need to set up Parent/ParentOffset here, because
6276       // we won't be changing the diagnostic state within imported FileIDs
6277       // (other than perhaps appending to the main source file, which has no
6278       // parent).
6279       auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
6280       F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
6281       for (unsigned I = 0; I != Transitions; ++I) {
6282         unsigned Offset = Record[Idx++];
6283         auto *State =
6284             ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
6285         F.StateTransitions.push_back({State, Offset});
6286       }
6287     }
6288
6289     // Read the final state.
6290     assert(Idx < Record.size() &&
6291            "Invalid data, missing final pragma diagnostic state");
6292     SourceLocation CurStateLoc =
6293         ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
6294     auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
6295
6296     if (!F.isModule()) {
6297       Diag.DiagStatesByLoc.CurDiagState = CurState;
6298       Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
6299
6300       // Preserve the property that the imaginary root file describes the
6301       // current state.
6302       FileID NullFile;
6303       auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
6304       if (T.empty())
6305         T.push_back({CurState, 0});
6306       else
6307         T[0].State = CurState;
6308     }
6309
6310     // Don't try to read these mappings again.
6311     Record.clear();
6312   }
6313 }
6314
6315 /// Get the correct cursor and offset for loading a type.
6316 ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
6317   GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
6318   assert(I != GlobalTypeMap.end() && "Corrupted global type map");
6319   ModuleFile *M = I->second;
6320   return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
6321 }
6322
6323 static llvm::Optional<Type::TypeClass> getTypeClassForCode(TypeCode code) {
6324   switch (code) {
6325 #define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
6326   case TYPE_##CODE_ID: return Type::CLASS_ID;
6327 #include "clang/Serialization/TypeBitCodes.def"
6328   default: return llvm::None;
6329   }
6330 }
6331
6332 /// Read and return the type with the given index..
6333 ///
6334 /// The index is the type ID, shifted and minus the number of predefs. This
6335 /// routine actually reads the record corresponding to the type at the given
6336 /// location. It is a helper routine for GetType, which deals with reading type
6337 /// IDs.
6338 QualType ASTReader::readTypeRecord(unsigned Index) {
6339   assert(ContextObj && "reading type with no AST context");
6340   ASTContext &Context = *ContextObj;
6341   RecordLocation Loc = TypeCursorForIndex(Index);
6342   BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
6343
6344   // Keep track of where we are in the stream, then jump back there
6345   // after reading this type.
6346   SavedStreamPosition SavedPosition(DeclsCursor);
6347
6348   ReadingKindTracker ReadingKind(Read_Type, *this);
6349
6350   // Note that we are loading a type record.
6351   Deserializing AType(this);
6352
6353   if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
6354     Error(std::move(Err));
6355     return QualType();
6356   }
6357   Expected<unsigned> RawCode = DeclsCursor.ReadCode();
6358   if (!RawCode) {
6359     Error(RawCode.takeError());
6360     return QualType();
6361   }
6362
6363   ASTRecordReader Record(*this, *Loc.F);
6364   Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get());
6365   if (!Code) {
6366     Error(Code.takeError());
6367     return QualType();
6368   }
6369   if (Code.get() == TYPE_EXT_QUAL) {
6370     QualType baseType = Record.readQualType();
6371     Qualifiers quals = Record.readQualifiers();
6372     return Context.getQualifiedType(baseType, quals);
6373   }
6374
6375   auto maybeClass = getTypeClassForCode((TypeCode) Code.get());
6376   if (!maybeClass) {
6377     Error("Unexpected code for type");
6378     return QualType();
6379   }
6380
6381   serialization::AbstractTypeReader<ASTRecordReader> TypeReader(Record);
6382   return TypeReader.read(*maybeClass);
6383 }
6384
6385 namespace clang {
6386
6387 class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
6388   ASTRecordReader &Reader;
6389
6390   SourceLocation readSourceLocation() {
6391     return Reader.readSourceLocation();
6392   }
6393
6394   TypeSourceInfo *GetTypeSourceInfo() {
6395     return Reader.readTypeSourceInfo();
6396   }
6397
6398   NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6399     return Reader.readNestedNameSpecifierLoc();
6400   }
6401
6402   Attr *ReadAttr() {
6403     return Reader.readAttr();
6404   }
6405
6406 public:
6407   TypeLocReader(ASTRecordReader &Reader) : Reader(Reader) {}
6408
6409   // We want compile-time assurance that we've enumerated all of
6410   // these, so unfortunately we have to declare them first, then
6411   // define them out-of-line.
6412 #define ABSTRACT_TYPELOC(CLASS, PARENT)
6413 #define TYPELOC(CLASS, PARENT) \
6414   void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6415 #include "clang/AST/TypeLocNodes.def"
6416
6417   void VisitFunctionTypeLoc(FunctionTypeLoc);
6418   void VisitArrayTypeLoc(ArrayTypeLoc);
6419 };
6420
6421 } // namespace clang
6422
6423 void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6424   // nothing to do
6425 }
6426
6427 void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6428   TL.setBuiltinLoc(readSourceLocation());
6429   if (TL.needsExtraLocalData()) {
6430     TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt()));
6431     TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Reader.readInt()));
6432     TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Reader.readInt()));
6433     TL.setModeAttr(Reader.readInt());
6434   }
6435 }
6436
6437 void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
6438   TL.setNameLoc(readSourceLocation());
6439 }
6440
6441 void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
6442   TL.setStarLoc(readSourceLocation());
6443 }
6444
6445 void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6446   // nothing to do
6447 }
6448
6449 void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6450   // nothing to do
6451 }
6452
6453 void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6454   TL.setExpansionLoc(readSourceLocation());
6455 }
6456
6457 void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6458   TL.setCaretLoc(readSourceLocation());
6459 }
6460
6461 void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6462   TL.setAmpLoc(readSourceLocation());
6463 }
6464
6465 void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6466   TL.setAmpAmpLoc(readSourceLocation());
6467 }
6468
6469 void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6470   TL.setStarLoc(readSourceLocation());
6471   TL.setClassTInfo(GetTypeSourceInfo());
6472 }
6473
6474 void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
6475   TL.setLBracketLoc(readSourceLocation());
6476   TL.setRBracketLoc(readSourceLocation());
6477   if (Reader.readBool())
6478     TL.setSizeExpr(Reader.readExpr());
6479   else
6480     TL.setSizeExpr(nullptr);
6481 }
6482
6483 void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6484   VisitArrayTypeLoc(TL);
6485 }
6486
6487 void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6488   VisitArrayTypeLoc(TL);
6489 }
6490
6491 void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6492   VisitArrayTypeLoc(TL);
6493 }
6494
6495 void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6496                                             DependentSizedArrayTypeLoc TL) {
6497   VisitArrayTypeLoc(TL);
6498 }
6499
6500 void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
6501     DependentAddressSpaceTypeLoc TL) {
6502
6503     TL.setAttrNameLoc(readSourceLocation());
6504     TL.setAttrOperandParensRange(Reader.readSourceRange());
6505     TL.setAttrExprOperand(Reader.readExpr());
6506 }
6507
6508 void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6509                                         DependentSizedExtVectorTypeLoc TL) {
6510   TL.setNameLoc(readSourceLocation());
6511 }
6512
6513 void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
6514   TL.setNameLoc(readSourceLocation());
6515 }
6516
6517 void TypeLocReader::VisitDependentVectorTypeLoc(
6518     DependentVectorTypeLoc TL) {
6519   TL.setNameLoc(readSourceLocation());
6520 }
6521
6522 void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6523   TL.setNameLoc(readSourceLocation());
6524 }
6525
6526 void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
6527   TL.setLocalRangeBegin(readSourceLocation());
6528   TL.setLParenLoc(readSourceLocation());
6529   TL.setRParenLoc(readSourceLocation());
6530   TL.setExceptionSpecRange(Reader.readSourceRange());
6531   TL.setLocalRangeEnd(readSourceLocation());
6532   for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
6533     TL.setParam(i, Reader.readDeclAs<ParmVarDecl>());
6534   }
6535 }
6536
6537 void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6538   VisitFunctionTypeLoc(TL);
6539 }
6540
6541 void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6542   VisitFunctionTypeLoc(TL);
6543 }
6544
6545 void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
6546   TL.setNameLoc(readSourceLocation());
6547 }
6548
6549 void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
6550   TL.setNameLoc(readSourceLocation());
6551 }
6552
6553 void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6554   TL.setTypeofLoc(readSourceLocation());
6555   TL.setLParenLoc(readSourceLocation());
6556   TL.setRParenLoc(readSourceLocation());
6557 }
6558
6559 void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6560   TL.setTypeofLoc(readSourceLocation());
6561   TL.setLParenLoc(readSourceLocation());
6562   TL.setRParenLoc(readSourceLocation());
6563   TL.setUnderlyingTInfo(GetTypeSourceInfo());
6564 }
6565
6566 void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6567   TL.setNameLoc(readSourceLocation());
6568 }
6569
6570 void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6571   TL.setKWLoc(readSourceLocation());
6572   TL.setLParenLoc(readSourceLocation());
6573   TL.setRParenLoc(readSourceLocation());
6574   TL.setUnderlyingTInfo(GetTypeSourceInfo());
6575 }
6576
6577 void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
6578   TL.setNameLoc(readSourceLocation());
6579   if (Reader.readBool()) {
6580     TL.setNestedNameSpecifierLoc(ReadNestedNameSpecifierLoc());
6581     TL.setTemplateKWLoc(readSourceLocation());
6582     TL.setConceptNameLoc(readSourceLocation());
6583     TL.setFoundDecl(Reader.readDeclAs<NamedDecl>());
6584     TL.setLAngleLoc(readSourceLocation());
6585     TL.setRAngleLoc(readSourceLocation());
6586     for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
6587       TL.setArgLocInfo(i, Reader.readTemplateArgumentLocInfo(
6588                               TL.getTypePtr()->getArg(i).getKind()));
6589   }
6590 }
6591
6592 void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6593     DeducedTemplateSpecializationTypeLoc TL) {
6594   TL.setTemplateNameLoc(readSourceLocation());
6595 }
6596
6597 void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
6598   TL.setNameLoc(readSourceLocation());
6599 }
6600
6601 void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
6602   TL.setNameLoc(readSourceLocation());
6603 }
6604
6605 void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6606   TL.setAttr(ReadAttr());
6607 }
6608
6609 void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
6610   TL.setNameLoc(readSourceLocation());
6611 }
6612
6613 void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6614                                             SubstTemplateTypeParmTypeLoc TL) {
6615   TL.setNameLoc(readSourceLocation());
6616 }
6617
6618 void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6619                                           SubstTemplateTypeParmPackTypeLoc TL) {
6620   TL.setNameLoc(readSourceLocation());
6621 }
6622
6623 void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6624                                            TemplateSpecializationTypeLoc TL) {
6625   TL.setTemplateKeywordLoc(readSourceLocation());
6626   TL.setTemplateNameLoc(readSourceLocation());
6627   TL.setLAngleLoc(readSourceLocation());
6628   TL.setRAngleLoc(readSourceLocation());
6629   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
6630     TL.setArgLocInfo(
6631         i,
6632         Reader.readTemplateArgumentLocInfo(
6633           TL.getTypePtr()->getArg(i).getKind()));
6634 }
6635
6636 void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
6637   TL.setLParenLoc(readSourceLocation());
6638   TL.setRParenLoc(readSourceLocation());
6639 }
6640
6641 void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
6642   TL.setElaboratedKeywordLoc(readSourceLocation());
6643   TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6644 }
6645
6646 void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
6647   TL.setNameLoc(readSourceLocation());
6648 }
6649
6650 void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6651   TL.setElaboratedKeywordLoc(readSourceLocation());
6652   TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6653   TL.setNameLoc(readSourceLocation());
6654 }
6655
6656 void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6657        DependentTemplateSpecializationTypeLoc TL) {
6658   TL.setElaboratedKeywordLoc(readSourceLocation());
6659   TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6660   TL.setTemplateKeywordLoc(readSourceLocation());
6661   TL.setTemplateNameLoc(readSourceLocation());
6662   TL.setLAngleLoc(readSourceLocation());
6663   TL.setRAngleLoc(readSourceLocation());
6664   for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
6665     TL.setArgLocInfo(
6666         I,
6667         Reader.readTemplateArgumentLocInfo(
6668             TL.getTypePtr()->getArg(I).getKind()));
6669 }
6670
6671 void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
6672   TL.setEllipsisLoc(readSourceLocation());
6673 }
6674
6675 void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
6676   TL.setNameLoc(readSourceLocation());
6677 }
6678
6679 void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6680   if (TL.getNumProtocols()) {
6681     TL.setProtocolLAngleLoc(readSourceLocation());
6682     TL.setProtocolRAngleLoc(readSourceLocation());
6683   }
6684   for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
6685     TL.setProtocolLoc(i, readSourceLocation());
6686 }
6687
6688 void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
6689   TL.setHasBaseTypeAsWritten(Reader.readBool());
6690   TL.setTypeArgsLAngleLoc(readSourceLocation());
6691   TL.setTypeArgsRAngleLoc(readSourceLocation());
6692   for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
6693     TL.setTypeArgTInfo(i, GetTypeSourceInfo());
6694   TL.setProtocolLAngleLoc(readSourceLocation());
6695   TL.setProtocolRAngleLoc(readSourceLocation());
6696   for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
6697     TL.setProtocolLoc(i, readSourceLocation());
6698 }
6699
6700 void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6701   TL.setStarLoc(readSourceLocation());
6702 }
6703
6704 void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6705   TL.setKWLoc(readSourceLocation());
6706   TL.setLParenLoc(readSourceLocation());
6707   TL.setRParenLoc(readSourceLocation());
6708 }
6709
6710 void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
6711   TL.setKWLoc(readSourceLocation());
6712 }
6713
6714 void ASTRecordReader::readTypeLoc(TypeLoc TL) {
6715   TypeLocReader TLR(*this);
6716   for (; !TL.isNull(); TL = TL.getNextTypeLoc())
6717     TLR.Visit(TL);
6718 }
6719
6720 TypeSourceInfo *ASTRecordReader::readTypeSourceInfo() {
6721   QualType InfoTy = readType();
6722   if (InfoTy.isNull())
6723     return nullptr;
6724
6725   TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
6726   readTypeLoc(TInfo->getTypeLoc());
6727   return TInfo;
6728 }
6729
6730 QualType ASTReader::GetType(TypeID ID) {
6731   assert(ContextObj && "reading type with no AST context");
6732   ASTContext &Context = *ContextObj;
6733
6734   unsigned FastQuals = ID & Qualifiers::FastMask;
6735   unsigned Index = ID >> Qualifiers::FastWidth;
6736
6737   if (Index < NUM_PREDEF_TYPE_IDS) {
6738     QualType T;
6739     switch ((PredefinedTypeIDs)Index) {
6740     case PREDEF_TYPE_NULL_ID:
6741       return QualType();
6742     case PREDEF_TYPE_VOID_ID:
6743       T = Context.VoidTy;
6744       break;
6745     case PREDEF_TYPE_BOOL_ID:
6746       T = Context.BoolTy;
6747       break;
6748     case PREDEF_TYPE_CHAR_U_ID:
6749     case PREDEF_TYPE_CHAR_S_ID:
6750       // FIXME: Check that the signedness of CharTy is correct!
6751       T = Context.CharTy;
6752       break;
6753     case PREDEF_TYPE_UCHAR_ID:
6754       T = Context.UnsignedCharTy;
6755       break;
6756     case PREDEF_TYPE_USHORT_ID:
6757       T = Context.UnsignedShortTy;
6758       break;
6759     case PREDEF_TYPE_UINT_ID:
6760       T = Context.UnsignedIntTy;
6761       break;
6762     case PREDEF_TYPE_ULONG_ID:
6763       T = Context.UnsignedLongTy;
6764       break;
6765     case PREDEF_TYPE_ULONGLONG_ID:
6766       T = Context.UnsignedLongLongTy;
6767       break;
6768     case PREDEF_TYPE_UINT128_ID:
6769       T = Context.UnsignedInt128Ty;
6770       break;
6771     case PREDEF_TYPE_SCHAR_ID:
6772       T = Context.SignedCharTy;
6773       break;
6774     case PREDEF_TYPE_WCHAR_ID:
6775       T = Context.WCharTy;
6776       break;
6777     case PREDEF_TYPE_SHORT_ID:
6778       T = Context.ShortTy;
6779       break;
6780     case PREDEF_TYPE_INT_ID:
6781       T = Context.IntTy;
6782       break;
6783     case PREDEF_TYPE_LONG_ID:
6784       T = Context.LongTy;
6785       break;
6786     case PREDEF_TYPE_LONGLONG_ID:
6787       T = Context.LongLongTy;
6788       break;
6789     case PREDEF_TYPE_INT128_ID:
6790       T = Context.Int128Ty;
6791       break;
6792     case PREDEF_TYPE_HALF_ID:
6793       T = Context.HalfTy;
6794       break;
6795     case PREDEF_TYPE_FLOAT_ID:
6796       T = Context.FloatTy;
6797       break;
6798     case PREDEF_TYPE_DOUBLE_ID:
6799       T = Context.DoubleTy;
6800       break;
6801     case PREDEF_TYPE_LONGDOUBLE_ID:
6802       T = Context.LongDoubleTy;
6803       break;
6804     case PREDEF_TYPE_SHORT_ACCUM_ID:
6805       T = Context.ShortAccumTy;
6806       break;
6807     case PREDEF_TYPE_ACCUM_ID:
6808       T = Context.AccumTy;
6809       break;
6810     case PREDEF_TYPE_LONG_ACCUM_ID:
6811       T = Context.LongAccumTy;
6812       break;
6813     case PREDEF_TYPE_USHORT_ACCUM_ID:
6814       T = Context.UnsignedShortAccumTy;
6815       break;
6816     case PREDEF_TYPE_UACCUM_ID:
6817       T = Context.UnsignedAccumTy;
6818       break;
6819     case PREDEF_TYPE_ULONG_ACCUM_ID:
6820       T = Context.UnsignedLongAccumTy;
6821       break;
6822     case PREDEF_TYPE_SHORT_FRACT_ID:
6823       T = Context.ShortFractTy;
6824       break;
6825     case PREDEF_TYPE_FRACT_ID:
6826       T = Context.FractTy;
6827       break;
6828     case PREDEF_TYPE_LONG_FRACT_ID:
6829       T = Context.LongFractTy;
6830       break;
6831     case PREDEF_TYPE_USHORT_FRACT_ID:
6832       T = Context.UnsignedShortFractTy;
6833       break;
6834     case PREDEF_TYPE_UFRACT_ID:
6835       T = Context.UnsignedFractTy;
6836       break;
6837     case PREDEF_TYPE_ULONG_FRACT_ID:
6838       T = Context.UnsignedLongFractTy;
6839       break;
6840     case PREDEF_TYPE_SAT_SHORT_ACCUM_ID:
6841       T = Context.SatShortAccumTy;
6842       break;
6843     case PREDEF_TYPE_SAT_ACCUM_ID:
6844       T = Context.SatAccumTy;
6845       break;
6846     case PREDEF_TYPE_SAT_LONG_ACCUM_ID:
6847       T = Context.SatLongAccumTy;
6848       break;
6849     case PREDEF_TYPE_SAT_USHORT_ACCUM_ID:
6850       T = Context.SatUnsignedShortAccumTy;
6851       break;
6852     case PREDEF_TYPE_SAT_UACCUM_ID:
6853       T = Context.SatUnsignedAccumTy;
6854       break;
6855     case PREDEF_TYPE_SAT_ULONG_ACCUM_ID:
6856       T = Context.SatUnsignedLongAccumTy;
6857       break;
6858     case PREDEF_TYPE_SAT_SHORT_FRACT_ID:
6859       T = Context.SatShortFractTy;
6860       break;
6861     case PREDEF_TYPE_SAT_FRACT_ID:
6862       T = Context.SatFractTy;
6863       break;
6864     case PREDEF_TYPE_SAT_LONG_FRACT_ID:
6865       T = Context.SatLongFractTy;
6866       break;
6867     case PREDEF_TYPE_SAT_USHORT_FRACT_ID:
6868       T = Context.SatUnsignedShortFractTy;
6869       break;
6870     case PREDEF_TYPE_SAT_UFRACT_ID:
6871       T = Context.SatUnsignedFractTy;
6872       break;
6873     case PREDEF_TYPE_SAT_ULONG_FRACT_ID:
6874       T = Context.SatUnsignedLongFractTy;
6875       break;
6876     case PREDEF_TYPE_FLOAT16_ID:
6877       T = Context.Float16Ty;
6878       break;
6879     case PREDEF_TYPE_FLOAT128_ID:
6880       T = Context.Float128Ty;
6881       break;
6882     case PREDEF_TYPE_OVERLOAD_ID:
6883       T = Context.OverloadTy;
6884       break;
6885     case PREDEF_TYPE_BOUND_MEMBER:
6886       T = Context.BoundMemberTy;
6887       break;
6888     case PREDEF_TYPE_PSEUDO_OBJECT:
6889       T = Context.PseudoObjectTy;
6890       break;
6891     case PREDEF_TYPE_DEPENDENT_ID:
6892       T = Context.DependentTy;
6893       break;
6894     case PREDEF_TYPE_UNKNOWN_ANY:
6895       T = Context.UnknownAnyTy;
6896       break;
6897     case PREDEF_TYPE_NULLPTR_ID:
6898       T = Context.NullPtrTy;
6899       break;
6900     case PREDEF_TYPE_CHAR8_ID:
6901       T = Context.Char8Ty;
6902       break;
6903     case PREDEF_TYPE_CHAR16_ID:
6904       T = Context.Char16Ty;
6905       break;
6906     case PREDEF_TYPE_CHAR32_ID:
6907       T = Context.Char32Ty;
6908       break;
6909     case PREDEF_TYPE_OBJC_ID:
6910       T = Context.ObjCBuiltinIdTy;
6911       break;
6912     case PREDEF_TYPE_OBJC_CLASS:
6913       T = Context.ObjCBuiltinClassTy;
6914       break;
6915     case PREDEF_TYPE_OBJC_SEL:
6916       T = Context.ObjCBuiltinSelTy;
6917       break;
6918 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6919     case PREDEF_TYPE_##Id##_ID: \
6920       T = Context.SingletonId; \
6921       break;
6922 #include "clang/Basic/OpenCLImageTypes.def"
6923 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6924     case PREDEF_TYPE_##Id##_ID: \
6925       T = Context.Id##Ty; \
6926       break;
6927 #include "clang/Basic/OpenCLExtensionTypes.def"
6928     case PREDEF_TYPE_SAMPLER_ID:
6929       T = Context.OCLSamplerTy;
6930       break;
6931     case PREDEF_TYPE_EVENT_ID:
6932       T = Context.OCLEventTy;
6933       break;
6934     case PREDEF_TYPE_CLK_EVENT_ID:
6935       T = Context.OCLClkEventTy;
6936       break;
6937     case PREDEF_TYPE_QUEUE_ID:
6938       T = Context.OCLQueueTy;
6939       break;
6940     case PREDEF_TYPE_RESERVE_ID_ID:
6941       T = Context.OCLReserveIDTy;
6942       break;
6943     case PREDEF_TYPE_AUTO_DEDUCT:
6944       T = Context.getAutoDeductType();
6945       break;
6946     case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6947       T = Context.getAutoRRefDeductType();
6948       break;
6949     case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6950       T = Context.ARCUnbridgedCastTy;
6951       break;
6952     case PREDEF_TYPE_BUILTIN_FN:
6953       T = Context.BuiltinFnTy;
6954       break;
6955     case PREDEF_TYPE_OMP_ARRAY_SECTION:
6956       T = Context.OMPArraySectionTy;
6957       break;
6958 #define SVE_TYPE(Name, Id, SingletonId) \
6959     case PREDEF_TYPE_##Id##_ID: \
6960       T = Context.SingletonId; \
6961       break;
6962 #include "clang/Basic/AArch64SVEACLETypes.def"
6963     }
6964
6965     assert(!T.isNull() && "Unknown predefined type");
6966     return T.withFastQualifiers(FastQuals);
6967   }
6968
6969   Index -= NUM_PREDEF_TYPE_IDS;
6970   assert(Index < TypesLoaded.size() && "Type index out-of-range");
6971   if (TypesLoaded[Index].isNull()) {
6972     TypesLoaded[Index] = readTypeRecord(Index);
6973     if (TypesLoaded[Index].isNull())
6974       return QualType();
6975
6976     TypesLoaded[Index]->setFromAST();
6977     if (DeserializationListener)
6978       DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6979                                         TypesLoaded[Index]);
6980   }
6981
6982   return TypesLoaded[Index].withFastQualifiers(FastQuals);
6983 }
6984
6985 QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6986   return GetType(getGlobalTypeID(F, LocalID));
6987 }
6988
6989 serialization::TypeID
6990 ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6991   unsigned FastQuals = LocalID & Qualifiers::FastMask;
6992   unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
6993
6994   if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6995     return LocalID;
6996
6997   if (!F.ModuleOffsetMap.empty())
6998     ReadModuleOffsetMap(F);
6999
7000   ContinuousRangeMap<uint32_t, int, 2>::iterator I
7001     = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
7002   assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
7003
7004   unsigned GlobalIndex = LocalIndex + I->second;
7005   return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
7006 }
7007
7008 TemplateArgumentLocInfo
7009 ASTRecordReader::readTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind) {
7010   switch (Kind) {
7011   case TemplateArgument::Expression:
7012     return readExpr();
7013   case TemplateArgument::Type:
7014     return readTypeSourceInfo();
7015   case TemplateArgument::Template: {
7016     NestedNameSpecifierLoc QualifierLoc =
7017       readNestedNameSpecifierLoc();
7018     SourceLocation TemplateNameLoc = readSourceLocation();
7019     return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
7020                                    SourceLocation());
7021   }
7022   case TemplateArgument::TemplateExpansion: {
7023     NestedNameSpecifierLoc QualifierLoc = readNestedNameSpecifierLoc();
7024     SourceLocation TemplateNameLoc = readSourceLocation();
7025     SourceLocation EllipsisLoc = readSourceLocation();
7026     return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
7027                                    EllipsisLoc);
7028   }
7029   case TemplateArgument::Null:
7030   case TemplateArgument::Integral:
7031   case TemplateArgument::Declaration:
7032   case TemplateArgument::NullPtr:
7033   case TemplateArgument::Pack:
7034     // FIXME: Is this right?
7035     return TemplateArgumentLocInfo();
7036   }
7037   llvm_unreachable("unexpected template argument loc");
7038 }
7039
7040 TemplateArgumentLoc ASTRecordReader::readTemplateArgumentLoc() {
7041   TemplateArgument Arg = readTemplateArgument();
7042
7043   if (Arg.getKind() == TemplateArgument::Expression) {
7044     if (readBool()) // bool InfoHasSameExpr.
7045       return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
7046   }
7047   return TemplateArgumentLoc(Arg, readTemplateArgumentLocInfo(Arg.getKind()));
7048 }
7049
7050 const ASTTemplateArgumentListInfo *
7051 ASTRecordReader::readASTTemplateArgumentListInfo() {
7052   SourceLocation LAngleLoc = readSourceLocation();
7053   SourceLocation RAngleLoc = readSourceLocation();
7054   unsigned NumArgsAsWritten = readInt();
7055   TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
7056   for (unsigned i = 0; i != NumArgsAsWritten; ++i)
7057     TemplArgsInfo.addArgument(readTemplateArgumentLoc());
7058   return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
7059 }
7060
7061 Decl *ASTReader::GetExternalDecl(uint32_t ID) {
7062   return GetDecl(ID);
7063 }
7064
7065 void ASTReader::CompleteRedeclChain(const Decl *D) {
7066   if (NumCurrentElementsDeserializing) {
7067     // We arrange to not care about the complete redeclaration chain while we're
7068     // deserializing. Just remember that the AST has marked this one as complete
7069     // but that it's not actually complete yet, so we know we still need to
7070     // complete it later.
7071     PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
7072     return;
7073   }
7074
7075   const DeclContext *DC = D->getDeclContext()->getRedeclContext();
7076
7077   // If this is a named declaration, complete it by looking it up
7078   // within its context.
7079   //
7080   // FIXME: Merging a function definition should merge
7081   // all mergeable entities within it.
7082   if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
7083       isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
7084     if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
7085       if (!getContext().getLangOpts().CPlusPlus &&
7086           isa<TranslationUnitDecl>(DC)) {
7087         // Outside of C++, we don't have a lookup table for the TU, so update
7088         // the identifier instead. (For C++ modules, we don't store decls
7089         // in the serialized identifier table, so we do the lookup in the TU.)
7090         auto *II = Name.getAsIdentifierInfo();
7091         assert(II && "non-identifier name in C?");
7092         if (II->isOutOfDate())
7093           updateOutOfDateIdentifier(*II);
7094       } else
7095         DC->lookup(Name);
7096     } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
7097       // Find all declarations of this kind from the relevant context.
7098       for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
7099         auto *DC = cast<DeclContext>(DCDecl);
7100         SmallVector<Decl*, 8> Decls;
7101         FindExternalLexicalDecls(
7102             DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
7103       }
7104     }
7105   }
7106
7107   if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
7108     CTSD->getSpecializedTemplate()->LoadLazySpecializations();
7109   if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
7110     VTSD->getSpecializedTemplate()->LoadLazySpecializations();
7111   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7112     if (auto *Template = FD->getPrimaryTemplate())
7113       Template->LoadLazySpecializations();
7114   }
7115 }
7116
7117 CXXCtorInitializer **
7118 ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
7119   RecordLocation Loc = getLocalBitOffset(Offset);
7120   BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7121   SavedStreamPosition SavedPosition(Cursor);
7122   if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7123     Error(std::move(Err));
7124     return nullptr;
7125   }
7126   ReadingKindTracker ReadingKind(Read_Decl, *this);
7127
7128   Expected<unsigned> MaybeCode = Cursor.ReadCode();
7129   if (!MaybeCode) {
7130     Error(MaybeCode.takeError());
7131     return nullptr;
7132   }
7133   unsigned Code = MaybeCode.get();
7134
7135   ASTRecordReader Record(*this, *Loc.F);
7136   Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
7137   if (!MaybeRecCode) {
7138     Error(MaybeRecCode.takeError());
7139     return nullptr;
7140   }
7141   if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
7142     Error("malformed AST file: missing C++ ctor initializers");
7143     return nullptr;
7144   }
7145
7146   return Record.readCXXCtorInitializers();
7147 }
7148
7149 CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
7150   assert(ContextObj && "reading base specifiers with no AST context");
7151   ASTContext &Context = *ContextObj;
7152
7153   RecordLocation Loc = getLocalBitOffset(Offset);
7154   BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7155   SavedStreamPosition SavedPosition(Cursor);
7156   if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7157     Error(std::move(Err));
7158     return nullptr;
7159   }
7160   ReadingKindTracker ReadingKind(Read_Decl, *this);
7161
7162   Expected<unsigned> MaybeCode = Cursor.ReadCode();
7163   if (!MaybeCode) {
7164     Error(MaybeCode.takeError());
7165     return nullptr;
7166   }
7167   unsigned Code = MaybeCode.get();
7168
7169   ASTRecordReader Record(*this, *Loc.F);
7170   Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
7171   if (!MaybeRecCode) {
7172     Error(MaybeCode.takeError());
7173     return nullptr;
7174   }
7175   unsigned RecCode = MaybeRecCode.get();
7176
7177   if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
7178     Error("malformed AST file: missing C++ base specifiers");
7179     return nullptr;
7180   }
7181
7182   unsigned NumBases = Record.readInt();
7183   void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
7184   CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
7185   for (unsigned I = 0; I != NumBases; ++I)
7186     Bases[I] = Record.readCXXBaseSpecifier();
7187   return Bases;
7188 }
7189
7190 serialization::DeclID
7191 ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
7192   if (LocalID < NUM_PREDEF_DECL_IDS)
7193     return LocalID;
7194
7195   if (!F.ModuleOffsetMap.empty())
7196     ReadModuleOffsetMap(F);
7197
7198   ContinuousRangeMap<uint32_t, int, 2>::iterator I
7199     = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
7200   assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
7201
7202   return LocalID + I->second;
7203 }
7204
7205 bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
7206                                    ModuleFile &M) const {
7207   // Predefined decls aren't from any module.
7208   if (ID < NUM_PREDEF_DECL_IDS)
7209     return false;
7210
7211   return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
7212          ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
7213 }
7214
7215 ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
7216   if (!D->isFromASTFile())
7217     return nullptr;
7218   GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
7219   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7220   return I->second;
7221 }
7222
7223 SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
7224   if (ID < NUM_PREDEF_DECL_IDS)
7225     return SourceLocation();
7226
7227   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7228
7229   if (Index > DeclsLoaded.size()) {
7230     Error("declaration ID out-of-range for AST file");
7231     return SourceLocation();
7232   }
7233
7234   if (Decl *D = DeclsLoaded[Index])
7235     return D->getLocation();
7236
7237   SourceLocation Loc;
7238   DeclCursorForID(ID, Loc);
7239   return Loc;
7240 }
7241
7242 static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
7243   switch (ID) {
7244   case PREDEF_DECL_NULL_ID:
7245     return nullptr;
7246
7247   case PREDEF_DECL_TRANSLATION_UNIT_ID:
7248     return Context.getTranslationUnitDecl();
7249
7250   case PREDEF_DECL_OBJC_ID_ID:
7251     return Context.getObjCIdDecl();
7252
7253   case PREDEF_DECL_OBJC_SEL_ID:
7254     return Context.getObjCSelDecl();
7255
7256   case PREDEF_DECL_OBJC_CLASS_ID:
7257     return Context.getObjCClassDecl();
7258
7259   case PREDEF_DECL_OBJC_PROTOCOL_ID:
7260     return Context.getObjCProtocolDecl();
7261
7262   case PREDEF_DECL_INT_128_ID:
7263     return Context.getInt128Decl();
7264
7265   case PREDEF_DECL_UNSIGNED_INT_128_ID:
7266     return Context.getUInt128Decl();
7267
7268   case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
7269     return Context.getObjCInstanceTypeDecl();
7270
7271   case PREDEF_DECL_BUILTIN_VA_LIST_ID:
7272     return Context.getBuiltinVaListDecl();
7273
7274   case PREDEF_DECL_VA_LIST_TAG:
7275     return Context.getVaListTagDecl();
7276
7277   case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
7278     return Context.getBuiltinMSVaListDecl();
7279
7280   case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
7281     return Context.getExternCContextDecl();
7282
7283   case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
7284     return Context.getMakeIntegerSeqDecl();
7285
7286   case PREDEF_DECL_CF_CONSTANT_STRING_ID:
7287     return Context.getCFConstantStringDecl();
7288
7289   case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
7290     return Context.getCFConstantStringTagDecl();
7291
7292   case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
7293     return Context.getTypePackElementDecl();
7294   }
7295   llvm_unreachable("PredefinedDeclIDs unknown enum value");
7296 }
7297
7298 Decl *ASTReader::GetExistingDecl(DeclID ID) {
7299   assert(ContextObj && "reading decl with no AST context");
7300   if (ID < NUM_PREDEF_DECL_IDS) {
7301     Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
7302     if (D) {
7303       // Track that we have merged the declaration with ID \p ID into the
7304       // pre-existing predefined declaration \p D.
7305       auto &Merged = KeyDecls[D->getCanonicalDecl()];
7306       if (Merged.empty())
7307         Merged.push_back(ID);
7308     }
7309     return D;
7310   }
7311
7312   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7313
7314   if (Index >= DeclsLoaded.size()) {
7315     assert(0 && "declaration ID out-of-range for AST file");
7316     Error("declaration ID out-of-range for AST file");
7317     return nullptr;
7318   }
7319
7320   return DeclsLoaded[Index];
7321 }
7322
7323 Decl *ASTReader::GetDecl(DeclID ID) {
7324   if (ID < NUM_PREDEF_DECL_IDS)
7325     return GetExistingDecl(ID);
7326
7327   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7328
7329   if (Index >= DeclsLoaded.size()) {
7330     assert(0 && "declaration ID out-of-range for AST file");
7331     Error("declaration ID out-of-range for AST file");
7332     return nullptr;
7333   }
7334
7335   if (!DeclsLoaded[Index]) {
7336     ReadDeclRecord(ID);
7337     if (DeserializationListener)
7338       DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7339   }
7340
7341   return DeclsLoaded[Index];
7342 }
7343
7344 DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
7345                                                   DeclID GlobalID) {
7346   if (GlobalID < NUM_PREDEF_DECL_IDS)
7347     return GlobalID;
7348
7349   GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7350   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7351   ModuleFile *Owner = I->second;
7352
7353   llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
7354     = M.GlobalToLocalDeclIDs.find(Owner);
7355   if (Pos == M.GlobalToLocalDeclIDs.end())
7356     return 0;
7357
7358   return GlobalID - Owner->BaseDeclID + Pos->second;
7359 }
7360
7361 serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
7362                                             const RecordData &Record,
7363                                             unsigned &Idx) {
7364   if (Idx >= Record.size()) {
7365     Error("Corrupted AST file");
7366     return 0;
7367   }
7368
7369   return getGlobalDeclID(F, Record[Idx++]);
7370 }
7371
7372 /// Resolve the offset of a statement into a statement.
7373 ///
7374 /// This operation will read a new statement from the external
7375 /// source each time it is called, and is meant to be used via a
7376 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7377 Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
7378   // Switch case IDs are per Decl.
7379   ClearSwitchCaseIDs();
7380
7381   // Offset here is a global offset across the entire chain.
7382   RecordLocation Loc = getLocalBitOffset(Offset);
7383   if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
7384     Error(std::move(Err));
7385     return nullptr;
7386   }
7387   assert(NumCurrentElementsDeserializing == 0 &&
7388          "should not be called while already deserializing");
7389   Deserializing D(this);
7390   return ReadStmtFromStream(*Loc.F);
7391 }
7392
7393 void ASTReader::FindExternalLexicalDecls(
7394     const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7395     SmallVectorImpl<Decl *> &Decls) {
7396   bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7397
7398   auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
7399     assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7400     for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7401       auto K = (Decl::Kind)+LexicalDecls[I];
7402       if (!IsKindWeWant(K))
7403         continue;
7404
7405       auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
7406
7407       // Don't add predefined declarations to the lexical context more
7408       // than once.
7409       if (ID < NUM_PREDEF_DECL_IDS) {
7410         if (PredefsVisited[ID])
7411           continue;
7412
7413         PredefsVisited[ID] = true;
7414       }
7415
7416       if (Decl *D = GetLocalDecl(*M, ID)) {
7417         assert(D->getKind() == K && "wrong kind for lexical decl");
7418         if (!DC->isDeclInLexicalTraversal(D))
7419           Decls.push_back(D);
7420       }
7421     }
7422   };
7423
7424   if (isa<TranslationUnitDecl>(DC)) {
7425     for (auto Lexical : TULexicalDecls)
7426       Visit(Lexical.first, Lexical.second);
7427   } else {
7428     auto I = LexicalDecls.find(DC);
7429     if (I != LexicalDecls.end())
7430       Visit(I->second.first, I->second.second);
7431   }
7432
7433   ++NumLexicalDeclContextsRead;
7434 }
7435
7436 namespace {
7437
7438 class DeclIDComp {
7439   ASTReader &Reader;
7440   ModuleFile &Mod;
7441
7442 public:
7443   DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7444
7445   bool operator()(LocalDeclID L, LocalDeclID R) const {
7446     SourceLocation LHS = getLocation(L);
7447     SourceLocation RHS = getLocation(R);
7448     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7449   }
7450
7451   bool operator()(SourceLocation LHS, LocalDeclID R) const {
7452     SourceLocation RHS = getLocation(R);
7453     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7454   }
7455
7456   bool operator()(LocalDeclID L, SourceLocation RHS) const {
7457     SourceLocation LHS = getLocation(L);
7458     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7459   }
7460
7461   SourceLocation getLocation(LocalDeclID ID) const {
7462     return Reader.getSourceManager().getFileLoc(
7463             Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7464   }
7465 };
7466
7467 } // namespace
7468
7469 void ASTReader::FindFileRegionDecls(FileID File,
7470                                     unsigned Offset, unsigned Length,
7471                                     SmallVectorImpl<Decl *> &Decls) {
7472   SourceManager &SM = getSourceManager();
7473
7474   llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7475   if (I == FileDeclIDs.end())
7476     return;
7477
7478   FileDeclsInfo &DInfo = I->second;
7479   if (DInfo.Decls.empty())
7480     return;
7481
7482   SourceLocation
7483     BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7484   SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7485
7486   DeclIDComp DIDComp(*this, *DInfo.Mod);
7487   ArrayRef<serialization::LocalDeclID>::iterator BeginIt =
7488       llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
7489   if (BeginIt != DInfo.Decls.begin())
7490     --BeginIt;
7491
7492   // If we are pointing at a top-level decl inside an objc container, we need
7493   // to backtrack until we find it otherwise we will fail to report that the
7494   // region overlaps with an objc container.
7495   while (BeginIt != DInfo.Decls.begin() &&
7496          GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7497              ->isTopLevelDeclInObjCContainer())
7498     --BeginIt;
7499
7500   ArrayRef<serialization::LocalDeclID>::iterator EndIt =
7501       llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
7502   if (EndIt != DInfo.Decls.end())
7503     ++EndIt;
7504
7505   for (ArrayRef<serialization::LocalDeclID>::iterator
7506          DIt = BeginIt; DIt != EndIt; ++DIt)
7507     Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7508 }
7509
7510 bool
7511 ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
7512                                           DeclarationName Name) {
7513   assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
7514          "DeclContext has no visible decls in storage");
7515   if (!Name)
7516     return false;
7517
7518   auto It = Lookups.find(DC);
7519   if (It == Lookups.end())
7520     return false;
7521
7522   Deserializing LookupResults(this);
7523
7524   // Load the list of declarations.
7525   SmallVector<NamedDecl *, 64> Decls;
7526   for (DeclID ID : It->second.Table.find(Name)) {
7527     NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7528     if (ND->getDeclName() == Name)
7529       Decls.push_back(ND);
7530   }
7531
7532   ++NumVisibleDeclContextsRead;
7533   SetExternalVisibleDeclsForName(DC, Name, Decls);
7534   return !Decls.empty();
7535 }
7536
7537 void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
7538   if (!DC->hasExternalVisibleStorage())
7539     return;
7540
7541   auto It = Lookups.find(DC);
7542   assert(It != Lookups.end() &&
7543          "have external visible storage but no lookup tables");
7544
7545   DeclsMap Decls;
7546
7547   for (DeclID ID : It->second.Table.findAll()) {
7548     NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7549     Decls[ND->getDeclName()].push_back(ND);
7550   }
7551
7552   ++NumVisibleDeclContextsRead;
7553
7554   for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
7555     SetExternalVisibleDeclsForName(DC, I->first, I->second);
7556   }
7557   const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
7558 }
7559
7560 const serialization::reader::DeclContextLookupTable *
7561 ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
7562   auto I = Lookups.find(Primary);
7563   return I == Lookups.end() ? nullptr : &I->second;
7564 }
7565
7566 /// Under non-PCH compilation the consumer receives the objc methods
7567 /// before receiving the implementation, and codegen depends on this.
7568 /// We simulate this by deserializing and passing to consumer the methods of the
7569 /// implementation before passing the deserialized implementation decl.
7570 static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
7571                                        ASTConsumer *Consumer) {
7572   assert(ImplD && Consumer);
7573
7574   for (auto *I : ImplD->methods())
7575     Consumer->HandleInterestingDecl(DeclGroupRef(I));
7576
7577   Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
7578 }
7579
7580 void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
7581   if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
7582     PassObjCImplDeclToConsumer(ImplD, Consumer);
7583   else
7584     Consumer->HandleInterestingDecl(DeclGroupRef(D));
7585 }
7586
7587 void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7588   this->Consumer = Consumer;
7589
7590   if (Consumer)
7591     PassInterestingDeclsToConsumer();
7592
7593   if (DeserializationListener)
7594     DeserializationListener->ReaderInitialized(this);
7595 }
7596
7597 void ASTReader::PrintStats() {
7598   std::fprintf(stderr, "*** AST File Statistics:\n");
7599
7600   unsigned NumTypesLoaded
7601     = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
7602                                       QualType());
7603   unsigned NumDeclsLoaded
7604     = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
7605                                       (Decl *)nullptr);
7606   unsigned NumIdentifiersLoaded
7607     = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
7608                                             IdentifiersLoaded.end(),
7609                                             (IdentifierInfo *)nullptr);
7610   unsigned NumMacrosLoaded
7611     = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
7612                                        MacrosLoaded.end(),
7613                                        (MacroInfo *)nullptr);
7614   unsigned NumSelectorsLoaded
7615     = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
7616                                           SelectorsLoaded.end(),
7617                                           Selector());
7618
7619   if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7620     std::fprintf(stderr, "  %u/%u source location entries read (%f%%)\n",
7621                  NumSLocEntriesRead, TotalNumSLocEntries,
7622                  ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7623   if (!TypesLoaded.empty())
7624     std::fprintf(stderr, "  %u/%u types read (%f%%)\n",
7625                  NumTypesLoaded, (unsigned)TypesLoaded.size(),
7626                  ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7627   if (!DeclsLoaded.empty())
7628     std::fprintf(stderr, "  %u/%u declarations read (%f%%)\n",
7629                  NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7630                  ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7631   if (!IdentifiersLoaded.empty())
7632     std::fprintf(stderr, "  %u/%u identifiers read (%f%%)\n",
7633                  NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7634                  ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7635   if (!MacrosLoaded.empty())
7636     std::fprintf(stderr, "  %u/%u macros read (%f%%)\n",
7637                  NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7638                  ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7639   if (!SelectorsLoaded.empty())
7640     std::fprintf(stderr, "  %u/%u selectors read (%f%%)\n",
7641                  NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7642                  ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7643   if (TotalNumStatements)
7644     std::fprintf(stderr, "  %u/%u statements read (%f%%)\n",
7645                  NumStatementsRead, TotalNumStatements,
7646                  ((float)NumStatementsRead/TotalNumStatements * 100));
7647   if (TotalNumMacros)
7648     std::fprintf(stderr, "  %u/%u macros read (%f%%)\n",
7649                  NumMacrosRead, TotalNumMacros,
7650                  ((float)NumMacrosRead/TotalNumMacros * 100));
7651   if (TotalLexicalDeclContexts)
7652     std::fprintf(stderr, "  %u/%u lexical declcontexts read (%f%%)\n",
7653                  NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7654                  ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7655                   * 100));
7656   if (TotalVisibleDeclContexts)
7657     std::fprintf(stderr, "  %u/%u visible declcontexts read (%f%%)\n",
7658                  NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7659                  ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7660                   * 100));
7661   if (TotalNumMethodPoolEntries)
7662     std::fprintf(stderr, "  %u/%u method pool entries read (%f%%)\n",
7663                  NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7664                  ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7665                   * 100));
7666   if (NumMethodPoolLookups)
7667     std::fprintf(stderr, "  %u/%u method pool lookups succeeded (%f%%)\n",
7668                  NumMethodPoolHits, NumMethodPoolLookups,
7669                  ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
7670   if (NumMethodPoolTableLookups)
7671     std::fprintf(stderr, "  %u/%u method pool table lookups succeeded (%f%%)\n",
7672                  NumMethodPoolTableHits, NumMethodPoolTableLookups,
7673                  ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7674                   * 100.0));
7675   if (NumIdentifierLookupHits)
7676     std::fprintf(stderr,
7677                  "  %u / %u identifier table lookups succeeded (%f%%)\n",
7678                  NumIdentifierLookupHits, NumIdentifierLookups,
7679                  (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
7680
7681   if (GlobalIndex) {
7682     std::fprintf(stderr, "\n");
7683     GlobalIndex->printStats();
7684   }
7685
7686   std::fprintf(stderr, "\n");
7687   dump();
7688   std::fprintf(stderr, "\n");
7689 }
7690
7691 template<typename Key, typename ModuleFile, unsigned InitialCapacity>
7692 LLVM_DUMP_METHOD static void
7693 dumpModuleIDMap(StringRef Name,
7694                 const ContinuousRangeMap<Key, ModuleFile *,
7695                                          InitialCapacity> &Map) {
7696   if (Map.begin() == Map.end())
7697     return;
7698
7699   using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>;
7700
7701   llvm::errs() << Name << ":\n";
7702   for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
7703        I != IEnd; ++I) {
7704     llvm::errs() << "  " << I->first << " -> " << I->second->FileName
7705       << "\n";
7706   }
7707 }
7708
7709 LLVM_DUMP_METHOD void ASTReader::dump() {
7710   llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7711   dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7712   dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7713   dumpModuleIDMap("Global type map", GlobalTypeMap);
7714   dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7715   dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7716   dumpModuleIDMap("Global macro map", GlobalMacroMap);
7717   dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7718   dumpModuleIDMap("Global selector map", GlobalSelectorMap);
7719   dumpModuleIDMap("Global preprocessed entity map",
7720                   GlobalPreprocessedEntityMap);
7721
7722   llvm::errs() << "\n*** PCH/Modules Loaded:";
7723   for (ModuleFile &M : ModuleMgr)
7724     M.dump();
7725 }
7726
7727 /// Return the amount of memory used by memory buffers, breaking down
7728 /// by heap-backed versus mmap'ed memory.
7729 void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
7730   for (ModuleFile &I : ModuleMgr) {
7731     if (llvm::MemoryBuffer *buf = I.Buffer) {
7732       size_t bytes = buf->getBufferSize();
7733       switch (buf->getBufferKind()) {
7734         case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7735           sizes.malloc_bytes += bytes;
7736           break;
7737         case llvm::MemoryBuffer::MemoryBuffer_MMap:
7738           sizes.mmap_bytes += bytes;
7739           break;
7740       }
7741     }
7742   }
7743 }
7744
7745 void ASTReader::InitializeSema(Sema &S) {
7746   SemaObj = &S;
7747   S.addExternalSource(this);
7748
7749   // Makes sure any declarations that were deserialized "too early"
7750   // still get added to the identifier's declaration chains.
7751   for (uint64_t ID : PreloadedDeclIDs) {
7752     NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7753     pushExternalDeclIntoScope(D, D->getDeclName());
7754   }
7755   PreloadedDeclIDs.clear();
7756
7757   // FIXME: What happens if these are changed by a module import?
7758   if (!FPPragmaOptions.empty()) {
7759     assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
7760     SemaObj->FPFeatures = FPOptions(FPPragmaOptions[0]);
7761   }
7762
7763   SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
7764   SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
7765   SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
7766
7767   UpdateSema();
7768 }
7769
7770 void ASTReader::UpdateSema() {
7771   assert(SemaObj && "no Sema to update");
7772
7773   // Load the offsets of the declarations that Sema references.
7774   // They will be lazily deserialized when needed.
7775   if (!SemaDeclRefs.empty()) {
7776     assert(SemaDeclRefs.size() % 3 == 0);
7777     for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
7778       if (!SemaObj->StdNamespace)
7779         SemaObj->StdNamespace = SemaDeclRefs[I];
7780       if (!SemaObj->StdBadAlloc)
7781         SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
7782       if (!SemaObj->StdAlignValT)
7783         SemaObj->StdAlignValT = SemaDeclRefs[I+2];
7784     }
7785     SemaDeclRefs.clear();
7786   }
7787
7788   // Update the state of pragmas. Use the same API as if we had encountered the
7789   // pragma in the source.
7790   if(OptimizeOffPragmaLocation.isValid())
7791     SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
7792   if (PragmaMSStructState != -1)
7793     SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
7794   if (PointersToMembersPragmaLocation.isValid()) {
7795     SemaObj->ActOnPragmaMSPointersToMembers(
7796         (LangOptions::PragmaMSPointersToMembersKind)
7797             PragmaMSPointersToMembersState,
7798         PointersToMembersPragmaLocation);
7799   }
7800   SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
7801
7802   if (PragmaPackCurrentValue) {
7803     // The bottom of the stack might have a default value. It must be adjusted
7804     // to the current value to ensure that the packing state is preserved after
7805     // popping entries that were included/imported from a PCH/module.
7806     bool DropFirst = false;
7807     if (!PragmaPackStack.empty() &&
7808         PragmaPackStack.front().Location.isInvalid()) {
7809       assert(PragmaPackStack.front().Value == SemaObj->PackStack.DefaultValue &&
7810              "Expected a default alignment value");
7811       SemaObj->PackStack.Stack.emplace_back(
7812           PragmaPackStack.front().SlotLabel, SemaObj->PackStack.CurrentValue,
7813           SemaObj->PackStack.CurrentPragmaLocation,
7814           PragmaPackStack.front().PushLocation);
7815       DropFirst = true;
7816     }
7817     for (const auto &Entry :
7818          llvm::makeArrayRef(PragmaPackStack).drop_front(DropFirst ? 1 : 0))
7819       SemaObj->PackStack.Stack.emplace_back(Entry.SlotLabel, Entry.Value,
7820                                             Entry.Location, Entry.PushLocation);
7821     if (PragmaPackCurrentLocation.isInvalid()) {
7822       assert(*PragmaPackCurrentValue == SemaObj->PackStack.DefaultValue &&
7823              "Expected a default alignment value");
7824       // Keep the current values.
7825     } else {
7826       SemaObj->PackStack.CurrentValue = *PragmaPackCurrentValue;
7827       SemaObj->PackStack.CurrentPragmaLocation = PragmaPackCurrentLocation;
7828     }
7829   }
7830 }
7831
7832 IdentifierInfo *ASTReader::get(StringRef Name) {
7833   // Note that we are loading an identifier.
7834   Deserializing AnIdentifier(this);
7835
7836   IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
7837                                   NumIdentifierLookups,
7838                                   NumIdentifierLookupHits);
7839
7840   // We don't need to do identifier table lookups in C++ modules (we preload
7841   // all interesting declarations, and don't need to use the scope for name
7842   // lookups). Perform the lookup in PCH files, though, since we don't build
7843   // a complete initial identifier table if we're carrying on from a PCH.
7844   if (PP.getLangOpts().CPlusPlus) {
7845     for (auto F : ModuleMgr.pch_modules())
7846       if (Visitor(*F))
7847         break;
7848   } else {
7849     // If there is a global index, look there first to determine which modules
7850     // provably do not have any results for this identifier.
7851     GlobalModuleIndex::HitSet Hits;
7852     GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7853     if (!loadGlobalIndex()) {
7854       if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7855         HitsPtr = &Hits;
7856       }
7857     }
7858
7859     ModuleMgr.visit(Visitor, HitsPtr);
7860   }
7861
7862   IdentifierInfo *II = Visitor.getIdentifierInfo();
7863   markIdentifierUpToDate(II);
7864   return II;
7865 }
7866
7867 namespace clang {
7868
7869   /// An identifier-lookup iterator that enumerates all of the
7870   /// identifiers stored within a set of AST files.
7871   class ASTIdentifierIterator : public IdentifierIterator {
7872     /// The AST reader whose identifiers are being enumerated.
7873     const ASTReader &Reader;
7874
7875     /// The current index into the chain of AST files stored in
7876     /// the AST reader.
7877     unsigned Index;
7878
7879     /// The current position within the identifier lookup table
7880     /// of the current AST file.
7881     ASTIdentifierLookupTable::key_iterator Current;
7882
7883     /// The end position within the identifier lookup table of
7884     /// the current AST file.
7885     ASTIdentifierLookupTable::key_iterator End;
7886
7887     /// Whether to skip any modules in the ASTReader.
7888     bool SkipModules;
7889
7890   public:
7891     explicit ASTIdentifierIterator(const ASTReader &Reader,
7892                                    bool SkipModules = false);
7893
7894     StringRef Next() override;
7895   };
7896
7897 } // namespace clang
7898
7899 ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7900                                              bool SkipModules)
7901     : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
7902 }
7903
7904 StringRef ASTIdentifierIterator::Next() {
7905   while (Current == End) {
7906     // If we have exhausted all of our AST files, we're done.
7907     if (Index == 0)
7908       return StringRef();
7909
7910     --Index;
7911     ModuleFile &F = Reader.ModuleMgr[Index];
7912     if (SkipModules && F.isModule())
7913       continue;
7914
7915     ASTIdentifierLookupTable *IdTable =
7916         (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
7917     Current = IdTable->key_begin();
7918     End = IdTable->key_end();
7919   }
7920
7921   // We have any identifiers remaining in the current AST file; return
7922   // the next one.
7923   StringRef Result = *Current;
7924   ++Current;
7925   return Result;
7926 }
7927
7928 namespace {
7929
7930 /// A utility for appending two IdentifierIterators.
7931 class ChainedIdentifierIterator : public IdentifierIterator {
7932   std::unique_ptr<IdentifierIterator> Current;
7933   std::unique_ptr<IdentifierIterator> Queued;
7934
7935 public:
7936   ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7937                             std::unique_ptr<IdentifierIterator> Second)
7938       : Current(std::move(First)), Queued(std::move(Second)) {}
7939
7940   StringRef Next() override {
7941     if (!Current)
7942       return StringRef();
7943
7944     StringRef result = Current->Next();
7945     if (!result.empty())
7946       return result;
7947
7948     // Try the queued iterator, which may itself be empty.
7949     Current.reset();
7950     std::swap(Current, Queued);
7951     return Next();
7952   }
7953 };
7954
7955 } // namespace
7956
7957 IdentifierIterator *ASTReader::getIdentifiers() {
7958   if (!loadGlobalIndex()) {
7959     std::unique_ptr<IdentifierIterator> ReaderIter(
7960         new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7961     std::unique_ptr<IdentifierIterator> ModulesIter(
7962         GlobalIndex->createIdentifierIterator());
7963     return new ChainedIdentifierIterator(std::move(ReaderIter),
7964                                          std::move(ModulesIter));
7965   }
7966
7967   return new ASTIdentifierIterator(*this);
7968 }
7969
7970 namespace clang {
7971 namespace serialization {
7972
7973   class ReadMethodPoolVisitor {
7974     ASTReader &Reader;
7975     Selector Sel;
7976     unsigned PriorGeneration;
7977     unsigned InstanceBits = 0;
7978     unsigned FactoryBits = 0;
7979     bool InstanceHasMoreThanOneDecl = false;
7980     bool FactoryHasMoreThanOneDecl = false;
7981     SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7982     SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
7983
7984   public:
7985     ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
7986                           unsigned PriorGeneration)
7987         : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
7988
7989     bool operator()(ModuleFile &M) {
7990       if (!M.SelectorLookupTable)
7991         return false;
7992
7993       // If we've already searched this module file, skip it now.
7994       if (M.Generation <= PriorGeneration)
7995         return true;
7996
7997       ++Reader.NumMethodPoolTableLookups;
7998       ASTSelectorLookupTable *PoolTable
7999         = (ASTSelectorLookupTable*)M.SelectorLookupTable;
8000       ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
8001       if (Pos == PoolTable->end())
8002         return false;
8003
8004       ++Reader.NumMethodPoolTableHits;
8005       ++Reader.NumSelectorsRead;
8006       // FIXME: Not quite happy with the statistics here. We probably should
8007       // disable this tracking when called via LoadSelector.
8008       // Also, should entries without methods count as misses?
8009       ++Reader.NumMethodPoolEntriesRead;
8010       ASTSelectorLookupTrait::data_type Data = *Pos;
8011       if (Reader.DeserializationListener)
8012         Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
8013
8014       InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
8015       FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
8016       InstanceBits = Data.InstanceBits;
8017       FactoryBits = Data.FactoryBits;
8018       InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
8019       FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
8020       return true;
8021     }
8022
8023     /// Retrieve the instance methods found by this visitor.
8024     ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
8025       return InstanceMethods;
8026     }
8027
8028     /// Retrieve the instance methods found by this visitor.
8029     ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
8030       return FactoryMethods;
8031     }
8032
8033     unsigned getInstanceBits() const { return InstanceBits; }
8034     unsigned getFactoryBits() const { return FactoryBits; }
8035
8036     bool instanceHasMoreThanOneDecl() const {
8037       return InstanceHasMoreThanOneDecl;
8038     }
8039
8040     bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
8041   };
8042
8043 } // namespace serialization
8044 } // namespace clang
8045
8046 /// Add the given set of methods to the method list.
8047 static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
8048                              ObjCMethodList &List) {
8049   for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
8050     S.addMethodToGlobalList(&List, Methods[I]);
8051   }
8052 }
8053
8054 void ASTReader::ReadMethodPool(Selector Sel) {
8055   // Get the selector generation and update it to the current generation.
8056   unsigned &Generation = SelectorGeneration[Sel];
8057   unsigned PriorGeneration = Generation;
8058   Generation = getGeneration();
8059   SelectorOutOfDate[Sel] = false;
8060
8061   // Search for methods defined with this selector.
8062   ++NumMethodPoolLookups;
8063   ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
8064   ModuleMgr.visit(Visitor);
8065
8066   if (Visitor.getInstanceMethods().empty() &&
8067       Visitor.getFactoryMethods().empty())
8068     return;
8069
8070   ++NumMethodPoolHits;
8071
8072   if (!getSema())
8073     return;
8074
8075   Sema &S = *getSema();
8076   Sema::GlobalMethodPool::iterator Pos
8077     = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
8078
8079   Pos->second.first.setBits(Visitor.getInstanceBits());
8080   Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
8081   Pos->second.second.setBits(Visitor.getFactoryBits());
8082   Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
8083
8084   // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
8085   // when building a module we keep every method individually and may need to
8086   // update hasMoreThanOneDecl as we add the methods.
8087   addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
8088   addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
8089 }
8090
8091 void ASTReader::updateOutOfDateSelector(Selector Sel) {
8092   if (SelectorOutOfDate[Sel])
8093     ReadMethodPool(Sel);
8094 }
8095
8096 void ASTReader::ReadKnownNamespaces(
8097                           SmallVectorImpl<NamespaceDecl *> &Namespaces) {
8098   Namespaces.clear();
8099
8100   for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
8101     if (NamespaceDecl *Namespace
8102                 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
8103       Namespaces.push_back(Namespace);
8104   }
8105 }
8106
8107 void ASTReader::ReadUndefinedButUsed(
8108     llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
8109   for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
8110     NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
8111     SourceLocation Loc =
8112         SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
8113     Undefined.insert(std::make_pair(D, Loc));
8114   }
8115 }
8116
8117 void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
8118     FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
8119                                                      Exprs) {
8120   for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
8121     FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
8122     uint64_t Count = DelayedDeleteExprs[Idx++];
8123     for (uint64_t C = 0; C < Count; ++C) {
8124       SourceLocation DeleteLoc =
8125           SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
8126       const bool IsArrayForm = DelayedDeleteExprs[Idx++];
8127       Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
8128     }
8129   }
8130 }
8131
8132 void ASTReader::ReadTentativeDefinitions(
8133                   SmallVectorImpl<VarDecl *> &TentativeDefs) {
8134   for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
8135     VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
8136     if (Var)
8137       TentativeDefs.push_back(Var);
8138   }
8139   TentativeDefinitions.clear();
8140 }
8141
8142 void ASTReader::ReadUnusedFileScopedDecls(
8143                                SmallVectorImpl<const DeclaratorDecl *> &Decls) {
8144   for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
8145     DeclaratorDecl *D
8146       = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
8147     if (D)
8148       Decls.push_back(D);
8149   }
8150   UnusedFileScopedDecls.clear();
8151 }
8152
8153 void ASTReader::ReadDelegatingConstructors(
8154                                  SmallVectorImpl<CXXConstructorDecl *> &Decls) {
8155   for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
8156     CXXConstructorDecl *D
8157       = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
8158     if (D)
8159       Decls.push_back(D);
8160   }
8161   DelegatingCtorDecls.clear();
8162 }
8163
8164 void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
8165   for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
8166     TypedefNameDecl *D
8167       = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
8168     if (D)
8169       Decls.push_back(D);
8170   }
8171   ExtVectorDecls.clear();
8172 }
8173
8174 void ASTReader::ReadUnusedLocalTypedefNameCandidates(
8175     llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
8176   for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
8177        ++I) {
8178     TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
8179         GetDecl(UnusedLocalTypedefNameCandidates[I]));
8180     if (D)
8181       Decls.insert(D);
8182   }
8183   UnusedLocalTypedefNameCandidates.clear();
8184 }
8185
8186 void ASTReader::ReadReferencedSelectors(
8187        SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
8188   if (ReferencedSelectorsData.empty())
8189     return;
8190
8191   // If there are @selector references added them to its pool. This is for
8192   // implementation of -Wselector.
8193   unsigned int DataSize = ReferencedSelectorsData.size()-1;
8194   unsigned I = 0;
8195   while (I < DataSize) {
8196     Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
8197     SourceLocation SelLoc
8198       = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
8199     Sels.push_back(std::make_pair(Sel, SelLoc));
8200   }
8201   ReferencedSelectorsData.clear();
8202 }
8203
8204 void ASTReader::ReadWeakUndeclaredIdentifiers(
8205        SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
8206   if (WeakUndeclaredIdentifiers.empty())
8207     return;
8208
8209   for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
8210     IdentifierInfo *WeakId
8211       = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8212     IdentifierInfo *AliasId
8213       = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8214     SourceLocation Loc
8215       = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
8216     bool Used = WeakUndeclaredIdentifiers[I++];
8217     WeakInfo WI(AliasId, Loc);
8218     WI.setUsed(Used);
8219     WeakIDs.push_back(std::make_pair(WeakId, WI));
8220   }
8221   WeakUndeclaredIdentifiers.clear();
8222 }
8223
8224 void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
8225   for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
8226     ExternalVTableUse VT;
8227     VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
8228     VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
8229     VT.DefinitionRequired = VTableUses[Idx++];
8230     VTables.push_back(VT);
8231   }
8232
8233   VTableUses.clear();
8234 }
8235
8236 void ASTReader::ReadPendingInstantiations(
8237        SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
8238   for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
8239     ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
8240     SourceLocation Loc
8241       = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
8242
8243     Pending.push_back(std::make_pair(D, Loc));
8244   }
8245   PendingInstantiations.clear();
8246 }
8247
8248 void ASTReader::ReadLateParsedTemplates(
8249     llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
8250         &LPTMap) {
8251   for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
8252        /* In loop */) {
8253     FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
8254
8255     auto LT = std::make_unique<LateParsedTemplate>();
8256     LT->D = GetDecl(LateParsedTemplates[Idx++]);
8257
8258     ModuleFile *F = getOwningModuleFile(LT->D);
8259     assert(F && "No module");
8260
8261     unsigned TokN = LateParsedTemplates[Idx++];
8262     LT->Toks.reserve(TokN);
8263     for (unsigned T = 0; T < TokN; ++T)
8264       LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
8265
8266     LPTMap.insert(std::make_pair(FD, std::move(LT)));
8267   }
8268
8269   LateParsedTemplates.clear();
8270 }
8271
8272 void ASTReader::LoadSelector(Selector Sel) {
8273   // It would be complicated to avoid reading the methods anyway. So don't.
8274   ReadMethodPool(Sel);
8275 }
8276
8277 void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
8278   assert(ID && "Non-zero identifier ID required");
8279   assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
8280   IdentifiersLoaded[ID - 1] = II;
8281   if (DeserializationListener)
8282     DeserializationListener->IdentifierRead(ID, II);
8283 }
8284
8285 /// Set the globally-visible declarations associated with the given
8286 /// identifier.
8287 ///
8288 /// If the AST reader is currently in a state where the given declaration IDs
8289 /// cannot safely be resolved, they are queued until it is safe to resolve
8290 /// them.
8291 ///
8292 /// \param II an IdentifierInfo that refers to one or more globally-visible
8293 /// declarations.
8294 ///
8295 /// \param DeclIDs the set of declaration IDs with the name @p II that are
8296 /// visible at global scope.
8297 ///
8298 /// \param Decls if non-null, this vector will be populated with the set of
8299 /// deserialized declarations. These declarations will not be pushed into
8300 /// scope.
8301 void
8302 ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
8303                               const SmallVectorImpl<uint32_t> &DeclIDs,
8304                                    SmallVectorImpl<Decl *> *Decls) {
8305   if (NumCurrentElementsDeserializing && !Decls) {
8306     PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
8307     return;
8308   }
8309
8310   for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
8311     if (!SemaObj) {
8312       // Queue this declaration so that it will be added to the
8313       // translation unit scope and identifier's declaration chain
8314       // once a Sema object is known.
8315       PreloadedDeclIDs.push_back(DeclIDs[I]);
8316       continue;
8317     }
8318
8319     NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
8320
8321     // If we're simply supposed to record the declarations, do so now.
8322     if (Decls) {
8323       Decls->push_back(D);
8324       continue;
8325     }
8326
8327     // Introduce this declaration into the translation-unit scope
8328     // and add it to the declaration chain for this identifier, so
8329     // that (unqualified) name lookup will find it.
8330     pushExternalDeclIntoScope(D, II);
8331   }
8332 }
8333
8334 IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
8335   if (ID == 0)
8336     return nullptr;
8337
8338   if (IdentifiersLoaded.empty()) {
8339     Error("no identifier table in AST file");
8340     return nullptr;
8341   }
8342
8343   ID -= 1;
8344   if (!IdentifiersLoaded[ID]) {
8345     GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8346     assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8347     ModuleFile *M = I->second;
8348     unsigned Index = ID - M->BaseIdentifierID;
8349     const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
8350
8351     // All of the strings in the AST file are preceded by a 16-bit length.
8352     // Extract that 16-bit length to avoid having to execute strlen().
8353     // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
8354     //  unsigned integers.  This is important to avoid integer overflow when
8355     //  we cast them to 'unsigned'.
8356     const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
8357     unsigned StrLen = (((unsigned) StrLenPtr[0])
8358                        | (((unsigned) StrLenPtr[1]) << 8)) - 1;
8359     auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
8360     IdentifiersLoaded[ID] = &II;
8361     markIdentifierFromAST(*this,  II);
8362     if (DeserializationListener)
8363       DeserializationListener->IdentifierRead(ID + 1, &II);
8364   }
8365
8366   return IdentifiersLoaded[ID];
8367 }
8368
8369 IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
8370   return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
8371 }
8372
8373 IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
8374   if (LocalID < NUM_PREDEF_IDENT_IDS)
8375     return LocalID;
8376
8377   if (!M.ModuleOffsetMap.empty())
8378     ReadModuleOffsetMap(M);
8379
8380   ContinuousRangeMap<uint32_t, int, 2>::iterator I
8381     = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
8382   assert(I != M.IdentifierRemap.end()
8383          && "Invalid index into identifier index remap");
8384
8385   return LocalID + I->second;
8386 }
8387
8388 MacroInfo *ASTReader::getMacro(MacroID ID) {
8389   if (ID == 0)
8390     return nullptr;
8391
8392   if (MacrosLoaded.empty()) {
8393     Error("no macro table in AST file");
8394     return nullptr;
8395   }
8396
8397   ID -= NUM_PREDEF_MACRO_IDS;
8398   if (!MacrosLoaded[ID]) {
8399     GlobalMacroMapType::iterator I
8400       = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8401     assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8402     ModuleFile *M = I->second;
8403     unsigned Index = ID - M->BaseMacroID;
8404     MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
8405
8406     if (DeserializationListener)
8407       DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8408                                          MacrosLoaded[ID]);
8409   }
8410
8411   return MacrosLoaded[ID];
8412 }
8413
8414 MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
8415   if (LocalID < NUM_PREDEF_MACRO_IDS)
8416     return LocalID;
8417
8418   if (!M.ModuleOffsetMap.empty())
8419     ReadModuleOffsetMap(M);
8420
8421   ContinuousRangeMap<uint32_t, int, 2>::iterator I
8422     = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8423   assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8424
8425   return LocalID + I->second;
8426 }
8427
8428 serialization::SubmoduleID
8429 ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
8430   if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8431     return LocalID;
8432
8433   if (!M.ModuleOffsetMap.empty())
8434     ReadModuleOffsetMap(M);
8435
8436   ContinuousRangeMap<uint32_t, int, 2>::iterator I
8437     = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
8438   assert(I != M.SubmoduleRemap.end()
8439          && "Invalid index into submodule index remap");
8440
8441   return LocalID + I->second;
8442 }
8443
8444 Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
8445   if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8446     assert(GlobalID == 0 && "Unhandled global submodule ID");
8447     return nullptr;
8448   }
8449
8450   if (GlobalID > SubmodulesLoaded.size()) {
8451     Error("submodule ID out of range in AST file");
8452     return nullptr;
8453   }
8454
8455   return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8456 }
8457
8458 Module *ASTReader::getModule(unsigned ID) {
8459   return getSubmodule(ID);
8460 }
8461
8462 bool ASTReader::DeclIsFromPCHWithObjectFile(const Decl *D) {
8463   ModuleFile *MF = getOwningModuleFile(D);
8464   return MF && MF->PCHHasObjectFile;
8465 }
8466
8467 ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
8468   if (ID & 1) {
8469     // It's a module, look it up by submodule ID.
8470     auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
8471     return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
8472   } else {
8473     // It's a prefix (preamble, PCH, ...). Look it up by index.
8474     unsigned IndexFromEnd = ID >> 1;
8475     assert(IndexFromEnd && "got reference to unknown module file");
8476     return getModuleManager().pch_modules().end()[-IndexFromEnd];
8477   }
8478 }
8479
8480 unsigned ASTReader::getModuleFileID(ModuleFile *F) {
8481   if (!F)
8482     return 1;
8483
8484   // For a file representing a module, use the submodule ID of the top-level
8485   // module as the file ID. For any other kind of file, the number of such
8486   // files loaded beforehand will be the same on reload.
8487   // FIXME: Is this true even if we have an explicit module file and a PCH?
8488   if (F->isModule())
8489     return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
8490
8491   auto PCHModules = getModuleManager().pch_modules();
8492   auto I = llvm::find(PCHModules, F);
8493   assert(I != PCHModules.end() && "emitting reference to unknown file");
8494   return (I - PCHModules.end()) << 1;
8495 }
8496
8497 llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
8498 ASTReader::getSourceDescriptor(unsigned ID) {
8499   if (const Module *M = getSubmodule(ID))
8500     return ExternalASTSource::ASTSourceDescriptor(*M);
8501
8502   // If there is only a single PCH, return it instead.
8503   // Chained PCH are not supported.
8504   const auto &PCHChain = ModuleMgr.pch_modules();
8505   if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
8506     ModuleFile &MF = ModuleMgr.getPrimaryModule();
8507     StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
8508     StringRef FileName = llvm::sys::path::filename(MF.FileName);
8509     return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
8510                                           MF.Signature);
8511   }
8512   return None;
8513 }
8514
8515 ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
8516   auto I = DefinitionSource.find(FD);
8517   if (I == DefinitionSource.end())
8518     return EK_ReplyHazy;
8519   return I->second ? EK_Never : EK_Always;
8520 }
8521
8522 Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
8523   return DecodeSelector(getGlobalSelectorID(M, LocalID));
8524 }
8525
8526 Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
8527   if (ID == 0)
8528     return Selector();
8529
8530   if (ID > SelectorsLoaded.size()) {
8531     Error("selector ID out of range in AST file");
8532     return Selector();
8533   }
8534
8535   if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
8536     // Load this selector from the selector table.
8537     GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
8538     assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
8539     ModuleFile &M = *I->second;
8540     ASTSelectorLookupTrait Trait(*this, M);
8541     unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
8542     SelectorsLoaded[ID - 1] =
8543       Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
8544     if (DeserializationListener)
8545       DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
8546   }
8547
8548   return SelectorsLoaded[ID - 1];
8549 }
8550
8551 Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
8552   return DecodeSelector(ID);
8553 }
8554
8555 uint32_t ASTReader::GetNumExternalSelectors() {
8556   // ID 0 (the null selector) is considered an external selector.
8557   return getTotalNumSelectors() + 1;
8558 }
8559
8560 serialization::SelectorID
8561 ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
8562   if (LocalID < NUM_PREDEF_SELECTOR_IDS)
8563     return LocalID;
8564
8565   if (!M.ModuleOffsetMap.empty())
8566     ReadModuleOffsetMap(M);
8567
8568   ContinuousRangeMap<uint32_t, int, 2>::iterator I
8569     = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
8570   assert(I != M.SelectorRemap.end()
8571          && "Invalid index into selector index remap");
8572
8573   return LocalID + I->second;
8574 }
8575
8576 DeclarationNameLoc
8577 ASTRecordReader::readDeclarationNameLoc(DeclarationName Name) {
8578   DeclarationNameLoc DNLoc;
8579   switch (Name.getNameKind()) {
8580   case DeclarationName::CXXConstructorName:
8581   case DeclarationName::CXXDestructorName:
8582   case DeclarationName::CXXConversionFunctionName:
8583     DNLoc.NamedType.TInfo = readTypeSourceInfo();
8584     break;
8585
8586   case DeclarationName::CXXOperatorName:
8587     DNLoc.CXXOperatorName.BeginOpNameLoc
8588       = readSourceLocation().getRawEncoding();
8589     DNLoc.CXXOperatorName.EndOpNameLoc
8590       = readSourceLocation().getRawEncoding();
8591     break;
8592
8593   case DeclarationName::CXXLiteralOperatorName:
8594     DNLoc.CXXLiteralOperatorName.OpNameLoc
8595       = readSourceLocation().getRawEncoding();
8596     break;
8597
8598   case DeclarationName::Identifier:
8599   case DeclarationName::ObjCZeroArgSelector:
8600   case DeclarationName::ObjCOneArgSelector:
8601   case DeclarationName::ObjCMultiArgSelector:
8602   case DeclarationName::CXXUsingDirective:
8603   case DeclarationName::CXXDeductionGuideName:
8604     break;
8605   }
8606   return DNLoc;
8607 }
8608
8609 DeclarationNameInfo ASTRecordReader::readDeclarationNameInfo() {
8610   DeclarationNameInfo NameInfo;
8611   NameInfo.setName(readDeclarationName());
8612   NameInfo.setLoc(readSourceLocation());
8613   NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName()));
8614   return NameInfo;
8615 }
8616
8617 void ASTRecordReader::readQualifierInfo(QualifierInfo &Info) {
8618   Info.QualifierLoc = readNestedNameSpecifierLoc();
8619   unsigned NumTPLists = readInt();
8620   Info.NumTemplParamLists = NumTPLists;
8621   if (NumTPLists) {
8622     Info.TemplParamLists =
8623         new (getContext()) TemplateParameterList *[NumTPLists];
8624     for (unsigned i = 0; i != NumTPLists; ++i)
8625       Info.TemplParamLists[i] = readTemplateParameterList();
8626   }
8627 }
8628
8629 TemplateParameterList *
8630 ASTRecordReader::readTemplateParameterList() {
8631   SourceLocation TemplateLoc = readSourceLocation();
8632   SourceLocation LAngleLoc = readSourceLocation();
8633   SourceLocation RAngleLoc = readSourceLocation();
8634
8635   unsigned NumParams = readInt();
8636   SmallVector<NamedDecl *, 16> Params;
8637   Params.reserve(NumParams);
8638   while (NumParams--)
8639     Params.push_back(readDeclAs<NamedDecl>());
8640
8641   bool HasRequiresClause = readBool();
8642   Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr;
8643
8644   TemplateParameterList *TemplateParams = TemplateParameterList::Create(
8645       getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
8646   return TemplateParams;
8647 }
8648
8649 void ASTRecordReader::readTemplateArgumentList(
8650                         SmallVectorImpl<TemplateArgument> &TemplArgs,
8651                         bool Canonicalize) {
8652   unsigned NumTemplateArgs = readInt();
8653   TemplArgs.reserve(NumTemplateArgs);
8654   while (NumTemplateArgs--)
8655     TemplArgs.push_back(readTemplateArgument(Canonicalize));
8656 }
8657
8658 /// Read a UnresolvedSet structure.
8659 void ASTRecordReader::readUnresolvedSet(LazyASTUnresolvedSet &Set) {
8660   unsigned NumDecls = readInt();
8661   Set.reserve(getContext(), NumDecls);
8662   while (NumDecls--) {
8663     DeclID ID = readDeclID();
8664     AccessSpecifier AS = (AccessSpecifier) readInt();
8665     Set.addLazyDecl(getContext(), ID, AS);
8666   }
8667 }
8668
8669 CXXBaseSpecifier
8670 ASTRecordReader::readCXXBaseSpecifier() {
8671   bool isVirtual = readBool();
8672   bool isBaseOfClass = readBool();
8673   AccessSpecifier AS = static_cast<AccessSpecifier>(readInt());
8674   bool inheritConstructors = readBool();
8675   TypeSourceInfo *TInfo = readTypeSourceInfo();
8676   SourceRange Range = readSourceRange();
8677   SourceLocation EllipsisLoc = readSourceLocation();
8678   CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
8679                           EllipsisLoc);
8680   Result.setInheritConstructors(inheritConstructors);
8681   return Result;
8682 }
8683
8684 CXXCtorInitializer **
8685 ASTRecordReader::readCXXCtorInitializers() {
8686   ASTContext &Context = getContext();
8687   unsigned NumInitializers = readInt();
8688   assert(NumInitializers && "wrote ctor initializers but have no inits");
8689   auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
8690   for (unsigned i = 0; i != NumInitializers; ++i) {
8691     TypeSourceInfo *TInfo = nullptr;
8692     bool IsBaseVirtual = false;
8693     FieldDecl *Member = nullptr;
8694     IndirectFieldDecl *IndirectMember = nullptr;
8695
8696     CtorInitializerType Type = (CtorInitializerType) readInt();
8697     switch (Type) {
8698     case CTOR_INITIALIZER_BASE:
8699       TInfo = readTypeSourceInfo();
8700       IsBaseVirtual = readBool();
8701       break;
8702
8703     case CTOR_INITIALIZER_DELEGATING:
8704       TInfo = readTypeSourceInfo();
8705       break;
8706
8707      case CTOR_INITIALIZER_MEMBER:
8708       Member = readDeclAs<FieldDecl>();
8709       break;
8710
8711      case CTOR_INITIALIZER_INDIRECT_MEMBER:
8712       IndirectMember = readDeclAs<IndirectFieldDecl>();
8713       break;
8714     }
8715
8716     SourceLocation MemberOrEllipsisLoc = readSourceLocation();
8717     Expr *Init = readExpr();
8718     SourceLocation LParenLoc = readSourceLocation();
8719     SourceLocation RParenLoc = readSourceLocation();
8720
8721     CXXCtorInitializer *BOMInit;
8722     if (Type == CTOR_INITIALIZER_BASE)
8723       BOMInit = new (Context)
8724           CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8725                              RParenLoc, MemberOrEllipsisLoc);
8726     else if (Type == CTOR_INITIALIZER_DELEGATING)
8727       BOMInit = new (Context)
8728           CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
8729     else if (Member)
8730       BOMInit = new (Context)
8731           CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8732                              Init, RParenLoc);
8733     else
8734       BOMInit = new (Context)
8735           CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8736                              LParenLoc, Init, RParenLoc);
8737
8738     if (/*IsWritten*/readBool()) {
8739       unsigned SourceOrder = readInt();
8740       BOMInit->setSourceOrder(SourceOrder);
8741     }
8742
8743     CtorInitializers[i] = BOMInit;
8744   }
8745
8746   return CtorInitializers;
8747 }
8748
8749 NestedNameSpecifierLoc
8750 ASTRecordReader::readNestedNameSpecifierLoc() {
8751   ASTContext &Context = getContext();
8752   unsigned N = readInt();
8753   NestedNameSpecifierLocBuilder Builder;
8754   for (unsigned I = 0; I != N; ++I) {
8755     auto Kind = readNestedNameSpecifierKind();
8756     switch (Kind) {
8757     case NestedNameSpecifier::Identifier: {
8758       IdentifierInfo *II = readIdentifier();
8759       SourceRange Range = readSourceRange();
8760       Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8761       break;
8762     }
8763
8764     case NestedNameSpecifier::Namespace: {
8765       NamespaceDecl *NS = readDeclAs<NamespaceDecl>();
8766       SourceRange Range = readSourceRange();
8767       Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8768       break;
8769     }
8770
8771     case NestedNameSpecifier::NamespaceAlias: {
8772       NamespaceAliasDecl *Alias = readDeclAs<NamespaceAliasDecl>();
8773       SourceRange Range = readSourceRange();
8774       Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8775       break;
8776     }
8777
8778     case NestedNameSpecifier::TypeSpec:
8779     case NestedNameSpecifier::TypeSpecWithTemplate: {
8780       bool Template = readBool();
8781       TypeSourceInfo *T = readTypeSourceInfo();
8782       if (!T)
8783         return NestedNameSpecifierLoc();
8784       SourceLocation ColonColonLoc = readSourceLocation();
8785
8786       // FIXME: 'template' keyword location not saved anywhere, so we fake it.
8787       Builder.Extend(Context,
8788                      Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8789                      T->getTypeLoc(), ColonColonLoc);
8790       break;
8791     }
8792
8793     case NestedNameSpecifier::Global: {
8794       SourceLocation ColonColonLoc = readSourceLocation();
8795       Builder.MakeGlobal(Context, ColonColonLoc);
8796       break;
8797     }
8798
8799     case NestedNameSpecifier::Super: {
8800       CXXRecordDecl *RD = readDeclAs<CXXRecordDecl>();
8801       SourceRange Range = readSourceRange();
8802       Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8803       break;
8804     }
8805     }
8806   }
8807
8808   return Builder.getWithLocInContext(Context);
8809 }
8810
8811 SourceRange
8812 ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8813                            unsigned &Idx) {
8814   SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8815   SourceLocation end = ReadSourceLocation(F, Record, Idx);
8816   return SourceRange(beg, end);
8817 }
8818
8819 static FixedPointSemantics
8820 ReadFixedPointSemantics(const SmallVectorImpl<uint64_t> &Record,
8821                         unsigned &Idx) {
8822   unsigned Width = Record[Idx++];
8823   unsigned Scale = Record[Idx++];
8824   uint64_t Tmp = Record[Idx++];
8825   bool IsSigned = Tmp & 0x1;
8826   bool IsSaturated = Tmp & 0x2;
8827   bool HasUnsignedPadding = Tmp & 0x4;
8828   return FixedPointSemantics(Width, Scale, IsSigned, IsSaturated,
8829                              HasUnsignedPadding);
8830 }
8831
8832 static const llvm::fltSemantics &
8833 readAPFloatSemantics(ASTRecordReader &reader) {
8834   return llvm::APFloatBase::EnumToSemantics(
8835     static_cast<llvm::APFloatBase::Semantics>(reader.readInt()));
8836 }
8837
8838 APValue ASTRecordReader::readAPValue() {
8839   unsigned Kind = readInt();
8840   switch ((APValue::ValueKind) Kind) {
8841   case APValue::None:
8842     return APValue();
8843   case APValue::Indeterminate:
8844     return APValue::IndeterminateValue();
8845   case APValue::Int:
8846     return APValue(readAPSInt());
8847   case APValue::Float: {
8848     const llvm::fltSemantics &FloatSema = readAPFloatSemantics(*this);
8849     return APValue(readAPFloat(FloatSema));
8850   }
8851   case APValue::FixedPoint: {
8852     FixedPointSemantics FPSema = ReadFixedPointSemantics(Record, Idx);
8853     return APValue(APFixedPoint(readAPInt(), FPSema));
8854   }
8855   case APValue::ComplexInt: {
8856     llvm::APSInt First = readAPSInt();
8857     return APValue(std::move(First), readAPSInt());
8858   }
8859   case APValue::ComplexFloat: {
8860     const llvm::fltSemantics &FloatSema1 = readAPFloatSemantics(*this);
8861     llvm::APFloat First = readAPFloat(FloatSema1);
8862     const llvm::fltSemantics &FloatSema2 = readAPFloatSemantics(*this);
8863     return APValue(std::move(First), readAPFloat(FloatSema2));
8864   }
8865   case APValue::LValue:
8866   case APValue::Vector:
8867   case APValue::Array:
8868   case APValue::Struct:
8869   case APValue::Union:
8870   case APValue::MemberPointer:
8871   case APValue::AddrLabelDiff:
8872     // TODO : Handle all these APValue::ValueKind.
8873     return APValue();
8874   }
8875   llvm_unreachable("Invalid APValue::ValueKind");
8876 }
8877
8878 /// Read a floating-point value
8879 llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) {
8880   return llvm::APFloat(Sem, readAPInt());
8881 }
8882
8883 // Read a string
8884 std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8885   unsigned Len = Record[Idx++];
8886   std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8887   Idx += Len;
8888   return Result;
8889 }
8890
8891 std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8892                                 unsigned &Idx) {
8893   std::string Filename = ReadString(Record, Idx);
8894   ResolveImportedPath(F, Filename);
8895   return Filename;
8896 }
8897
8898 std::string ASTReader::ReadPath(StringRef BaseDirectory,
8899                                 const RecordData &Record, unsigned &Idx) {
8900   std::string Filename = ReadString(Record, Idx);
8901   if (!BaseDirectory.empty())
8902     ResolveImportedPath(Filename, BaseDirectory);
8903   return Filename;
8904 }
8905
8906 VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8907                                          unsigned &Idx) {
8908   unsigned Major = Record[Idx++];
8909   unsigned Minor = Record[Idx++];
8910   unsigned Subminor = Record[Idx++];
8911   if (Minor == 0)
8912     return VersionTuple(Major);
8913   if (Subminor == 0)
8914     return VersionTuple(Major, Minor - 1);
8915   return VersionTuple(Major, Minor - 1, Subminor - 1);
8916 }
8917
8918 CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8919                                           const RecordData &Record,
8920                                           unsigned &Idx) {
8921   CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8922   return CXXTemporary::Create(getContext(), Decl);
8923 }
8924
8925 DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
8926   return Diag(CurrentImportLoc, DiagID);
8927 }
8928
8929 DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
8930   return Diags.Report(Loc, DiagID);
8931 }
8932
8933 /// Retrieve the identifier table associated with the
8934 /// preprocessor.
8935 IdentifierTable &ASTReader::getIdentifierTable() {
8936   return PP.getIdentifierTable();
8937 }
8938
8939 /// Record that the given ID maps to the given switch-case
8940 /// statement.
8941 void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
8942   assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
8943          "Already have a SwitchCase with this ID");
8944   (*CurrSwitchCaseStmts)[ID] = SC;
8945 }
8946
8947 /// Retrieve the switch-case statement with the given ID.
8948 SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
8949   assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
8950   return (*CurrSwitchCaseStmts)[ID];
8951 }
8952
8953 void ASTReader::ClearSwitchCaseIDs() {
8954   CurrSwitchCaseStmts->clear();
8955 }
8956
8957 void ASTReader::ReadComments() {
8958   ASTContext &Context = getContext();
8959   std::vector<RawComment *> Comments;
8960   for (SmallVectorImpl<std::pair<BitstreamCursor,
8961                                  serialization::ModuleFile *>>::iterator
8962        I = CommentsCursors.begin(),
8963        E = CommentsCursors.end();
8964        I != E; ++I) {
8965     Comments.clear();
8966     BitstreamCursor &Cursor = I->first;
8967     serialization::ModuleFile &F = *I->second;
8968     SavedStreamPosition SavedPosition(Cursor);
8969
8970     RecordData Record;
8971     while (true) {
8972       Expected<llvm::BitstreamEntry> MaybeEntry =
8973           Cursor.advanceSkippingSubblocks(
8974               BitstreamCursor::AF_DontPopBlockAtEnd);
8975       if (!MaybeEntry) {
8976         Error(MaybeEntry.takeError());
8977         return;
8978       }
8979       llvm::BitstreamEntry Entry = MaybeEntry.get();
8980
8981       switch (Entry.Kind) {
8982       case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8983       case llvm::BitstreamEntry::Error:
8984         Error("malformed block record in AST file");
8985         return;
8986       case llvm::BitstreamEntry::EndBlock:
8987         goto NextCursor;
8988       case llvm::BitstreamEntry::Record:
8989         // The interesting case.
8990         break;
8991       }
8992
8993       // Read a record.
8994       Record.clear();
8995       Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
8996       if (!MaybeComment) {
8997         Error(MaybeComment.takeError());
8998         return;
8999       }
9000       switch ((CommentRecordTypes)MaybeComment.get()) {
9001       case COMMENTS_RAW_COMMENT: {
9002         unsigned Idx = 0;
9003         SourceRange SR = ReadSourceRange(F, Record, Idx);
9004         RawComment::CommentKind Kind =
9005             (RawComment::CommentKind) Record[Idx++];
9006         bool IsTrailingComment = Record[Idx++];
9007         bool IsAlmostTrailingComment = Record[Idx++];
9008         Comments.push_back(new (Context) RawComment(
9009             SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
9010         break;
9011       }
9012       }
9013     }
9014   NextCursor:
9015     llvm::DenseMap<FileID, std::map<unsigned, RawComment *>>
9016         FileToOffsetToComment;
9017     for (RawComment *C : Comments) {
9018       SourceLocation CommentLoc = C->getBeginLoc();
9019       if (CommentLoc.isValid()) {
9020         std::pair<FileID, unsigned> Loc =
9021             SourceMgr.getDecomposedLoc(CommentLoc);
9022         if (Loc.first.isValid())
9023           Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
9024       }
9025     }
9026   }
9027 }
9028
9029 void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
9030                                 bool IncludeSystem, bool Complain,
9031                     llvm::function_ref<void(const serialization::InputFile &IF,
9032                                             bool isSystem)> Visitor) {
9033   unsigned NumUserInputs = MF.NumUserInputFiles;
9034   unsigned NumInputs = MF.InputFilesLoaded.size();
9035   assert(NumUserInputs <= NumInputs);
9036   unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9037   for (unsigned I = 0; I < N; ++I) {
9038     bool IsSystem = I >= NumUserInputs;
9039     InputFile IF = getInputFile(MF, I+1, Complain);
9040     Visitor(IF, IsSystem);
9041   }
9042 }
9043
9044 void ASTReader::visitTopLevelModuleMaps(
9045     serialization::ModuleFile &MF,
9046     llvm::function_ref<void(const FileEntry *FE)> Visitor) {
9047   unsigned NumInputs = MF.InputFilesLoaded.size();
9048   for (unsigned I = 0; I < NumInputs; ++I) {
9049     InputFileInfo IFI = readInputFileInfo(MF, I + 1);
9050     if (IFI.TopLevelModuleMap)
9051       // FIXME: This unnecessarily re-reads the InputFileInfo.
9052       if (auto *FE = getInputFile(MF, I + 1).getFile())
9053         Visitor(FE);
9054   }
9055 }
9056
9057 std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
9058   // If we know the owning module, use it.
9059   if (Module *M = D->getImportedOwningModule())
9060     return M->getFullModuleName();
9061
9062   // Otherwise, use the name of the top-level module the decl is within.
9063   if (ModuleFile *M = getOwningModuleFile(D))
9064     return M->ModuleName;
9065
9066   // Not from a module.
9067   return {};
9068 }
9069
9070 void ASTReader::finishPendingActions() {
9071   while (!PendingIdentifierInfos.empty() || !PendingFunctionTypes.empty() ||
9072          !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
9073          !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
9074          !PendingUpdateRecords.empty()) {
9075     // If any identifiers with corresponding top-level declarations have
9076     // been loaded, load those declarations now.
9077     using TopLevelDeclsMap =
9078         llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
9079     TopLevelDeclsMap TopLevelDecls;
9080
9081     while (!PendingIdentifierInfos.empty()) {
9082       IdentifierInfo *II = PendingIdentifierInfos.back().first;
9083       SmallVector<uint32_t, 4> DeclIDs =
9084           std::move(PendingIdentifierInfos.back().second);
9085       PendingIdentifierInfos.pop_back();
9086
9087       SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
9088     }
9089
9090     // Load each function type that we deferred loading because it was a
9091     // deduced type that might refer to a local type declared within itself.
9092     for (unsigned I = 0; I != PendingFunctionTypes.size(); ++I) {
9093       auto *FD = PendingFunctionTypes[I].first;
9094       FD->setType(GetType(PendingFunctionTypes[I].second));
9095
9096       // If we gave a function a deduced return type, remember that we need to
9097       // propagate that along the redeclaration chain.
9098       auto *DT = FD->getReturnType()->getContainedDeducedType();
9099       if (DT && DT->isDeduced())
9100         PendingDeducedTypeUpdates.insert(
9101             {FD->getCanonicalDecl(), FD->getReturnType()});
9102     }
9103     PendingFunctionTypes.clear();
9104
9105     // For each decl chain that we wanted to complete while deserializing, mark
9106     // it as "still needs to be completed".
9107     for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
9108       markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
9109     }
9110     PendingIncompleteDeclChains.clear();
9111
9112     // Load pending declaration chains.
9113     for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
9114       loadPendingDeclChain(PendingDeclChains[I].first,
9115                            PendingDeclChains[I].second);
9116     PendingDeclChains.clear();
9117
9118     // Make the most recent of the top-level declarations visible.
9119     for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
9120            TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
9121       IdentifierInfo *II = TLD->first;
9122       for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
9123         pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
9124       }
9125     }
9126
9127     // Load any pending macro definitions.
9128     for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
9129       IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
9130       SmallVector<PendingMacroInfo, 2> GlobalIDs;
9131       GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
9132       // Initialize the macro history from chained-PCHs ahead of module imports.
9133       for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
9134            ++IDIdx) {
9135         const PendingMacroInfo &Info = GlobalIDs[IDIdx];
9136         if (!Info.M->isModule())
9137           resolvePendingMacro(II, Info);
9138       }
9139       // Handle module imports.
9140       for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
9141            ++IDIdx) {
9142         const PendingMacroInfo &Info = GlobalIDs[IDIdx];
9143         if (Info.M->isModule())
9144           resolvePendingMacro(II, Info);
9145       }
9146     }
9147     PendingMacroIDs.clear();
9148
9149     // Wire up the DeclContexts for Decls that we delayed setting until
9150     // recursive loading is completed.
9151     while (!PendingDeclContextInfos.empty()) {
9152       PendingDeclContextInfo Info = PendingDeclContextInfos.front();
9153       PendingDeclContextInfos.pop_front();
9154       DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
9155       DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
9156       Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9157     }
9158
9159     // Perform any pending declaration updates.
9160     while (!PendingUpdateRecords.empty()) {
9161       auto Update = PendingUpdateRecords.pop_back_val();
9162       ReadingKindTracker ReadingKind(Read_Decl, *this);
9163       loadDeclUpdateRecords(Update);
9164     }
9165   }
9166
9167   // At this point, all update records for loaded decls are in place, so any
9168   // fake class definitions should have become real.
9169   assert(PendingFakeDefinitionData.empty() &&
9170          "faked up a class definition but never saw the real one");
9171
9172   // If we deserialized any C++ or Objective-C class definitions, any
9173   // Objective-C protocol definitions, or any redeclarable templates, make sure
9174   // that all redeclarations point to the definitions. Note that this can only
9175   // happen now, after the redeclaration chains have been fully wired.
9176   for (Decl *D : PendingDefinitions) {
9177     if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9178       if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
9179         // Make sure that the TagType points at the definition.
9180         const_cast<TagType*>(TagT)->decl = TD;
9181       }
9182
9183       if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
9184         for (auto *R = getMostRecentExistingDecl(RD); R;
9185              R = R->getPreviousDecl()) {
9186           assert((R == D) ==
9187                      cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
9188                  "declaration thinks it's the definition but it isn't");
9189           cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
9190         }
9191       }
9192
9193       continue;
9194     }
9195
9196     if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
9197       // Make sure that the ObjCInterfaceType points at the definition.
9198       const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9199         ->Decl = ID;
9200
9201       for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9202         cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9203
9204       continue;
9205     }
9206
9207     if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
9208       for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9209         cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9210
9211       continue;
9212     }
9213
9214     auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
9215     for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9216       cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
9217   }
9218   PendingDefinitions.clear();
9219
9220   // Load the bodies of any functions or methods we've encountered. We do
9221   // this now (delayed) so that we can be sure that the declaration chains
9222   // have been fully wired up (hasBody relies on this).
9223   // FIXME: We shouldn't require complete redeclaration chains here.
9224   for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9225                                PBEnd = PendingBodies.end();
9226        PB != PBEnd; ++PB) {
9227     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
9228       // For a function defined inline within a class template, force the
9229       // canonical definition to be the one inside the canonical definition of
9230       // the template. This ensures that we instantiate from a correct view
9231       // of the template.
9232       //
9233       // Sadly we can't do this more generally: we can't be sure that all
9234       // copies of an arbitrary class definition will have the same members
9235       // defined (eg, some member functions may not be instantiated, and some
9236       // special members may or may not have been implicitly defined).
9237       if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent()))
9238         if (RD->isDependentContext() && !RD->isThisDeclarationADefinition())
9239           continue;
9240
9241       // FIXME: Check for =delete/=default?
9242       // FIXME: Complain about ODR violations here?
9243       const FunctionDecl *Defn = nullptr;
9244       if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
9245         FD->setLazyBody(PB->second);
9246       } else {
9247         auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
9248         mergeDefinitionVisibility(NonConstDefn, FD);
9249
9250         if (!FD->isLateTemplateParsed() &&
9251             !NonConstDefn->isLateTemplateParsed() &&
9252             FD->getODRHash() != NonConstDefn->getODRHash()) {
9253           if (!isa<CXXMethodDecl>(FD)) {
9254             PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9255           } else if (FD->getLexicalParent()->isFileContext() &&
9256                      NonConstDefn->getLexicalParent()->isFileContext()) {
9257             // Only diagnose out-of-line method definitions.  If they are
9258             // in class definitions, then an error will be generated when
9259             // processing the class bodies.
9260             PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9261           }
9262         }
9263       }
9264       continue;
9265     }
9266
9267     ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
9268     if (!getContext().getLangOpts().Modules || !MD->hasBody())
9269       MD->setLazyBody(PB->second);
9270   }
9271   PendingBodies.clear();
9272
9273   // Do some cleanup.
9274   for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9275     getContext().deduplicateMergedDefinitonsFor(ND);
9276   PendingMergedDefinitionsToDeduplicate.clear();
9277 }
9278
9279 void ASTReader::diagnoseOdrViolations() {
9280   if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
9281       PendingFunctionOdrMergeFailures.empty() &&
9282       PendingEnumOdrMergeFailures.empty())
9283     return;
9284
9285   // Trigger the import of the full definition of each class that had any
9286   // odr-merging problems, so we can produce better diagnostics for them.
9287   // These updates may in turn find and diagnose some ODR failures, so take
9288   // ownership of the set first.
9289   auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
9290   PendingOdrMergeFailures.clear();
9291   for (auto &Merge : OdrMergeFailures) {
9292     Merge.first->buildLookup();
9293     Merge.first->decls_begin();
9294     Merge.first->bases_begin();
9295     Merge.first->vbases_begin();
9296     for (auto &RecordPair : Merge.second) {
9297       auto *RD = RecordPair.first;
9298       RD->decls_begin();
9299       RD->bases_begin();
9300       RD->vbases_begin();
9301     }
9302   }
9303
9304   // Trigger the import of functions.
9305   auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
9306   PendingFunctionOdrMergeFailures.clear();
9307   for (auto &Merge : FunctionOdrMergeFailures) {
9308     Merge.first->buildLookup();
9309     Merge.first->decls_begin();
9310     Merge.first->getBody();
9311     for (auto &FD : Merge.second) {
9312       FD->buildLookup();
9313       FD->decls_begin();
9314       FD->getBody();
9315     }
9316   }
9317
9318   // Trigger the import of enums.
9319   auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
9320   PendingEnumOdrMergeFailures.clear();
9321   for (auto &Merge : EnumOdrMergeFailures) {
9322     Merge.first->decls_begin();
9323     for (auto &Enum : Merge.second) {
9324       Enum->decls_begin();
9325     }
9326   }
9327
9328   // For each declaration from a merged context, check that the canonical
9329   // definition of that context also contains a declaration of the same
9330   // entity.
9331   //
9332   // Caution: this loop does things that might invalidate iterators into
9333   // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
9334   while (!PendingOdrMergeChecks.empty()) {
9335     NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
9336
9337     // FIXME: Skip over implicit declarations for now. This matters for things
9338     // like implicitly-declared special member functions. This isn't entirely
9339     // correct; we can end up with multiple unmerged declarations of the same
9340     // implicit entity.
9341     if (D->isImplicit())
9342       continue;
9343
9344     DeclContext *CanonDef = D->getDeclContext();
9345
9346     bool Found = false;
9347     const Decl *DCanon = D->getCanonicalDecl();
9348
9349     for (auto RI : D->redecls()) {
9350       if (RI->getLexicalDeclContext() == CanonDef) {
9351         Found = true;
9352         break;
9353       }
9354     }
9355     if (Found)
9356       continue;
9357
9358     // Quick check failed, time to do the slow thing. Note, we can't just
9359     // look up the name of D in CanonDef here, because the member that is
9360     // in CanonDef might not be found by name lookup (it might have been
9361     // replaced by a more recent declaration in the lookup table), and we
9362     // can't necessarily find it in the redeclaration chain because it might
9363     // be merely mergeable, not redeclarable.
9364     llvm::SmallVector<const NamedDecl*, 4> Candidates;
9365     for (auto *CanonMember : CanonDef->decls()) {
9366       if (CanonMember->getCanonicalDecl() == DCanon) {
9367         // This can happen if the declaration is merely mergeable and not
9368         // actually redeclarable (we looked for redeclarations earlier).
9369         //
9370         // FIXME: We should be able to detect this more efficiently, without
9371         // pulling in all of the members of CanonDef.
9372         Found = true;
9373         break;
9374       }
9375       if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
9376         if (ND->getDeclName() == D->getDeclName())
9377           Candidates.push_back(ND);
9378     }
9379
9380     if (!Found) {
9381       // The AST doesn't like TagDecls becoming invalid after they've been
9382       // completed. We only really need to mark FieldDecls as invalid here.
9383       if (!isa<TagDecl>(D))
9384         D->setInvalidDecl();
9385
9386       // Ensure we don't accidentally recursively enter deserialization while
9387       // we're producing our diagnostic.
9388       Deserializing RecursionGuard(this);
9389
9390       std::string CanonDefModule =
9391           getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
9392       Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9393         << D << getOwningModuleNameForDiagnostic(D)
9394         << CanonDef << CanonDefModule.empty() << CanonDefModule;
9395
9396       if (Candidates.empty())
9397         Diag(cast<Decl>(CanonDef)->getLocation(),
9398              diag::note_module_odr_violation_no_possible_decls) << D;
9399       else {
9400         for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
9401           Diag(Candidates[I]->getLocation(),
9402                diag::note_module_odr_violation_possible_decl)
9403             << Candidates[I];
9404       }
9405
9406       DiagnosedOdrMergeFailures.insert(CanonDef);
9407     }
9408   }
9409
9410   if (OdrMergeFailures.empty() && FunctionOdrMergeFailures.empty() &&
9411       EnumOdrMergeFailures.empty())
9412     return;
9413
9414   // Ensure we don't accidentally recursively enter deserialization while
9415   // we're producing our diagnostics.
9416   Deserializing RecursionGuard(this);
9417
9418   // Common code for hashing helpers.
9419   ODRHash Hash;
9420   auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
9421     Hash.clear();
9422     Hash.AddQualType(Ty);
9423     return Hash.CalculateHash();
9424   };
9425
9426   auto ComputeODRHash = [&Hash](const Stmt *S) {
9427     assert(S);
9428     Hash.clear();
9429     Hash.AddStmt(S);
9430     return Hash.CalculateHash();
9431   };
9432
9433   auto ComputeSubDeclODRHash = [&Hash](const Decl *D) {
9434     assert(D);
9435     Hash.clear();
9436     Hash.AddSubDecl(D);
9437     return Hash.CalculateHash();
9438   };
9439
9440   auto ComputeTemplateArgumentODRHash = [&Hash](const TemplateArgument &TA) {
9441     Hash.clear();
9442     Hash.AddTemplateArgument(TA);
9443     return Hash.CalculateHash();
9444   };
9445
9446   auto ComputeTemplateParameterListODRHash =
9447       [&Hash](const TemplateParameterList *TPL) {
9448         assert(TPL);
9449         Hash.clear();
9450         Hash.AddTemplateParameterList(TPL);
9451         return Hash.CalculateHash();
9452       };
9453
9454   // Issue any pending ODR-failure diagnostics.
9455   for (auto &Merge : OdrMergeFailures) {
9456     // If we've already pointed out a specific problem with this class, don't
9457     // bother issuing a general "something's different" diagnostic.
9458     if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
9459       continue;
9460
9461     bool Diagnosed = false;
9462     CXXRecordDecl *FirstRecord = Merge.first;
9463     std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
9464     for (auto &RecordPair : Merge.second) {
9465       CXXRecordDecl *SecondRecord = RecordPair.first;
9466       // Multiple different declarations got merged together; tell the user
9467       // where they came from.
9468       if (FirstRecord == SecondRecord)
9469         continue;
9470
9471       std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
9472
9473       auto *FirstDD = FirstRecord->DefinitionData;
9474       auto *SecondDD = RecordPair.second;
9475
9476       assert(FirstDD && SecondDD && "Definitions without DefinitionData");
9477
9478       // Diagnostics from DefinitionData are emitted here.
9479       if (FirstDD != SecondDD) {
9480         enum ODRDefinitionDataDifference {
9481           NumBases,
9482           NumVBases,
9483           BaseType,
9484           BaseVirtual,
9485           BaseAccess,
9486         };
9487         auto ODRDiagError = [FirstRecord, &FirstModule,
9488                              this](SourceLocation Loc, SourceRange Range,
9489                                    ODRDefinitionDataDifference DiffType) {
9490           return Diag(Loc, diag::err_module_odr_violation_definition_data)
9491                  << FirstRecord << FirstModule.empty() << FirstModule << Range
9492                  << DiffType;
9493         };
9494         auto ODRDiagNote = [&SecondModule,
9495                             this](SourceLocation Loc, SourceRange Range,
9496                                   ODRDefinitionDataDifference DiffType) {
9497           return Diag(Loc, diag::note_module_odr_violation_definition_data)
9498                  << SecondModule << Range << DiffType;
9499         };
9500
9501         unsigned FirstNumBases = FirstDD->NumBases;
9502         unsigned FirstNumVBases = FirstDD->NumVBases;
9503         unsigned SecondNumBases = SecondDD->NumBases;
9504         unsigned SecondNumVBases = SecondDD->NumVBases;
9505
9506         auto GetSourceRange = [](struct CXXRecordDecl::DefinitionData *DD) {
9507           unsigned NumBases = DD->NumBases;
9508           if (NumBases == 0) return SourceRange();
9509           auto bases = DD->bases();
9510           return SourceRange(bases[0].getBeginLoc(),
9511                              bases[NumBases - 1].getEndLoc());
9512         };
9513
9514         if (FirstNumBases != SecondNumBases) {
9515           ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
9516                        NumBases)
9517               << FirstNumBases;
9518           ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
9519                       NumBases)
9520               << SecondNumBases;
9521           Diagnosed = true;
9522           break;
9523         }
9524
9525         if (FirstNumVBases != SecondNumVBases) {
9526           ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
9527                        NumVBases)
9528               << FirstNumVBases;
9529           ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
9530                       NumVBases)
9531               << SecondNumVBases;
9532           Diagnosed = true;
9533           break;
9534         }
9535
9536         auto FirstBases = FirstDD->bases();
9537         auto SecondBases = SecondDD->bases();
9538         unsigned i = 0;
9539         for (i = 0; i < FirstNumBases; ++i) {
9540           auto FirstBase = FirstBases[i];
9541           auto SecondBase = SecondBases[i];
9542           if (ComputeQualTypeODRHash(FirstBase.getType()) !=
9543               ComputeQualTypeODRHash(SecondBase.getType())) {
9544             ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9545                          BaseType)
9546                 << (i + 1) << FirstBase.getType();
9547             ODRDiagNote(SecondRecord->getLocation(),
9548                         SecondBase.getSourceRange(), BaseType)
9549                 << (i + 1) << SecondBase.getType();
9550             break;
9551           }
9552
9553           if (FirstBase.isVirtual() != SecondBase.isVirtual()) {
9554             ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9555                          BaseVirtual)
9556                 << (i + 1) << FirstBase.isVirtual() << FirstBase.getType();
9557             ODRDiagNote(SecondRecord->getLocation(),
9558                         SecondBase.getSourceRange(), BaseVirtual)
9559                 << (i + 1) << SecondBase.isVirtual() << SecondBase.getType();
9560             break;
9561           }
9562
9563           if (FirstBase.getAccessSpecifierAsWritten() !=
9564               SecondBase.getAccessSpecifierAsWritten()) {
9565             ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9566                          BaseAccess)
9567                 << (i + 1) << FirstBase.getType()
9568                 << (int)FirstBase.getAccessSpecifierAsWritten();
9569             ODRDiagNote(SecondRecord->getLocation(),
9570                         SecondBase.getSourceRange(), BaseAccess)
9571                 << (i + 1) << SecondBase.getType()
9572                 << (int)SecondBase.getAccessSpecifierAsWritten();
9573             break;
9574           }
9575         }
9576
9577         if (i != FirstNumBases) {
9578           Diagnosed = true;
9579           break;
9580         }
9581       }
9582
9583       using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
9584
9585       const ClassTemplateDecl *FirstTemplate =
9586           FirstRecord->getDescribedClassTemplate();
9587       const ClassTemplateDecl *SecondTemplate =
9588           SecondRecord->getDescribedClassTemplate();
9589
9590       assert(!FirstTemplate == !SecondTemplate &&
9591              "Both pointers should be null or non-null");
9592
9593       enum ODRTemplateDifference {
9594         ParamEmptyName,
9595         ParamName,
9596         ParamSingleDefaultArgument,
9597         ParamDifferentDefaultArgument,
9598       };
9599
9600       if (FirstTemplate && SecondTemplate) {
9601         DeclHashes FirstTemplateHashes;
9602         DeclHashes SecondTemplateHashes;
9603
9604         auto PopulateTemplateParameterHashs =
9605             [&ComputeSubDeclODRHash](DeclHashes &Hashes,
9606                                      const ClassTemplateDecl *TD) {
9607               for (auto *D : TD->getTemplateParameters()->asArray()) {
9608                 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
9609               }
9610             };
9611
9612         PopulateTemplateParameterHashs(FirstTemplateHashes, FirstTemplate);
9613         PopulateTemplateParameterHashs(SecondTemplateHashes, SecondTemplate);
9614
9615         assert(FirstTemplateHashes.size() == SecondTemplateHashes.size() &&
9616                "Number of template parameters should be equal.");
9617
9618         auto FirstIt = FirstTemplateHashes.begin();
9619         auto FirstEnd = FirstTemplateHashes.end();
9620         auto SecondIt = SecondTemplateHashes.begin();
9621         for (; FirstIt != FirstEnd; ++FirstIt, ++SecondIt) {
9622           if (FirstIt->second == SecondIt->second)
9623             continue;
9624
9625           auto ODRDiagError = [FirstRecord, &FirstModule,
9626                                this](SourceLocation Loc, SourceRange Range,
9627                                      ODRTemplateDifference DiffType) {
9628             return Diag(Loc, diag::err_module_odr_violation_template_parameter)
9629                    << FirstRecord << FirstModule.empty() << FirstModule << Range
9630                    << DiffType;
9631           };
9632           auto ODRDiagNote = [&SecondModule,
9633                               this](SourceLocation Loc, SourceRange Range,
9634                                     ODRTemplateDifference DiffType) {
9635             return Diag(Loc, diag::note_module_odr_violation_template_parameter)
9636                    << SecondModule << Range << DiffType;
9637           };
9638
9639           const NamedDecl* FirstDecl = cast<NamedDecl>(FirstIt->first);
9640           const NamedDecl* SecondDecl = cast<NamedDecl>(SecondIt->first);
9641
9642           assert(FirstDecl->getKind() == SecondDecl->getKind() &&
9643                  "Parameter Decl's should be the same kind.");
9644
9645           DeclarationName FirstName = FirstDecl->getDeclName();
9646           DeclarationName SecondName = SecondDecl->getDeclName();
9647
9648           if (FirstName != SecondName) {
9649             const bool FirstNameEmpty =
9650                 FirstName.isIdentifier() && !FirstName.getAsIdentifierInfo();
9651             const bool SecondNameEmpty =
9652                 SecondName.isIdentifier() && !SecondName.getAsIdentifierInfo();
9653             assert((!FirstNameEmpty || !SecondNameEmpty) &&
9654                    "Both template parameters cannot be unnamed.");
9655             ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9656                          FirstNameEmpty ? ParamEmptyName : ParamName)
9657                 << FirstName;
9658             ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9659                         SecondNameEmpty ? ParamEmptyName : ParamName)
9660                 << SecondName;
9661             break;
9662           }
9663
9664           switch (FirstDecl->getKind()) {
9665           default:
9666             llvm_unreachable("Invalid template parameter type.");
9667           case Decl::TemplateTypeParm: {
9668             const auto *FirstParam = cast<TemplateTypeParmDecl>(FirstDecl);
9669             const auto *SecondParam = cast<TemplateTypeParmDecl>(SecondDecl);
9670             const bool HasFirstDefaultArgument =
9671                 FirstParam->hasDefaultArgument() &&
9672                 !FirstParam->defaultArgumentWasInherited();
9673             const bool HasSecondDefaultArgument =
9674                 SecondParam->hasDefaultArgument() &&
9675                 !SecondParam->defaultArgumentWasInherited();
9676
9677             if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9678               ODRDiagError(FirstDecl->getLocation(),
9679                            FirstDecl->getSourceRange(),
9680                            ParamSingleDefaultArgument)
9681                   << HasFirstDefaultArgument;
9682               ODRDiagNote(SecondDecl->getLocation(),
9683                           SecondDecl->getSourceRange(),
9684                           ParamSingleDefaultArgument)
9685                   << HasSecondDefaultArgument;
9686               break;
9687             }
9688
9689             assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9690                    "Expecting default arguments.");
9691
9692             ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9693                          ParamDifferentDefaultArgument);
9694             ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9695                         ParamDifferentDefaultArgument);
9696
9697             break;
9698           }
9699           case Decl::NonTypeTemplateParm: {
9700             const auto *FirstParam = cast<NonTypeTemplateParmDecl>(FirstDecl);
9701             const auto *SecondParam = cast<NonTypeTemplateParmDecl>(SecondDecl);
9702             const bool HasFirstDefaultArgument =
9703                 FirstParam->hasDefaultArgument() &&
9704                 !FirstParam->defaultArgumentWasInherited();
9705             const bool HasSecondDefaultArgument =
9706                 SecondParam->hasDefaultArgument() &&
9707                 !SecondParam->defaultArgumentWasInherited();
9708
9709             if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9710               ODRDiagError(FirstDecl->getLocation(),
9711                            FirstDecl->getSourceRange(),
9712                            ParamSingleDefaultArgument)
9713                   << HasFirstDefaultArgument;
9714               ODRDiagNote(SecondDecl->getLocation(),
9715                           SecondDecl->getSourceRange(),
9716                           ParamSingleDefaultArgument)
9717                   << HasSecondDefaultArgument;
9718               break;
9719             }
9720
9721             assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9722                    "Expecting default arguments.");
9723
9724             ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9725                          ParamDifferentDefaultArgument);
9726             ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9727                         ParamDifferentDefaultArgument);
9728
9729             break;
9730           }
9731           case Decl::TemplateTemplateParm: {
9732             const auto *FirstParam = cast<TemplateTemplateParmDecl>(FirstDecl);
9733             const auto *SecondParam =
9734                 cast<TemplateTemplateParmDecl>(SecondDecl);
9735             const bool HasFirstDefaultArgument =
9736                 FirstParam->hasDefaultArgument() &&
9737                 !FirstParam->defaultArgumentWasInherited();
9738             const bool HasSecondDefaultArgument =
9739                 SecondParam->hasDefaultArgument() &&
9740                 !SecondParam->defaultArgumentWasInherited();
9741
9742             if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9743               ODRDiagError(FirstDecl->getLocation(),
9744                            FirstDecl->getSourceRange(),
9745                            ParamSingleDefaultArgument)
9746                   << HasFirstDefaultArgument;
9747               ODRDiagNote(SecondDecl->getLocation(),
9748                           SecondDecl->getSourceRange(),
9749                           ParamSingleDefaultArgument)
9750                   << HasSecondDefaultArgument;
9751               break;
9752             }
9753
9754             assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9755                    "Expecting default arguments.");
9756
9757             ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9758                          ParamDifferentDefaultArgument);
9759             ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9760                         ParamDifferentDefaultArgument);
9761
9762             break;
9763           }
9764           }
9765
9766           break;
9767         }
9768
9769         if (FirstIt != FirstEnd) {
9770           Diagnosed = true;
9771           break;
9772         }
9773       }
9774
9775       DeclHashes FirstHashes;
9776       DeclHashes SecondHashes;
9777
9778       auto PopulateHashes = [&ComputeSubDeclODRHash, FirstRecord](
9779                                 DeclHashes &Hashes, CXXRecordDecl *Record) {
9780         for (auto *D : Record->decls()) {
9781           // Due to decl merging, the first CXXRecordDecl is the parent of
9782           // Decls in both records.
9783           if (!ODRHash::isWhitelistedDecl(D, FirstRecord))
9784             continue;
9785           Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
9786         }
9787       };
9788       PopulateHashes(FirstHashes, FirstRecord);
9789       PopulateHashes(SecondHashes, SecondRecord);
9790
9791       // Used with err_module_odr_violation_mismatch_decl and
9792       // note_module_odr_violation_mismatch_decl
9793       // This list should be the same Decl's as in ODRHash::isWhiteListedDecl
9794       enum {
9795         EndOfClass,
9796         PublicSpecifer,
9797         PrivateSpecifer,
9798         ProtectedSpecifer,
9799         StaticAssert,
9800         Field,
9801         CXXMethod,
9802         TypeAlias,
9803         TypeDef,
9804         Var,
9805         Friend,
9806         FunctionTemplate,
9807         Other
9808       } FirstDiffType = Other,
9809         SecondDiffType = Other;
9810
9811       auto DifferenceSelector = [](Decl *D) {
9812         assert(D && "valid Decl required");
9813         switch (D->getKind()) {
9814         default:
9815           return Other;
9816         case Decl::AccessSpec:
9817           switch (D->getAccess()) {
9818           case AS_public:
9819             return PublicSpecifer;
9820           case AS_private:
9821             return PrivateSpecifer;
9822           case AS_protected:
9823             return ProtectedSpecifer;
9824           case AS_none:
9825             break;
9826           }
9827           llvm_unreachable("Invalid access specifier");
9828         case Decl::StaticAssert:
9829           return StaticAssert;
9830         case Decl::Field:
9831           return Field;
9832         case Decl::CXXMethod:
9833         case Decl::CXXConstructor:
9834         case Decl::CXXDestructor:
9835           return CXXMethod;
9836         case Decl::TypeAlias:
9837           return TypeAlias;
9838         case Decl::Typedef:
9839           return TypeDef;
9840         case Decl::Var:
9841           return Var;
9842         case Decl::Friend:
9843           return Friend;
9844         case Decl::FunctionTemplate:
9845           return FunctionTemplate;
9846         }
9847       };
9848
9849       Decl *FirstDecl = nullptr;
9850       Decl *SecondDecl = nullptr;
9851       auto FirstIt = FirstHashes.begin();
9852       auto SecondIt = SecondHashes.begin();
9853
9854       // If there is a diagnoseable difference, FirstDiffType and
9855       // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
9856       // filled in if not EndOfClass.
9857       while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
9858         if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
9859             FirstIt->second == SecondIt->second) {
9860           ++FirstIt;
9861           ++SecondIt;
9862           continue;
9863         }
9864
9865         FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
9866         SecondDecl = SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
9867
9868         FirstDiffType = FirstDecl ? DifferenceSelector(FirstDecl) : EndOfClass;
9869         SecondDiffType =
9870             SecondDecl ? DifferenceSelector(SecondDecl) : EndOfClass;
9871
9872         break;
9873       }
9874
9875       if (FirstDiffType == Other || SecondDiffType == Other) {
9876         // Reaching this point means an unexpected Decl was encountered
9877         // or no difference was detected.  This causes a generic error
9878         // message to be emitted.
9879         Diag(FirstRecord->getLocation(),
9880              diag::err_module_odr_violation_different_definitions)
9881             << FirstRecord << FirstModule.empty() << FirstModule;
9882
9883         if (FirstDecl) {
9884           Diag(FirstDecl->getLocation(), diag::note_first_module_difference)
9885               << FirstRecord << FirstDecl->getSourceRange();
9886         }
9887
9888         Diag(SecondRecord->getLocation(),
9889              diag::note_module_odr_violation_different_definitions)
9890             << SecondModule;
9891
9892         if (SecondDecl) {
9893           Diag(SecondDecl->getLocation(), diag::note_second_module_difference)
9894               << SecondDecl->getSourceRange();
9895         }
9896
9897         Diagnosed = true;
9898         break;
9899       }
9900
9901       if (FirstDiffType != SecondDiffType) {
9902         SourceLocation FirstLoc;
9903         SourceRange FirstRange;
9904         if (FirstDiffType == EndOfClass) {
9905           FirstLoc = FirstRecord->getBraceRange().getEnd();
9906         } else {
9907           FirstLoc = FirstIt->first->getLocation();
9908           FirstRange = FirstIt->first->getSourceRange();
9909         }
9910         Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
9911             << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
9912             << FirstDiffType;
9913
9914         SourceLocation SecondLoc;
9915         SourceRange SecondRange;
9916         if (SecondDiffType == EndOfClass) {
9917           SecondLoc = SecondRecord->getBraceRange().getEnd();
9918         } else {
9919           SecondLoc = SecondDecl->getLocation();
9920           SecondRange = SecondDecl->getSourceRange();
9921         }
9922         Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
9923             << SecondModule << SecondRange << SecondDiffType;
9924         Diagnosed = true;
9925         break;
9926       }
9927
9928       assert(FirstDiffType == SecondDiffType);
9929
9930       // Used with err_module_odr_violation_mismatch_decl_diff and
9931       // note_module_odr_violation_mismatch_decl_diff
9932       enum ODRDeclDifference {
9933         StaticAssertCondition,
9934         StaticAssertMessage,
9935         StaticAssertOnlyMessage,
9936         FieldName,
9937         FieldTypeName,
9938         FieldSingleBitField,
9939         FieldDifferentWidthBitField,
9940         FieldSingleMutable,
9941         FieldSingleInitializer,
9942         FieldDifferentInitializers,
9943         MethodName,
9944         MethodDeleted,
9945         MethodDefaulted,
9946         MethodVirtual,
9947         MethodStatic,
9948         MethodVolatile,
9949         MethodConst,
9950         MethodInline,
9951         MethodNumberParameters,
9952         MethodParameterType,
9953         MethodParameterName,
9954         MethodParameterSingleDefaultArgument,
9955         MethodParameterDifferentDefaultArgument,
9956         MethodNoTemplateArguments,
9957         MethodDifferentNumberTemplateArguments,
9958         MethodDifferentTemplateArgument,
9959         MethodSingleBody,
9960         MethodDifferentBody,
9961         TypedefName,
9962         TypedefType,
9963         VarName,
9964         VarType,
9965         VarSingleInitializer,
9966         VarDifferentInitializer,
9967         VarConstexpr,
9968         FriendTypeFunction,
9969         FriendType,
9970         FriendFunction,
9971         FunctionTemplateDifferentNumberParameters,
9972         FunctionTemplateParameterDifferentKind,
9973         FunctionTemplateParameterName,
9974         FunctionTemplateParameterSingleDefaultArgument,
9975         FunctionTemplateParameterDifferentDefaultArgument,
9976         FunctionTemplateParameterDifferentType,
9977         FunctionTemplatePackParameter,
9978       };
9979
9980       // These lambdas have the common portions of the ODR diagnostics.  This
9981       // has the same return as Diag(), so addition parameters can be passed
9982       // in with operator<<
9983       auto ODRDiagError = [FirstRecord, &FirstModule, this](
9984           SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9985         return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
9986                << FirstRecord << FirstModule.empty() << FirstModule << Range
9987                << DiffType;
9988       };
9989       auto ODRDiagNote = [&SecondModule, this](
9990           SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9991         return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
9992                << SecondModule << Range << DiffType;
9993       };
9994
9995       switch (FirstDiffType) {
9996       case Other:
9997       case EndOfClass:
9998       case PublicSpecifer:
9999       case PrivateSpecifer:
10000       case ProtectedSpecifer:
10001         llvm_unreachable("Invalid diff type");
10002
10003       case StaticAssert: {
10004         StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
10005         StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
10006
10007         Expr *FirstExpr = FirstSA->getAssertExpr();
10008         Expr *SecondExpr = SecondSA->getAssertExpr();
10009         unsigned FirstODRHash = ComputeODRHash(FirstExpr);
10010         unsigned SecondODRHash = ComputeODRHash(SecondExpr);
10011         if (FirstODRHash != SecondODRHash) {
10012           ODRDiagError(FirstExpr->getBeginLoc(), FirstExpr->getSourceRange(),
10013                        StaticAssertCondition);
10014           ODRDiagNote(SecondExpr->getBeginLoc(), SecondExpr->getSourceRange(),
10015                       StaticAssertCondition);
10016           Diagnosed = true;
10017           break;
10018         }
10019
10020         StringLiteral *FirstStr = FirstSA->getMessage();
10021         StringLiteral *SecondStr = SecondSA->getMessage();
10022         assert((FirstStr || SecondStr) && "Both messages cannot be empty");
10023         if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
10024           SourceLocation FirstLoc, SecondLoc;
10025           SourceRange FirstRange, SecondRange;
10026           if (FirstStr) {
10027             FirstLoc = FirstStr->getBeginLoc();
10028             FirstRange = FirstStr->getSourceRange();
10029           } else {
10030             FirstLoc = FirstSA->getBeginLoc();
10031             FirstRange = FirstSA->getSourceRange();
10032           }
10033           if (SecondStr) {
10034             SecondLoc = SecondStr->getBeginLoc();
10035             SecondRange = SecondStr->getSourceRange();
10036           } else {
10037             SecondLoc = SecondSA->getBeginLoc();
10038             SecondRange = SecondSA->getSourceRange();
10039           }
10040           ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage)
10041               << (FirstStr == nullptr);
10042           ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage)
10043               << (SecondStr == nullptr);
10044           Diagnosed = true;
10045           break;
10046         }
10047
10048         if (FirstStr && SecondStr &&
10049             FirstStr->getString() != SecondStr->getString()) {
10050           ODRDiagError(FirstStr->getBeginLoc(), FirstStr->getSourceRange(),
10051                        StaticAssertMessage);
10052           ODRDiagNote(SecondStr->getBeginLoc(), SecondStr->getSourceRange(),
10053                       StaticAssertMessage);
10054           Diagnosed = true;
10055           break;
10056         }
10057         break;
10058       }
10059       case Field: {
10060         FieldDecl *FirstField = cast<FieldDecl>(FirstDecl);
10061         FieldDecl *SecondField = cast<FieldDecl>(SecondDecl);
10062         IdentifierInfo *FirstII = FirstField->getIdentifier();
10063         IdentifierInfo *SecondII = SecondField->getIdentifier();
10064         if (FirstII->getName() != SecondII->getName()) {
10065           ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10066                        FieldName)
10067               << FirstII;
10068           ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10069                       FieldName)
10070               << SecondII;
10071
10072           Diagnosed = true;
10073           break;
10074         }
10075
10076         assert(getContext().hasSameType(FirstField->getType(),
10077                                         SecondField->getType()));
10078
10079         QualType FirstType = FirstField->getType();
10080         QualType SecondType = SecondField->getType();
10081         if (ComputeQualTypeODRHash(FirstType) !=
10082             ComputeQualTypeODRHash(SecondType)) {
10083           ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10084                        FieldTypeName)
10085               << FirstII << FirstType;
10086           ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10087                       FieldTypeName)
10088               << SecondII << SecondType;
10089
10090           Diagnosed = true;
10091           break;
10092         }
10093
10094         const bool IsFirstBitField = FirstField->isBitField();
10095         const bool IsSecondBitField = SecondField->isBitField();
10096         if (IsFirstBitField != IsSecondBitField) {
10097           ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10098                        FieldSingleBitField)
10099               << FirstII << IsFirstBitField;
10100           ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10101                       FieldSingleBitField)
10102               << SecondII << IsSecondBitField;
10103           Diagnosed = true;
10104           break;
10105         }
10106
10107         if (IsFirstBitField && IsSecondBitField) {
10108           unsigned FirstBitWidthHash =
10109               ComputeODRHash(FirstField->getBitWidth());
10110           unsigned SecondBitWidthHash =
10111               ComputeODRHash(SecondField->getBitWidth());
10112           if (FirstBitWidthHash != SecondBitWidthHash) {
10113             ODRDiagError(FirstField->getLocation(),
10114                          FirstField->getSourceRange(),
10115                          FieldDifferentWidthBitField)
10116                 << FirstII << FirstField->getBitWidth()->getSourceRange();
10117             ODRDiagNote(SecondField->getLocation(),
10118                         SecondField->getSourceRange(),
10119                         FieldDifferentWidthBitField)
10120                 << SecondII << SecondField->getBitWidth()->getSourceRange();
10121             Diagnosed = true;
10122             break;
10123           }
10124         }
10125
10126         const bool IsFirstMutable = FirstField->isMutable();
10127         const bool IsSecondMutable = SecondField->isMutable();
10128         if (IsFirstMutable != IsSecondMutable) {
10129           ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10130                        FieldSingleMutable)
10131               << FirstII << IsFirstMutable;
10132           ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10133                       FieldSingleMutable)
10134               << SecondII << IsSecondMutable;
10135           Diagnosed = true;
10136           break;
10137         }
10138
10139         const Expr *FirstInitializer = FirstField->getInClassInitializer();
10140         const Expr *SecondInitializer = SecondField->getInClassInitializer();
10141         if ((!FirstInitializer && SecondInitializer) ||
10142             (FirstInitializer && !SecondInitializer)) {
10143           ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10144                        FieldSingleInitializer)
10145               << FirstII << (FirstInitializer != nullptr);
10146           ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10147                       FieldSingleInitializer)
10148               << SecondII << (SecondInitializer != nullptr);
10149           Diagnosed = true;
10150           break;
10151         }
10152
10153         if (FirstInitializer && SecondInitializer) {
10154           unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
10155           unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
10156           if (FirstInitHash != SecondInitHash) {
10157             ODRDiagError(FirstField->getLocation(),
10158                          FirstField->getSourceRange(),
10159                          FieldDifferentInitializers)
10160                 << FirstII << FirstInitializer->getSourceRange();
10161             ODRDiagNote(SecondField->getLocation(),
10162                         SecondField->getSourceRange(),
10163                         FieldDifferentInitializers)
10164                 << SecondII << SecondInitializer->getSourceRange();
10165             Diagnosed = true;
10166             break;
10167           }
10168         }
10169
10170         break;
10171       }
10172       case CXXMethod: {
10173         enum {
10174           DiagMethod,
10175           DiagConstructor,
10176           DiagDestructor,
10177         } FirstMethodType,
10178             SecondMethodType;
10179         auto GetMethodTypeForDiagnostics = [](const CXXMethodDecl* D) {
10180           if (isa<CXXConstructorDecl>(D)) return DiagConstructor;
10181           if (isa<CXXDestructorDecl>(D)) return DiagDestructor;
10182           return DiagMethod;
10183         };
10184         const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
10185         const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
10186         FirstMethodType = GetMethodTypeForDiagnostics(FirstMethod);
10187         SecondMethodType = GetMethodTypeForDiagnostics(SecondMethod);
10188         auto FirstName = FirstMethod->getDeclName();
10189         auto SecondName = SecondMethod->getDeclName();
10190         if (FirstMethodType != SecondMethodType || FirstName != SecondName) {
10191           ODRDiagError(FirstMethod->getLocation(),
10192                        FirstMethod->getSourceRange(), MethodName)
10193               << FirstMethodType << FirstName;
10194           ODRDiagNote(SecondMethod->getLocation(),
10195                       SecondMethod->getSourceRange(), MethodName)
10196               << SecondMethodType << SecondName;
10197
10198           Diagnosed = true;
10199           break;
10200         }
10201
10202         const bool FirstDeleted = FirstMethod->isDeletedAsWritten();
10203         const bool SecondDeleted = SecondMethod->isDeletedAsWritten();
10204         if (FirstDeleted != SecondDeleted) {
10205           ODRDiagError(FirstMethod->getLocation(),
10206                        FirstMethod->getSourceRange(), MethodDeleted)
10207               << FirstMethodType << FirstName << FirstDeleted;
10208
10209           ODRDiagNote(SecondMethod->getLocation(),
10210                       SecondMethod->getSourceRange(), MethodDeleted)
10211               << SecondMethodType << SecondName << SecondDeleted;
10212           Diagnosed = true;
10213           break;
10214         }
10215
10216         const bool FirstDefaulted = FirstMethod->isExplicitlyDefaulted();
10217         const bool SecondDefaulted = SecondMethod->isExplicitlyDefaulted();
10218         if (FirstDefaulted != SecondDefaulted) {
10219           ODRDiagError(FirstMethod->getLocation(),
10220                        FirstMethod->getSourceRange(), MethodDefaulted)
10221               << FirstMethodType << FirstName << FirstDefaulted;
10222
10223           ODRDiagNote(SecondMethod->getLocation(),
10224                       SecondMethod->getSourceRange(), MethodDefaulted)
10225               << SecondMethodType << SecondName << SecondDefaulted;
10226           Diagnosed = true;
10227           break;
10228         }
10229
10230         const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
10231         const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
10232         const bool FirstPure = FirstMethod->isPure();
10233         const bool SecondPure = SecondMethod->isPure();
10234         if ((FirstVirtual || SecondVirtual) &&
10235             (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
10236           ODRDiagError(FirstMethod->getLocation(),
10237                        FirstMethod->getSourceRange(), MethodVirtual)
10238               << FirstMethodType << FirstName << FirstPure << FirstVirtual;
10239           ODRDiagNote(SecondMethod->getLocation(),
10240                       SecondMethod->getSourceRange(), MethodVirtual)
10241               << SecondMethodType << SecondName << SecondPure << SecondVirtual;
10242           Diagnosed = true;
10243           break;
10244         }
10245
10246         // CXXMethodDecl::isStatic uses the canonical Decl.  With Decl merging,
10247         // FirstDecl is the canonical Decl of SecondDecl, so the storage
10248         // class needs to be checked instead.
10249         const auto FirstStorage = FirstMethod->getStorageClass();
10250         const auto SecondStorage = SecondMethod->getStorageClass();
10251         const bool FirstStatic = FirstStorage == SC_Static;
10252         const bool SecondStatic = SecondStorage == SC_Static;
10253         if (FirstStatic != SecondStatic) {
10254           ODRDiagError(FirstMethod->getLocation(),
10255                        FirstMethod->getSourceRange(), MethodStatic)
10256               << FirstMethodType << FirstName << FirstStatic;
10257           ODRDiagNote(SecondMethod->getLocation(),
10258                       SecondMethod->getSourceRange(), MethodStatic)
10259               << SecondMethodType << SecondName << SecondStatic;
10260           Diagnosed = true;
10261           break;
10262         }
10263
10264         const bool FirstVolatile = FirstMethod->isVolatile();
10265         const bool SecondVolatile = SecondMethod->isVolatile();
10266         if (FirstVolatile != SecondVolatile) {
10267           ODRDiagError(FirstMethod->getLocation(),
10268                        FirstMethod->getSourceRange(), MethodVolatile)
10269               << FirstMethodType << FirstName << FirstVolatile;
10270           ODRDiagNote(SecondMethod->getLocation(),
10271                       SecondMethod->getSourceRange(), MethodVolatile)
10272               << SecondMethodType << SecondName << SecondVolatile;
10273           Diagnosed = true;
10274           break;
10275         }
10276
10277         const bool FirstConst = FirstMethod->isConst();
10278         const bool SecondConst = SecondMethod->isConst();
10279         if (FirstConst != SecondConst) {
10280           ODRDiagError(FirstMethod->getLocation(),
10281                        FirstMethod->getSourceRange(), MethodConst)
10282               << FirstMethodType << FirstName << FirstConst;
10283           ODRDiagNote(SecondMethod->getLocation(),
10284                       SecondMethod->getSourceRange(), MethodConst)
10285               << SecondMethodType << SecondName << SecondConst;
10286           Diagnosed = true;
10287           break;
10288         }
10289
10290         const bool FirstInline = FirstMethod->isInlineSpecified();
10291         const bool SecondInline = SecondMethod->isInlineSpecified();
10292         if (FirstInline != SecondInline) {
10293           ODRDiagError(FirstMethod->getLocation(),
10294                        FirstMethod->getSourceRange(), MethodInline)
10295               << FirstMethodType << FirstName << FirstInline;
10296           ODRDiagNote(SecondMethod->getLocation(),
10297                       SecondMethod->getSourceRange(), MethodInline)
10298               << SecondMethodType << SecondName << SecondInline;
10299           Diagnosed = true;
10300           break;
10301         }
10302
10303         const unsigned FirstNumParameters = FirstMethod->param_size();
10304         const unsigned SecondNumParameters = SecondMethod->param_size();
10305         if (FirstNumParameters != SecondNumParameters) {
10306           ODRDiagError(FirstMethod->getLocation(),
10307                        FirstMethod->getSourceRange(), MethodNumberParameters)
10308               << FirstMethodType << FirstName << FirstNumParameters;
10309           ODRDiagNote(SecondMethod->getLocation(),
10310                       SecondMethod->getSourceRange(), MethodNumberParameters)
10311               << SecondMethodType << SecondName << SecondNumParameters;
10312           Diagnosed = true;
10313           break;
10314         }
10315
10316         // Need this status boolean to know when break out of the switch.
10317         bool ParameterMismatch = false;
10318         for (unsigned I = 0; I < FirstNumParameters; ++I) {
10319           const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I);
10320           const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I);
10321
10322           QualType FirstParamType = FirstParam->getType();
10323           QualType SecondParamType = SecondParam->getType();
10324           if (FirstParamType != SecondParamType &&
10325               ComputeQualTypeODRHash(FirstParamType) !=
10326                   ComputeQualTypeODRHash(SecondParamType)) {
10327             if (const DecayedType *ParamDecayedType =
10328                     FirstParamType->getAs<DecayedType>()) {
10329               ODRDiagError(FirstMethod->getLocation(),
10330                            FirstMethod->getSourceRange(), MethodParameterType)
10331                   << FirstMethodType << FirstName << (I + 1) << FirstParamType
10332                   << true << ParamDecayedType->getOriginalType();
10333             } else {
10334               ODRDiagError(FirstMethod->getLocation(),
10335                            FirstMethod->getSourceRange(), MethodParameterType)
10336                   << FirstMethodType << FirstName << (I + 1) << FirstParamType
10337                   << false;
10338             }
10339
10340             if (const DecayedType *ParamDecayedType =
10341                     SecondParamType->getAs<DecayedType>()) {
10342               ODRDiagNote(SecondMethod->getLocation(),
10343                           SecondMethod->getSourceRange(), MethodParameterType)
10344                   << SecondMethodType << SecondName << (I + 1)
10345                   << SecondParamType << true
10346                   << ParamDecayedType->getOriginalType();
10347             } else {
10348               ODRDiagNote(SecondMethod->getLocation(),
10349                           SecondMethod->getSourceRange(), MethodParameterType)
10350                   << SecondMethodType << SecondName << (I + 1)
10351                   << SecondParamType << false;
10352             }
10353             ParameterMismatch = true;
10354             break;
10355           }
10356
10357           DeclarationName FirstParamName = FirstParam->getDeclName();
10358           DeclarationName SecondParamName = SecondParam->getDeclName();
10359           if (FirstParamName != SecondParamName) {
10360             ODRDiagError(FirstMethod->getLocation(),
10361                          FirstMethod->getSourceRange(), MethodParameterName)
10362                 << FirstMethodType << FirstName << (I + 1) << FirstParamName;
10363             ODRDiagNote(SecondMethod->getLocation(),
10364                         SecondMethod->getSourceRange(), MethodParameterName)
10365                 << SecondMethodType << SecondName << (I + 1) << SecondParamName;
10366             ParameterMismatch = true;
10367             break;
10368           }
10369
10370           const Expr *FirstInit = FirstParam->getInit();
10371           const Expr *SecondInit = SecondParam->getInit();
10372           if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
10373             ODRDiagError(FirstMethod->getLocation(),
10374                          FirstMethod->getSourceRange(),
10375                          MethodParameterSingleDefaultArgument)
10376                 << FirstMethodType << FirstName << (I + 1)
10377                 << (FirstInit == nullptr)
10378                 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
10379             ODRDiagNote(SecondMethod->getLocation(),
10380                         SecondMethod->getSourceRange(),
10381                         MethodParameterSingleDefaultArgument)
10382                 << SecondMethodType << SecondName << (I + 1)
10383                 << (SecondInit == nullptr)
10384                 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
10385             ParameterMismatch = true;
10386             break;
10387           }
10388
10389           if (FirstInit && SecondInit &&
10390               ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
10391             ODRDiagError(FirstMethod->getLocation(),
10392                          FirstMethod->getSourceRange(),
10393                          MethodParameterDifferentDefaultArgument)
10394                 << FirstMethodType << FirstName << (I + 1)
10395                 << FirstInit->getSourceRange();
10396             ODRDiagNote(SecondMethod->getLocation(),
10397                         SecondMethod->getSourceRange(),
10398                         MethodParameterDifferentDefaultArgument)
10399                 << SecondMethodType << SecondName << (I + 1)
10400                 << SecondInit->getSourceRange();
10401             ParameterMismatch = true;
10402             break;
10403
10404           }
10405         }
10406
10407         if (ParameterMismatch) {
10408           Diagnosed = true;
10409           break;
10410         }
10411
10412         const auto *FirstTemplateArgs =
10413             FirstMethod->getTemplateSpecializationArgs();
10414         const auto *SecondTemplateArgs =
10415             SecondMethod->getTemplateSpecializationArgs();
10416
10417         if ((FirstTemplateArgs && !SecondTemplateArgs) ||
10418             (!FirstTemplateArgs && SecondTemplateArgs)) {
10419           ODRDiagError(FirstMethod->getLocation(),
10420                        FirstMethod->getSourceRange(), MethodNoTemplateArguments)
10421               << FirstMethodType << FirstName << (FirstTemplateArgs != nullptr);
10422           ODRDiagNote(SecondMethod->getLocation(),
10423                       SecondMethod->getSourceRange(), MethodNoTemplateArguments)
10424               << SecondMethodType << SecondName
10425               << (SecondTemplateArgs != nullptr);
10426
10427           Diagnosed = true;
10428           break;
10429         }
10430
10431         if (FirstTemplateArgs && SecondTemplateArgs) {
10432           // Remove pack expansions from argument list.
10433           auto ExpandTemplateArgumentList =
10434               [](const TemplateArgumentList *TAL) {
10435                 llvm::SmallVector<const TemplateArgument *, 8> ExpandedList;
10436                 for (const TemplateArgument &TA : TAL->asArray()) {
10437                   if (TA.getKind() != TemplateArgument::Pack) {
10438                     ExpandedList.push_back(&TA);
10439                     continue;
10440                   }
10441                   for (const TemplateArgument &PackTA : TA.getPackAsArray()) {
10442                     ExpandedList.push_back(&PackTA);
10443                   }
10444                 }
10445                 return ExpandedList;
10446               };
10447           llvm::SmallVector<const TemplateArgument *, 8> FirstExpandedList =
10448               ExpandTemplateArgumentList(FirstTemplateArgs);
10449           llvm::SmallVector<const TemplateArgument *, 8> SecondExpandedList =
10450               ExpandTemplateArgumentList(SecondTemplateArgs);
10451
10452           if (FirstExpandedList.size() != SecondExpandedList.size()) {
10453             ODRDiagError(FirstMethod->getLocation(),
10454                          FirstMethod->getSourceRange(),
10455                          MethodDifferentNumberTemplateArguments)
10456                 << FirstMethodType << FirstName
10457                 << (unsigned)FirstExpandedList.size();
10458             ODRDiagNote(SecondMethod->getLocation(),
10459                         SecondMethod->getSourceRange(),
10460                         MethodDifferentNumberTemplateArguments)
10461                 << SecondMethodType << SecondName
10462                 << (unsigned)SecondExpandedList.size();
10463
10464             Diagnosed = true;
10465             break;
10466           }
10467
10468           bool TemplateArgumentMismatch = false;
10469           for (unsigned i = 0, e = FirstExpandedList.size(); i != e; ++i) {
10470             const TemplateArgument &FirstTA = *FirstExpandedList[i],
10471                                    &SecondTA = *SecondExpandedList[i];
10472             if (ComputeTemplateArgumentODRHash(FirstTA) ==
10473                 ComputeTemplateArgumentODRHash(SecondTA)) {
10474               continue;
10475             }
10476
10477             ODRDiagError(FirstMethod->getLocation(),
10478                          FirstMethod->getSourceRange(),
10479                          MethodDifferentTemplateArgument)
10480                 << FirstMethodType << FirstName << FirstTA << i + 1;
10481             ODRDiagNote(SecondMethod->getLocation(),
10482                         SecondMethod->getSourceRange(),
10483                         MethodDifferentTemplateArgument)
10484                 << SecondMethodType << SecondName << SecondTA << i + 1;
10485
10486             TemplateArgumentMismatch = true;
10487             break;
10488           }
10489
10490           if (TemplateArgumentMismatch) {
10491             Diagnosed = true;
10492             break;
10493           }
10494         }
10495
10496         // Compute the hash of the method as if it has no body.
10497         auto ComputeCXXMethodODRHash = [&Hash](const CXXMethodDecl *D) {
10498           Hash.clear();
10499           Hash.AddFunctionDecl(D, true /*SkipBody*/);
10500           return Hash.CalculateHash();
10501         };
10502
10503         // Compare the hash generated to the hash stored.  A difference means
10504         // that a body was present in the original source.  Due to merging,
10505         // the stardard way of detecting a body will not work.
10506         const bool HasFirstBody =
10507             ComputeCXXMethodODRHash(FirstMethod) != FirstMethod->getODRHash();
10508         const bool HasSecondBody =
10509             ComputeCXXMethodODRHash(SecondMethod) != SecondMethod->getODRHash();
10510
10511         if (HasFirstBody != HasSecondBody) {
10512           ODRDiagError(FirstMethod->getLocation(),
10513                        FirstMethod->getSourceRange(), MethodSingleBody)
10514               << FirstMethodType << FirstName << HasFirstBody;
10515           ODRDiagNote(SecondMethod->getLocation(),
10516                       SecondMethod->getSourceRange(), MethodSingleBody)
10517               << SecondMethodType << SecondName << HasSecondBody;
10518           Diagnosed = true;
10519           break;
10520         }
10521
10522         if (HasFirstBody && HasSecondBody) {
10523           ODRDiagError(FirstMethod->getLocation(),
10524                        FirstMethod->getSourceRange(), MethodDifferentBody)
10525               << FirstMethodType << FirstName;
10526           ODRDiagNote(SecondMethod->getLocation(),
10527                       SecondMethod->getSourceRange(), MethodDifferentBody)
10528               << SecondMethodType << SecondName;
10529           Diagnosed = true;
10530           break;
10531         }
10532
10533         break;
10534       }
10535       case TypeAlias:
10536       case TypeDef: {
10537         TypedefNameDecl *FirstTD = cast<TypedefNameDecl>(FirstDecl);
10538         TypedefNameDecl *SecondTD = cast<TypedefNameDecl>(SecondDecl);
10539         auto FirstName = FirstTD->getDeclName();
10540         auto SecondName = SecondTD->getDeclName();
10541         if (FirstName != SecondName) {
10542           ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
10543                        TypedefName)
10544               << (FirstDiffType == TypeAlias) << FirstName;
10545           ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
10546                       TypedefName)
10547               << (FirstDiffType == TypeAlias) << SecondName;
10548           Diagnosed = true;
10549           break;
10550         }
10551
10552         QualType FirstType = FirstTD->getUnderlyingType();
10553         QualType SecondType = SecondTD->getUnderlyingType();
10554         if (ComputeQualTypeODRHash(FirstType) !=
10555             ComputeQualTypeODRHash(SecondType)) {
10556           ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
10557                        TypedefType)
10558               << (FirstDiffType == TypeAlias) << FirstName << FirstType;
10559           ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
10560                       TypedefType)
10561               << (FirstDiffType == TypeAlias) << SecondName << SecondType;
10562           Diagnosed = true;
10563           break;
10564         }
10565         break;
10566       }
10567       case Var: {
10568         VarDecl *FirstVD = cast<VarDecl>(FirstDecl);
10569         VarDecl *SecondVD = cast<VarDecl>(SecondDecl);
10570         auto FirstName = FirstVD->getDeclName();
10571         auto SecondName = SecondVD->getDeclName();
10572         if (FirstName != SecondName) {
10573           ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10574                        VarName)
10575               << FirstName;
10576           ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10577                       VarName)
10578               << SecondName;
10579           Diagnosed = true;
10580           break;
10581         }
10582
10583         QualType FirstType = FirstVD->getType();
10584         QualType SecondType = SecondVD->getType();
10585         if (ComputeQualTypeODRHash(FirstType) !=
10586                         ComputeQualTypeODRHash(SecondType)) {
10587           ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10588                        VarType)
10589               << FirstName << FirstType;
10590           ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10591                       VarType)
10592               << SecondName << SecondType;
10593           Diagnosed = true;
10594           break;
10595         }
10596
10597         const Expr *FirstInit = FirstVD->getInit();
10598         const Expr *SecondInit = SecondVD->getInit();
10599         if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
10600           ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10601                        VarSingleInitializer)
10602               << FirstName << (FirstInit == nullptr)
10603               << (FirstInit ? FirstInit->getSourceRange(): SourceRange());
10604           ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10605                       VarSingleInitializer)
10606               << SecondName << (SecondInit == nullptr)
10607               << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
10608           Diagnosed = true;
10609           break;
10610         }
10611
10612         if (FirstInit && SecondInit &&
10613             ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
10614           ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10615                        VarDifferentInitializer)
10616               << FirstName << FirstInit->getSourceRange();
10617           ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10618                       VarDifferentInitializer)
10619               << SecondName << SecondInit->getSourceRange();
10620           Diagnosed = true;
10621           break;
10622         }
10623
10624         const bool FirstIsConstexpr = FirstVD->isConstexpr();
10625         const bool SecondIsConstexpr = SecondVD->isConstexpr();
10626         if (FirstIsConstexpr != SecondIsConstexpr) {
10627           ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10628                        VarConstexpr)
10629               << FirstName << FirstIsConstexpr;
10630           ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10631                       VarConstexpr)
10632               << SecondName << SecondIsConstexpr;
10633           Diagnosed = true;
10634           break;
10635         }
10636         break;
10637       }
10638       case Friend: {
10639         FriendDecl *FirstFriend = cast<FriendDecl>(FirstDecl);
10640         FriendDecl *SecondFriend = cast<FriendDecl>(SecondDecl);
10641
10642         NamedDecl *FirstND = FirstFriend->getFriendDecl();
10643         NamedDecl *SecondND = SecondFriend->getFriendDecl();
10644
10645         TypeSourceInfo *FirstTSI = FirstFriend->getFriendType();
10646         TypeSourceInfo *SecondTSI = SecondFriend->getFriendType();
10647
10648         if (FirstND && SecondND) {
10649           ODRDiagError(FirstFriend->getFriendLoc(),
10650                        FirstFriend->getSourceRange(), FriendFunction)
10651               << FirstND;
10652           ODRDiagNote(SecondFriend->getFriendLoc(),
10653                       SecondFriend->getSourceRange(), FriendFunction)
10654               << SecondND;
10655
10656           Diagnosed = true;
10657           break;
10658         }
10659
10660         if (FirstTSI && SecondTSI) {
10661           QualType FirstFriendType = FirstTSI->getType();
10662           QualType SecondFriendType = SecondTSI->getType();
10663           assert(ComputeQualTypeODRHash(FirstFriendType) !=
10664                  ComputeQualTypeODRHash(SecondFriendType));
10665           ODRDiagError(FirstFriend->getFriendLoc(),
10666                        FirstFriend->getSourceRange(), FriendType)
10667               << FirstFriendType;
10668           ODRDiagNote(SecondFriend->getFriendLoc(),
10669                       SecondFriend->getSourceRange(), FriendType)
10670               << SecondFriendType;
10671           Diagnosed = true;
10672           break;
10673         }
10674
10675         ODRDiagError(FirstFriend->getFriendLoc(), FirstFriend->getSourceRange(),
10676                      FriendTypeFunction)
10677             << (FirstTSI == nullptr);
10678         ODRDiagNote(SecondFriend->getFriendLoc(),
10679                     SecondFriend->getSourceRange(), FriendTypeFunction)
10680             << (SecondTSI == nullptr);
10681
10682         Diagnosed = true;
10683         break;
10684       }
10685       case FunctionTemplate: {
10686         FunctionTemplateDecl *FirstTemplate =
10687             cast<FunctionTemplateDecl>(FirstDecl);
10688         FunctionTemplateDecl *SecondTemplate =
10689             cast<FunctionTemplateDecl>(SecondDecl);
10690
10691         TemplateParameterList *FirstTPL =
10692             FirstTemplate->getTemplateParameters();
10693         TemplateParameterList *SecondTPL =
10694             SecondTemplate->getTemplateParameters();
10695
10696         if (FirstTPL->size() != SecondTPL->size()) {
10697           ODRDiagError(FirstTemplate->getLocation(),
10698                        FirstTemplate->getSourceRange(),
10699                        FunctionTemplateDifferentNumberParameters)
10700               << FirstTemplate << FirstTPL->size();
10701           ODRDiagNote(SecondTemplate->getLocation(),
10702                       SecondTemplate->getSourceRange(),
10703                       FunctionTemplateDifferentNumberParameters)
10704               << SecondTemplate  << SecondTPL->size();
10705
10706           Diagnosed = true;
10707           break;
10708         }
10709
10710         bool ParameterMismatch = false;
10711         for (unsigned i = 0, e = FirstTPL->size(); i != e; ++i) {
10712           NamedDecl *FirstParam = FirstTPL->getParam(i);
10713           NamedDecl *SecondParam = SecondTPL->getParam(i);
10714
10715           if (FirstParam->getKind() != SecondParam->getKind()) {
10716             enum {
10717               TemplateTypeParameter,
10718               NonTypeTemplateParameter,
10719               TemplateTemplateParameter,
10720             };
10721             auto GetParamType = [](NamedDecl *D) {
10722               switch (D->getKind()) {
10723                 default:
10724                   llvm_unreachable("Unexpected template parameter type");
10725                 case Decl::TemplateTypeParm:
10726                   return TemplateTypeParameter;
10727                 case Decl::NonTypeTemplateParm:
10728                   return NonTypeTemplateParameter;
10729                 case Decl::TemplateTemplateParm:
10730                   return TemplateTemplateParameter;
10731               }
10732             };
10733
10734             ODRDiagError(FirstTemplate->getLocation(),
10735                          FirstTemplate->getSourceRange(),
10736                          FunctionTemplateParameterDifferentKind)
10737                 << FirstTemplate << (i + 1) << GetParamType(FirstParam);
10738             ODRDiagNote(SecondTemplate->getLocation(),
10739                         SecondTemplate->getSourceRange(),
10740                         FunctionTemplateParameterDifferentKind)
10741                 << SecondTemplate << (i + 1) << GetParamType(SecondParam);
10742
10743             ParameterMismatch = true;
10744             break;
10745           }
10746
10747           if (FirstParam->getName() != SecondParam->getName()) {
10748             ODRDiagError(FirstTemplate->getLocation(),
10749                          FirstTemplate->getSourceRange(),
10750                          FunctionTemplateParameterName)
10751                 << FirstTemplate << (i + 1) << (bool)FirstParam->getIdentifier()
10752                 << FirstParam;
10753             ODRDiagNote(SecondTemplate->getLocation(),
10754                         SecondTemplate->getSourceRange(),
10755                         FunctionTemplateParameterName)
10756                 << SecondTemplate << (i + 1)
10757                 << (bool)SecondParam->getIdentifier() << SecondParam;
10758             ParameterMismatch = true;
10759             break;
10760           }
10761
10762           if (isa<TemplateTypeParmDecl>(FirstParam) &&
10763               isa<TemplateTypeParmDecl>(SecondParam)) {
10764             TemplateTypeParmDecl *FirstTTPD =
10765                 cast<TemplateTypeParmDecl>(FirstParam);
10766             TemplateTypeParmDecl *SecondTTPD =
10767                 cast<TemplateTypeParmDecl>(SecondParam);
10768             bool HasFirstDefaultArgument =
10769                 FirstTTPD->hasDefaultArgument() &&
10770                 !FirstTTPD->defaultArgumentWasInherited();
10771             bool HasSecondDefaultArgument =
10772                 SecondTTPD->hasDefaultArgument() &&
10773                 !SecondTTPD->defaultArgumentWasInherited();
10774             if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10775               ODRDiagError(FirstTemplate->getLocation(),
10776                            FirstTemplate->getSourceRange(),
10777                            FunctionTemplateParameterSingleDefaultArgument)
10778                   << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
10779               ODRDiagNote(SecondTemplate->getLocation(),
10780                           SecondTemplate->getSourceRange(),
10781                           FunctionTemplateParameterSingleDefaultArgument)
10782                   << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
10783               ParameterMismatch = true;
10784               break;
10785             }
10786
10787             if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
10788               QualType FirstType = FirstTTPD->getDefaultArgument();
10789               QualType SecondType = SecondTTPD->getDefaultArgument();
10790               if (ComputeQualTypeODRHash(FirstType) !=
10791                   ComputeQualTypeODRHash(SecondType)) {
10792                 ODRDiagError(FirstTemplate->getLocation(),
10793                              FirstTemplate->getSourceRange(),
10794                              FunctionTemplateParameterDifferentDefaultArgument)
10795                     << FirstTemplate << (i + 1) << FirstType;
10796                 ODRDiagNote(SecondTemplate->getLocation(),
10797                             SecondTemplate->getSourceRange(),
10798                             FunctionTemplateParameterDifferentDefaultArgument)
10799                     << SecondTemplate << (i + 1) << SecondType;
10800                 ParameterMismatch = true;
10801                 break;
10802               }
10803             }
10804
10805             if (FirstTTPD->isParameterPack() !=
10806                 SecondTTPD->isParameterPack()) {
10807               ODRDiagError(FirstTemplate->getLocation(),
10808                            FirstTemplate->getSourceRange(),
10809                            FunctionTemplatePackParameter)
10810                   << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
10811               ODRDiagNote(SecondTemplate->getLocation(),
10812                           SecondTemplate->getSourceRange(),
10813                           FunctionTemplatePackParameter)
10814                   << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
10815               ParameterMismatch = true;
10816               break;
10817             }
10818           }
10819
10820           if (isa<TemplateTemplateParmDecl>(FirstParam) &&
10821               isa<TemplateTemplateParmDecl>(SecondParam)) {
10822             TemplateTemplateParmDecl *FirstTTPD =
10823                 cast<TemplateTemplateParmDecl>(FirstParam);
10824             TemplateTemplateParmDecl *SecondTTPD =
10825                 cast<TemplateTemplateParmDecl>(SecondParam);
10826
10827             TemplateParameterList *FirstTPL =
10828                 FirstTTPD->getTemplateParameters();
10829             TemplateParameterList *SecondTPL =
10830                 SecondTTPD->getTemplateParameters();
10831
10832             if (ComputeTemplateParameterListODRHash(FirstTPL) !=
10833                 ComputeTemplateParameterListODRHash(SecondTPL)) {
10834               ODRDiagError(FirstTemplate->getLocation(),
10835                            FirstTemplate->getSourceRange(),
10836                            FunctionTemplateParameterDifferentType)
10837                   << FirstTemplate << (i + 1);
10838               ODRDiagNote(SecondTemplate->getLocation(),
10839                           SecondTemplate->getSourceRange(),
10840                           FunctionTemplateParameterDifferentType)
10841                   << SecondTemplate << (i + 1);
10842               ParameterMismatch = true;
10843               break;
10844             }
10845
10846             bool HasFirstDefaultArgument =
10847                 FirstTTPD->hasDefaultArgument() &&
10848                 !FirstTTPD->defaultArgumentWasInherited();
10849             bool HasSecondDefaultArgument =
10850                 SecondTTPD->hasDefaultArgument() &&
10851                 !SecondTTPD->defaultArgumentWasInherited();
10852             if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10853               ODRDiagError(FirstTemplate->getLocation(),
10854                            FirstTemplate->getSourceRange(),
10855                            FunctionTemplateParameterSingleDefaultArgument)
10856                   << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
10857               ODRDiagNote(SecondTemplate->getLocation(),
10858                           SecondTemplate->getSourceRange(),
10859                           FunctionTemplateParameterSingleDefaultArgument)
10860                   << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
10861               ParameterMismatch = true;
10862               break;
10863             }
10864
10865             if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
10866               TemplateArgument FirstTA =
10867                   FirstTTPD->getDefaultArgument().getArgument();
10868               TemplateArgument SecondTA =
10869                   SecondTTPD->getDefaultArgument().getArgument();
10870               if (ComputeTemplateArgumentODRHash(FirstTA) !=
10871                   ComputeTemplateArgumentODRHash(SecondTA)) {
10872                 ODRDiagError(FirstTemplate->getLocation(),
10873                              FirstTemplate->getSourceRange(),
10874                              FunctionTemplateParameterDifferentDefaultArgument)
10875                     << FirstTemplate << (i + 1) << FirstTA;
10876                 ODRDiagNote(SecondTemplate->getLocation(),
10877                             SecondTemplate->getSourceRange(),
10878                             FunctionTemplateParameterDifferentDefaultArgument)
10879                     << SecondTemplate << (i + 1) << SecondTA;
10880                 ParameterMismatch = true;
10881                 break;
10882               }
10883             }
10884
10885             if (FirstTTPD->isParameterPack() !=
10886                 SecondTTPD->isParameterPack()) {
10887               ODRDiagError(FirstTemplate->getLocation(),
10888                            FirstTemplate->getSourceRange(),
10889                            FunctionTemplatePackParameter)
10890                   << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
10891               ODRDiagNote(SecondTemplate->getLocation(),
10892                           SecondTemplate->getSourceRange(),
10893                           FunctionTemplatePackParameter)
10894                   << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
10895               ParameterMismatch = true;
10896               break;
10897             }
10898           }
10899
10900           if (isa<NonTypeTemplateParmDecl>(FirstParam) &&
10901               isa<NonTypeTemplateParmDecl>(SecondParam)) {
10902             NonTypeTemplateParmDecl *FirstNTTPD =
10903                 cast<NonTypeTemplateParmDecl>(FirstParam);
10904             NonTypeTemplateParmDecl *SecondNTTPD =
10905                 cast<NonTypeTemplateParmDecl>(SecondParam);
10906
10907             QualType FirstType = FirstNTTPD->getType();
10908             QualType SecondType = SecondNTTPD->getType();
10909             if (ComputeQualTypeODRHash(FirstType) !=
10910                 ComputeQualTypeODRHash(SecondType)) {
10911               ODRDiagError(FirstTemplate->getLocation(),
10912                            FirstTemplate->getSourceRange(),
10913                            FunctionTemplateParameterDifferentType)
10914                   << FirstTemplate << (i + 1);
10915               ODRDiagNote(SecondTemplate->getLocation(),
10916                           SecondTemplate->getSourceRange(),
10917                           FunctionTemplateParameterDifferentType)
10918                   << SecondTemplate << (i + 1);
10919               ParameterMismatch = true;
10920               break;
10921             }
10922
10923             bool HasFirstDefaultArgument =
10924                 FirstNTTPD->hasDefaultArgument() &&
10925                 !FirstNTTPD->defaultArgumentWasInherited();
10926             bool HasSecondDefaultArgument =
10927                 SecondNTTPD->hasDefaultArgument() &&
10928                 !SecondNTTPD->defaultArgumentWasInherited();
10929             if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10930               ODRDiagError(FirstTemplate->getLocation(),
10931                            FirstTemplate->getSourceRange(),
10932                            FunctionTemplateParameterSingleDefaultArgument)
10933                   << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
10934               ODRDiagNote(SecondTemplate->getLocation(),
10935                           SecondTemplate->getSourceRange(),
10936                           FunctionTemplateParameterSingleDefaultArgument)
10937                   << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
10938               ParameterMismatch = true;
10939               break;
10940             }
10941
10942             if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
10943               Expr *FirstDefaultArgument = FirstNTTPD->getDefaultArgument();
10944               Expr *SecondDefaultArgument = SecondNTTPD->getDefaultArgument();
10945               if (ComputeODRHash(FirstDefaultArgument) !=
10946                   ComputeODRHash(SecondDefaultArgument)) {
10947                 ODRDiagError(FirstTemplate->getLocation(),
10948                              FirstTemplate->getSourceRange(),
10949                              FunctionTemplateParameterDifferentDefaultArgument)
10950                     << FirstTemplate << (i + 1) << FirstDefaultArgument;
10951                 ODRDiagNote(SecondTemplate->getLocation(),
10952                             SecondTemplate->getSourceRange(),
10953                             FunctionTemplateParameterDifferentDefaultArgument)
10954                     << SecondTemplate << (i + 1) << SecondDefaultArgument;
10955                 ParameterMismatch = true;
10956                 break;
10957               }
10958             }
10959
10960             if (FirstNTTPD->isParameterPack() !=
10961                 SecondNTTPD->isParameterPack()) {
10962               ODRDiagError(FirstTemplate->getLocation(),
10963                            FirstTemplate->getSourceRange(),
10964                            FunctionTemplatePackParameter)
10965                   << FirstTemplate << (i + 1) << FirstNTTPD->isParameterPack();
10966               ODRDiagNote(SecondTemplate->getLocation(),
10967                           SecondTemplate->getSourceRange(),
10968                           FunctionTemplatePackParameter)
10969                   << SecondTemplate << (i + 1)
10970                   << SecondNTTPD->isParameterPack();
10971               ParameterMismatch = true;
10972               break;
10973             }
10974           }
10975         }
10976
10977         if (ParameterMismatch) {
10978           Diagnosed = true;
10979           break;
10980         }
10981
10982         break;
10983       }
10984       }
10985
10986       if (Diagnosed)
10987         continue;
10988
10989       Diag(FirstDecl->getLocation(),
10990            diag::err_module_odr_violation_mismatch_decl_unknown)
10991           << FirstRecord << FirstModule.empty() << FirstModule << FirstDiffType
10992           << FirstDecl->getSourceRange();
10993       Diag(SecondDecl->getLocation(),
10994            diag::note_module_odr_violation_mismatch_decl_unknown)
10995           << SecondModule << FirstDiffType << SecondDecl->getSourceRange();
10996       Diagnosed = true;
10997     }
10998
10999     if (!Diagnosed) {
11000       // All definitions are updates to the same declaration. This happens if a
11001       // module instantiates the declaration of a class template specialization
11002       // and two or more other modules instantiate its definition.
11003       //
11004       // FIXME: Indicate which modules had instantiations of this definition.
11005       // FIXME: How can this even happen?
11006       Diag(Merge.first->getLocation(),
11007            diag::err_module_odr_violation_different_instantiations)
11008         << Merge.first;
11009     }
11010   }
11011
11012   // Issue ODR failures diagnostics for functions.
11013   for (auto &Merge : FunctionOdrMergeFailures) {
11014     enum ODRFunctionDifference {
11015       ReturnType,
11016       ParameterName,
11017       ParameterType,
11018       ParameterSingleDefaultArgument,
11019       ParameterDifferentDefaultArgument,
11020       FunctionBody,
11021     };
11022
11023     FunctionDecl *FirstFunction = Merge.first;
11024     std::string FirstModule = getOwningModuleNameForDiagnostic(FirstFunction);
11025
11026     bool Diagnosed = false;
11027     for (auto &SecondFunction : Merge.second) {
11028
11029       if (FirstFunction == SecondFunction)
11030         continue;
11031
11032       std::string SecondModule =
11033           getOwningModuleNameForDiagnostic(SecondFunction);
11034
11035       auto ODRDiagError = [FirstFunction, &FirstModule,
11036                            this](SourceLocation Loc, SourceRange Range,
11037                                  ODRFunctionDifference DiffType) {
11038         return Diag(Loc, diag::err_module_odr_violation_function)
11039                << FirstFunction << FirstModule.empty() << FirstModule << Range
11040                << DiffType;
11041       };
11042       auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
11043                                                SourceRange Range,
11044                                                ODRFunctionDifference DiffType) {
11045         return Diag(Loc, diag::note_module_odr_violation_function)
11046                << SecondModule << Range << DiffType;
11047       };
11048
11049       if (ComputeQualTypeODRHash(FirstFunction->getReturnType()) !=
11050           ComputeQualTypeODRHash(SecondFunction->getReturnType())) {
11051         ODRDiagError(FirstFunction->getReturnTypeSourceRange().getBegin(),
11052                      FirstFunction->getReturnTypeSourceRange(), ReturnType)
11053             << FirstFunction->getReturnType();
11054         ODRDiagNote(SecondFunction->getReturnTypeSourceRange().getBegin(),
11055                     SecondFunction->getReturnTypeSourceRange(), ReturnType)
11056             << SecondFunction->getReturnType();
11057         Diagnosed = true;
11058         break;
11059       }
11060
11061       assert(FirstFunction->param_size() == SecondFunction->param_size() &&
11062              "Merged functions with different number of parameters");
11063
11064       auto ParamSize = FirstFunction->param_size();
11065       bool ParameterMismatch = false;
11066       for (unsigned I = 0; I < ParamSize; ++I) {
11067         auto *FirstParam = FirstFunction->getParamDecl(I);
11068         auto *SecondParam = SecondFunction->getParamDecl(I);
11069
11070         assert(getContext().hasSameType(FirstParam->getType(),
11071                                       SecondParam->getType()) &&
11072                "Merged function has different parameter types.");
11073
11074         if (FirstParam->getDeclName() != SecondParam->getDeclName()) {
11075           ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11076                        ParameterName)
11077               << I + 1 << FirstParam->getDeclName();
11078           ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11079                       ParameterName)
11080               << I + 1 << SecondParam->getDeclName();
11081           ParameterMismatch = true;
11082           break;
11083         };
11084
11085         QualType FirstParamType = FirstParam->getType();
11086         QualType SecondParamType = SecondParam->getType();
11087         if (FirstParamType != SecondParamType &&
11088             ComputeQualTypeODRHash(FirstParamType) !=
11089                 ComputeQualTypeODRHash(SecondParamType)) {
11090           if (const DecayedType *ParamDecayedType =
11091                   FirstParamType->getAs<DecayedType>()) {
11092             ODRDiagError(FirstParam->getLocation(),
11093                          FirstParam->getSourceRange(), ParameterType)
11094                 << (I + 1) << FirstParamType << true
11095                 << ParamDecayedType->getOriginalType();
11096           } else {
11097             ODRDiagError(FirstParam->getLocation(),
11098                          FirstParam->getSourceRange(), ParameterType)
11099                 << (I + 1) << FirstParamType << false;
11100           }
11101
11102           if (const DecayedType *ParamDecayedType =
11103                   SecondParamType->getAs<DecayedType>()) {
11104             ODRDiagNote(SecondParam->getLocation(),
11105                         SecondParam->getSourceRange(), ParameterType)
11106                 << (I + 1) << SecondParamType << true
11107                 << ParamDecayedType->getOriginalType();
11108           } else {
11109             ODRDiagNote(SecondParam->getLocation(),
11110                         SecondParam->getSourceRange(), ParameterType)
11111                 << (I + 1) << SecondParamType << false;
11112           }
11113           ParameterMismatch = true;
11114           break;
11115         }
11116
11117         const Expr *FirstInit = FirstParam->getInit();
11118         const Expr *SecondInit = SecondParam->getInit();
11119         if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
11120           ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11121                        ParameterSingleDefaultArgument)
11122               << (I + 1) << (FirstInit == nullptr)
11123               << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
11124           ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11125                       ParameterSingleDefaultArgument)
11126               << (I + 1) << (SecondInit == nullptr)
11127               << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
11128           ParameterMismatch = true;
11129           break;
11130         }
11131
11132         if (FirstInit && SecondInit &&
11133             ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11134           ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11135                        ParameterDifferentDefaultArgument)
11136               << (I + 1) << FirstInit->getSourceRange();
11137           ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11138                       ParameterDifferentDefaultArgument)
11139               << (I + 1) << SecondInit->getSourceRange();
11140           ParameterMismatch = true;
11141           break;
11142         }
11143
11144         assert(ComputeSubDeclODRHash(FirstParam) ==
11145                    ComputeSubDeclODRHash(SecondParam) &&
11146                "Undiagnosed parameter difference.");
11147       }
11148
11149       if (ParameterMismatch) {
11150         Diagnosed = true;
11151         break;
11152       }
11153
11154       // If no error has been generated before now, assume the problem is in
11155       // the body and generate a message.
11156       ODRDiagError(FirstFunction->getLocation(),
11157                    FirstFunction->getSourceRange(), FunctionBody);
11158       ODRDiagNote(SecondFunction->getLocation(),
11159                   SecondFunction->getSourceRange(), FunctionBody);
11160       Diagnosed = true;
11161       break;
11162     }
11163     (void)Diagnosed;
11164     assert(Diagnosed && "Unable to emit ODR diagnostic.");
11165   }
11166
11167   // Issue ODR failures diagnostics for enums.
11168   for (auto &Merge : EnumOdrMergeFailures) {
11169     enum ODREnumDifference {
11170       SingleScopedEnum,
11171       EnumTagKeywordMismatch,
11172       SingleSpecifiedType,
11173       DifferentSpecifiedTypes,
11174       DifferentNumberEnumConstants,
11175       EnumConstantName,
11176       EnumConstantSingleInitilizer,
11177       EnumConstantDifferentInitilizer,
11178     };
11179
11180     // If we've already pointed out a specific problem with this enum, don't
11181     // bother issuing a general "something's different" diagnostic.
11182     if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11183       continue;
11184
11185     EnumDecl *FirstEnum = Merge.first;
11186     std::string FirstModule = getOwningModuleNameForDiagnostic(FirstEnum);
11187
11188     using DeclHashes =
11189         llvm::SmallVector<std::pair<EnumConstantDecl *, unsigned>, 4>;
11190     auto PopulateHashes = [&ComputeSubDeclODRHash, FirstEnum](
11191                               DeclHashes &Hashes, EnumDecl *Enum) {
11192       for (auto *D : Enum->decls()) {
11193         // Due to decl merging, the first EnumDecl is the parent of
11194         // Decls in both records.
11195         if (!ODRHash::isWhitelistedDecl(D, FirstEnum))
11196           continue;
11197         assert(isa<EnumConstantDecl>(D) && "Unexpected Decl kind");
11198         Hashes.emplace_back(cast<EnumConstantDecl>(D),
11199                             ComputeSubDeclODRHash(D));
11200       }
11201     };
11202     DeclHashes FirstHashes;
11203     PopulateHashes(FirstHashes, FirstEnum);
11204     bool Diagnosed = false;
11205     for (auto &SecondEnum : Merge.second) {
11206
11207       if (FirstEnum == SecondEnum)
11208         continue;
11209
11210       std::string SecondModule =
11211           getOwningModuleNameForDiagnostic(SecondEnum);
11212
11213       auto ODRDiagError = [FirstEnum, &FirstModule,
11214                            this](SourceLocation Loc, SourceRange Range,
11215                                  ODREnumDifference DiffType) {
11216         return Diag(Loc, diag::err_module_odr_violation_enum)
11217                << FirstEnum << FirstModule.empty() << FirstModule << Range
11218                << DiffType;
11219       };
11220       auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
11221                                                SourceRange Range,
11222                                                ODREnumDifference DiffType) {
11223         return Diag(Loc, diag::note_module_odr_violation_enum)
11224                << SecondModule << Range << DiffType;
11225       };
11226
11227       if (FirstEnum->isScoped() != SecondEnum->isScoped()) {
11228         ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11229                      SingleScopedEnum)
11230             << FirstEnum->isScoped();
11231         ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11232                     SingleScopedEnum)
11233             << SecondEnum->isScoped();
11234         Diagnosed = true;
11235         continue;
11236       }
11237
11238       if (FirstEnum->isScoped() && SecondEnum->isScoped()) {
11239         if (FirstEnum->isScopedUsingClassTag() !=
11240             SecondEnum->isScopedUsingClassTag()) {
11241           ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11242                        EnumTagKeywordMismatch)
11243               << FirstEnum->isScopedUsingClassTag();
11244           ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11245                       EnumTagKeywordMismatch)
11246               << SecondEnum->isScopedUsingClassTag();
11247           Diagnosed = true;
11248           continue;
11249         }
11250       }
11251
11252       QualType FirstUnderlyingType =
11253           FirstEnum->getIntegerTypeSourceInfo()
11254               ? FirstEnum->getIntegerTypeSourceInfo()->getType()
11255               : QualType();
11256       QualType SecondUnderlyingType =
11257           SecondEnum->getIntegerTypeSourceInfo()
11258               ? SecondEnum->getIntegerTypeSourceInfo()->getType()
11259               : QualType();
11260       if (FirstUnderlyingType.isNull() != SecondUnderlyingType.isNull()) {
11261           ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11262                        SingleSpecifiedType)
11263               << !FirstUnderlyingType.isNull();
11264           ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11265                       SingleSpecifiedType)
11266               << !SecondUnderlyingType.isNull();
11267           Diagnosed = true;
11268           continue;
11269       }
11270
11271       if (!FirstUnderlyingType.isNull() && !SecondUnderlyingType.isNull()) {
11272         if (ComputeQualTypeODRHash(FirstUnderlyingType) !=
11273             ComputeQualTypeODRHash(SecondUnderlyingType)) {
11274           ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11275                        DifferentSpecifiedTypes)
11276               << FirstUnderlyingType;
11277           ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11278                       DifferentSpecifiedTypes)
11279               << SecondUnderlyingType;
11280           Diagnosed = true;
11281           continue;
11282         }
11283       }
11284
11285       DeclHashes SecondHashes;
11286       PopulateHashes(SecondHashes, SecondEnum);
11287
11288       if (FirstHashes.size() != SecondHashes.size()) {
11289         ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11290                      DifferentNumberEnumConstants)
11291             << (int)FirstHashes.size();
11292         ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11293                     DifferentNumberEnumConstants)
11294             << (int)SecondHashes.size();
11295         Diagnosed = true;
11296         continue;
11297       }
11298
11299       for (unsigned I = 0; I < FirstHashes.size(); ++I) {
11300         if (FirstHashes[I].second == SecondHashes[I].second)
11301           continue;
11302         const EnumConstantDecl *FirstEnumConstant = FirstHashes[I].first;
11303         const EnumConstantDecl *SecondEnumConstant = SecondHashes[I].first;
11304
11305         if (FirstEnumConstant->getDeclName() !=
11306             SecondEnumConstant->getDeclName()) {
11307
11308           ODRDiagError(FirstEnumConstant->getLocation(),
11309                        FirstEnumConstant->getSourceRange(), EnumConstantName)
11310               << I + 1 << FirstEnumConstant;
11311           ODRDiagNote(SecondEnumConstant->getLocation(),
11312                       SecondEnumConstant->getSourceRange(), EnumConstantName)
11313               << I + 1 << SecondEnumConstant;
11314           Diagnosed = true;
11315           break;
11316         }
11317
11318         const Expr *FirstInit = FirstEnumConstant->getInitExpr();
11319         const Expr *SecondInit = SecondEnumConstant->getInitExpr();
11320         if (!FirstInit && !SecondInit)
11321           continue;
11322
11323         if (!FirstInit || !SecondInit) {
11324           ODRDiagError(FirstEnumConstant->getLocation(),
11325                        FirstEnumConstant->getSourceRange(),
11326                        EnumConstantSingleInitilizer)
11327               << I + 1 << FirstEnumConstant << (FirstInit != nullptr);
11328           ODRDiagNote(SecondEnumConstant->getLocation(),
11329                       SecondEnumConstant->getSourceRange(),
11330                       EnumConstantSingleInitilizer)
11331               << I + 1 << SecondEnumConstant << (SecondInit != nullptr);
11332           Diagnosed = true;
11333           break;
11334         }
11335
11336         if (ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11337           ODRDiagError(FirstEnumConstant->getLocation(),
11338                        FirstEnumConstant->getSourceRange(),
11339                        EnumConstantDifferentInitilizer)
11340               << I + 1 << FirstEnumConstant;
11341           ODRDiagNote(SecondEnumConstant->getLocation(),
11342                       SecondEnumConstant->getSourceRange(),
11343                       EnumConstantDifferentInitilizer)
11344               << I + 1 << SecondEnumConstant;
11345           Diagnosed = true;
11346           break;
11347         }
11348       }
11349     }
11350
11351     (void)Diagnosed;
11352     assert(Diagnosed && "Unable to emit ODR diagnostic.");
11353   }
11354 }
11355
11356 void ASTReader::StartedDeserializing() {
11357   if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
11358     ReadTimer->startTimer();
11359 }
11360
11361 void ASTReader::FinishedDeserializing() {
11362   assert(NumCurrentElementsDeserializing &&
11363          "FinishedDeserializing not paired with StartedDeserializing");
11364   if (NumCurrentElementsDeserializing == 1) {
11365     // We decrease NumCurrentElementsDeserializing only after pending actions
11366     // are finished, to avoid recursively re-calling finishPendingActions().
11367     finishPendingActions();
11368   }
11369   --NumCurrentElementsDeserializing;
11370
11371   if (NumCurrentElementsDeserializing == 0) {
11372     // Propagate exception specification and deduced type updates along
11373     // redeclaration chains.
11374     //
11375     // We do this now rather than in finishPendingActions because we want to
11376     // be able to walk the complete redeclaration chains of the updated decls.
11377     while (!PendingExceptionSpecUpdates.empty() ||
11378            !PendingDeducedTypeUpdates.empty()) {
11379       auto ESUpdates = std::move(PendingExceptionSpecUpdates);
11380       PendingExceptionSpecUpdates.clear();
11381       for (auto Update : ESUpdates) {
11382         ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11383         auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
11384         auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
11385         if (auto *Listener = getContext().getASTMutationListener())
11386           Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
11387         for (auto *Redecl : Update.second->redecls())
11388           getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
11389       }
11390
11391       auto DTUpdates = std::move(PendingDeducedTypeUpdates);
11392       PendingDeducedTypeUpdates.clear();
11393       for (auto Update : DTUpdates) {
11394         ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11395         // FIXME: If the return type is already deduced, check that it matches.
11396         getContext().adjustDeducedFunctionResultType(Update.first,
11397                                                      Update.second);
11398       }
11399     }
11400
11401     if (ReadTimer)
11402       ReadTimer->stopTimer();
11403
11404     diagnoseOdrViolations();
11405
11406     // We are not in recursive loading, so it's safe to pass the "interesting"
11407     // decls to the consumer.
11408     if (Consumer)
11409       PassInterestingDeclsToConsumer();
11410   }
11411 }
11412
11413 void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
11414   if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
11415     // Remove any fake results before adding any real ones.
11416     auto It = PendingFakeLookupResults.find(II);
11417     if (It != PendingFakeLookupResults.end()) {
11418       for (auto *ND : It->second)
11419         SemaObj->IdResolver.RemoveDecl(ND);
11420       // FIXME: this works around module+PCH performance issue.
11421       // Rather than erase the result from the map, which is O(n), just clear
11422       // the vector of NamedDecls.
11423       It->second.clear();
11424     }
11425   }
11426
11427   if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
11428     SemaObj->TUScope->AddDecl(D);
11429   } else if (SemaObj->TUScope) {
11430     // Adding the decl to IdResolver may have failed because it was already in
11431     // (even though it was not added in scope). If it is already in, make sure
11432     // it gets in the scope as well.
11433     if (std::find(SemaObj->IdResolver.begin(Name),
11434                   SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
11435       SemaObj->TUScope->AddDecl(D);
11436   }
11437 }
11438
11439 ASTReader::ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache,
11440                      ASTContext *Context,
11441                      const PCHContainerReader &PCHContainerRdr,
11442                      ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
11443                      StringRef isysroot, bool DisableValidation,
11444                      bool AllowASTWithCompilerErrors,
11445                      bool AllowConfigurationMismatch, bool ValidateSystemInputs,
11446                      bool ValidateASTInputFilesContent, bool UseGlobalIndex,
11447                      std::unique_ptr<llvm::Timer> ReadTimer)
11448     : Listener(DisableValidation
11449                    ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
11450                    : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
11451       SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
11452       PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
11453       ContextObj(Context), ModuleMgr(PP.getFileManager(), ModuleCache,
11454                                      PCHContainerRdr, PP.getHeaderSearchInfo()),
11455       DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
11456       DisableValidation(DisableValidation),
11457       AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
11458       AllowConfigurationMismatch(AllowConfigurationMismatch),
11459       ValidateSystemInputs(ValidateSystemInputs),
11460       ValidateASTInputFilesContent(ValidateASTInputFilesContent),
11461       UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
11462   SourceMgr.setExternalSLocEntrySource(this);
11463
11464   for (const auto &Ext : Extensions) {
11465     auto BlockName = Ext->getExtensionMetadata().BlockName;
11466     auto Known = ModuleFileExtensions.find(BlockName);
11467     if (Known != ModuleFileExtensions.end()) {
11468       Diags.Report(diag::warn_duplicate_module_file_extension)
11469         << BlockName;
11470       continue;
11471     }
11472
11473     ModuleFileExtensions.insert({BlockName, Ext});
11474   }
11475 }
11476
11477 ASTReader::~ASTReader() {
11478   if (OwnsDeserializationListener)
11479     delete DeserializationListener;
11480 }
11481
11482 IdentifierResolver &ASTReader::getIdResolver() {
11483   return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
11484 }
11485
11486 Expected<unsigned> ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
11487                                                unsigned AbbrevID) {
11488   Idx = 0;
11489   Record.clear();
11490   return Cursor.readRecord(AbbrevID, Record);
11491 }
11492 //===----------------------------------------------------------------------===//
11493 //// OMPClauseReader implementation
11494 ////===----------------------------------------------------------------------===//
11495
11496 // This has to be in namespace clang because it's friended by all
11497 // of the OMP clauses.
11498 namespace clang {
11499
11500 class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> {
11501   ASTRecordReader &Record;
11502   ASTContext &Context;
11503
11504 public:
11505   OMPClauseReader(ASTRecordReader &Record)
11506       : Record(Record), Context(Record.getContext()) {}
11507
11508 #define OPENMP_CLAUSE(Name, Class) void Visit##Class(Class *C);
11509 #include "clang/Basic/OpenMPKinds.def"
11510   OMPClause *readClause();
11511   void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C);
11512   void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C);
11513 };
11514
11515 } // end namespace clang
11516
11517 OMPClause *ASTRecordReader::readOMPClause() {
11518   return OMPClauseReader(*this).readClause();
11519 }
11520
11521 OMPClause *OMPClauseReader::readClause() {
11522   OMPClause *C = nullptr;
11523   switch (Record.readInt()) {
11524   case OMPC_if:
11525     C = new (Context) OMPIfClause();
11526     break;
11527   case OMPC_final:
11528     C = new (Context) OMPFinalClause();
11529     break;
11530   case OMPC_num_threads:
11531     C = new (Context) OMPNumThreadsClause();
11532     break;
11533   case OMPC_safelen:
11534     C = new (Context) OMPSafelenClause();
11535     break;
11536   case OMPC_simdlen:
11537     C = new (Context) OMPSimdlenClause();
11538     break;
11539   case OMPC_allocator:
11540     C = new (Context) OMPAllocatorClause();
11541     break;
11542   case OMPC_collapse:
11543     C = new (Context) OMPCollapseClause();
11544     break;
11545   case OMPC_default:
11546     C = new (Context) OMPDefaultClause();
11547     break;
11548   case OMPC_proc_bind:
11549     C = new (Context) OMPProcBindClause();
11550     break;
11551   case OMPC_schedule:
11552     C = new (Context) OMPScheduleClause();
11553     break;
11554   case OMPC_ordered:
11555     C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
11556     break;
11557   case OMPC_nowait:
11558     C = new (Context) OMPNowaitClause();
11559     break;
11560   case OMPC_untied:
11561     C = new (Context) OMPUntiedClause();
11562     break;
11563   case OMPC_mergeable:
11564     C = new (Context) OMPMergeableClause();
11565     break;
11566   case OMPC_read:
11567     C = new (Context) OMPReadClause();
11568     break;
11569   case OMPC_write:
11570     C = new (Context) OMPWriteClause();
11571     break;
11572   case OMPC_update:
11573     C = new (Context) OMPUpdateClause();
11574     break;
11575   case OMPC_capture:
11576     C = new (Context) OMPCaptureClause();
11577     break;
11578   case OMPC_seq_cst:
11579     C = new (Context) OMPSeqCstClause();
11580     break;
11581   case OMPC_threads:
11582     C = new (Context) OMPThreadsClause();
11583     break;
11584   case OMPC_simd:
11585     C = new (Context) OMPSIMDClause();
11586     break;
11587   case OMPC_nogroup:
11588     C = new (Context) OMPNogroupClause();
11589     break;
11590   case OMPC_unified_address:
11591     C = new (Context) OMPUnifiedAddressClause();
11592     break;
11593   case OMPC_unified_shared_memory:
11594     C = new (Context) OMPUnifiedSharedMemoryClause();
11595     break;
11596   case OMPC_reverse_offload:
11597     C = new (Context) OMPReverseOffloadClause();
11598     break;
11599   case OMPC_dynamic_allocators:
11600     C = new (Context) OMPDynamicAllocatorsClause();
11601     break;
11602   case OMPC_atomic_default_mem_order:
11603     C = new (Context) OMPAtomicDefaultMemOrderClause();
11604     break;
11605  case OMPC_private:
11606     C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
11607     break;
11608   case OMPC_firstprivate:
11609     C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
11610     break;
11611   case OMPC_lastprivate:
11612     C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
11613     break;
11614   case OMPC_shared:
11615     C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
11616     break;
11617   case OMPC_reduction:
11618     C = OMPReductionClause::CreateEmpty(Context, Record.readInt());
11619     break;
11620   case OMPC_task_reduction:
11621     C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
11622     break;
11623   case OMPC_in_reduction:
11624     C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
11625     break;
11626   case OMPC_linear:
11627     C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
11628     break;
11629   case OMPC_aligned:
11630     C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
11631     break;
11632   case OMPC_copyin:
11633     C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
11634     break;
11635   case OMPC_copyprivate:
11636     C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
11637     break;
11638   case OMPC_flush:
11639     C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
11640     break;
11641   case OMPC_depend: {
11642     unsigned NumVars = Record.readInt();
11643     unsigned NumLoops = Record.readInt();
11644     C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
11645     break;
11646   }
11647   case OMPC_device:
11648     C = new (Context) OMPDeviceClause();
11649     break;
11650   case OMPC_map: {
11651     OMPMappableExprListSizeTy Sizes;
11652     Sizes.NumVars = Record.readInt();
11653     Sizes.NumUniqueDeclarations = Record.readInt();
11654     Sizes.NumComponentLists = Record.readInt();
11655     Sizes.NumComponents = Record.readInt();
11656     C = OMPMapClause::CreateEmpty(Context, Sizes);
11657     break;
11658   }
11659   case OMPC_num_teams:
11660     C = new (Context) OMPNumTeamsClause();
11661     break;
11662   case OMPC_thread_limit:
11663     C = new (Context) OMPThreadLimitClause();
11664     break;
11665   case OMPC_priority:
11666     C = new (Context) OMPPriorityClause();
11667     break;
11668   case OMPC_grainsize:
11669     C = new (Context) OMPGrainsizeClause();
11670     break;
11671   case OMPC_num_tasks:
11672     C = new (Context) OMPNumTasksClause();
11673     break;
11674   case OMPC_hint:
11675     C = new (Context) OMPHintClause();
11676     break;
11677   case OMPC_dist_schedule:
11678     C = new (Context) OMPDistScheduleClause();
11679     break;
11680   case OMPC_defaultmap:
11681     C = new (Context) OMPDefaultmapClause();
11682     break;
11683   case OMPC_to: {
11684     OMPMappableExprListSizeTy Sizes;
11685     Sizes.NumVars = Record.readInt();
11686     Sizes.NumUniqueDeclarations = Record.readInt();
11687     Sizes.NumComponentLists = Record.readInt();
11688     Sizes.NumComponents = Record.readInt();
11689     C = OMPToClause::CreateEmpty(Context, Sizes);
11690     break;
11691   }
11692   case OMPC_from: {
11693     OMPMappableExprListSizeTy Sizes;
11694     Sizes.NumVars = Record.readInt();
11695     Sizes.NumUniqueDeclarations = Record.readInt();
11696     Sizes.NumComponentLists = Record.readInt();
11697     Sizes.NumComponents = Record.readInt();
11698     C = OMPFromClause::CreateEmpty(Context, Sizes);
11699     break;
11700   }
11701   case OMPC_use_device_ptr: {
11702     OMPMappableExprListSizeTy Sizes;
11703     Sizes.NumVars = Record.readInt();
11704     Sizes.NumUniqueDeclarations = Record.readInt();
11705     Sizes.NumComponentLists = Record.readInt();
11706     Sizes.NumComponents = Record.readInt();
11707     C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
11708     break;
11709   }
11710   case OMPC_is_device_ptr: {
11711     OMPMappableExprListSizeTy Sizes;
11712     Sizes.NumVars = Record.readInt();
11713     Sizes.NumUniqueDeclarations = Record.readInt();
11714     Sizes.NumComponentLists = Record.readInt();
11715     Sizes.NumComponents = Record.readInt();
11716     C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
11717     break;
11718   }
11719   case OMPC_allocate:
11720     C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
11721     break;
11722   case OMPC_nontemporal:
11723     C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt());
11724     break;
11725   }
11726   assert(C && "Unknown OMPClause type");
11727
11728   Visit(C);
11729   C->setLocStart(Record.readSourceLocation());
11730   C->setLocEnd(Record.readSourceLocation());
11731
11732   return C;
11733 }
11734
11735 void OMPClauseReader::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
11736   C->setPreInitStmt(Record.readSubStmt(),
11737                     static_cast<OpenMPDirectiveKind>(Record.readInt()));
11738 }
11739
11740 void OMPClauseReader::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
11741   VisitOMPClauseWithPreInit(C);
11742   C->setPostUpdateExpr(Record.readSubExpr());
11743 }
11744
11745 void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
11746   VisitOMPClauseWithPreInit(C);
11747   C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
11748   C->setNameModifierLoc(Record.readSourceLocation());
11749   C->setColonLoc(Record.readSourceLocation());
11750   C->setCondition(Record.readSubExpr());
11751   C->setLParenLoc(Record.readSourceLocation());
11752 }
11753
11754 void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
11755   VisitOMPClauseWithPreInit(C);
11756   C->setCondition(Record.readSubExpr());
11757   C->setLParenLoc(Record.readSourceLocation());
11758 }
11759
11760 void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
11761   VisitOMPClauseWithPreInit(C);
11762   C->setNumThreads(Record.readSubExpr());
11763   C->setLParenLoc(Record.readSourceLocation());
11764 }
11765
11766 void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
11767   C->setSafelen(Record.readSubExpr());
11768   C->setLParenLoc(Record.readSourceLocation());
11769 }
11770
11771 void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
11772   C->setSimdlen(Record.readSubExpr());
11773   C->setLParenLoc(Record.readSourceLocation());
11774 }
11775
11776 void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
11777   C->setAllocator(Record.readExpr());
11778   C->setLParenLoc(Record.readSourceLocation());
11779 }
11780
11781 void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
11782   C->setNumForLoops(Record.readSubExpr());
11783   C->setLParenLoc(Record.readSourceLocation());
11784 }
11785
11786 void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
11787   C->setDefaultKind(
11788        static_cast<OpenMPDefaultClauseKind>(Record.readInt()));
11789   C->setLParenLoc(Record.readSourceLocation());
11790   C->setDefaultKindKwLoc(Record.readSourceLocation());
11791 }
11792
11793 void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
11794   C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt()));
11795   C->setLParenLoc(Record.readSourceLocation());
11796   C->setProcBindKindKwLoc(Record.readSourceLocation());
11797 }
11798
11799 void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
11800   VisitOMPClauseWithPreInit(C);
11801   C->setScheduleKind(
11802        static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
11803   C->setFirstScheduleModifier(
11804       static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11805   C->setSecondScheduleModifier(
11806       static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11807   C->setChunkSize(Record.readSubExpr());
11808   C->setLParenLoc(Record.readSourceLocation());
11809   C->setFirstScheduleModifierLoc(Record.readSourceLocation());
11810   C->setSecondScheduleModifierLoc(Record.readSourceLocation());
11811   C->setScheduleKindLoc(Record.readSourceLocation());
11812   C->setCommaLoc(Record.readSourceLocation());
11813 }
11814
11815 void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
11816   C->setNumForLoops(Record.readSubExpr());
11817   for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11818     C->setLoopNumIterations(I, Record.readSubExpr());
11819   for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11820     C->setLoopCounter(I, Record.readSubExpr());
11821   C->setLParenLoc(Record.readSourceLocation());
11822 }
11823
11824 void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {}
11825
11826 void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
11827
11828 void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
11829
11830 void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
11831
11832 void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
11833
11834 void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *) {}
11835
11836 void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
11837
11838 void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
11839
11840 void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
11841
11842 void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
11843
11844 void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
11845
11846 void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
11847
11848 void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
11849     OMPUnifiedSharedMemoryClause *) {}
11850
11851 void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
11852
11853 void
11854 OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
11855 }
11856
11857 void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
11858     OMPAtomicDefaultMemOrderClause *C) {
11859   C->setAtomicDefaultMemOrderKind(
11860       static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
11861   C->setLParenLoc(Record.readSourceLocation());
11862   C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
11863 }
11864
11865 void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
11866   C->setLParenLoc(Record.readSourceLocation());
11867   unsigned NumVars = C->varlist_size();
11868   SmallVector<Expr *, 16> Vars;
11869   Vars.reserve(NumVars);
11870   for (unsigned i = 0; i != NumVars; ++i)
11871     Vars.push_back(Record.readSubExpr());
11872   C->setVarRefs(Vars);
11873   Vars.clear();
11874   for (unsigned i = 0; i != NumVars; ++i)
11875     Vars.push_back(Record.readSubExpr());
11876   C->setPrivateCopies(Vars);
11877 }
11878
11879 void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
11880   VisitOMPClauseWithPreInit(C);
11881   C->setLParenLoc(Record.readSourceLocation());
11882   unsigned NumVars = C->varlist_size();
11883   SmallVector<Expr *, 16> Vars;
11884   Vars.reserve(NumVars);
11885   for (unsigned i = 0; i != NumVars; ++i)
11886     Vars.push_back(Record.readSubExpr());
11887   C->setVarRefs(Vars);
11888   Vars.clear();
11889   for (unsigned i = 0; i != NumVars; ++i)
11890     Vars.push_back(Record.readSubExpr());
11891   C->setPrivateCopies(Vars);
11892   Vars.clear();
11893   for (unsigned i = 0; i != NumVars; ++i)
11894     Vars.push_back(Record.readSubExpr());
11895   C->setInits(Vars);
11896 }
11897
11898 void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
11899   VisitOMPClauseWithPostUpdate(C);
11900   C->setLParenLoc(Record.readSourceLocation());
11901   C->setKind(Record.readEnum<OpenMPLastprivateModifier>());
11902   C->setKindLoc(Record.readSourceLocation());
11903   C->setColonLoc(Record.readSourceLocation());
11904   unsigned NumVars = C->varlist_size();
11905   SmallVector<Expr *, 16> Vars;
11906   Vars.reserve(NumVars);
11907   for (unsigned i = 0; i != NumVars; ++i)
11908     Vars.push_back(Record.readSubExpr());
11909   C->setVarRefs(Vars);
11910   Vars.clear();
11911   for (unsigned i = 0; i != NumVars; ++i)
11912     Vars.push_back(Record.readSubExpr());
11913   C->setPrivateCopies(Vars);
11914   Vars.clear();
11915   for (unsigned i = 0; i != NumVars; ++i)
11916     Vars.push_back(Record.readSubExpr());
11917   C->setSourceExprs(Vars);
11918   Vars.clear();
11919   for (unsigned i = 0; i != NumVars; ++i)
11920     Vars.push_back(Record.readSubExpr());
11921   C->setDestinationExprs(Vars);
11922   Vars.clear();
11923   for (unsigned i = 0; i != NumVars; ++i)
11924     Vars.push_back(Record.readSubExpr());
11925   C->setAssignmentOps(Vars);
11926 }
11927
11928 void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
11929   C->setLParenLoc(Record.readSourceLocation());
11930   unsigned NumVars = C->varlist_size();
11931   SmallVector<Expr *, 16> Vars;
11932   Vars.reserve(NumVars);
11933   for (unsigned i = 0; i != NumVars; ++i)
11934     Vars.push_back(Record.readSubExpr());
11935   C->setVarRefs(Vars);
11936 }
11937
11938 void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
11939   VisitOMPClauseWithPostUpdate(C);
11940   C->setLParenLoc(Record.readSourceLocation());
11941   C->setColonLoc(Record.readSourceLocation());
11942   NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
11943   DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
11944   C->setQualifierLoc(NNSL);
11945   C->setNameInfo(DNI);
11946
11947   unsigned NumVars = C->varlist_size();
11948   SmallVector<Expr *, 16> Vars;
11949   Vars.reserve(NumVars);
11950   for (unsigned i = 0; i != NumVars; ++i)
11951     Vars.push_back(Record.readSubExpr());
11952   C->setVarRefs(Vars);
11953   Vars.clear();
11954   for (unsigned i = 0; i != NumVars; ++i)
11955     Vars.push_back(Record.readSubExpr());
11956   C->setPrivates(Vars);
11957   Vars.clear();
11958   for (unsigned i = 0; i != NumVars; ++i)
11959     Vars.push_back(Record.readSubExpr());
11960   C->setLHSExprs(Vars);
11961   Vars.clear();
11962   for (unsigned i = 0; i != NumVars; ++i)
11963     Vars.push_back(Record.readSubExpr());
11964   C->setRHSExprs(Vars);
11965   Vars.clear();
11966   for (unsigned i = 0; i != NumVars; ++i)
11967     Vars.push_back(Record.readSubExpr());
11968   C->setReductionOps(Vars);
11969 }
11970
11971 void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
11972   VisitOMPClauseWithPostUpdate(C);
11973   C->setLParenLoc(Record.readSourceLocation());
11974   C->setColonLoc(Record.readSourceLocation());
11975   NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
11976   DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
11977   C->setQualifierLoc(NNSL);
11978   C->setNameInfo(DNI);
11979
11980   unsigned NumVars = C->varlist_size();
11981   SmallVector<Expr *, 16> Vars;
11982   Vars.reserve(NumVars);
11983   for (unsigned I = 0; I != NumVars; ++I)
11984     Vars.push_back(Record.readSubExpr());
11985   C->setVarRefs(Vars);
11986   Vars.clear();
11987   for (unsigned I = 0; I != NumVars; ++I)
11988     Vars.push_back(Record.readSubExpr());
11989   C->setPrivates(Vars);
11990   Vars.clear();
11991   for (unsigned I = 0; I != NumVars; ++I)
11992     Vars.push_back(Record.readSubExpr());
11993   C->setLHSExprs(Vars);
11994   Vars.clear();
11995   for (unsigned I = 0; I != NumVars; ++I)
11996     Vars.push_back(Record.readSubExpr());
11997   C->setRHSExprs(Vars);
11998   Vars.clear();
11999   for (unsigned I = 0; I != NumVars; ++I)
12000     Vars.push_back(Record.readSubExpr());
12001   C->setReductionOps(Vars);
12002 }
12003
12004 void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
12005   VisitOMPClauseWithPostUpdate(C);
12006   C->setLParenLoc(Record.readSourceLocation());
12007   C->setColonLoc(Record.readSourceLocation());
12008   NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12009   DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
12010   C->setQualifierLoc(NNSL);
12011   C->setNameInfo(DNI);
12012
12013   unsigned NumVars = C->varlist_size();
12014   SmallVector<Expr *, 16> Vars;
12015   Vars.reserve(NumVars);
12016   for (unsigned I = 0; I != NumVars; ++I)
12017     Vars.push_back(Record.readSubExpr());
12018   C->setVarRefs(Vars);
12019   Vars.clear();
12020   for (unsigned I = 0; I != NumVars; ++I)
12021     Vars.push_back(Record.readSubExpr());
12022   C->setPrivates(Vars);
12023   Vars.clear();
12024   for (unsigned I = 0; I != NumVars; ++I)
12025     Vars.push_back(Record.readSubExpr());
12026   C->setLHSExprs(Vars);
12027   Vars.clear();
12028   for (unsigned I = 0; I != NumVars; ++I)
12029     Vars.push_back(Record.readSubExpr());
12030   C->setRHSExprs(Vars);
12031   Vars.clear();
12032   for (unsigned I = 0; I != NumVars; ++I)
12033     Vars.push_back(Record.readSubExpr());
12034   C->setReductionOps(Vars);
12035   Vars.clear();
12036   for (unsigned I = 0; I != NumVars; ++I)
12037     Vars.push_back(Record.readSubExpr());
12038   C->setTaskgroupDescriptors(Vars);
12039 }
12040
12041 void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
12042   VisitOMPClauseWithPostUpdate(C);
12043   C->setLParenLoc(Record.readSourceLocation());
12044   C->setColonLoc(Record.readSourceLocation());
12045   C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
12046   C->setModifierLoc(Record.readSourceLocation());
12047   unsigned NumVars = C->varlist_size();
12048   SmallVector<Expr *, 16> Vars;
12049   Vars.reserve(NumVars);
12050   for (unsigned i = 0; i != NumVars; ++i)
12051     Vars.push_back(Record.readSubExpr());
12052   C->setVarRefs(Vars);
12053   Vars.clear();
12054   for (unsigned i = 0; i != NumVars; ++i)
12055     Vars.push_back(Record.readSubExpr());
12056   C->setPrivates(Vars);
12057   Vars.clear();
12058   for (unsigned i = 0; i != NumVars; ++i)
12059     Vars.push_back(Record.readSubExpr());
12060   C->setInits(Vars);
12061   Vars.clear();
12062   for (unsigned i = 0; i != NumVars; ++i)
12063     Vars.push_back(Record.readSubExpr());
12064   C->setUpdates(Vars);
12065   Vars.clear();
12066   for (unsigned i = 0; i != NumVars; ++i)
12067     Vars.push_back(Record.readSubExpr());
12068   C->setFinals(Vars);
12069   C->setStep(Record.readSubExpr());
12070   C->setCalcStep(Record.readSubExpr());
12071   Vars.clear();
12072   for (unsigned I = 0; I != NumVars + 1; ++I)
12073     Vars.push_back(Record.readSubExpr());
12074   C->setUsedExprs(Vars);
12075 }
12076
12077 void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
12078   C->setLParenLoc(Record.readSourceLocation());
12079   C->setColonLoc(Record.readSourceLocation());
12080   unsigned NumVars = C->varlist_size();
12081   SmallVector<Expr *, 16> Vars;
12082   Vars.reserve(NumVars);
12083   for (unsigned i = 0; i != NumVars; ++i)
12084     Vars.push_back(Record.readSubExpr());
12085   C->setVarRefs(Vars);
12086   C->setAlignment(Record.readSubExpr());
12087 }
12088
12089 void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
12090   C->setLParenLoc(Record.readSourceLocation());
12091   unsigned NumVars = C->varlist_size();
12092   SmallVector<Expr *, 16> Exprs;
12093   Exprs.reserve(NumVars);
12094   for (unsigned i = 0; i != NumVars; ++i)
12095     Exprs.push_back(Record.readSubExpr());
12096   C->setVarRefs(Exprs);
12097   Exprs.clear();
12098   for (unsigned i = 0; i != NumVars; ++i)
12099     Exprs.push_back(Record.readSubExpr());
12100   C->setSourceExprs(Exprs);
12101   Exprs.clear();
12102   for (unsigned i = 0; i != NumVars; ++i)
12103     Exprs.push_back(Record.readSubExpr());
12104   C->setDestinationExprs(Exprs);
12105   Exprs.clear();
12106   for (unsigned i = 0; i != NumVars; ++i)
12107     Exprs.push_back(Record.readSubExpr());
12108   C->setAssignmentOps(Exprs);
12109 }
12110
12111 void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
12112   C->setLParenLoc(Record.readSourceLocation());
12113   unsigned NumVars = C->varlist_size();
12114   SmallVector<Expr *, 16> Exprs;
12115   Exprs.reserve(NumVars);
12116   for (unsigned i = 0; i != NumVars; ++i)
12117     Exprs.push_back(Record.readSubExpr());
12118   C->setVarRefs(Exprs);
12119   Exprs.clear();
12120   for (unsigned i = 0; i != NumVars; ++i)
12121     Exprs.push_back(Record.readSubExpr());
12122   C->setSourceExprs(Exprs);
12123   Exprs.clear();
12124   for (unsigned i = 0; i != NumVars; ++i)
12125     Exprs.push_back(Record.readSubExpr());
12126   C->setDestinationExprs(Exprs);
12127   Exprs.clear();
12128   for (unsigned i = 0; i != NumVars; ++i)
12129     Exprs.push_back(Record.readSubExpr());
12130   C->setAssignmentOps(Exprs);
12131 }
12132
12133 void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
12134   C->setLParenLoc(Record.readSourceLocation());
12135   unsigned NumVars = C->varlist_size();
12136   SmallVector<Expr *, 16> Vars;
12137   Vars.reserve(NumVars);
12138   for (unsigned i = 0; i != NumVars; ++i)
12139     Vars.push_back(Record.readSubExpr());
12140   C->setVarRefs(Vars);
12141 }
12142
12143 void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
12144   C->setLParenLoc(Record.readSourceLocation());
12145   C->setDependencyKind(
12146       static_cast<OpenMPDependClauseKind>(Record.readInt()));
12147   C->setDependencyLoc(Record.readSourceLocation());
12148   C->setColonLoc(Record.readSourceLocation());
12149   unsigned NumVars = C->varlist_size();
12150   SmallVector<Expr *, 16> Vars;
12151   Vars.reserve(NumVars);
12152   for (unsigned I = 0; I != NumVars; ++I)
12153     Vars.push_back(Record.readSubExpr());
12154   C->setVarRefs(Vars);
12155   for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
12156     C->setLoopData(I, Record.readSubExpr());
12157 }
12158
12159 void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
12160   VisitOMPClauseWithPreInit(C);
12161   C->setDevice(Record.readSubExpr());
12162   C->setLParenLoc(Record.readSourceLocation());
12163 }
12164
12165 void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
12166   C->setLParenLoc(Record.readSourceLocation());
12167   for (unsigned I = 0; I < OMPMapClause::NumberOfModifiers; ++I) {
12168     C->setMapTypeModifier(
12169         I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
12170     C->setMapTypeModifierLoc(I, Record.readSourceLocation());
12171   }
12172   C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12173   C->setMapperIdInfo(Record.readDeclarationNameInfo());
12174   C->setMapType(
12175      static_cast<OpenMPMapClauseKind>(Record.readInt()));
12176   C->setMapLoc(Record.readSourceLocation());
12177   C->setColonLoc(Record.readSourceLocation());
12178   auto NumVars = C->varlist_size();
12179   auto UniqueDecls = C->getUniqueDeclarationsNum();
12180   auto TotalLists = C->getTotalComponentListNum();
12181   auto TotalComponents = C->getTotalComponentsNum();
12182
12183   SmallVector<Expr *, 16> Vars;
12184   Vars.reserve(NumVars);
12185   for (unsigned i = 0; i != NumVars; ++i)
12186     Vars.push_back(Record.readExpr());
12187   C->setVarRefs(Vars);
12188
12189   SmallVector<Expr *, 16> UDMappers;
12190   UDMappers.reserve(NumVars);
12191   for (unsigned I = 0; I < NumVars; ++I)
12192     UDMappers.push_back(Record.readExpr());
12193   C->setUDMapperRefs(UDMappers);
12194
12195   SmallVector<ValueDecl *, 16> Decls;
12196   Decls.reserve(UniqueDecls);
12197   for (unsigned i = 0; i < UniqueDecls; ++i)
12198     Decls.push_back(Record.readDeclAs<ValueDecl>());
12199   C->setUniqueDecls(Decls);
12200
12201   SmallVector<unsigned, 16> ListsPerDecl;
12202   ListsPerDecl.reserve(UniqueDecls);
12203   for (unsigned i = 0; i < UniqueDecls; ++i)
12204     ListsPerDecl.push_back(Record.readInt());
12205   C->setDeclNumLists(ListsPerDecl);
12206
12207   SmallVector<unsigned, 32> ListSizes;
12208   ListSizes.reserve(TotalLists);
12209   for (unsigned i = 0; i < TotalLists; ++i)
12210     ListSizes.push_back(Record.readInt());
12211   C->setComponentListSizes(ListSizes);
12212
12213   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12214   Components.reserve(TotalComponents);
12215   for (unsigned i = 0; i < TotalComponents; ++i) {
12216     Expr *AssociatedExpr = Record.readExpr();
12217     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12218     Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12219         AssociatedExpr, AssociatedDecl));
12220   }
12221   C->setComponents(Components, ListSizes);
12222 }
12223
12224 void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
12225   C->setLParenLoc(Record.readSourceLocation());
12226   C->setColonLoc(Record.readSourceLocation());
12227   C->setAllocator(Record.readSubExpr());
12228   unsigned NumVars = C->varlist_size();
12229   SmallVector<Expr *, 16> Vars;
12230   Vars.reserve(NumVars);
12231   for (unsigned i = 0; i != NumVars; ++i)
12232     Vars.push_back(Record.readSubExpr());
12233   C->setVarRefs(Vars);
12234 }
12235
12236 void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
12237   VisitOMPClauseWithPreInit(C);
12238   C->setNumTeams(Record.readSubExpr());
12239   C->setLParenLoc(Record.readSourceLocation());
12240 }
12241
12242 void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
12243   VisitOMPClauseWithPreInit(C);
12244   C->setThreadLimit(Record.readSubExpr());
12245   C->setLParenLoc(Record.readSourceLocation());
12246 }
12247
12248 void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
12249   VisitOMPClauseWithPreInit(C);
12250   C->setPriority(Record.readSubExpr());
12251   C->setLParenLoc(Record.readSourceLocation());
12252 }
12253
12254 void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
12255   VisitOMPClauseWithPreInit(C);
12256   C->setGrainsize(Record.readSubExpr());
12257   C->setLParenLoc(Record.readSourceLocation());
12258 }
12259
12260 void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
12261   VisitOMPClauseWithPreInit(C);
12262   C->setNumTasks(Record.readSubExpr());
12263   C->setLParenLoc(Record.readSourceLocation());
12264 }
12265
12266 void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
12267   C->setHint(Record.readSubExpr());
12268   C->setLParenLoc(Record.readSourceLocation());
12269 }
12270
12271 void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
12272   VisitOMPClauseWithPreInit(C);
12273   C->setDistScheduleKind(
12274       static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
12275   C->setChunkSize(Record.readSubExpr());
12276   C->setLParenLoc(Record.readSourceLocation());
12277   C->setDistScheduleKindLoc(Record.readSourceLocation());
12278   C->setCommaLoc(Record.readSourceLocation());
12279 }
12280
12281 void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
12282   C->setDefaultmapKind(
12283        static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
12284   C->setDefaultmapModifier(
12285       static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
12286   C->setLParenLoc(Record.readSourceLocation());
12287   C->setDefaultmapModifierLoc(Record.readSourceLocation());
12288   C->setDefaultmapKindLoc(Record.readSourceLocation());
12289 }
12290
12291 void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
12292   C->setLParenLoc(Record.readSourceLocation());
12293   C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12294   C->setMapperIdInfo(Record.readDeclarationNameInfo());
12295   auto NumVars = C->varlist_size();
12296   auto UniqueDecls = C->getUniqueDeclarationsNum();
12297   auto TotalLists = C->getTotalComponentListNum();
12298   auto TotalComponents = C->getTotalComponentsNum();
12299
12300   SmallVector<Expr *, 16> Vars;
12301   Vars.reserve(NumVars);
12302   for (unsigned i = 0; i != NumVars; ++i)
12303     Vars.push_back(Record.readSubExpr());
12304   C->setVarRefs(Vars);
12305
12306   SmallVector<Expr *, 16> UDMappers;
12307   UDMappers.reserve(NumVars);
12308   for (unsigned I = 0; I < NumVars; ++I)
12309     UDMappers.push_back(Record.readSubExpr());
12310   C->setUDMapperRefs(UDMappers);
12311
12312   SmallVector<ValueDecl *, 16> Decls;
12313   Decls.reserve(UniqueDecls);
12314   for (unsigned i = 0; i < UniqueDecls; ++i)
12315     Decls.push_back(Record.readDeclAs<ValueDecl>());
12316   C->setUniqueDecls(Decls);
12317
12318   SmallVector<unsigned, 16> ListsPerDecl;
12319   ListsPerDecl.reserve(UniqueDecls);
12320   for (unsigned i = 0; i < UniqueDecls; ++i)
12321     ListsPerDecl.push_back(Record.readInt());
12322   C->setDeclNumLists(ListsPerDecl);
12323
12324   SmallVector<unsigned, 32> ListSizes;
12325   ListSizes.reserve(TotalLists);
12326   for (unsigned i = 0; i < TotalLists; ++i)
12327     ListSizes.push_back(Record.readInt());
12328   C->setComponentListSizes(ListSizes);
12329
12330   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12331   Components.reserve(TotalComponents);
12332   for (unsigned i = 0; i < TotalComponents; ++i) {
12333     Expr *AssociatedExpr = Record.readSubExpr();
12334     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12335     Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12336         AssociatedExpr, AssociatedDecl));
12337   }
12338   C->setComponents(Components, ListSizes);
12339 }
12340
12341 void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
12342   C->setLParenLoc(Record.readSourceLocation());
12343   C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12344   C->setMapperIdInfo(Record.readDeclarationNameInfo());
12345   auto NumVars = C->varlist_size();
12346   auto UniqueDecls = C->getUniqueDeclarationsNum();
12347   auto TotalLists = C->getTotalComponentListNum();
12348   auto TotalComponents = C->getTotalComponentsNum();
12349
12350   SmallVector<Expr *, 16> Vars;
12351   Vars.reserve(NumVars);
12352   for (unsigned i = 0; i != NumVars; ++i)
12353     Vars.push_back(Record.readSubExpr());
12354   C->setVarRefs(Vars);
12355
12356   SmallVector<Expr *, 16> UDMappers;
12357   UDMappers.reserve(NumVars);
12358   for (unsigned I = 0; I < NumVars; ++I)
12359     UDMappers.push_back(Record.readSubExpr());
12360   C->setUDMapperRefs(UDMappers);
12361
12362   SmallVector<ValueDecl *, 16> Decls;
12363   Decls.reserve(UniqueDecls);
12364   for (unsigned i = 0; i < UniqueDecls; ++i)
12365     Decls.push_back(Record.readDeclAs<ValueDecl>());
12366   C->setUniqueDecls(Decls);
12367
12368   SmallVector<unsigned, 16> ListsPerDecl;
12369   ListsPerDecl.reserve(UniqueDecls);
12370   for (unsigned i = 0; i < UniqueDecls; ++i)
12371     ListsPerDecl.push_back(Record.readInt());
12372   C->setDeclNumLists(ListsPerDecl);
12373
12374   SmallVector<unsigned, 32> ListSizes;
12375   ListSizes.reserve(TotalLists);
12376   for (unsigned i = 0; i < TotalLists; ++i)
12377     ListSizes.push_back(Record.readInt());
12378   C->setComponentListSizes(ListSizes);
12379
12380   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12381   Components.reserve(TotalComponents);
12382   for (unsigned i = 0; i < TotalComponents; ++i) {
12383     Expr *AssociatedExpr = Record.readSubExpr();
12384     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12385     Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12386         AssociatedExpr, AssociatedDecl));
12387   }
12388   C->setComponents(Components, ListSizes);
12389 }
12390
12391 void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
12392   C->setLParenLoc(Record.readSourceLocation());
12393   auto NumVars = C->varlist_size();
12394   auto UniqueDecls = C->getUniqueDeclarationsNum();
12395   auto TotalLists = C->getTotalComponentListNum();
12396   auto TotalComponents = C->getTotalComponentsNum();
12397
12398   SmallVector<Expr *, 16> Vars;
12399   Vars.reserve(NumVars);
12400   for (unsigned i = 0; i != NumVars; ++i)
12401     Vars.push_back(Record.readSubExpr());
12402   C->setVarRefs(Vars);
12403   Vars.clear();
12404   for (unsigned i = 0; i != NumVars; ++i)
12405     Vars.push_back(Record.readSubExpr());
12406   C->setPrivateCopies(Vars);
12407   Vars.clear();
12408   for (unsigned i = 0; i != NumVars; ++i)
12409     Vars.push_back(Record.readSubExpr());
12410   C->setInits(Vars);
12411
12412   SmallVector<ValueDecl *, 16> Decls;
12413   Decls.reserve(UniqueDecls);
12414   for (unsigned i = 0; i < UniqueDecls; ++i)
12415     Decls.push_back(Record.readDeclAs<ValueDecl>());
12416   C->setUniqueDecls(Decls);
12417
12418   SmallVector<unsigned, 16> ListsPerDecl;
12419   ListsPerDecl.reserve(UniqueDecls);
12420   for (unsigned i = 0; i < UniqueDecls; ++i)
12421     ListsPerDecl.push_back(Record.readInt());
12422   C->setDeclNumLists(ListsPerDecl);
12423
12424   SmallVector<unsigned, 32> ListSizes;
12425   ListSizes.reserve(TotalLists);
12426   for (unsigned i = 0; i < TotalLists; ++i)
12427     ListSizes.push_back(Record.readInt());
12428   C->setComponentListSizes(ListSizes);
12429
12430   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12431   Components.reserve(TotalComponents);
12432   for (unsigned i = 0; i < TotalComponents; ++i) {
12433     Expr *AssociatedExpr = Record.readSubExpr();
12434     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12435     Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12436         AssociatedExpr, AssociatedDecl));
12437   }
12438   C->setComponents(Components, ListSizes);
12439 }
12440
12441 void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
12442   C->setLParenLoc(Record.readSourceLocation());
12443   auto NumVars = C->varlist_size();
12444   auto UniqueDecls = C->getUniqueDeclarationsNum();
12445   auto TotalLists = C->getTotalComponentListNum();
12446   auto TotalComponents = C->getTotalComponentsNum();
12447
12448   SmallVector<Expr *, 16> Vars;
12449   Vars.reserve(NumVars);
12450   for (unsigned i = 0; i != NumVars; ++i)
12451     Vars.push_back(Record.readSubExpr());
12452   C->setVarRefs(Vars);
12453   Vars.clear();
12454
12455   SmallVector<ValueDecl *, 16> Decls;
12456   Decls.reserve(UniqueDecls);
12457   for (unsigned i = 0; i < UniqueDecls; ++i)
12458     Decls.push_back(Record.readDeclAs<ValueDecl>());
12459   C->setUniqueDecls(Decls);
12460
12461   SmallVector<unsigned, 16> ListsPerDecl;
12462   ListsPerDecl.reserve(UniqueDecls);
12463   for (unsigned i = 0; i < UniqueDecls; ++i)
12464     ListsPerDecl.push_back(Record.readInt());
12465   C->setDeclNumLists(ListsPerDecl);
12466
12467   SmallVector<unsigned, 32> ListSizes;
12468   ListSizes.reserve(TotalLists);
12469   for (unsigned i = 0; i < TotalLists; ++i)
12470     ListSizes.push_back(Record.readInt());
12471   C->setComponentListSizes(ListSizes);
12472
12473   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12474   Components.reserve(TotalComponents);
12475   for (unsigned i = 0; i < TotalComponents; ++i) {
12476     Expr *AssociatedExpr = Record.readSubExpr();
12477     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12478     Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12479         AssociatedExpr, AssociatedDecl));
12480   }
12481   C->setComponents(Components, ListSizes);
12482 }
12483
12484 void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
12485   C->setLParenLoc(Record.readSourceLocation());
12486   unsigned NumVars = C->varlist_size();
12487   SmallVector<Expr *, 16> Vars;
12488   Vars.reserve(NumVars);
12489   for (unsigned i = 0; i != NumVars; ++i)
12490     Vars.push_back(Record.readSubExpr());
12491   C->setVarRefs(Vars);
12492   Vars.clear();
12493   Vars.reserve(NumVars);
12494   for (unsigned i = 0; i != NumVars; ++i)
12495     Vars.push_back(Record.readSubExpr());
12496   C->setPrivateRefs(Vars);
12497 }