]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Serialization/ASTReader.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r304222, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Serialization / ASTReader.cpp
1 //===-- ASTReader.cpp - AST File Reader -----------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines the ASTReader class, which reads AST files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/Serialization/ASTReader.h"
15 #include "ASTCommon.h"
16 #include "ASTReaderInternals.h"
17 #include "clang/AST/ASTConsumer.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/ASTMutationListener.h"
20 #include "clang/AST/ASTUnresolvedSet.h"
21 #include "clang/AST/Decl.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclGroup.h"
24 #include "clang/AST/DeclObjC.h"
25 #include "clang/AST/DeclTemplate.h"
26 #include "clang/AST/Expr.h"
27 #include "clang/AST/ExprCXX.h"
28 #include "clang/AST/NestedNameSpecifier.h"
29 #include "clang/AST/ODRHash.h"
30 #include "clang/AST/RawCommentList.h"
31 #include "clang/AST/Type.h"
32 #include "clang/AST/TypeLocVisitor.h"
33 #include "clang/AST/UnresolvedSet.h"
34 #include "clang/Basic/CommentOptions.h"
35 #include "clang/Basic/DiagnosticOptions.h"
36 #include "clang/Basic/ExceptionSpecificationType.h"
37 #include "clang/Basic/FileManager.h"
38 #include "clang/Basic/FileSystemOptions.h"
39 #include "clang/Basic/LangOptions.h"
40 #include "clang/Basic/MemoryBufferCache.h"
41 #include "clang/Basic/ObjCRuntime.h"
42 #include "clang/Basic/OperatorKinds.h"
43 #include "clang/Basic/Sanitizers.h"
44 #include "clang/Basic/SourceManager.h"
45 #include "clang/Basic/SourceManagerInternals.h"
46 #include "clang/Basic/Specifiers.h"
47 #include "clang/Basic/TargetInfo.h"
48 #include "clang/Basic/TargetOptions.h"
49 #include "clang/Basic/TokenKinds.h"
50 #include "clang/Basic/Version.h"
51 #include "clang/Basic/VersionTuple.h"
52 #include "clang/Frontend/PCHContainerOperations.h"
53 #include "clang/Lex/HeaderSearch.h"
54 #include "clang/Lex/HeaderSearchOptions.h"
55 #include "clang/Lex/MacroInfo.h"
56 #include "clang/Lex/ModuleMap.h"
57 #include "clang/Lex/PreprocessingRecord.h"
58 #include "clang/Lex/Preprocessor.h"
59 #include "clang/Lex/PreprocessorOptions.h"
60 #include "clang/Sema/Scope.h"
61 #include "clang/Sema/Sema.h"
62 #include "clang/Sema/Weak.h"
63 #include "clang/Serialization/ASTDeserializationListener.h"
64 #include "clang/Serialization/GlobalModuleIndex.h"
65 #include "clang/Serialization/ModuleManager.h"
66 #include "clang/Serialization/SerializationDiagnostic.h"
67 #include "llvm/ADT/APFloat.h"
68 #include "llvm/ADT/APInt.h"
69 #include "llvm/ADT/APSInt.h"
70 #include "llvm/ADT/Hashing.h"
71 #include "llvm/ADT/SmallString.h"
72 #include "llvm/ADT/StringExtras.h"
73 #include "llvm/ADT/Triple.h"
74 #include "llvm/Bitcode/BitstreamReader.h"
75 #include "llvm/Support/Compression.h"
76 #include "llvm/Support/Compiler.h"
77 #include "llvm/Support/Error.h"
78 #include "llvm/Support/ErrorHandling.h"
79 #include "llvm/Support/FileSystem.h"
80 #include "llvm/Support/MemoryBuffer.h"
81 #include "llvm/Support/Path.h"
82 #include "llvm/Support/SaveAndRestore.h"
83 #include "llvm/Support/raw_ostream.h"
84 #include <algorithm>
85 #include <cassert>
86 #include <cstdint>
87 #include <cstdio>
88 #include <cstring>
89 #include <ctime>
90 #include <iterator>
91 #include <limits>
92 #include <map>
93 #include <memory>
94 #include <new>
95 #include <string>
96 #include <system_error>
97 #include <tuple>
98 #include <utility>
99 #include <vector>
100
101 using namespace clang;
102 using namespace clang::serialization;
103 using namespace clang::serialization::reader;
104 using llvm::BitstreamCursor;
105
106 //===----------------------------------------------------------------------===//
107 // ChainedASTReaderListener implementation
108 //===----------------------------------------------------------------------===//
109
110 bool
111 ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
112   return First->ReadFullVersionInformation(FullVersion) ||
113          Second->ReadFullVersionInformation(FullVersion);
114 }
115
116 void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
117   First->ReadModuleName(ModuleName);
118   Second->ReadModuleName(ModuleName);
119 }
120
121 void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
122   First->ReadModuleMapFile(ModuleMapPath);
123   Second->ReadModuleMapFile(ModuleMapPath);
124 }
125
126 bool
127 ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
128                                               bool Complain,
129                                               bool AllowCompatibleDifferences) {
130   return First->ReadLanguageOptions(LangOpts, Complain,
131                                     AllowCompatibleDifferences) ||
132          Second->ReadLanguageOptions(LangOpts, Complain,
133                                      AllowCompatibleDifferences);
134 }
135
136 bool ChainedASTReaderListener::ReadTargetOptions(
137     const TargetOptions &TargetOpts, bool Complain,
138     bool AllowCompatibleDifferences) {
139   return First->ReadTargetOptions(TargetOpts, Complain,
140                                   AllowCompatibleDifferences) ||
141          Second->ReadTargetOptions(TargetOpts, Complain,
142                                    AllowCompatibleDifferences);
143 }
144
145 bool ChainedASTReaderListener::ReadDiagnosticOptions(
146     IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
147   return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
148          Second->ReadDiagnosticOptions(DiagOpts, Complain);
149 }
150
151 bool
152 ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
153                                                 bool Complain) {
154   return First->ReadFileSystemOptions(FSOpts, Complain) ||
155          Second->ReadFileSystemOptions(FSOpts, Complain);
156 }
157
158 bool ChainedASTReaderListener::ReadHeaderSearchOptions(
159     const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
160     bool Complain) {
161   return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
162                                         Complain) ||
163          Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
164                                          Complain);
165 }
166
167 bool ChainedASTReaderListener::ReadPreprocessorOptions(
168     const PreprocessorOptions &PPOpts, bool Complain,
169     std::string &SuggestedPredefines) {
170   return First->ReadPreprocessorOptions(PPOpts, Complain,
171                                         SuggestedPredefines) ||
172          Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
173 }
174 void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
175                                            unsigned Value) {
176   First->ReadCounter(M, Value);
177   Second->ReadCounter(M, Value);
178 }
179 bool ChainedASTReaderListener::needsInputFileVisitation() {
180   return First->needsInputFileVisitation() ||
181          Second->needsInputFileVisitation();
182 }
183 bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
184   return First->needsSystemInputFileVisitation() ||
185   Second->needsSystemInputFileVisitation();
186 }
187 void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
188                                                ModuleKind Kind) {
189   First->visitModuleFile(Filename, Kind);
190   Second->visitModuleFile(Filename, Kind);
191 }
192
193 bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
194                                               bool isSystem,
195                                               bool isOverridden,
196                                               bool isExplicitModule) {
197   bool Continue = false;
198   if (First->needsInputFileVisitation() &&
199       (!isSystem || First->needsSystemInputFileVisitation()))
200     Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
201                                       isExplicitModule);
202   if (Second->needsInputFileVisitation() &&
203       (!isSystem || Second->needsSystemInputFileVisitation()))
204     Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
205                                        isExplicitModule);
206   return Continue;
207 }
208
209 void ChainedASTReaderListener::readModuleFileExtension(
210        const ModuleFileExtensionMetadata &Metadata) {
211   First->readModuleFileExtension(Metadata);
212   Second->readModuleFileExtension(Metadata);
213 }
214
215 //===----------------------------------------------------------------------===//
216 // PCH validator implementation
217 //===----------------------------------------------------------------------===//
218
219 ASTReaderListener::~ASTReaderListener() {}
220
221 /// \brief Compare the given set of language options against an existing set of
222 /// language options.
223 ///
224 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
225 /// \param AllowCompatibleDifferences If true, differences between compatible
226 ///        language options will be permitted.
227 ///
228 /// \returns true if the languagae options mis-match, false otherwise.
229 static bool checkLanguageOptions(const LangOptions &LangOpts,
230                                  const LangOptions &ExistingLangOpts,
231                                  DiagnosticsEngine *Diags,
232                                  bool AllowCompatibleDifferences = true) {
233 #define LANGOPT(Name, Bits, Default, Description)                 \
234   if (ExistingLangOpts.Name != LangOpts.Name) {                   \
235     if (Diags)                                                    \
236       Diags->Report(diag::err_pch_langopt_mismatch)               \
237         << Description << LangOpts.Name << ExistingLangOpts.Name; \
238     return true;                                                  \
239   }
240
241 #define VALUE_LANGOPT(Name, Bits, Default, Description)   \
242   if (ExistingLangOpts.Name != LangOpts.Name) {           \
243     if (Diags)                                            \
244       Diags->Report(diag::err_pch_langopt_value_mismatch) \
245         << Description;                                   \
246     return true;                                          \
247   }
248
249 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description)   \
250   if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) {  \
251     if (Diags)                                                 \
252       Diags->Report(diag::err_pch_langopt_value_mismatch)      \
253         << Description;                                        \
254     return true;                                               \
255   }
256
257 #define COMPATIBLE_LANGOPT(Name, Bits, Default, Description)  \
258   if (!AllowCompatibleDifferences)                            \
259     LANGOPT(Name, Bits, Default, Description)
260
261 #define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description)  \
262   if (!AllowCompatibleDifferences)                                 \
263     ENUM_LANGOPT(Name, Bits, Default, Description)
264
265 #define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
266   if (!AllowCompatibleDifferences)                                 \
267     VALUE_LANGOPT(Name, Bits, Default, Description)
268
269 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
270 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
271 #define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
272 #include "clang/Basic/LangOptions.def"
273
274   if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
275     if (Diags)
276       Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
277     return true;
278   }
279
280   if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
281     if (Diags)
282       Diags->Report(diag::err_pch_langopt_value_mismatch)
283       << "target Objective-C runtime";
284     return true;
285   }
286
287   if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
288       LangOpts.CommentOpts.BlockCommandNames) {
289     if (Diags)
290       Diags->Report(diag::err_pch_langopt_value_mismatch)
291         << "block command names";
292     return true;
293   }
294
295   return false;
296 }
297
298 /// \brief Compare the given set of target options against an existing set of
299 /// target options.
300 ///
301 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
302 ///
303 /// \returns true if the target options mis-match, false otherwise.
304 static bool checkTargetOptions(const TargetOptions &TargetOpts,
305                                const TargetOptions &ExistingTargetOpts,
306                                DiagnosticsEngine *Diags,
307                                bool AllowCompatibleDifferences = true) {
308 #define CHECK_TARGET_OPT(Field, Name)                             \
309   if (TargetOpts.Field != ExistingTargetOpts.Field) {             \
310     if (Diags)                                                    \
311       Diags->Report(diag::err_pch_targetopt_mismatch)             \
312         << Name << TargetOpts.Field << ExistingTargetOpts.Field;  \
313     return true;                                                  \
314   }
315
316   // The triple and ABI must match exactly.
317   CHECK_TARGET_OPT(Triple, "target");
318   CHECK_TARGET_OPT(ABI, "target ABI");
319
320   // We can tolerate different CPUs in many cases, notably when one CPU
321   // supports a strict superset of another. When allowing compatible
322   // differences skip this check.
323   if (!AllowCompatibleDifferences)
324     CHECK_TARGET_OPT(CPU, "target CPU");
325
326 #undef CHECK_TARGET_OPT
327
328   // Compare feature sets.
329   SmallVector<StringRef, 4> ExistingFeatures(
330                                              ExistingTargetOpts.FeaturesAsWritten.begin(),
331                                              ExistingTargetOpts.FeaturesAsWritten.end());
332   SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
333                                          TargetOpts.FeaturesAsWritten.end());
334   std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
335   std::sort(ReadFeatures.begin(), ReadFeatures.end());
336
337   // We compute the set difference in both directions explicitly so that we can
338   // diagnose the differences differently.
339   SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
340   std::set_difference(
341       ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
342       ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
343   std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
344                       ExistingFeatures.begin(), ExistingFeatures.end(),
345                       std::back_inserter(UnmatchedReadFeatures));
346
347   // If we are allowing compatible differences and the read feature set is
348   // a strict subset of the existing feature set, there is nothing to diagnose.
349   if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
350     return false;
351
352   if (Diags) {
353     for (StringRef Feature : UnmatchedReadFeatures)
354       Diags->Report(diag::err_pch_targetopt_feature_mismatch)
355           << /* is-existing-feature */ false << Feature;
356     for (StringRef Feature : UnmatchedExistingFeatures)
357       Diags->Report(diag::err_pch_targetopt_feature_mismatch)
358           << /* is-existing-feature */ true << Feature;
359   }
360
361   return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
362 }
363
364 bool
365 PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
366                                   bool Complain,
367                                   bool AllowCompatibleDifferences) {
368   const LangOptions &ExistingLangOpts = PP.getLangOpts();
369   return checkLanguageOptions(LangOpts, ExistingLangOpts,
370                               Complain ? &Reader.Diags : nullptr,
371                               AllowCompatibleDifferences);
372 }
373
374 bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
375                                      bool Complain,
376                                      bool AllowCompatibleDifferences) {
377   const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
378   return checkTargetOptions(TargetOpts, ExistingTargetOpts,
379                             Complain ? &Reader.Diags : nullptr,
380                             AllowCompatibleDifferences);
381 }
382
383 namespace {
384
385   typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
386     MacroDefinitionsMap;
387   typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
388     DeclsMap;
389
390 } // end anonymous namespace
391
392 static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
393                                          DiagnosticsEngine &Diags,
394                                          bool Complain) {
395   typedef DiagnosticsEngine::Level Level;
396
397   // Check current mappings for new -Werror mappings, and the stored mappings
398   // for cases that were explicitly mapped to *not* be errors that are now
399   // errors because of options like -Werror.
400   DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
401
402   for (DiagnosticsEngine *MappingSource : MappingSources) {
403     for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
404       diag::kind DiagID = DiagIDMappingPair.first;
405       Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
406       if (CurLevel < DiagnosticsEngine::Error)
407         continue; // not significant
408       Level StoredLevel =
409           StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
410       if (StoredLevel < DiagnosticsEngine::Error) {
411         if (Complain)
412           Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
413               Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
414         return true;
415       }
416     }
417   }
418
419   return false;
420 }
421
422 static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
423   diag::Severity Ext = Diags.getExtensionHandlingBehavior();
424   if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
425     return true;
426   return Ext >= diag::Severity::Error;
427 }
428
429 static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
430                                     DiagnosticsEngine &Diags,
431                                     bool IsSystem, bool Complain) {
432   // Top-level options
433   if (IsSystem) {
434     if (Diags.getSuppressSystemWarnings())
435       return false;
436     // If -Wsystem-headers was not enabled before, be conservative
437     if (StoredDiags.getSuppressSystemWarnings()) {
438       if (Complain)
439         Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
440       return true;
441     }
442   }
443
444   if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
445     if (Complain)
446       Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
447     return true;
448   }
449
450   if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
451       !StoredDiags.getEnableAllWarnings()) {
452     if (Complain)
453       Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
454     return true;
455   }
456
457   if (isExtHandlingFromDiagsError(Diags) &&
458       !isExtHandlingFromDiagsError(StoredDiags)) {
459     if (Complain)
460       Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
461     return true;
462   }
463
464   return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
465 }
466
467 /// Return the top import module if it is implicit, nullptr otherwise.
468 static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
469                                           Preprocessor &PP) {
470   // If the original import came from a file explicitly generated by the user,
471   // don't check the diagnostic mappings.
472   // FIXME: currently this is approximated by checking whether this is not a
473   // module import of an implicitly-loaded module file.
474   // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
475   // the transitive closure of its imports, since unrelated modules cannot be
476   // imported until after this module finishes validation.
477   ModuleFile *TopImport = &*ModuleMgr.rbegin();
478   while (!TopImport->ImportedBy.empty())
479     TopImport = TopImport->ImportedBy[0];
480   if (TopImport->Kind != MK_ImplicitModule)
481     return nullptr;
482
483   StringRef ModuleName = TopImport->ModuleName;
484   assert(!ModuleName.empty() && "diagnostic options read before module name");
485
486   Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
487   assert(M && "missing module");
488   return M;
489 }
490
491 bool PCHValidator::ReadDiagnosticOptions(
492     IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
493   DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
494   IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
495   IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
496       new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
497   // This should never fail, because we would have processed these options
498   // before writing them to an ASTFile.
499   ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
500
501   ModuleManager &ModuleMgr = Reader.getModuleManager();
502   assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
503
504   Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
505   if (!TopM)
506     return false;
507
508   // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
509   // contains the union of their flags.
510   return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
511                                  Complain);
512 }
513
514 /// \brief Collect the macro definitions provided by the given preprocessor
515 /// options.
516 static void
517 collectMacroDefinitions(const PreprocessorOptions &PPOpts,
518                         MacroDefinitionsMap &Macros,
519                         SmallVectorImpl<StringRef> *MacroNames = nullptr) {
520   for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
521     StringRef Macro = PPOpts.Macros[I].first;
522     bool IsUndef = PPOpts.Macros[I].second;
523
524     std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
525     StringRef MacroName = MacroPair.first;
526     StringRef MacroBody = MacroPair.second;
527
528     // For an #undef'd macro, we only care about the name.
529     if (IsUndef) {
530       if (MacroNames && !Macros.count(MacroName))
531         MacroNames->push_back(MacroName);
532
533       Macros[MacroName] = std::make_pair("", true);
534       continue;
535     }
536
537     // For a #define'd macro, figure out the actual definition.
538     if (MacroName.size() == Macro.size())
539       MacroBody = "1";
540     else {
541       // Note: GCC drops anything following an end-of-line character.
542       StringRef::size_type End = MacroBody.find_first_of("\n\r");
543       MacroBody = MacroBody.substr(0, End);
544     }
545
546     if (MacroNames && !Macros.count(MacroName))
547       MacroNames->push_back(MacroName);
548     Macros[MacroName] = std::make_pair(MacroBody, false);
549   }
550 }
551
552 /// \brief Check the preprocessor options deserialized from the control block
553 /// against the preprocessor options in an existing preprocessor.
554 ///
555 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
556 /// \param Validate If true, validate preprocessor options. If false, allow
557 ///        macros defined by \p ExistingPPOpts to override those defined by
558 ///        \p PPOpts in SuggestedPredefines.
559 static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
560                                      const PreprocessorOptions &ExistingPPOpts,
561                                      DiagnosticsEngine *Diags,
562                                      FileManager &FileMgr,
563                                      std::string &SuggestedPredefines,
564                                      const LangOptions &LangOpts,
565                                      bool Validate = true) {
566   // Check macro definitions.
567   MacroDefinitionsMap ASTFileMacros;
568   collectMacroDefinitions(PPOpts, ASTFileMacros);
569   MacroDefinitionsMap ExistingMacros;
570   SmallVector<StringRef, 4> ExistingMacroNames;
571   collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
572
573   for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
574     // Dig out the macro definition in the existing preprocessor options.
575     StringRef MacroName = ExistingMacroNames[I];
576     std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
577
578     // Check whether we know anything about this macro name or not.
579     llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
580       = ASTFileMacros.find(MacroName);
581     if (!Validate || Known == ASTFileMacros.end()) {
582       // FIXME: Check whether this identifier was referenced anywhere in the
583       // AST file. If so, we should reject the AST file. Unfortunately, this
584       // information isn't in the control block. What shall we do about it?
585
586       if (Existing.second) {
587         SuggestedPredefines += "#undef ";
588         SuggestedPredefines += MacroName.str();
589         SuggestedPredefines += '\n';
590       } else {
591         SuggestedPredefines += "#define ";
592         SuggestedPredefines += MacroName.str();
593         SuggestedPredefines += ' ';
594         SuggestedPredefines += Existing.first.str();
595         SuggestedPredefines += '\n';
596       }
597       continue;
598     }
599
600     // If the macro was defined in one but undef'd in the other, we have a
601     // conflict.
602     if (Existing.second != Known->second.second) {
603       if (Diags) {
604         Diags->Report(diag::err_pch_macro_def_undef)
605           << MacroName << Known->second.second;
606       }
607       return true;
608     }
609
610     // If the macro was #undef'd in both, or if the macro bodies are identical,
611     // it's fine.
612     if (Existing.second || Existing.first == Known->second.first)
613       continue;
614
615     // The macro bodies differ; complain.
616     if (Diags) {
617       Diags->Report(diag::err_pch_macro_def_conflict)
618         << MacroName << Known->second.first << Existing.first;
619     }
620     return true;
621   }
622
623   // Check whether we're using predefines.
624   if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) {
625     if (Diags) {
626       Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
627     }
628     return true;
629   }
630
631   // Detailed record is important since it is used for the module cache hash.
632   if (LangOpts.Modules &&
633       PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) {
634     if (Diags) {
635       Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
636     }
637     return true;
638   }
639
640   // Compute the #include and #include_macros lines we need.
641   for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
642     StringRef File = ExistingPPOpts.Includes[I];
643     if (File == ExistingPPOpts.ImplicitPCHInclude)
644       continue;
645
646     if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
647           != PPOpts.Includes.end())
648       continue;
649
650     SuggestedPredefines += "#include \"";
651     SuggestedPredefines += File;
652     SuggestedPredefines += "\"\n";
653   }
654
655   for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
656     StringRef File = ExistingPPOpts.MacroIncludes[I];
657     if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
658                   File)
659         != PPOpts.MacroIncludes.end())
660       continue;
661
662     SuggestedPredefines += "#__include_macros \"";
663     SuggestedPredefines += File;
664     SuggestedPredefines += "\"\n##\n";
665   }
666
667   return false;
668 }
669
670 bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
671                                            bool Complain,
672                                            std::string &SuggestedPredefines) {
673   const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
674
675   return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
676                                   Complain? &Reader.Diags : nullptr,
677                                   PP.getFileManager(),
678                                   SuggestedPredefines,
679                                   PP.getLangOpts());
680 }
681
682 bool SimpleASTReaderListener::ReadPreprocessorOptions(
683                                   const PreprocessorOptions &PPOpts,
684                                   bool Complain,
685                                   std::string &SuggestedPredefines) {
686   return checkPreprocessorOptions(PPOpts,
687                                   PP.getPreprocessorOpts(),
688                                   nullptr,
689                                   PP.getFileManager(),
690                                   SuggestedPredefines,
691                                   PP.getLangOpts(),
692                                   false);
693 }
694
695 /// Check the header search options deserialized from the control block
696 /// against the header search options in an existing preprocessor.
697 ///
698 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
699 static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
700                                      StringRef SpecificModuleCachePath,
701                                      StringRef ExistingModuleCachePath,
702                                      DiagnosticsEngine *Diags,
703                                      const LangOptions &LangOpts) {
704   if (LangOpts.Modules) {
705     if (SpecificModuleCachePath != ExistingModuleCachePath) {
706       if (Diags)
707         Diags->Report(diag::err_pch_modulecache_mismatch)
708           << SpecificModuleCachePath << ExistingModuleCachePath;
709       return true;
710     }
711   }
712
713   return false;
714 }
715
716 bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
717                                            StringRef SpecificModuleCachePath,
718                                            bool Complain) {
719   return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
720                                   PP.getHeaderSearchInfo().getModuleCachePath(),
721                                   Complain ? &Reader.Diags : nullptr,
722                                   PP.getLangOpts());
723 }
724
725 void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
726   PP.setCounterValue(Value);
727 }
728
729 //===----------------------------------------------------------------------===//
730 // AST reader implementation
731 //===----------------------------------------------------------------------===//
732
733 void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
734                                            bool TakeOwnership) {
735   DeserializationListener = Listener;
736   OwnsDeserializationListener = TakeOwnership;
737 }
738
739 unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
740   return serialization::ComputeHash(Sel);
741 }
742
743 std::pair<unsigned, unsigned>
744 ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
745   using namespace llvm::support;
746   unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
747   unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
748   return std::make_pair(KeyLen, DataLen);
749 }
750
751 ASTSelectorLookupTrait::internal_key_type
752 ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
753   using namespace llvm::support;
754   SelectorTable &SelTable = Reader.getContext().Selectors;
755   unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
756   IdentifierInfo *FirstII = Reader.getLocalIdentifier(
757       F, endian::readNext<uint32_t, little, unaligned>(d));
758   if (N == 0)
759     return SelTable.getNullarySelector(FirstII);
760   else if (N == 1)
761     return SelTable.getUnarySelector(FirstII);
762
763   SmallVector<IdentifierInfo *, 16> Args;
764   Args.push_back(FirstII);
765   for (unsigned I = 1; I != N; ++I)
766     Args.push_back(Reader.getLocalIdentifier(
767         F, endian::readNext<uint32_t, little, unaligned>(d)));
768
769   return SelTable.getSelector(N, Args.data());
770 }
771
772 ASTSelectorLookupTrait::data_type
773 ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
774                                  unsigned DataLen) {
775   using namespace llvm::support;
776
777   data_type Result;
778
779   Result.ID = Reader.getGlobalSelectorID(
780       F, endian::readNext<uint32_t, little, unaligned>(d));
781   unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
782   unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
783   Result.InstanceBits = FullInstanceBits & 0x3;
784   Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
785   Result.FactoryBits = FullFactoryBits & 0x3;
786   Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
787   unsigned NumInstanceMethods = FullInstanceBits >> 3;
788   unsigned NumFactoryMethods = FullFactoryBits >> 3;
789
790   // Load instance methods
791   for (unsigned I = 0; I != NumInstanceMethods; ++I) {
792     if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
793             F, endian::readNext<uint32_t, little, unaligned>(d)))
794       Result.Instance.push_back(Method);
795   }
796
797   // Load factory methods
798   for (unsigned I = 0; I != NumFactoryMethods; ++I) {
799     if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
800             F, endian::readNext<uint32_t, little, unaligned>(d)))
801       Result.Factory.push_back(Method);
802   }
803
804   return Result;
805 }
806
807 unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
808   return llvm::HashString(a);
809 }
810
811 std::pair<unsigned, unsigned>
812 ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
813   using namespace llvm::support;
814   unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
815   unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
816   return std::make_pair(KeyLen, DataLen);
817 }
818
819 ASTIdentifierLookupTraitBase::internal_key_type
820 ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
821   assert(n >= 2 && d[n-1] == '\0');
822   return StringRef((const char*) d, n-1);
823 }
824
825 /// \brief Whether the given identifier is "interesting".
826 static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
827                                     bool IsModule) {
828   return II.hadMacroDefinition() ||
829          II.isPoisoned() ||
830          (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
831          II.hasRevertedTokenIDToIdentifier() ||
832          (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) &&
833           II.getFETokenInfo<void>());
834 }
835
836 static bool readBit(unsigned &Bits) {
837   bool Value = Bits & 0x1;
838   Bits >>= 1;
839   return Value;
840 }
841
842 IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
843   using namespace llvm::support;
844   unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
845   return Reader.getGlobalIdentifierID(F, RawID >> 1);
846 }
847
848 static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
849   if (!II.isFromAST()) {
850     II.setIsFromAST();
851     bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
852     if (isInterestingIdentifier(Reader, II, IsModule))
853       II.setChangedSinceDeserialization();
854   }
855 }
856
857 IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
858                                                    const unsigned char* d,
859                                                    unsigned DataLen) {
860   using namespace llvm::support;
861   unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
862   bool IsInteresting = RawID & 0x01;
863
864   // Wipe out the "is interesting" bit.
865   RawID = RawID >> 1;
866
867   // Build the IdentifierInfo and link the identifier ID with it.
868   IdentifierInfo *II = KnownII;
869   if (!II) {
870     II = &Reader.getIdentifierTable().getOwn(k);
871     KnownII = II;
872   }
873   markIdentifierFromAST(Reader, *II);
874   Reader.markIdentifierUpToDate(II);
875
876   IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
877   if (!IsInteresting) {
878     // For uninteresting identifiers, there's nothing else to do. Just notify
879     // the reader that we've finished loading this identifier.
880     Reader.SetIdentifierInfo(ID, II);
881     return II;
882   }
883
884   unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
885   unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
886   bool CPlusPlusOperatorKeyword = readBit(Bits);
887   bool HasRevertedTokenIDToIdentifier = readBit(Bits);
888   bool HasRevertedBuiltin = readBit(Bits);
889   bool Poisoned = readBit(Bits);
890   bool ExtensionToken = readBit(Bits);
891   bool HadMacroDefinition = readBit(Bits);
892
893   assert(Bits == 0 && "Extra bits in the identifier?");
894   DataLen -= 8;
895
896   // Set or check the various bits in the IdentifierInfo structure.
897   // Token IDs are read-only.
898   if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
899     II->revertTokenIDToIdentifier();
900   if (!F.isModule())
901     II->setObjCOrBuiltinID(ObjCOrBuiltinID);
902   else if (HasRevertedBuiltin && II->getBuiltinID()) {
903     II->revertBuiltin();
904     assert((II->hasRevertedBuiltin() ||
905             II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
906            "Incorrect ObjC keyword or builtin ID");
907   }
908   assert(II->isExtensionToken() == ExtensionToken &&
909          "Incorrect extension token flag");
910   (void)ExtensionToken;
911   if (Poisoned)
912     II->setIsPoisoned(true);
913   assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
914          "Incorrect C++ operator keyword flag");
915   (void)CPlusPlusOperatorKeyword;
916
917   // If this identifier is a macro, deserialize the macro
918   // definition.
919   if (HadMacroDefinition) {
920     uint32_t MacroDirectivesOffset =
921         endian::readNext<uint32_t, little, unaligned>(d);
922     DataLen -= 4;
923
924     Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
925   }
926
927   Reader.SetIdentifierInfo(ID, II);
928
929   // Read all of the declarations visible at global scope with this
930   // name.
931   if (DataLen > 0) {
932     SmallVector<uint32_t, 4> DeclIDs;
933     for (; DataLen > 0; DataLen -= 4)
934       DeclIDs.push_back(Reader.getGlobalDeclID(
935           F, endian::readNext<uint32_t, little, unaligned>(d)));
936     Reader.SetGloballyVisibleDecls(II, DeclIDs);
937   }
938
939   return II;
940 }
941
942 DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
943     : Kind(Name.getNameKind()) {
944   switch (Kind) {
945   case DeclarationName::Identifier:
946     Data = (uint64_t)Name.getAsIdentifierInfo();
947     break;
948   case DeclarationName::ObjCZeroArgSelector:
949   case DeclarationName::ObjCOneArgSelector:
950   case DeclarationName::ObjCMultiArgSelector:
951     Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
952     break;
953   case DeclarationName::CXXOperatorName:
954     Data = Name.getCXXOverloadedOperator();
955     break;
956   case DeclarationName::CXXLiteralOperatorName:
957     Data = (uint64_t)Name.getCXXLiteralIdentifier();
958     break;
959   case DeclarationName::CXXDeductionGuideName:
960     Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
961                ->getDeclName().getAsIdentifierInfo();
962     break;
963   case DeclarationName::CXXConstructorName:
964   case DeclarationName::CXXDestructorName:
965   case DeclarationName::CXXConversionFunctionName:
966   case DeclarationName::CXXUsingDirective:
967     Data = 0;
968     break;
969   }
970 }
971
972 unsigned DeclarationNameKey::getHash() const {
973   llvm::FoldingSetNodeID ID;
974   ID.AddInteger(Kind);
975
976   switch (Kind) {
977   case DeclarationName::Identifier:
978   case DeclarationName::CXXLiteralOperatorName:
979   case DeclarationName::CXXDeductionGuideName:
980     ID.AddString(((IdentifierInfo*)Data)->getName());
981     break;
982   case DeclarationName::ObjCZeroArgSelector:
983   case DeclarationName::ObjCOneArgSelector:
984   case DeclarationName::ObjCMultiArgSelector:
985     ID.AddInteger(serialization::ComputeHash(Selector(Data)));
986     break;
987   case DeclarationName::CXXOperatorName:
988     ID.AddInteger((OverloadedOperatorKind)Data);
989     break;
990   case DeclarationName::CXXConstructorName:
991   case DeclarationName::CXXDestructorName:
992   case DeclarationName::CXXConversionFunctionName:
993   case DeclarationName::CXXUsingDirective:
994     break;
995   }
996
997   return ID.ComputeHash();
998 }
999
1000 ModuleFile *
1001 ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
1002   using namespace llvm::support;
1003   uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
1004   return Reader.getLocalModuleFile(F, ModuleFileID);
1005 }
1006
1007 std::pair<unsigned, unsigned>
1008 ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
1009   using namespace llvm::support;
1010   unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
1011   unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
1012   return std::make_pair(KeyLen, DataLen);
1013 }
1014
1015 ASTDeclContextNameLookupTrait::internal_key_type
1016 ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
1017   using namespace llvm::support;
1018
1019   auto Kind = (DeclarationName::NameKind)*d++;
1020   uint64_t Data;
1021   switch (Kind) {
1022   case DeclarationName::Identifier:
1023   case DeclarationName::CXXLiteralOperatorName:
1024   case DeclarationName::CXXDeductionGuideName:
1025     Data = (uint64_t)Reader.getLocalIdentifier(
1026         F, endian::readNext<uint32_t, little, unaligned>(d));
1027     break;
1028   case DeclarationName::ObjCZeroArgSelector:
1029   case DeclarationName::ObjCOneArgSelector:
1030   case DeclarationName::ObjCMultiArgSelector:
1031     Data =
1032         (uint64_t)Reader.getLocalSelector(
1033                              F, endian::readNext<uint32_t, little, unaligned>(
1034                                     d)).getAsOpaquePtr();
1035     break;
1036   case DeclarationName::CXXOperatorName:
1037     Data = *d++; // OverloadedOperatorKind
1038     break;
1039   case DeclarationName::CXXConstructorName:
1040   case DeclarationName::CXXDestructorName:
1041   case DeclarationName::CXXConversionFunctionName:
1042   case DeclarationName::CXXUsingDirective:
1043     Data = 0;
1044     break;
1045   }
1046
1047   return DeclarationNameKey(Kind, Data);
1048 }
1049
1050 void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1051                                                  const unsigned char *d,
1052                                                  unsigned DataLen,
1053                                                  data_type_builder &Val) {
1054   using namespace llvm::support;
1055   for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1056     uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1057     Val.insert(Reader.getGlobalDeclID(F, LocalID));
1058   }
1059 }
1060
1061 bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1062                                               BitstreamCursor &Cursor,
1063                                               uint64_t Offset,
1064                                               DeclContext *DC) {
1065   assert(Offset != 0);
1066
1067   SavedStreamPosition SavedPosition(Cursor);
1068   Cursor.JumpToBit(Offset);
1069
1070   RecordData Record;
1071   StringRef Blob;
1072   unsigned Code = Cursor.ReadCode();
1073   unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1074   if (RecCode != DECL_CONTEXT_LEXICAL) {
1075     Error("Expected lexical block");
1076     return true;
1077   }
1078
1079   assert(!isa<TranslationUnitDecl>(DC) &&
1080          "expected a TU_UPDATE_LEXICAL record for TU");
1081   // If we are handling a C++ class template instantiation, we can see multiple
1082   // lexical updates for the same record. It's important that we select only one
1083   // of them, so that field numbering works properly. Just pick the first one we
1084   // see.
1085   auto &Lex = LexicalDecls[DC];
1086   if (!Lex.first) {
1087     Lex = std::make_pair(
1088         &M, llvm::makeArrayRef(
1089                 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1090                     Blob.data()),
1091                 Blob.size() / 4));
1092   }
1093   DC->setHasExternalLexicalStorage(true);
1094   return false;
1095 }
1096
1097 bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1098                                               BitstreamCursor &Cursor,
1099                                               uint64_t Offset,
1100                                               DeclID ID) {
1101   assert(Offset != 0);
1102
1103   SavedStreamPosition SavedPosition(Cursor);
1104   Cursor.JumpToBit(Offset);
1105
1106   RecordData Record;
1107   StringRef Blob;
1108   unsigned Code = Cursor.ReadCode();
1109   unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1110   if (RecCode != DECL_CONTEXT_VISIBLE) {
1111     Error("Expected visible lookup table block");
1112     return true;
1113   }
1114
1115   // We can't safely determine the primary context yet, so delay attaching the
1116   // lookup table until we're done with recursive deserialization.
1117   auto *Data = (const unsigned char*)Blob.data();
1118   PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
1119   return false;
1120 }
1121
1122 void ASTReader::Error(StringRef Msg) const {
1123   Error(diag::err_fe_pch_malformed, Msg);
1124   if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1125       !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
1126     Diag(diag::note_module_cache_path)
1127       << PP.getHeaderSearchInfo().getModuleCachePath();
1128   }
1129 }
1130
1131 void ASTReader::Error(unsigned DiagID,
1132                       StringRef Arg1, StringRef Arg2) const {
1133   if (Diags.isDiagnosticInFlight())
1134     Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1135   else
1136     Diag(DiagID) << Arg1 << Arg2;
1137 }
1138
1139 //===----------------------------------------------------------------------===//
1140 // Source Manager Deserialization
1141 //===----------------------------------------------------------------------===//
1142
1143 /// \brief Read the line table in the source manager block.
1144 /// \returns true if there was an error.
1145 bool ASTReader::ParseLineTable(ModuleFile &F,
1146                                const RecordData &Record) {
1147   unsigned Idx = 0;
1148   LineTableInfo &LineTable = SourceMgr.getLineTable();
1149
1150   // Parse the file names
1151   std::map<int, int> FileIDs;
1152   for (unsigned I = 0; Record[Idx]; ++I) {
1153     // Extract the file name
1154     auto Filename = ReadPath(F, Record, Idx);
1155     FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1156   }
1157   ++Idx;
1158
1159   // Parse the line entries
1160   std::vector<LineEntry> Entries;
1161   while (Idx < Record.size()) {
1162     int FID = Record[Idx++];
1163     assert(FID >= 0 && "Serialized line entries for non-local file.");
1164     // Remap FileID from 1-based old view.
1165     FID += F.SLocEntryBaseID - 1;
1166
1167     // Extract the line entries
1168     unsigned NumEntries = Record[Idx++];
1169     assert(NumEntries && "no line entries for file ID");
1170     Entries.clear();
1171     Entries.reserve(NumEntries);
1172     for (unsigned I = 0; I != NumEntries; ++I) {
1173       unsigned FileOffset = Record[Idx++];
1174       unsigned LineNo = Record[Idx++];
1175       int FilenameID = FileIDs[Record[Idx++]];
1176       SrcMgr::CharacteristicKind FileKind
1177         = (SrcMgr::CharacteristicKind)Record[Idx++];
1178       unsigned IncludeOffset = Record[Idx++];
1179       Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1180                                        FileKind, IncludeOffset));
1181     }
1182     LineTable.AddEntry(FileID::get(FID), Entries);
1183   }
1184
1185   return false;
1186 }
1187
1188 /// \brief Read a source manager block
1189 bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1190   using namespace SrcMgr;
1191
1192   BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1193
1194   // Set the source-location entry cursor to the current position in
1195   // the stream. This cursor will be used to read the contents of the
1196   // source manager block initially, and then lazily read
1197   // source-location entries as needed.
1198   SLocEntryCursor = F.Stream;
1199
1200   // The stream itself is going to skip over the source manager block.
1201   if (F.Stream.SkipBlock()) {
1202     Error("malformed block record in AST file");
1203     return true;
1204   }
1205
1206   // Enter the source manager block.
1207   if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1208     Error("malformed source manager block record in AST file");
1209     return true;
1210   }
1211
1212   RecordData Record;
1213   while (true) {
1214     llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
1215
1216     switch (E.Kind) {
1217     case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1218     case llvm::BitstreamEntry::Error:
1219       Error("malformed block record in AST file");
1220       return true;
1221     case llvm::BitstreamEntry::EndBlock:
1222       return false;
1223     case llvm::BitstreamEntry::Record:
1224       // The interesting case.
1225       break;
1226     }
1227
1228     // Read a record.
1229     Record.clear();
1230     StringRef Blob;
1231     switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
1232     default:  // Default behavior: ignore.
1233       break;
1234
1235     case SM_SLOC_FILE_ENTRY:
1236     case SM_SLOC_BUFFER_ENTRY:
1237     case SM_SLOC_EXPANSION_ENTRY:
1238       // Once we hit one of the source location entries, we're done.
1239       return false;
1240     }
1241   }
1242 }
1243
1244 /// \brief If a header file is not found at the path that we expect it to be
1245 /// and the PCH file was moved from its original location, try to resolve the
1246 /// file by assuming that header+PCH were moved together and the header is in
1247 /// the same place relative to the PCH.
1248 static std::string
1249 resolveFileRelativeToOriginalDir(const std::string &Filename,
1250                                  const std::string &OriginalDir,
1251                                  const std::string &CurrDir) {
1252   assert(OriginalDir != CurrDir &&
1253          "No point trying to resolve the file if the PCH dir didn't change");
1254   using namespace llvm::sys;
1255   SmallString<128> filePath(Filename);
1256   fs::make_absolute(filePath);
1257   assert(path::is_absolute(OriginalDir));
1258   SmallString<128> currPCHPath(CurrDir);
1259
1260   path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1261                        fileDirE = path::end(path::parent_path(filePath));
1262   path::const_iterator origDirI = path::begin(OriginalDir),
1263                        origDirE = path::end(OriginalDir);
1264   // Skip the common path components from filePath and OriginalDir.
1265   while (fileDirI != fileDirE && origDirI != origDirE &&
1266          *fileDirI == *origDirI) {
1267     ++fileDirI;
1268     ++origDirI;
1269   }
1270   for (; origDirI != origDirE; ++origDirI)
1271     path::append(currPCHPath, "..");
1272   path::append(currPCHPath, fileDirI, fileDirE);
1273   path::append(currPCHPath, path::filename(Filename));
1274   return currPCHPath.str();
1275 }
1276
1277 bool ASTReader::ReadSLocEntry(int ID) {
1278   if (ID == 0)
1279     return false;
1280
1281   if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1282     Error("source location entry ID out-of-range for AST file");
1283     return true;
1284   }
1285
1286   // Local helper to read the (possibly-compressed) buffer data following the
1287   // entry record.
1288   auto ReadBuffer = [this](
1289       BitstreamCursor &SLocEntryCursor,
1290       StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1291     RecordData Record;
1292     StringRef Blob;
1293     unsigned Code = SLocEntryCursor.ReadCode();
1294     unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1295
1296     if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1297       if (!llvm::zlib::isAvailable()) {
1298         Error("zlib is not available");
1299         return nullptr;
1300       }
1301       SmallString<0> Uncompressed;
1302       if (llvm::Error E =
1303               llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
1304         Error("could not decompress embedded file contents: " +
1305               llvm::toString(std::move(E)));
1306         return nullptr;
1307       }
1308       return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1309     } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1310       return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1311     } else {
1312       Error("AST record has invalid code");
1313       return nullptr;
1314     }
1315   };
1316
1317   ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1318   F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
1319   BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1320   unsigned BaseOffset = F->SLocEntryBaseOffset;
1321
1322   ++NumSLocEntriesRead;
1323   llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1324   if (Entry.Kind != llvm::BitstreamEntry::Record) {
1325     Error("incorrectly-formatted source location entry in AST file");
1326     return true;
1327   }
1328
1329   RecordData Record;
1330   StringRef Blob;
1331   switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
1332   default:
1333     Error("incorrectly-formatted source location entry in AST file");
1334     return true;
1335
1336   case SM_SLOC_FILE_ENTRY: {
1337     // We will detect whether a file changed and return 'Failure' for it, but
1338     // we will also try to fail gracefully by setting up the SLocEntry.
1339     unsigned InputID = Record[4];
1340     InputFile IF = getInputFile(*F, InputID);
1341     const FileEntry *File = IF.getFile();
1342     bool OverriddenBuffer = IF.isOverridden();
1343
1344     // Note that we only check if a File was returned. If it was out-of-date
1345     // we have complained but we will continue creating a FileID to recover
1346     // gracefully.
1347     if (!File)
1348       return true;
1349
1350     SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1351     if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1352       // This is the module's main file.
1353       IncludeLoc = getImportLocation(F);
1354     }
1355     SrcMgr::CharacteristicKind
1356       FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1357     FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1358                                         ID, BaseOffset + Record[0]);
1359     SrcMgr::FileInfo &FileInfo =
1360           const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1361     FileInfo.NumCreatedFIDs = Record[5];
1362     if (Record[3])
1363       FileInfo.setHasLineDirectives();
1364
1365     const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1366     unsigned NumFileDecls = Record[7];
1367     if (NumFileDecls) {
1368       assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1369       FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1370                                                              NumFileDecls));
1371     }
1372
1373     const SrcMgr::ContentCache *ContentCache
1374       = SourceMgr.getOrCreateContentCache(File,
1375                               /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1376     if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1377         ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1378         !ContentCache->getRawBuffer()) {
1379       auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1380       if (!Buffer)
1381         return true;
1382       SourceMgr.overrideFileContents(File, std::move(Buffer));
1383     }
1384
1385     break;
1386   }
1387
1388   case SM_SLOC_BUFFER_ENTRY: {
1389     const char *Name = Blob.data();
1390     unsigned Offset = Record[0];
1391     SrcMgr::CharacteristicKind
1392       FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1393     SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1394     if (IncludeLoc.isInvalid() && F->isModule()) {
1395       IncludeLoc = getImportLocation(F);
1396     }
1397
1398     auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1399     if (!Buffer)
1400       return true;
1401     SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
1402                            BaseOffset + Offset, IncludeLoc);
1403     break;
1404   }
1405
1406   case SM_SLOC_EXPANSION_ENTRY: {
1407     SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1408     SourceMgr.createExpansionLoc(SpellingLoc,
1409                                      ReadSourceLocation(*F, Record[2]),
1410                                      ReadSourceLocation(*F, Record[3]),
1411                                      Record[4],
1412                                      ID,
1413                                      BaseOffset + Record[0]);
1414     break;
1415   }
1416   }
1417
1418   return false;
1419 }
1420
1421 std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1422   if (ID == 0)
1423     return std::make_pair(SourceLocation(), "");
1424
1425   if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1426     Error("source location entry ID out-of-range for AST file");
1427     return std::make_pair(SourceLocation(), "");
1428   }
1429
1430   // Find which module file this entry lands in.
1431   ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1432   if (!M->isModule())
1433     return std::make_pair(SourceLocation(), "");
1434
1435   // FIXME: Can we map this down to a particular submodule? That would be
1436   // ideal.
1437   return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
1438 }
1439
1440 /// \brief Find the location where the module F is imported.
1441 SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1442   if (F->ImportLoc.isValid())
1443     return F->ImportLoc;
1444
1445   // Otherwise we have a PCH. It's considered to be "imported" at the first
1446   // location of its includer.
1447   if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1448     // Main file is the importer.
1449     assert(SourceMgr.getMainFileID().isValid() && "missing main file");
1450     return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
1451   }
1452   return F->ImportedBy[0]->FirstLoc;
1453 }
1454
1455 /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1456 /// specified cursor.  Read the abbreviations that are at the top of the block
1457 /// and then leave the cursor pointing into the block.
1458 bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
1459   if (Cursor.EnterSubBlock(BlockID))
1460     return true;
1461
1462   while (true) {
1463     uint64_t Offset = Cursor.GetCurrentBitNo();
1464     unsigned Code = Cursor.ReadCode();
1465
1466     // We expect all abbrevs to be at the start of the block.
1467     if (Code != llvm::bitc::DEFINE_ABBREV) {
1468       Cursor.JumpToBit(Offset);
1469       return false;
1470     }
1471     Cursor.ReadAbbrevRecord();
1472   }
1473 }
1474
1475 Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
1476                            unsigned &Idx) {
1477   Token Tok;
1478   Tok.startToken();
1479   Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1480   Tok.setLength(Record[Idx++]);
1481   if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1482     Tok.setIdentifierInfo(II);
1483   Tok.setKind((tok::TokenKind)Record[Idx++]);
1484   Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1485   return Tok;
1486 }
1487
1488 MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
1489   BitstreamCursor &Stream = F.MacroCursor;
1490
1491   // Keep track of where we are in the stream, then jump back there
1492   // after reading this macro.
1493   SavedStreamPosition SavedPosition(Stream);
1494
1495   Stream.JumpToBit(Offset);
1496   RecordData Record;
1497   SmallVector<IdentifierInfo*, 16> MacroArgs;
1498   MacroInfo *Macro = nullptr;
1499
1500   while (true) {
1501     // Advance to the next record, but if we get to the end of the block, don't
1502     // pop it (removing all the abbreviations from the cursor) since we want to
1503     // be able to reseek within the block and read entries.
1504     unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
1505     llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1506
1507     switch (Entry.Kind) {
1508     case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1509     case llvm::BitstreamEntry::Error:
1510       Error("malformed block record in AST file");
1511       return Macro;
1512     case llvm::BitstreamEntry::EndBlock:
1513       return Macro;
1514     case llvm::BitstreamEntry::Record:
1515       // The interesting case.
1516       break;
1517     }
1518
1519     // Read a record.
1520     Record.clear();
1521     PreprocessorRecordTypes RecType =
1522       (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
1523     switch (RecType) {
1524     case PP_MODULE_MACRO:
1525     case PP_MACRO_DIRECTIVE_HISTORY:
1526       return Macro;
1527
1528     case PP_MACRO_OBJECT_LIKE:
1529     case PP_MACRO_FUNCTION_LIKE: {
1530       // If we already have a macro, that means that we've hit the end
1531       // of the definition of the macro we were looking for. We're
1532       // done.
1533       if (Macro)
1534         return Macro;
1535
1536       unsigned NextIndex = 1; // Skip identifier ID.
1537       SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
1538       MacroInfo *MI = PP.AllocateMacroInfo(Loc);
1539       MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
1540       MI->setIsUsed(Record[NextIndex++]);
1541       MI->setUsedForHeaderGuard(Record[NextIndex++]);
1542
1543       if (RecType == PP_MACRO_FUNCTION_LIKE) {
1544         // Decode function-like macro info.
1545         bool isC99VarArgs = Record[NextIndex++];
1546         bool isGNUVarArgs = Record[NextIndex++];
1547         bool hasCommaPasting = Record[NextIndex++];
1548         MacroArgs.clear();
1549         unsigned NumArgs = Record[NextIndex++];
1550         for (unsigned i = 0; i != NumArgs; ++i)
1551           MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1552
1553         // Install function-like macro info.
1554         MI->setIsFunctionLike();
1555         if (isC99VarArgs) MI->setIsC99Varargs();
1556         if (isGNUVarArgs) MI->setIsGNUVarargs();
1557         if (hasCommaPasting) MI->setHasCommaPasting();
1558         MI->setArgumentList(MacroArgs, PP.getPreprocessorAllocator());
1559       }
1560
1561       // Remember that we saw this macro last so that we add the tokens that
1562       // form its body to it.
1563       Macro = MI;
1564
1565       if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1566           Record[NextIndex]) {
1567         // We have a macro definition. Register the association
1568         PreprocessedEntityID
1569             GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1570         PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
1571         PreprocessingRecord::PPEntityID PPID =
1572             PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1573         MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1574             PPRec.getPreprocessedEntity(PPID));
1575         if (PPDef)
1576           PPRec.RegisterMacroDefinition(Macro, PPDef);
1577       }
1578
1579       ++NumMacrosRead;
1580       break;
1581     }
1582
1583     case PP_TOKEN: {
1584       // If we see a TOKEN before a PP_MACRO_*, then the file is
1585       // erroneous, just pretend we didn't see this.
1586       if (!Macro) break;
1587
1588       unsigned Idx = 0;
1589       Token Tok = ReadToken(F, Record, Idx);
1590       Macro->AddTokenToBody(Tok);
1591       break;
1592     }
1593     }
1594   }
1595 }
1596
1597 PreprocessedEntityID
1598 ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
1599                                          unsigned LocalID) const {
1600   if (!M.ModuleOffsetMap.empty())
1601     ReadModuleOffsetMap(M);
1602
1603   ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1604     I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1605   assert(I != M.PreprocessedEntityRemap.end()
1606          && "Invalid index into preprocessed entity index remap");
1607
1608   return LocalID + I->second;
1609 }
1610
1611 unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1612   return llvm::hash_combine(ikey.Size, ikey.ModTime);
1613 }
1614
1615 HeaderFileInfoTrait::internal_key_type
1616 HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1617   internal_key_type ikey = {FE->getSize(),
1618                             M.HasTimestamps ? FE->getModificationTime() : 0,
1619                             FE->getName(), /*Imported*/ false};
1620   return ikey;
1621 }
1622
1623 bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1624   if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
1625     return false;
1626
1627   if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
1628     return true;
1629
1630   // Determine whether the actual files are equivalent.
1631   FileManager &FileMgr = Reader.getFileManager();
1632   auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1633     if (!Key.Imported)
1634       return FileMgr.getFile(Key.Filename);
1635
1636     std::string Resolved = Key.Filename;
1637     Reader.ResolveImportedPath(M, Resolved);
1638     return FileMgr.getFile(Resolved);
1639   };
1640
1641   const FileEntry *FEA = GetFile(a);
1642   const FileEntry *FEB = GetFile(b);
1643   return FEA && FEA == FEB;
1644 }
1645
1646 std::pair<unsigned, unsigned>
1647 HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1648   using namespace llvm::support;
1649   unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
1650   unsigned DataLen = (unsigned) *d++;
1651   return std::make_pair(KeyLen, DataLen);
1652 }
1653
1654 HeaderFileInfoTrait::internal_key_type
1655 HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
1656   using namespace llvm::support;
1657   internal_key_type ikey;
1658   ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1659   ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
1660   ikey.Filename = (const char *)d;
1661   ikey.Imported = true;
1662   return ikey;
1663 }
1664
1665 HeaderFileInfoTrait::data_type
1666 HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
1667                               unsigned DataLen) {
1668   const unsigned char *End = d + DataLen;
1669   using namespace llvm::support;
1670   HeaderFileInfo HFI;
1671   unsigned Flags = *d++;
1672   // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1673   HFI.isImport |= (Flags >> 4) & 0x01;
1674   HFI.isPragmaOnce |= (Flags >> 3) & 0x01;
1675   HFI.DirInfo = (Flags >> 1) & 0x03;
1676   HFI.IndexHeaderMapHeader = Flags & 0x01;
1677   // FIXME: Find a better way to handle this. Maybe just store a
1678   // "has been included" flag?
1679   HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1680                              HFI.NumIncludes);
1681   HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1682       M, endian::readNext<uint32_t, little, unaligned>(d));
1683   if (unsigned FrameworkOffset =
1684           endian::readNext<uint32_t, little, unaligned>(d)) {
1685     // The framework offset is 1 greater than the actual offset,
1686     // since 0 is used as an indicator for "no framework name".
1687     StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1688     HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1689   }
1690
1691   assert((End - d) % 4 == 0 &&
1692          "Wrong data length in HeaderFileInfo deserialization");
1693   while (d != End) {
1694     uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
1695     auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1696     LocalSMID >>= 2;
1697
1698     // This header is part of a module. Associate it with the module to enable
1699     // implicit module import.
1700     SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1701     Module *Mod = Reader.getSubmodule(GlobalSMID);
1702     FileManager &FileMgr = Reader.getFileManager();
1703     ModuleMap &ModMap =
1704         Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1705
1706     std::string Filename = key.Filename;
1707     if (key.Imported)
1708       Reader.ResolveImportedPath(M, Filename);
1709     // FIXME: This is not always the right filename-as-written, but we're not
1710     // going to use this information to rebuild the module, so it doesn't make
1711     // a lot of difference.
1712     Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
1713     ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1714     HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
1715   }
1716
1717   // This HeaderFileInfo was externally loaded.
1718   HFI.External = true;
1719   HFI.IsValid = true;
1720   return HFI;
1721 }
1722
1723 void ASTReader::addPendingMacro(IdentifierInfo *II,
1724                                 ModuleFile *M,
1725                                 uint64_t MacroDirectivesOffset) {
1726   assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1727   PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
1728 }
1729
1730 void ASTReader::ReadDefinedMacros() {
1731   // Note that we are loading defined macros.
1732   Deserializing Macros(this);
1733
1734   for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
1735     BitstreamCursor &MacroCursor = I.MacroCursor;
1736
1737     // If there was no preprocessor block, skip this file.
1738     if (MacroCursor.getBitcodeBytes().empty())
1739       continue;
1740
1741     BitstreamCursor Cursor = MacroCursor;
1742     Cursor.JumpToBit(I.MacroStartOffset);
1743
1744     RecordData Record;
1745     while (true) {
1746       llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1747
1748       switch (E.Kind) {
1749       case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1750       case llvm::BitstreamEntry::Error:
1751         Error("malformed block record in AST file");
1752         return;
1753       case llvm::BitstreamEntry::EndBlock:
1754         goto NextCursor;
1755
1756       case llvm::BitstreamEntry::Record:
1757         Record.clear();
1758         switch (Cursor.readRecord(E.ID, Record)) {
1759         default:  // Default behavior: ignore.
1760           break;
1761
1762         case PP_MACRO_OBJECT_LIKE:
1763         case PP_MACRO_FUNCTION_LIKE: {
1764           IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
1765           if (II->isOutOfDate())
1766             updateOutOfDateIdentifier(*II);
1767           break;
1768         }
1769
1770         case PP_TOKEN:
1771           // Ignore tokens.
1772           break;
1773         }
1774         break;
1775       }
1776     }
1777     NextCursor:  ;
1778   }
1779 }
1780
1781 namespace {
1782
1783   /// \brief Visitor class used to look up identifirs in an AST file.
1784   class IdentifierLookupVisitor {
1785     StringRef Name;
1786     unsigned NameHash;
1787     unsigned PriorGeneration;
1788     unsigned &NumIdentifierLookups;
1789     unsigned &NumIdentifierLookupHits;
1790     IdentifierInfo *Found;
1791
1792   public:
1793     IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1794                             unsigned &NumIdentifierLookups,
1795                             unsigned &NumIdentifierLookupHits)
1796       : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1797         PriorGeneration(PriorGeneration),
1798         NumIdentifierLookups(NumIdentifierLookups),
1799         NumIdentifierLookupHits(NumIdentifierLookupHits),
1800         Found()
1801     {
1802     }
1803
1804     bool operator()(ModuleFile &M) {
1805       // If we've already searched this module file, skip it now.
1806       if (M.Generation <= PriorGeneration)
1807         return true;
1808
1809       ASTIdentifierLookupTable *IdTable
1810         = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1811       if (!IdTable)
1812         return false;
1813
1814       ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
1815                                      Found);
1816       ++NumIdentifierLookups;
1817       ASTIdentifierLookupTable::iterator Pos =
1818           IdTable->find_hashed(Name, NameHash, &Trait);
1819       if (Pos == IdTable->end())
1820         return false;
1821
1822       // Dereferencing the iterator has the effect of building the
1823       // IdentifierInfo node and populating it with the various
1824       // declarations it needs.
1825       ++NumIdentifierLookupHits;
1826       Found = *Pos;
1827       return true;
1828     }
1829
1830     // \brief Retrieve the identifier info found within the module
1831     // files.
1832     IdentifierInfo *getIdentifierInfo() const { return Found; }
1833   };
1834
1835 } // end anonymous namespace
1836
1837 void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1838   // Note that we are loading an identifier.
1839   Deserializing AnIdentifier(this);
1840
1841   unsigned PriorGeneration = 0;
1842   if (getContext().getLangOpts().Modules)
1843     PriorGeneration = IdentifierGeneration[&II];
1844
1845   // If there is a global index, look there first to determine which modules
1846   // provably do not have any results for this identifier.
1847   GlobalModuleIndex::HitSet Hits;
1848   GlobalModuleIndex::HitSet *HitsPtr = nullptr;
1849   if (!loadGlobalIndex()) {
1850     if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1851       HitsPtr = &Hits;
1852     }
1853   }
1854
1855   IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
1856                                   NumIdentifierLookups,
1857                                   NumIdentifierLookupHits);
1858   ModuleMgr.visit(Visitor, HitsPtr);
1859   markIdentifierUpToDate(&II);
1860 }
1861
1862 void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1863   if (!II)
1864     return;
1865
1866   II->setOutOfDate(false);
1867
1868   // Update the generation for this identifier.
1869   if (getContext().getLangOpts().Modules)
1870     IdentifierGeneration[II] = getGeneration();
1871 }
1872
1873 void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1874                                     const PendingMacroInfo &PMInfo) {
1875   ModuleFile &M = *PMInfo.M;
1876
1877   BitstreamCursor &Cursor = M.MacroCursor;
1878   SavedStreamPosition SavedPosition(Cursor);
1879   Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
1880
1881   struct ModuleMacroRecord {
1882     SubmoduleID SubModID;
1883     MacroInfo *MI;
1884     SmallVector<SubmoduleID, 8> Overrides;
1885   };
1886   llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
1887
1888   // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1889   // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1890   // macro histroy.
1891   RecordData Record;
1892   while (true) {
1893     llvm::BitstreamEntry Entry =
1894         Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1895     if (Entry.Kind != llvm::BitstreamEntry::Record) {
1896       Error("malformed block record in AST file");
1897       return;
1898     }
1899
1900     Record.clear();
1901     switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
1902     case PP_MACRO_DIRECTIVE_HISTORY:
1903       break;
1904
1905     case PP_MODULE_MACRO: {
1906       ModuleMacros.push_back(ModuleMacroRecord());
1907       auto &Info = ModuleMacros.back();
1908       Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1909       Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
1910       for (int I = 2, N = Record.size(); I != N; ++I)
1911         Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
1912       continue;
1913     }
1914
1915     default:
1916       Error("malformed block record in AST file");
1917       return;
1918     }
1919
1920     // We found the macro directive history; that's the last record
1921     // for this macro.
1922     break;
1923   }
1924
1925   // Module macros are listed in reverse dependency order.
1926   {
1927     std::reverse(ModuleMacros.begin(), ModuleMacros.end());
1928     llvm::SmallVector<ModuleMacro*, 8> Overrides;
1929     for (auto &MMR : ModuleMacros) {
1930       Overrides.clear();
1931       for (unsigned ModID : MMR.Overrides) {
1932         Module *Mod = getSubmodule(ModID);
1933         auto *Macro = PP.getModuleMacro(Mod, II);
1934         assert(Macro && "missing definition for overridden macro");
1935         Overrides.push_back(Macro);
1936       }
1937
1938       bool Inserted = false;
1939       Module *Owner = getSubmodule(MMR.SubModID);
1940       PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
1941     }
1942   }
1943
1944   // Don't read the directive history for a module; we don't have anywhere
1945   // to put it.
1946   if (M.isModule())
1947     return;
1948
1949   // Deserialize the macro directives history in reverse source-order.
1950   MacroDirective *Latest = nullptr, *Earliest = nullptr;
1951   unsigned Idx = 0, N = Record.size();
1952   while (Idx < N) {
1953     MacroDirective *MD = nullptr;
1954     SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
1955     MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1956     switch (K) {
1957     case MacroDirective::MD_Define: {
1958       MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
1959       MD = PP.AllocateDefMacroDirective(MI, Loc);
1960       break;
1961     }
1962     case MacroDirective::MD_Undefine: {
1963       MD = PP.AllocateUndefMacroDirective(Loc);
1964       break;
1965     }
1966     case MacroDirective::MD_Visibility:
1967       bool isPublic = Record[Idx++];
1968       MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1969       break;
1970     }
1971
1972     if (!Latest)
1973       Latest = MD;
1974     if (Earliest)
1975       Earliest->setPrevious(MD);
1976     Earliest = MD;
1977   }
1978
1979   if (Latest)
1980     PP.setLoadedMacroDirective(II, Earliest, Latest);
1981 }
1982
1983 ASTReader::InputFileInfo
1984 ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
1985   // Go find this input file.
1986   BitstreamCursor &Cursor = F.InputFilesCursor;
1987   SavedStreamPosition SavedPosition(Cursor);
1988   Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1989
1990   unsigned Code = Cursor.ReadCode();
1991   RecordData Record;
1992   StringRef Blob;
1993
1994   unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1995   assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1996          "invalid record type for input file");
1997   (void)Result;
1998
1999   assert(Record[0] == ID && "Bogus stored ID or offset");
2000   InputFileInfo R;
2001   R.StoredSize = static_cast<off_t>(Record[1]);
2002   R.StoredTime = static_cast<time_t>(Record[2]);
2003   R.Overridden = static_cast<bool>(Record[3]);
2004   R.Transient = static_cast<bool>(Record[4]);
2005   R.Filename = Blob;
2006   ResolveImportedPath(F, R.Filename);
2007   return R;
2008 }
2009
2010 static unsigned moduleKindForDiagnostic(ModuleKind Kind);
2011 InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
2012   // If this ID is bogus, just return an empty input file.
2013   if (ID == 0 || ID > F.InputFilesLoaded.size())
2014     return InputFile();
2015
2016   // If we've already loaded this input file, return it.
2017   if (F.InputFilesLoaded[ID-1].getFile())
2018     return F.InputFilesLoaded[ID-1];
2019
2020   if (F.InputFilesLoaded[ID-1].isNotFound())
2021     return InputFile();
2022
2023   // Go find this input file.
2024   BitstreamCursor &Cursor = F.InputFilesCursor;
2025   SavedStreamPosition SavedPosition(Cursor);
2026   Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2027
2028   InputFileInfo FI = readInputFileInfo(F, ID);
2029   off_t StoredSize = FI.StoredSize;
2030   time_t StoredTime = FI.StoredTime;
2031   bool Overridden = FI.Overridden;
2032   bool Transient = FI.Transient;
2033   StringRef Filename = FI.Filename;
2034
2035   const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
2036
2037   // If we didn't find the file, resolve it relative to the
2038   // original directory from which this AST file was created.
2039   if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
2040       F.OriginalDir != CurrentDir) {
2041     std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2042                                                             F.OriginalDir,
2043                                                             CurrentDir);
2044     if (!Resolved.empty())
2045       File = FileMgr.getFile(Resolved);
2046   }
2047
2048   // For an overridden file, create a virtual file with the stored
2049   // size/timestamp.
2050   if ((Overridden || Transient) && File == nullptr)
2051     File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
2052
2053   if (File == nullptr) {
2054     if (Complain) {
2055       std::string ErrorStr = "could not find file '";
2056       ErrorStr += Filename;
2057       ErrorStr += "' referenced by AST file '";
2058       ErrorStr += F.FileName;
2059       ErrorStr += "'";
2060       Error(ErrorStr);
2061     }
2062     // Record that we didn't find the file.
2063     F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2064     return InputFile();
2065   }
2066
2067   // Check if there was a request to override the contents of the file
2068   // that was part of the precompiled header. Overridding such a file
2069   // can lead to problems when lexing using the source locations from the
2070   // PCH.
2071   SourceManager &SM = getSourceManager();
2072   // FIXME: Reject if the overrides are different.
2073   if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
2074     if (Complain)
2075       Error(diag::err_fe_pch_file_overridden, Filename);
2076     // After emitting the diagnostic, recover by disabling the override so
2077     // that the original file will be used.
2078     //
2079     // FIXME: This recovery is just as broken as the original state; there may
2080     // be another precompiled module that's using the overridden contents, or
2081     // we might be half way through parsing it. Instead, we should treat the
2082     // overridden contents as belonging to a separate FileEntry.
2083     SM.disableFileContentsOverride(File);
2084     // The FileEntry is a virtual file entry with the size of the contents
2085     // that would override the original contents. Set it to the original's
2086     // size/time.
2087     FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2088                             StoredSize, StoredTime);
2089   }
2090
2091   bool IsOutOfDate = false;
2092
2093   // For an overridden file, there is nothing to validate.
2094   if (!Overridden && //
2095       (StoredSize != File->getSize() ||
2096        (StoredTime && StoredTime != File->getModificationTime() &&
2097         !DisableValidation)
2098        )) {
2099     if (Complain) {
2100       // Build a list of the PCH imports that got us here (in reverse).
2101       SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2102       while (ImportStack.back()->ImportedBy.size() > 0)
2103         ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
2104
2105       // The top-level PCH is stale.
2106       StringRef TopLevelPCHName(ImportStack.back()->FileName);
2107       unsigned DiagnosticKind = moduleKindForDiagnostic(ImportStack.back()->Kind);
2108       if (DiagnosticKind == 0)
2109         Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
2110       else if (DiagnosticKind == 1)
2111         Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName);
2112       else
2113         Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName);
2114
2115       // Print the import stack.
2116       if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2117         Diag(diag::note_pch_required_by)
2118           << Filename << ImportStack[0]->FileName;
2119         for (unsigned I = 1; I < ImportStack.size(); ++I)
2120           Diag(diag::note_pch_required_by)
2121             << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
2122       }
2123
2124       if (!Diags.isDiagnosticInFlight())
2125         Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
2126     }
2127
2128     IsOutOfDate = true;
2129   }
2130   // FIXME: If the file is overridden and we've already opened it,
2131   // issue an error (or split it into a separate FileEntry).
2132
2133   InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
2134
2135   // Note that we've loaded this input file.
2136   F.InputFilesLoaded[ID-1] = IF;
2137   return IF;
2138 }
2139
2140 /// \brief If we are loading a relocatable PCH or module file, and the filename
2141 /// is not an absolute path, add the system or module root to the beginning of
2142 /// the file name.
2143 void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2144   // Resolve relative to the base directory, if we have one.
2145   if (!M.BaseDirectory.empty())
2146     return ResolveImportedPath(Filename, M.BaseDirectory);
2147 }
2148
2149 void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
2150   if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2151     return;
2152
2153   SmallString<128> Buffer;
2154   llvm::sys::path::append(Buffer, Prefix, Filename);
2155   Filename.assign(Buffer.begin(), Buffer.end());
2156 }
2157
2158 static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2159   switch (ARR) {
2160   case ASTReader::Failure: return true;
2161   case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2162   case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2163   case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2164   case ASTReader::ConfigurationMismatch:
2165     return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2166   case ASTReader::HadErrors: return true;
2167   case ASTReader::Success: return false;
2168   }
2169
2170   llvm_unreachable("unknown ASTReadResult");
2171 }
2172
2173 ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2174     BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2175     bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
2176     std::string &SuggestedPredefines) {
2177   if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2178     return Failure;
2179
2180   // Read all of the records in the options block.
2181   RecordData Record;
2182   ASTReadResult Result = Success;
2183   while (true) {
2184     llvm::BitstreamEntry Entry = Stream.advance();
2185
2186     switch (Entry.Kind) {
2187     case llvm::BitstreamEntry::Error:
2188     case llvm::BitstreamEntry::SubBlock:
2189       return Failure;
2190
2191     case llvm::BitstreamEntry::EndBlock:
2192       return Result;
2193
2194     case llvm::BitstreamEntry::Record:
2195       // The interesting case.
2196       break;
2197     }
2198
2199     // Read and process a record.
2200     Record.clear();
2201     switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2202     case LANGUAGE_OPTIONS: {
2203       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2204       if (ParseLanguageOptions(Record, Complain, Listener,
2205                                AllowCompatibleConfigurationMismatch))
2206         Result = ConfigurationMismatch;
2207       break;
2208     }
2209
2210     case TARGET_OPTIONS: {
2211       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2212       if (ParseTargetOptions(Record, Complain, Listener,
2213                              AllowCompatibleConfigurationMismatch))
2214         Result = ConfigurationMismatch;
2215       break;
2216     }
2217
2218     case FILE_SYSTEM_OPTIONS: {
2219       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2220       if (!AllowCompatibleConfigurationMismatch &&
2221           ParseFileSystemOptions(Record, Complain, Listener))
2222         Result = ConfigurationMismatch;
2223       break;
2224     }
2225
2226     case HEADER_SEARCH_OPTIONS: {
2227       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2228       if (!AllowCompatibleConfigurationMismatch &&
2229           ParseHeaderSearchOptions(Record, Complain, Listener))
2230         Result = ConfigurationMismatch;
2231       break;
2232     }
2233
2234     case PREPROCESSOR_OPTIONS:
2235       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2236       if (!AllowCompatibleConfigurationMismatch &&
2237           ParsePreprocessorOptions(Record, Complain, Listener,
2238                                    SuggestedPredefines))
2239         Result = ConfigurationMismatch;
2240       break;
2241     }
2242   }
2243 }
2244
2245 ASTReader::ASTReadResult
2246 ASTReader::ReadControlBlock(ModuleFile &F,
2247                             SmallVectorImpl<ImportedModule> &Loaded,
2248                             const ModuleFile *ImportedBy,
2249                             unsigned ClientLoadCapabilities) {
2250   BitstreamCursor &Stream = F.Stream;
2251   ASTReadResult Result = Success;
2252
2253   if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2254     Error("malformed block record in AST file");
2255     return Failure;
2256   }
2257
2258   // Lambda to read the unhashed control block the first time it's called.
2259   //
2260   // For PCM files, the unhashed control block cannot be read until after the
2261   // MODULE_NAME record.  However, PCH files have no MODULE_NAME, and yet still
2262   // need to look ahead before reading the IMPORTS record.  For consistency,
2263   // this block is always read somehow (see BitstreamEntry::EndBlock).
2264   bool HasReadUnhashedControlBlock = false;
2265   auto readUnhashedControlBlockOnce = [&]() {
2266     if (!HasReadUnhashedControlBlock) {
2267       HasReadUnhashedControlBlock = true;
2268       if (ASTReadResult Result =
2269               readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2270         return Result;
2271     }
2272     return Success;
2273   };
2274
2275   // Read all of the records and blocks in the control block.
2276   RecordData Record;
2277   unsigned NumInputs = 0;
2278   unsigned NumUserInputs = 0;
2279   while (true) {
2280     llvm::BitstreamEntry Entry = Stream.advance();
2281
2282     switch (Entry.Kind) {
2283     case llvm::BitstreamEntry::Error:
2284       Error("malformed block record in AST file");
2285       return Failure;
2286     case llvm::BitstreamEntry::EndBlock: {
2287       // Validate the module before returning.  This call catches an AST with
2288       // no module name and no imports.
2289       if (ASTReadResult Result = readUnhashedControlBlockOnce())
2290         return Result;
2291
2292       // Validate input files.
2293       const HeaderSearchOptions &HSOpts =
2294           PP.getHeaderSearchInfo().getHeaderSearchOpts();
2295
2296       // All user input files reside at the index range [0, NumUserInputs), and
2297       // system input files reside at [NumUserInputs, NumInputs). For explicitly
2298       // loaded module files, ignore missing inputs.
2299       if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2300           F.Kind != MK_PrebuiltModule) {
2301         bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2302
2303         // If we are reading a module, we will create a verification timestamp,
2304         // so we verify all input files.  Otherwise, verify only user input
2305         // files.
2306
2307         unsigned N = NumUserInputs;
2308         if (ValidateSystemInputs ||
2309             (HSOpts.ModulesValidateOncePerBuildSession &&
2310              F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
2311              F.Kind == MK_ImplicitModule))
2312           N = NumInputs;
2313
2314         for (unsigned I = 0; I < N; ++I) {
2315           InputFile IF = getInputFile(F, I+1, Complain);
2316           if (!IF.getFile() || IF.isOutOfDate())
2317             return OutOfDate;
2318         }
2319       }
2320
2321       if (Listener)
2322         Listener->visitModuleFile(F.FileName, F.Kind);
2323
2324       if (Listener && Listener->needsInputFileVisitation()) {
2325         unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2326                                                                 : NumUserInputs;
2327         for (unsigned I = 0; I < N; ++I) {
2328           bool IsSystem = I >= NumUserInputs;
2329           InputFileInfo FI = readInputFileInfo(F, I+1);
2330           Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
2331                                    F.Kind == MK_ExplicitModule ||
2332                                    F.Kind == MK_PrebuiltModule);
2333         }
2334       }
2335
2336       return Result;
2337     }
2338
2339     case llvm::BitstreamEntry::SubBlock:
2340       switch (Entry.ID) {
2341       case INPUT_FILES_BLOCK_ID:
2342         F.InputFilesCursor = Stream;
2343         if (Stream.SkipBlock() || // Skip with the main cursor
2344             // Read the abbreviations
2345             ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2346           Error("malformed block record in AST file");
2347           return Failure;
2348         }
2349         continue;
2350
2351       case OPTIONS_BLOCK_ID:
2352         // If we're reading the first module for this group, check its options
2353         // are compatible with ours. For modules it imports, no further checking
2354         // is required, because we checked them when we built it.
2355         if (Listener && !ImportedBy) {
2356           // Should we allow the configuration of the module file to differ from
2357           // the configuration of the current translation unit in a compatible
2358           // way?
2359           //
2360           // FIXME: Allow this for files explicitly specified with -include-pch.
2361           bool AllowCompatibleConfigurationMismatch =
2362               F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
2363
2364           Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2365                                     AllowCompatibleConfigurationMismatch,
2366                                     *Listener, SuggestedPredefines);
2367           if (Result == Failure) {
2368             Error("malformed block record in AST file");
2369             return Result;
2370           }
2371
2372           if (DisableValidation ||
2373               (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2374             Result = Success;
2375
2376           // If we can't load the module, exit early since we likely
2377           // will rebuild the module anyway. The stream may be in the
2378           // middle of a block.
2379           if (Result != Success)
2380             return Result;
2381         } else if (Stream.SkipBlock()) {
2382           Error("malformed block record in AST file");
2383           return Failure;
2384         }
2385         continue;
2386
2387       default:
2388         if (Stream.SkipBlock()) {
2389           Error("malformed block record in AST file");
2390           return Failure;
2391         }
2392         continue;
2393       }
2394
2395     case llvm::BitstreamEntry::Record:
2396       // The interesting case.
2397       break;
2398     }
2399
2400     // Read and process a record.
2401     Record.clear();
2402     StringRef Blob;
2403     switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
2404     case METADATA: {
2405       if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2406         if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2407           Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2408                                         : diag::err_pch_version_too_new);
2409         return VersionMismatch;
2410       }
2411
2412       bool hasErrors = Record[6];
2413       if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2414         Diag(diag::err_pch_with_compiler_errors);
2415         return HadErrors;
2416       }
2417       if (hasErrors) {
2418         Diags.ErrorOccurred = true;
2419         Diags.UncompilableErrorOccurred = true;
2420         Diags.UnrecoverableErrorOccurred = true;
2421       }
2422
2423       F.RelocatablePCH = Record[4];
2424       // Relative paths in a relocatable PCH are relative to our sysroot.
2425       if (F.RelocatablePCH)
2426         F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
2427
2428       F.HasTimestamps = Record[5];
2429
2430       const std::string &CurBranch = getClangFullRepositoryVersion();
2431       StringRef ASTBranch = Blob;
2432       if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2433         if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2434           Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
2435         return VersionMismatch;
2436       }
2437       break;
2438     }
2439
2440     case IMPORTS: {
2441       // Validate the AST before processing any imports (otherwise, untangling
2442       // them can be error-prone and expensive).  A module will have a name and
2443       // will already have been validated, but this catches the PCH case.
2444       if (ASTReadResult Result = readUnhashedControlBlockOnce())
2445         return Result;
2446
2447       // Load each of the imported PCH files.
2448       unsigned Idx = 0, N = Record.size();
2449       while (Idx < N) {
2450         // Read information about the AST file.
2451         ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2452         // The import location will be the local one for now; we will adjust
2453         // all import locations of module imports after the global source
2454         // location info are setup, in ReadAST.
2455         SourceLocation ImportLoc =
2456             ReadUntranslatedSourceLocation(Record[Idx++]);
2457         off_t StoredSize = (off_t)Record[Idx++];
2458         time_t StoredModTime = (time_t)Record[Idx++];
2459         ASTFileSignature StoredSignature = {
2460             {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2461               (uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2462               (uint32_t)Record[Idx++]}}};
2463         auto ImportedFile = ReadPath(F, Record, Idx);
2464
2465         // If our client can't cope with us being out of date, we can't cope with
2466         // our dependency being missing.
2467         unsigned Capabilities = ClientLoadCapabilities;
2468         if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2469           Capabilities &= ~ARR_Missing;
2470
2471         // Load the AST file.
2472         auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2473                                   Loaded, StoredSize, StoredModTime,
2474                                   StoredSignature, Capabilities);
2475
2476         // If we diagnosed a problem, produce a backtrace.
2477         if (isDiagnosedResult(Result, Capabilities))
2478           Diag(diag::note_module_file_imported_by)
2479               << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2480
2481         switch (Result) {
2482         case Failure: return Failure;
2483           // If we have to ignore the dependency, we'll have to ignore this too.
2484         case Missing:
2485         case OutOfDate: return OutOfDate;
2486         case VersionMismatch: return VersionMismatch;
2487         case ConfigurationMismatch: return ConfigurationMismatch;
2488         case HadErrors: return HadErrors;
2489         case Success: break;
2490         }
2491       }
2492       break;
2493     }
2494
2495     case ORIGINAL_FILE:
2496       F.OriginalSourceFileID = FileID::get(Record[0]);
2497       F.ActualOriginalSourceFileName = Blob;
2498       F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2499       ResolveImportedPath(F, F.OriginalSourceFileName);
2500       break;
2501
2502     case ORIGINAL_FILE_ID:
2503       F.OriginalSourceFileID = FileID::get(Record[0]);
2504       break;
2505
2506     case ORIGINAL_PCH_DIR:
2507       F.OriginalDir = Blob;
2508       break;
2509
2510     case MODULE_NAME:
2511       F.ModuleName = Blob;
2512       if (Listener)
2513         Listener->ReadModuleName(F.ModuleName);
2514
2515       // Validate the AST as soon as we have a name so we can exit early on
2516       // failure.
2517       if (ASTReadResult Result = readUnhashedControlBlockOnce())
2518         return Result;
2519
2520       break;
2521
2522     case MODULE_DIRECTORY: {
2523       assert(!F.ModuleName.empty() &&
2524              "MODULE_DIRECTORY found before MODULE_NAME");
2525       // If we've already loaded a module map file covering this module, we may
2526       // have a better path for it (relative to the current build).
2527       Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2528       if (M && M->Directory) {
2529         // If we're implicitly loading a module, the base directory can't
2530         // change between the build and use.
2531         if (F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
2532           const DirectoryEntry *BuildDir =
2533               PP.getFileManager().getDirectory(Blob);
2534           if (!BuildDir || BuildDir != M->Directory) {
2535             if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2536               Diag(diag::err_imported_module_relocated)
2537                   << F.ModuleName << Blob << M->Directory->getName();
2538             return OutOfDate;
2539           }
2540         }
2541         F.BaseDirectory = M->Directory->getName();
2542       } else {
2543         F.BaseDirectory = Blob;
2544       }
2545       break;
2546     }
2547
2548     case MODULE_MAP_FILE:
2549       if (ASTReadResult Result =
2550               ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2551         return Result;
2552       break;
2553
2554     case INPUT_FILE_OFFSETS:
2555       NumInputs = Record[0];
2556       NumUserInputs = Record[1];
2557       F.InputFileOffsets =
2558           (const llvm::support::unaligned_uint64_t *)Blob.data();
2559       F.InputFilesLoaded.resize(NumInputs);
2560       F.NumUserInputFiles = NumUserInputs;
2561       break;
2562     }
2563   }
2564 }
2565
2566 ASTReader::ASTReadResult
2567 ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
2568   BitstreamCursor &Stream = F.Stream;
2569
2570   if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2571     Error("malformed block record in AST file");
2572     return Failure;
2573   }
2574
2575   // Read all of the records and blocks for the AST file.
2576   RecordData Record;
2577   while (true) {
2578     llvm::BitstreamEntry Entry = Stream.advance();
2579
2580     switch (Entry.Kind) {
2581     case llvm::BitstreamEntry::Error:
2582       Error("error at end of module block in AST file");
2583       return Failure;
2584     case llvm::BitstreamEntry::EndBlock: {
2585       // Outside of C++, we do not store a lookup map for the translation unit.
2586       // Instead, mark it as needing a lookup map to be built if this module
2587       // contains any declarations lexically within it (which it always does!).
2588       // This usually has no cost, since we very rarely need the lookup map for
2589       // the translation unit outside C++.
2590       DeclContext *DC = Context.getTranslationUnitDecl();
2591       if (DC->hasExternalLexicalStorage() &&
2592           !getContext().getLangOpts().CPlusPlus)
2593         DC->setMustBuildLookupTable();
2594
2595       return Success;
2596     }
2597     case llvm::BitstreamEntry::SubBlock:
2598       switch (Entry.ID) {
2599       case DECLTYPES_BLOCK_ID:
2600         // We lazily load the decls block, but we want to set up the
2601         // DeclsCursor cursor to point into it.  Clone our current bitcode
2602         // cursor to it, enter the block and read the abbrevs in that block.
2603         // With the main cursor, we just skip over it.
2604         F.DeclsCursor = Stream;
2605         if (Stream.SkipBlock() ||  // Skip with the main cursor.
2606             // Read the abbrevs.
2607             ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2608           Error("malformed block record in AST file");
2609           return Failure;
2610         }
2611         break;
2612
2613       case PREPROCESSOR_BLOCK_ID:
2614         F.MacroCursor = Stream;
2615         if (!PP.getExternalSource())
2616           PP.setExternalSource(this);
2617
2618         if (Stream.SkipBlock() ||
2619             ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2620           Error("malformed block record in AST file");
2621           return Failure;
2622         }
2623         F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2624         break;
2625
2626       case PREPROCESSOR_DETAIL_BLOCK_ID:
2627         F.PreprocessorDetailCursor = Stream;
2628         if (Stream.SkipBlock() ||
2629             ReadBlockAbbrevs(F.PreprocessorDetailCursor,
2630                              PREPROCESSOR_DETAIL_BLOCK_ID)) {
2631               Error("malformed preprocessor detail record in AST file");
2632               return Failure;
2633             }
2634         F.PreprocessorDetailStartOffset
2635         = F.PreprocessorDetailCursor.GetCurrentBitNo();
2636
2637         if (!PP.getPreprocessingRecord())
2638           PP.createPreprocessingRecord();
2639         if (!PP.getPreprocessingRecord()->getExternalSource())
2640           PP.getPreprocessingRecord()->SetExternalSource(*this);
2641         break;
2642
2643       case SOURCE_MANAGER_BLOCK_ID:
2644         if (ReadSourceManagerBlock(F))
2645           return Failure;
2646         break;
2647
2648       case SUBMODULE_BLOCK_ID:
2649         if (ASTReadResult Result =
2650                 ReadSubmoduleBlock(F, ClientLoadCapabilities))
2651           return Result;
2652         break;
2653
2654       case COMMENTS_BLOCK_ID: {
2655         BitstreamCursor C = Stream;
2656         if (Stream.SkipBlock() ||
2657             ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2658           Error("malformed comments block in AST file");
2659           return Failure;
2660         }
2661         CommentsCursors.push_back(std::make_pair(C, &F));
2662         break;
2663       }
2664
2665       default:
2666         if (Stream.SkipBlock()) {
2667           Error("malformed block record in AST file");
2668           return Failure;
2669         }
2670         break;
2671       }
2672       continue;
2673
2674     case llvm::BitstreamEntry::Record:
2675       // The interesting case.
2676       break;
2677     }
2678
2679     // Read and process a record.
2680     Record.clear();
2681     StringRef Blob;
2682     switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
2683     default:  // Default behavior: ignore.
2684       break;
2685
2686     case TYPE_OFFSET: {
2687       if (F.LocalNumTypes != 0) {
2688         Error("duplicate TYPE_OFFSET record in AST file");
2689         return Failure;
2690       }
2691       F.TypeOffsets = (const uint32_t *)Blob.data();
2692       F.LocalNumTypes = Record[0];
2693       unsigned LocalBaseTypeIndex = Record[1];
2694       F.BaseTypeIndex = getTotalNumTypes();
2695
2696       if (F.LocalNumTypes > 0) {
2697         // Introduce the global -> local mapping for types within this module.
2698         GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2699
2700         // Introduce the local -> global mapping for types within this module.
2701         F.TypeRemap.insertOrReplace(
2702           std::make_pair(LocalBaseTypeIndex,
2703                          F.BaseTypeIndex - LocalBaseTypeIndex));
2704
2705         TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2706       }
2707       break;
2708     }
2709
2710     case DECL_OFFSET: {
2711       if (F.LocalNumDecls != 0) {
2712         Error("duplicate DECL_OFFSET record in AST file");
2713         return Failure;
2714       }
2715       F.DeclOffsets = (const DeclOffset *)Blob.data();
2716       F.LocalNumDecls = Record[0];
2717       unsigned LocalBaseDeclID = Record[1];
2718       F.BaseDeclID = getTotalNumDecls();
2719
2720       if (F.LocalNumDecls > 0) {
2721         // Introduce the global -> local mapping for declarations within this
2722         // module.
2723         GlobalDeclMap.insert(
2724           std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2725
2726         // Introduce the local -> global mapping for declarations within this
2727         // module.
2728         F.DeclRemap.insertOrReplace(
2729           std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2730
2731         // Introduce the global -> local mapping for declarations within this
2732         // module.
2733         F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2734
2735         DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2736       }
2737       break;
2738     }
2739
2740     case TU_UPDATE_LEXICAL: {
2741       DeclContext *TU = Context.getTranslationUnitDecl();
2742       LexicalContents Contents(
2743           reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2744               Blob.data()),
2745           static_cast<unsigned int>(Blob.size() / 4));
2746       TULexicalDecls.push_back(std::make_pair(&F, Contents));
2747       TU->setHasExternalLexicalStorage(true);
2748       break;
2749     }
2750
2751     case UPDATE_VISIBLE: {
2752       unsigned Idx = 0;
2753       serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2754       auto *Data = (const unsigned char*)Blob.data();
2755       PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
2756       // If we've already loaded the decl, perform the updates when we finish
2757       // loading this block.
2758       if (Decl *D = GetExistingDecl(ID))
2759         PendingUpdateRecords.push_back(
2760             PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
2761       break;
2762     }
2763
2764     case IDENTIFIER_TABLE:
2765       F.IdentifierTableData = Blob.data();
2766       if (Record[0]) {
2767         F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2768             (const unsigned char *)F.IdentifierTableData + Record[0],
2769             (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2770             (const unsigned char *)F.IdentifierTableData,
2771             ASTIdentifierLookupTrait(*this, F));
2772
2773         PP.getIdentifierTable().setExternalIdentifierLookup(this);
2774       }
2775       break;
2776
2777     case IDENTIFIER_OFFSET: {
2778       if (F.LocalNumIdentifiers != 0) {
2779         Error("duplicate IDENTIFIER_OFFSET record in AST file");
2780         return Failure;
2781       }
2782       F.IdentifierOffsets = (const uint32_t *)Blob.data();
2783       F.LocalNumIdentifiers = Record[0];
2784       unsigned LocalBaseIdentifierID = Record[1];
2785       F.BaseIdentifierID = getTotalNumIdentifiers();
2786
2787       if (F.LocalNumIdentifiers > 0) {
2788         // Introduce the global -> local mapping for identifiers within this
2789         // module.
2790         GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2791                                                   &F));
2792
2793         // Introduce the local -> global mapping for identifiers within this
2794         // module.
2795         F.IdentifierRemap.insertOrReplace(
2796           std::make_pair(LocalBaseIdentifierID,
2797                          F.BaseIdentifierID - LocalBaseIdentifierID));
2798
2799         IdentifiersLoaded.resize(IdentifiersLoaded.size()
2800                                  + F.LocalNumIdentifiers);
2801       }
2802       break;
2803     }
2804
2805     case INTERESTING_IDENTIFIERS:
2806       F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2807       break;
2808
2809     case EAGERLY_DESERIALIZED_DECLS:
2810       // FIXME: Skip reading this record if our ASTConsumer doesn't care
2811       // about "interesting" decls (for instance, if we're building a module).
2812       for (unsigned I = 0, N = Record.size(); I != N; ++I)
2813         EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2814       break;
2815
2816     case MODULAR_CODEGEN_DECLS:
2817       // FIXME: Skip reading this record if our ASTConsumer doesn't care about
2818       // them (ie: if we're not codegenerating this module).
2819       if (F.Kind == MK_MainFile)
2820         for (unsigned I = 0, N = Record.size(); I != N; ++I)
2821           EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2822       break;
2823
2824     case SPECIAL_TYPES:
2825       if (SpecialTypes.empty()) {
2826         for (unsigned I = 0, N = Record.size(); I != N; ++I)
2827           SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2828         break;
2829       }
2830
2831       if (SpecialTypes.size() != Record.size()) {
2832         Error("invalid special-types record");
2833         return Failure;
2834       }
2835
2836       for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2837         serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2838         if (!SpecialTypes[I])
2839           SpecialTypes[I] = ID;
2840         // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2841         // merge step?
2842       }
2843       break;
2844
2845     case STATISTICS:
2846       TotalNumStatements += Record[0];
2847       TotalNumMacros += Record[1];
2848       TotalLexicalDeclContexts += Record[2];
2849       TotalVisibleDeclContexts += Record[3];
2850       break;
2851
2852     case UNUSED_FILESCOPED_DECLS:
2853       for (unsigned I = 0, N = Record.size(); I != N; ++I)
2854         UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2855       break;
2856
2857     case DELEGATING_CTORS:
2858       for (unsigned I = 0, N = Record.size(); I != N; ++I)
2859         DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2860       break;
2861
2862     case WEAK_UNDECLARED_IDENTIFIERS:
2863       if (Record.size() % 4 != 0) {
2864         Error("invalid weak identifiers record");
2865         return Failure;
2866       }
2867
2868       // FIXME: Ignore weak undeclared identifiers from non-original PCH
2869       // files. This isn't the way to do it :)
2870       WeakUndeclaredIdentifiers.clear();
2871
2872       // Translate the weak, undeclared identifiers into global IDs.
2873       for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2874         WeakUndeclaredIdentifiers.push_back(
2875           getGlobalIdentifierID(F, Record[I++]));
2876         WeakUndeclaredIdentifiers.push_back(
2877           getGlobalIdentifierID(F, Record[I++]));
2878         WeakUndeclaredIdentifiers.push_back(
2879           ReadSourceLocation(F, Record, I).getRawEncoding());
2880         WeakUndeclaredIdentifiers.push_back(Record[I++]);
2881       }
2882       break;
2883
2884     case SELECTOR_OFFSETS: {
2885       F.SelectorOffsets = (const uint32_t *)Blob.data();
2886       F.LocalNumSelectors = Record[0];
2887       unsigned LocalBaseSelectorID = Record[1];
2888       F.BaseSelectorID = getTotalNumSelectors();
2889
2890       if (F.LocalNumSelectors > 0) {
2891         // Introduce the global -> local mapping for selectors within this
2892         // module.
2893         GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2894
2895         // Introduce the local -> global mapping for selectors within this
2896         // module.
2897         F.SelectorRemap.insertOrReplace(
2898           std::make_pair(LocalBaseSelectorID,
2899                          F.BaseSelectorID - LocalBaseSelectorID));
2900
2901         SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2902       }
2903       break;
2904     }
2905
2906     case METHOD_POOL:
2907       F.SelectorLookupTableData = (const unsigned char *)Blob.data();
2908       if (Record[0])
2909         F.SelectorLookupTable
2910           = ASTSelectorLookupTable::Create(
2911                         F.SelectorLookupTableData + Record[0],
2912                         F.SelectorLookupTableData,
2913                         ASTSelectorLookupTrait(*this, F));
2914       TotalNumMethodPoolEntries += Record[1];
2915       break;
2916
2917     case REFERENCED_SELECTOR_POOL:
2918       if (!Record.empty()) {
2919         for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2920           ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2921                                                                 Record[Idx++]));
2922           ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2923                                               getRawEncoding());
2924         }
2925       }
2926       break;
2927
2928     case PP_CONDITIONAL_STACK:
2929       if (!Record.empty()) {
2930         SmallVector<PPConditionalInfo, 4> ConditionalStack;
2931         for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2932           auto Loc = ReadSourceLocation(F, Record, Idx);
2933           bool WasSkipping = Record[Idx++];
2934           bool FoundNonSkip = Record[Idx++];
2935           bool FoundElse = Record[Idx++];
2936           ConditionalStack.push_back(
2937               {Loc, WasSkipping, FoundNonSkip, FoundElse});
2938         }
2939         PP.setReplayablePreambleConditionalStack(ConditionalStack);
2940       }
2941       break;
2942
2943     case PP_COUNTER_VALUE:
2944       if (!Record.empty() && Listener)
2945         Listener->ReadCounter(F, Record[0]);
2946       break;
2947
2948     case FILE_SORTED_DECLS:
2949       F.FileSortedDecls = (const DeclID *)Blob.data();
2950       F.NumFileSortedDecls = Record[0];
2951       break;
2952
2953     case SOURCE_LOCATION_OFFSETS: {
2954       F.SLocEntryOffsets = (const uint32_t *)Blob.data();
2955       F.LocalNumSLocEntries = Record[0];
2956       unsigned SLocSpaceSize = Record[1];
2957       std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
2958           SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2959                                               SLocSpaceSize);
2960       if (!F.SLocEntryBaseID) {
2961         Error("ran out of source locations");
2962         break;
2963       }
2964       // Make our entry in the range map. BaseID is negative and growing, so
2965       // we invert it. Because we invert it, though, we need the other end of
2966       // the range.
2967       unsigned RangeStart =
2968           unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2969       GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2970       F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2971
2972       // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2973       assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2974       GlobalSLocOffsetMap.insert(
2975           std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2976                            - SLocSpaceSize,&F));
2977
2978       // Initialize the remapping table.
2979       // Invalid stays invalid.
2980       F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
2981       // This module. Base was 2 when being compiled.
2982       F.SLocRemap.insertOrReplace(std::make_pair(2U,
2983                                   static_cast<int>(F.SLocEntryBaseOffset - 2)));
2984
2985       TotalNumSLocEntries += F.LocalNumSLocEntries;
2986       break;
2987     }
2988
2989     case MODULE_OFFSET_MAP:
2990       F.ModuleOffsetMap = Blob;
2991       break;
2992
2993     case SOURCE_MANAGER_LINE_TABLE:
2994       if (ParseLineTable(F, Record))
2995         return Failure;
2996       break;
2997
2998     case SOURCE_LOCATION_PRELOADS: {
2999       // Need to transform from the local view (1-based IDs) to the global view,
3000       // which is based off F.SLocEntryBaseID.
3001       if (!F.PreloadSLocEntries.empty()) {
3002         Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
3003         return Failure;
3004       }
3005
3006       F.PreloadSLocEntries.swap(Record);
3007       break;
3008     }
3009
3010     case EXT_VECTOR_DECLS:
3011       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3012         ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3013       break;
3014
3015     case VTABLE_USES:
3016       if (Record.size() % 3 != 0) {
3017         Error("Invalid VTABLE_USES record");
3018         return Failure;
3019       }
3020
3021       // Later tables overwrite earlier ones.
3022       // FIXME: Modules will have some trouble with this. This is clearly not
3023       // the right way to do this.
3024       VTableUses.clear();
3025
3026       for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3027         VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3028         VTableUses.push_back(
3029           ReadSourceLocation(F, Record, Idx).getRawEncoding());
3030         VTableUses.push_back(Record[Idx++]);
3031       }
3032       break;
3033
3034     case PENDING_IMPLICIT_INSTANTIATIONS:
3035       if (PendingInstantiations.size() % 2 != 0) {
3036         Error("Invalid existing PendingInstantiations");
3037         return Failure;
3038       }
3039
3040       if (Record.size() % 2 != 0) {
3041         Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
3042         return Failure;
3043       }
3044
3045       for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3046         PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3047         PendingInstantiations.push_back(
3048           ReadSourceLocation(F, Record, I).getRawEncoding());
3049       }
3050       break;
3051
3052     case SEMA_DECL_REFS:
3053       if (Record.size() != 3) {
3054         Error("Invalid SEMA_DECL_REFS block");
3055         return Failure;
3056       }
3057       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3058         SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3059       break;
3060
3061     case PPD_ENTITIES_OFFSETS: {
3062       F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3063       assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3064       F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
3065
3066       unsigned LocalBasePreprocessedEntityID = Record[0];
3067
3068       unsigned StartingID;
3069       if (!PP.getPreprocessingRecord())
3070         PP.createPreprocessingRecord();
3071       if (!PP.getPreprocessingRecord()->getExternalSource())
3072         PP.getPreprocessingRecord()->SetExternalSource(*this);
3073       StartingID
3074         = PP.getPreprocessingRecord()
3075             ->allocateLoadedEntities(F.NumPreprocessedEntities);
3076       F.BasePreprocessedEntityID = StartingID;
3077
3078       if (F.NumPreprocessedEntities > 0) {
3079         // Introduce the global -> local mapping for preprocessed entities in
3080         // this module.
3081         GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
3082
3083         // Introduce the local -> global mapping for preprocessed entities in
3084         // this module.
3085         F.PreprocessedEntityRemap.insertOrReplace(
3086           std::make_pair(LocalBasePreprocessedEntityID,
3087             F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3088       }
3089
3090       break;
3091     }
3092
3093     case DECL_UPDATE_OFFSETS: {
3094       if (Record.size() % 2 != 0) {
3095         Error("invalid DECL_UPDATE_OFFSETS block in AST file");
3096         return Failure;
3097       }
3098       for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3099         GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3100         DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3101
3102         // If we've already loaded the decl, perform the updates when we finish
3103         // loading this block.
3104         if (Decl *D = GetExistingDecl(ID))
3105           PendingUpdateRecords.push_back(
3106               PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
3107       }
3108       break;
3109     }
3110
3111     case OBJC_CATEGORIES_MAP: {
3112       if (F.LocalNumObjCCategoriesInMap != 0) {
3113         Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
3114         return Failure;
3115       }
3116
3117       F.LocalNumObjCCategoriesInMap = Record[0];
3118       F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
3119       break;
3120     }
3121
3122     case OBJC_CATEGORIES:
3123       F.ObjCCategories.swap(Record);
3124       break;
3125
3126     case CUDA_SPECIAL_DECL_REFS:
3127       // Later tables overwrite earlier ones.
3128       // FIXME: Modules will have trouble with this.
3129       CUDASpecialDeclRefs.clear();
3130       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3131         CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3132       break;
3133
3134     case HEADER_SEARCH_TABLE: {
3135       F.HeaderFileInfoTableData = Blob.data();
3136       F.LocalNumHeaderFileInfos = Record[1];
3137       if (Record[0]) {
3138         F.HeaderFileInfoTable
3139           = HeaderFileInfoLookupTable::Create(
3140                    (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3141                    (const unsigned char *)F.HeaderFileInfoTableData,
3142                    HeaderFileInfoTrait(*this, F,
3143                                        &PP.getHeaderSearchInfo(),
3144                                        Blob.data() + Record[2]));
3145
3146         PP.getHeaderSearchInfo().SetExternalSource(this);
3147         if (!PP.getHeaderSearchInfo().getExternalLookup())
3148           PP.getHeaderSearchInfo().SetExternalLookup(this);
3149       }
3150       break;
3151     }
3152
3153     case FP_PRAGMA_OPTIONS:
3154       // Later tables overwrite earlier ones.
3155       FPPragmaOptions.swap(Record);
3156       break;
3157
3158     case OPENCL_EXTENSIONS:
3159       for (unsigned I = 0, E = Record.size(); I != E; ) {
3160         auto Name = ReadString(Record, I);
3161         auto &Opt = OpenCLExtensions.OptMap[Name];
3162         Opt.Supported = Record[I++] != 0;
3163         Opt.Enabled = Record[I++] != 0;
3164         Opt.Avail = Record[I++];
3165         Opt.Core = Record[I++];
3166       }
3167       break;
3168
3169     case OPENCL_EXTENSION_TYPES:
3170       for (unsigned I = 0, E = Record.size(); I != E;) {
3171         auto TypeID = static_cast<::TypeID>(Record[I++]);
3172         auto *Type = GetType(TypeID).getTypePtr();
3173         auto NumExt = static_cast<unsigned>(Record[I++]);
3174         for (unsigned II = 0; II != NumExt; ++II) {
3175           auto Ext = ReadString(Record, I);
3176           OpenCLTypeExtMap[Type].insert(Ext);
3177         }
3178       }
3179       break;
3180
3181     case OPENCL_EXTENSION_DECLS:
3182       for (unsigned I = 0, E = Record.size(); I != E;) {
3183         auto DeclID = static_cast<::DeclID>(Record[I++]);
3184         auto *Decl = GetDecl(DeclID);
3185         auto NumExt = static_cast<unsigned>(Record[I++]);
3186         for (unsigned II = 0; II != NumExt; ++II) {
3187           auto Ext = ReadString(Record, I);
3188           OpenCLDeclExtMap[Decl].insert(Ext);
3189         }
3190       }
3191       break;
3192
3193     case TENTATIVE_DEFINITIONS:
3194       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3195         TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3196       break;
3197
3198     case KNOWN_NAMESPACES:
3199       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3200         KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3201       break;
3202
3203     case UNDEFINED_BUT_USED:
3204       if (UndefinedButUsed.size() % 2 != 0) {
3205         Error("Invalid existing UndefinedButUsed");
3206         return Failure;
3207       }
3208
3209       if (Record.size() % 2 != 0) {
3210         Error("invalid undefined-but-used record");
3211         return Failure;
3212       }
3213       for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3214         UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3215         UndefinedButUsed.push_back(
3216             ReadSourceLocation(F, Record, I).getRawEncoding());
3217       }
3218       break;
3219     case DELETE_EXPRS_TO_ANALYZE:
3220       for (unsigned I = 0, N = Record.size(); I != N;) {
3221         DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3222         const uint64_t Count = Record[I++];
3223         DelayedDeleteExprs.push_back(Count);
3224         for (uint64_t C = 0; C < Count; ++C) {
3225           DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3226           bool IsArrayForm = Record[I++] == 1;
3227           DelayedDeleteExprs.push_back(IsArrayForm);
3228         }
3229       }
3230       break;
3231
3232     case IMPORTED_MODULES: {
3233       if (!F.isModule()) {
3234         // If we aren't loading a module (which has its own exports), make
3235         // all of the imported modules visible.
3236         // FIXME: Deal with macros-only imports.
3237         for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3238           unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3239           SourceLocation Loc = ReadSourceLocation(F, Record, I);
3240           if (GlobalID) {
3241             ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
3242             if (DeserializationListener)
3243               DeserializationListener->ModuleImportRead(GlobalID, Loc);
3244           }
3245         }
3246       }
3247       break;
3248     }
3249
3250     case MACRO_OFFSET: {
3251       if (F.LocalNumMacros != 0) {
3252         Error("duplicate MACRO_OFFSET record in AST file");
3253         return Failure;
3254       }
3255       F.MacroOffsets = (const uint32_t *)Blob.data();
3256       F.LocalNumMacros = Record[0];
3257       unsigned LocalBaseMacroID = Record[1];
3258       F.BaseMacroID = getTotalNumMacros();
3259
3260       if (F.LocalNumMacros > 0) {
3261         // Introduce the global -> local mapping for macros within this module.
3262         GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3263
3264         // Introduce the local -> global mapping for macros within this module.
3265         F.MacroRemap.insertOrReplace(
3266           std::make_pair(LocalBaseMacroID,
3267                          F.BaseMacroID - LocalBaseMacroID));
3268
3269         MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3270       }
3271       break;
3272     }
3273
3274     case LATE_PARSED_TEMPLATE: {
3275       LateParsedTemplates.append(Record.begin(), Record.end());
3276       break;
3277     }
3278
3279     case OPTIMIZE_PRAGMA_OPTIONS:
3280       if (Record.size() != 1) {
3281         Error("invalid pragma optimize record");
3282         return Failure;
3283       }
3284       OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3285       break;
3286
3287     case MSSTRUCT_PRAGMA_OPTIONS:
3288       if (Record.size() != 1) {
3289         Error("invalid pragma ms_struct record");
3290         return Failure;
3291       }
3292       PragmaMSStructState = Record[0];
3293       break;
3294
3295     case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3296       if (Record.size() != 2) {
3297         Error("invalid pragma ms_struct record");
3298         return Failure;
3299       }
3300       PragmaMSPointersToMembersState = Record[0];
3301       PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3302       break;
3303
3304     case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3305       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3306         UnusedLocalTypedefNameCandidates.push_back(
3307             getGlobalDeclID(F, Record[I]));
3308       break;
3309
3310     case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3311       if (Record.size() != 1) {
3312         Error("invalid cuda pragma options record");
3313         return Failure;
3314       }
3315       ForceCUDAHostDeviceDepth = Record[0];
3316       break;
3317
3318     case PACK_PRAGMA_OPTIONS: {
3319       if (Record.size() < 3) {
3320         Error("invalid pragma pack record");
3321         return Failure;
3322       }
3323       PragmaPackCurrentValue = Record[0];
3324       PragmaPackCurrentLocation = ReadSourceLocation(F, Record[1]);
3325       unsigned NumStackEntries = Record[2];
3326       unsigned Idx = 3;
3327       // Reset the stack when importing a new module.
3328       PragmaPackStack.clear();
3329       for (unsigned I = 0; I < NumStackEntries; ++I) {
3330         PragmaPackStackEntry Entry;
3331         Entry.Value = Record[Idx++];
3332         Entry.Location = ReadSourceLocation(F, Record[Idx++]);
3333         PragmaPackStrings.push_back(ReadString(Record, Idx));
3334         Entry.SlotLabel = PragmaPackStrings.back();
3335         PragmaPackStack.push_back(Entry);
3336       }
3337       break;
3338     }
3339     }
3340   }
3341 }
3342
3343 void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3344   assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3345
3346   // Additional remapping information.
3347   const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
3348   const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3349   F.ModuleOffsetMap = StringRef();
3350
3351   // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3352   if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3353     F.SLocRemap.insert(std::make_pair(0U, 0));
3354     F.SLocRemap.insert(std::make_pair(2U, 1));
3355   }
3356
3357   // Continuous range maps we may be updating in our module.
3358   typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
3359       RemapBuilder;
3360   RemapBuilder SLocRemap(F.SLocRemap);
3361   RemapBuilder IdentifierRemap(F.IdentifierRemap);
3362   RemapBuilder MacroRemap(F.MacroRemap);
3363   RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3364   RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3365   RemapBuilder SelectorRemap(F.SelectorRemap);
3366   RemapBuilder DeclRemap(F.DeclRemap);
3367   RemapBuilder TypeRemap(F.TypeRemap);
3368
3369   while (Data < DataEnd) {
3370     // FIXME: Looking up dependency modules by filename is horrible.
3371     using namespace llvm::support;
3372     uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3373     StringRef Name = StringRef((const char*)Data, Len);
3374     Data += Len;
3375     ModuleFile *OM = ModuleMgr.lookup(Name);
3376     if (!OM) {
3377       std::string Msg =
3378           "SourceLocation remap refers to unknown module, cannot find ";
3379       Msg.append(Name);
3380       Error(Msg);
3381       return;
3382     }
3383
3384     uint32_t SLocOffset =
3385         endian::readNext<uint32_t, little, unaligned>(Data);
3386     uint32_t IdentifierIDOffset =
3387         endian::readNext<uint32_t, little, unaligned>(Data);
3388     uint32_t MacroIDOffset =
3389         endian::readNext<uint32_t, little, unaligned>(Data);
3390     uint32_t PreprocessedEntityIDOffset =
3391         endian::readNext<uint32_t, little, unaligned>(Data);
3392     uint32_t SubmoduleIDOffset =
3393         endian::readNext<uint32_t, little, unaligned>(Data);
3394     uint32_t SelectorIDOffset =
3395         endian::readNext<uint32_t, little, unaligned>(Data);
3396     uint32_t DeclIDOffset =
3397         endian::readNext<uint32_t, little, unaligned>(Data);
3398     uint32_t TypeIndexOffset =
3399         endian::readNext<uint32_t, little, unaligned>(Data);
3400
3401     uint32_t None = std::numeric_limits<uint32_t>::max();
3402
3403     auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3404                          RemapBuilder &Remap) {
3405       if (Offset != None)
3406         Remap.insert(std::make_pair(Offset,
3407                                     static_cast<int>(BaseOffset - Offset)));
3408     };
3409     mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3410     mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3411     mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3412     mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3413               PreprocessedEntityRemap);
3414     mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3415     mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3416     mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3417     mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3418
3419     // Global -> local mappings.
3420     F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3421   }
3422 }
3423
3424 ASTReader::ASTReadResult
3425 ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3426                                   const ModuleFile *ImportedBy,
3427                                   unsigned ClientLoadCapabilities) {
3428   unsigned Idx = 0;
3429   F.ModuleMapPath = ReadPath(F, Record, Idx);
3430
3431   if (F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule) {
3432     // For an explicitly-loaded module, we don't care whether the original
3433     // module map file exists or matches.
3434     return Success;
3435   }
3436
3437   // Try to resolve ModuleName in the current header search context and
3438   // verify that it is found in the same module map file as we saved. If the
3439   // top-level AST file is a main file, skip this check because there is no
3440   // usable header search context.
3441   assert(!F.ModuleName.empty() &&
3442          "MODULE_NAME should come before MODULE_MAP_FILE");
3443   if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
3444     // An implicitly-loaded module file should have its module listed in some
3445     // module map file that we've already loaded.
3446     Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
3447     auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3448     const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3449     if (!ModMap) {
3450       assert(ImportedBy && "top-level import should be verified");
3451       if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3452         if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3453           // This module was defined by an imported (explicit) module.
3454           Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3455                                                << ASTFE->getName();
3456         else
3457           // This module was built with a different module map.
3458           Diag(diag::err_imported_module_not_found)
3459               << F.ModuleName << F.FileName << ImportedBy->FileName
3460               << F.ModuleMapPath;
3461       }
3462       return OutOfDate;
3463     }
3464
3465     assert(M->Name == F.ModuleName && "found module with different name");
3466
3467     // Check the primary module map file.
3468     const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
3469     if (StoredModMap == nullptr || StoredModMap != ModMap) {
3470       assert(ModMap && "found module is missing module map file");
3471       assert(ImportedBy && "top-level import should be verified");
3472       if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3473         Diag(diag::err_imported_module_modmap_changed)
3474           << F.ModuleName << ImportedBy->FileName
3475           << ModMap->getName() << F.ModuleMapPath;
3476       return OutOfDate;
3477     }
3478
3479     llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3480     for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3481       // FIXME: we should use input files rather than storing names.
3482       std::string Filename = ReadPath(F, Record, Idx);
3483       const FileEntry *F =
3484           FileMgr.getFile(Filename, false, false);
3485       if (F == nullptr) {
3486         if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3487           Error("could not find file '" + Filename +"' referenced by AST file");
3488         return OutOfDate;
3489       }
3490       AdditionalStoredMaps.insert(F);
3491     }
3492
3493     // Check any additional module map files (e.g. module.private.modulemap)
3494     // that are not in the pcm.
3495     if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3496       for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3497         // Remove files that match
3498         // Note: SmallPtrSet::erase is really remove
3499         if (!AdditionalStoredMaps.erase(ModMap)) {
3500           if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3501             Diag(diag::err_module_different_modmap)
3502               << F.ModuleName << /*new*/0 << ModMap->getName();
3503           return OutOfDate;
3504         }
3505       }
3506     }
3507
3508     // Check any additional module map files that are in the pcm, but not
3509     // found in header search. Cases that match are already removed.
3510     for (const FileEntry *ModMap : AdditionalStoredMaps) {
3511       if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3512         Diag(diag::err_module_different_modmap)
3513           << F.ModuleName << /*not new*/1 << ModMap->getName();
3514       return OutOfDate;
3515     }
3516   }
3517
3518   if (Listener)
3519     Listener->ReadModuleMapFile(F.ModuleMapPath);
3520   return Success;
3521 }
3522
3523
3524 /// \brief Move the given method to the back of the global list of methods.
3525 static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3526   // Find the entry for this selector in the method pool.
3527   Sema::GlobalMethodPool::iterator Known
3528     = S.MethodPool.find(Method->getSelector());
3529   if (Known == S.MethodPool.end())
3530     return;
3531
3532   // Retrieve the appropriate method list.
3533   ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3534                                                     : Known->second.second;
3535   bool Found = false;
3536   for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
3537     if (!Found) {
3538       if (List->getMethod() == Method) {
3539         Found = true;
3540       } else {
3541         // Keep searching.
3542         continue;
3543       }
3544     }
3545
3546     if (List->getNext())
3547       List->setMethod(List->getNext()->getMethod());
3548     else
3549       List->setMethod(Method);
3550   }
3551 }
3552
3553 void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
3554   assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
3555   for (Decl *D : Names) {
3556     bool wasHidden = D->Hidden;
3557     D->Hidden = false;
3558
3559     if (wasHidden && SemaObj) {
3560       if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3561         moveMethodToBackOfGlobalList(*SemaObj, Method);
3562       }
3563     }
3564   }
3565 }
3566
3567 void ASTReader::makeModuleVisible(Module *Mod,
3568                                   Module::NameVisibilityKind NameVisibility,
3569                                   SourceLocation ImportLoc) {
3570   llvm::SmallPtrSet<Module *, 4> Visited;
3571   SmallVector<Module *, 4> Stack;
3572   Stack.push_back(Mod);
3573   while (!Stack.empty()) {
3574     Mod = Stack.pop_back_val();
3575
3576     if (NameVisibility <= Mod->NameVisibility) {
3577       // This module already has this level of visibility (or greater), so
3578       // there is nothing more to do.
3579       continue;
3580     }
3581
3582     if (!Mod->isAvailable()) {
3583       // Modules that aren't available cannot be made visible.
3584       continue;
3585     }
3586
3587     // Update the module's name visibility.
3588     Mod->NameVisibility = NameVisibility;
3589
3590     // If we've already deserialized any names from this module,
3591     // mark them as visible.
3592     HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3593     if (Hidden != HiddenNamesMap.end()) {
3594       auto HiddenNames = std::move(*Hidden);
3595       HiddenNamesMap.erase(Hidden);
3596       makeNamesVisible(HiddenNames.second, HiddenNames.first);
3597       assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3598              "making names visible added hidden names");
3599     }
3600
3601     // Push any exported modules onto the stack to be marked as visible.
3602     SmallVector<Module *, 16> Exports;
3603     Mod->getExportedModules(Exports);
3604     for (SmallVectorImpl<Module *>::iterator
3605            I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3606       Module *Exported = *I;
3607       if (Visited.insert(Exported).second)
3608         Stack.push_back(Exported);
3609     }
3610   }
3611 }
3612
3613 /// We've merged the definition \p MergedDef into the existing definition
3614 /// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
3615 /// visible.
3616 void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
3617                                           NamedDecl *MergedDef) {
3618   // FIXME: This doesn't correctly handle the case where MergedDef is visible
3619   // in modules other than its owning module. We should instead give the
3620   // ASTContext a list of merged definitions for Def.
3621   if (Def->isHidden()) {
3622     // If MergedDef is visible or becomes visible, make the definition visible.
3623     if (!MergedDef->isHidden())
3624       Def->Hidden = false;
3625     else if (getContext().getLangOpts().ModulesLocalVisibility) {
3626       getContext().mergeDefinitionIntoModule(
3627           Def, MergedDef->getImportedOwningModule(),
3628           /*NotifyListeners*/ false);
3629       PendingMergedDefinitionsToDeduplicate.insert(Def);
3630     } else {
3631       auto SubmoduleID = MergedDef->getOwningModuleID();
3632       assert(SubmoduleID && "hidden definition in no module");
3633       HiddenNamesMap[getSubmodule(SubmoduleID)].push_back(Def);
3634     }
3635   }
3636 }
3637
3638 bool ASTReader::loadGlobalIndex() {
3639   if (GlobalIndex)
3640     return false;
3641
3642   if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3643       !Context.getLangOpts().Modules)
3644     return true;
3645
3646   // Try to load the global index.
3647   TriedLoadingGlobalIndex = true;
3648   StringRef ModuleCachePath
3649     = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3650   std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
3651     = GlobalModuleIndex::readIndex(ModuleCachePath);
3652   if (!Result.first)
3653     return true;
3654
3655   GlobalIndex.reset(Result.first);
3656   ModuleMgr.setGlobalIndex(GlobalIndex.get());
3657   return false;
3658 }
3659
3660 bool ASTReader::isGlobalIndexUnavailable() const {
3661   return Context.getLangOpts().Modules && UseGlobalIndex &&
3662          !hasGlobalIndex() && TriedLoadingGlobalIndex;
3663 }
3664
3665 static void updateModuleTimestamp(ModuleFile &MF) {
3666   // Overwrite the timestamp file contents so that file's mtime changes.
3667   std::string TimestampFilename = MF.getTimestampFilename();
3668   std::error_code EC;
3669   llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3670   if (EC)
3671     return;
3672   OS << "Timestamp file\n";
3673 }
3674
3675 /// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3676 /// cursor into the start of the given block ID, returning false on success and
3677 /// true on failure.
3678 static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
3679   while (true) {
3680     llvm::BitstreamEntry Entry = Cursor.advance();
3681     switch (Entry.Kind) {
3682     case llvm::BitstreamEntry::Error:
3683     case llvm::BitstreamEntry::EndBlock:
3684       return true;
3685
3686     case llvm::BitstreamEntry::Record:
3687       // Ignore top-level records.
3688       Cursor.skipRecord(Entry.ID);
3689       break;
3690
3691     case llvm::BitstreamEntry::SubBlock:
3692       if (Entry.ID == BlockID) {
3693         if (Cursor.EnterSubBlock(BlockID))
3694           return true;
3695         // Found it!
3696         return false;
3697       }
3698
3699       if (Cursor.SkipBlock())
3700         return true;
3701     }
3702   }
3703 }
3704
3705 ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
3706                                             ModuleKind Type,
3707                                             SourceLocation ImportLoc,
3708                                             unsigned ClientLoadCapabilities,
3709                                             SmallVectorImpl<ImportedSubmodule> *Imported) {
3710   llvm::SaveAndRestore<SourceLocation>
3711     SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3712
3713   // Defer any pending actions until we get to the end of reading the AST file.
3714   Deserializing AnASTFile(this);
3715
3716   // Bump the generation number.
3717   unsigned PreviousGeneration = incrementGeneration(Context);
3718
3719   unsigned NumModules = ModuleMgr.size();
3720   SmallVector<ImportedModule, 4> Loaded;
3721   switch (ASTReadResult ReadResult =
3722               ReadASTCore(FileName, Type, ImportLoc,
3723                           /*ImportedBy=*/nullptr, Loaded, 0, 0,
3724                           ASTFileSignature(), ClientLoadCapabilities)) {
3725   case Failure:
3726   case Missing:
3727   case OutOfDate:
3728   case VersionMismatch:
3729   case ConfigurationMismatch:
3730   case HadErrors: {
3731     llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3732     for (const ImportedModule &IM : Loaded)
3733       LoadedSet.insert(IM.Mod);
3734
3735     ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet,
3736                             Context.getLangOpts().Modules
3737                                 ? &PP.getHeaderSearchInfo().getModuleMap()
3738                                 : nullptr);
3739
3740     // If we find that any modules are unusable, the global index is going
3741     // to be out-of-date. Just remove it.
3742     GlobalIndex.reset();
3743     ModuleMgr.setGlobalIndex(nullptr);
3744     return ReadResult;
3745   }
3746   case Success:
3747     break;
3748   }
3749
3750   // Here comes stuff that we only do once the entire chain is loaded.
3751
3752   // Load the AST blocks of all of the modules that we loaded.
3753   for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3754                                               MEnd = Loaded.end();
3755        M != MEnd; ++M) {
3756     ModuleFile &F = *M->Mod;
3757
3758     // Read the AST block.
3759     if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3760       return Result;
3761
3762     // Read the extension blocks.
3763     while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3764       if (ASTReadResult Result = ReadExtensionBlock(F))
3765         return Result;
3766     }
3767
3768     // Once read, set the ModuleFile bit base offset and update the size in
3769     // bits of all files we've seen.
3770     F.GlobalBitOffset = TotalModulesSizeInBits;
3771     TotalModulesSizeInBits += F.SizeInBits;
3772     GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3773
3774     // Preload SLocEntries.
3775     for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3776       int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3777       // Load it through the SourceManager and don't call ReadSLocEntry()
3778       // directly because the entry may have already been loaded in which case
3779       // calling ReadSLocEntry() directly would trigger an assertion in
3780       // SourceManager.
3781       SourceMgr.getLoadedSLocEntryByID(Index);
3782     }
3783
3784     // Map the original source file ID into the ID space of the current
3785     // compilation.
3786     if (F.OriginalSourceFileID.isValid()) {
3787       F.OriginalSourceFileID = FileID::get(
3788           F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1);
3789     }
3790
3791     // Preload all the pending interesting identifiers by marking them out of
3792     // date.
3793     for (auto Offset : F.PreloadIdentifierOffsets) {
3794       const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3795           F.IdentifierTableData + Offset);
3796
3797       ASTIdentifierLookupTrait Trait(*this, F);
3798       auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3799       auto Key = Trait.ReadKey(Data, KeyDataLen.first);
3800       auto &II = PP.getIdentifierTable().getOwn(Key);
3801       II.setOutOfDate(true);
3802
3803       // Mark this identifier as being from an AST file so that we can track
3804       // whether we need to serialize it.
3805       markIdentifierFromAST(*this, II);
3806
3807       // Associate the ID with the identifier so that the writer can reuse it.
3808       auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3809       SetIdentifierInfo(ID, &II);
3810     }
3811   }
3812
3813   // Setup the import locations and notify the module manager that we've
3814   // committed to these module files.
3815   for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3816                                               MEnd = Loaded.end();
3817        M != MEnd; ++M) {
3818     ModuleFile &F = *M->Mod;
3819
3820     ModuleMgr.moduleFileAccepted(&F);
3821
3822     // Set the import location.
3823     F.DirectImportLoc = ImportLoc;
3824     // FIXME: We assume that locations from PCH / preamble do not need
3825     // any translation.
3826     if (!M->ImportedBy)
3827       F.ImportLoc = M->ImportLoc;
3828     else
3829       F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
3830   }
3831
3832   if (!Context.getLangOpts().CPlusPlus ||
3833       (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
3834        Type != MK_PrebuiltModule)) {
3835     // Mark all of the identifiers in the identifier table as being out of date,
3836     // so that various accessors know to check the loaded modules when the
3837     // identifier is used.
3838     //
3839     // For C++ modules, we don't need information on many identifiers (just
3840     // those that provide macros or are poisoned), so we mark all of
3841     // the interesting ones via PreloadIdentifierOffsets.
3842     for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3843                                 IdEnd = PP.getIdentifierTable().end();
3844          Id != IdEnd; ++Id)
3845       Id->second->setOutOfDate(true);
3846   }
3847   // Mark selectors as out of date.
3848   for (auto Sel : SelectorGeneration)
3849     SelectorOutOfDate[Sel.first] = true;
3850
3851   // Resolve any unresolved module exports.
3852   for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3853     UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
3854     SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3855     Module *ResolvedMod = getSubmodule(GlobalID);
3856
3857     switch (Unresolved.Kind) {
3858     case UnresolvedModuleRef::Conflict:
3859       if (ResolvedMod) {
3860         Module::Conflict Conflict;
3861         Conflict.Other = ResolvedMod;
3862         Conflict.Message = Unresolved.String.str();
3863         Unresolved.Mod->Conflicts.push_back(Conflict);
3864       }
3865       continue;
3866
3867     case UnresolvedModuleRef::Import:
3868       if (ResolvedMod)
3869         Unresolved.Mod->Imports.insert(ResolvedMod);
3870       continue;
3871
3872     case UnresolvedModuleRef::Export:
3873       if (ResolvedMod || Unresolved.IsWildcard)
3874         Unresolved.Mod->Exports.push_back(
3875           Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3876       continue;
3877     }
3878   }
3879   UnresolvedModuleRefs.clear();
3880
3881   if (Imported)
3882     Imported->append(ImportedModules.begin(),
3883                      ImportedModules.end());
3884
3885   // FIXME: How do we load the 'use'd modules? They may not be submodules.
3886   // Might be unnecessary as use declarations are only used to build the
3887   // module itself.
3888
3889   InitializeContext();
3890
3891   if (SemaObj)
3892     UpdateSema();
3893
3894   if (DeserializationListener)
3895     DeserializationListener->ReaderInitialized(this);
3896
3897   ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3898   if (PrimaryModule.OriginalSourceFileID.isValid()) {
3899     // If this AST file is a precompiled preamble, then set the
3900     // preamble file ID of the source manager to the file source file
3901     // from which the preamble was built.
3902     if (Type == MK_Preamble) {
3903       SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3904     } else if (Type == MK_MainFile) {
3905       SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3906     }
3907   }
3908
3909   // For any Objective-C class definitions we have already loaded, make sure
3910   // that we load any additional categories.
3911   for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3912     loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3913                        ObjCClassesLoaded[I],
3914                        PreviousGeneration);
3915   }
3916
3917   if (PP.getHeaderSearchInfo()
3918           .getHeaderSearchOpts()
3919           .ModulesValidateOncePerBuildSession) {
3920     // Now we are certain that the module and all modules it depends on are
3921     // up to date.  Create or update timestamp files for modules that are
3922     // located in the module cache (not for PCH files that could be anywhere
3923     // in the filesystem).
3924     for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3925       ImportedModule &M = Loaded[I];
3926       if (M.Mod->Kind == MK_ImplicitModule) {
3927         updateModuleTimestamp(*M.Mod);
3928       }
3929     }
3930   }
3931
3932   return Success;
3933 }
3934
3935 static ASTFileSignature readASTFileSignature(StringRef PCH);
3936
3937 /// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3938 static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
3939   return Stream.canSkipToPos(4) &&
3940          Stream.Read(8) == 'C' &&
3941          Stream.Read(8) == 'P' &&
3942          Stream.Read(8) == 'C' &&
3943          Stream.Read(8) == 'H';
3944 }
3945
3946 static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3947   switch (Kind) {
3948   case MK_PCH:
3949     return 0; // PCH
3950   case MK_ImplicitModule:
3951   case MK_ExplicitModule:
3952   case MK_PrebuiltModule:
3953     return 1; // module
3954   case MK_MainFile:
3955   case MK_Preamble:
3956     return 2; // main source file
3957   }
3958   llvm_unreachable("unknown module kind");
3959 }
3960
3961 ASTReader::ASTReadResult
3962 ASTReader::ReadASTCore(StringRef FileName,
3963                        ModuleKind Type,
3964                        SourceLocation ImportLoc,
3965                        ModuleFile *ImportedBy,
3966                        SmallVectorImpl<ImportedModule> &Loaded,
3967                        off_t ExpectedSize, time_t ExpectedModTime,
3968                        ASTFileSignature ExpectedSignature,
3969                        unsigned ClientLoadCapabilities) {
3970   ModuleFile *M;
3971   std::string ErrorStr;
3972   ModuleManager::AddModuleResult AddResult
3973     = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
3974                           getGeneration(), ExpectedSize, ExpectedModTime,
3975                           ExpectedSignature, readASTFileSignature,
3976                           M, ErrorStr);
3977
3978   switch (AddResult) {
3979   case ModuleManager::AlreadyLoaded:
3980     return Success;
3981
3982   case ModuleManager::NewlyLoaded:
3983     // Load module file below.
3984     break;
3985
3986   case ModuleManager::Missing:
3987     // The module file was missing; if the client can handle that, return
3988     // it.
3989     if (ClientLoadCapabilities & ARR_Missing)
3990       return Missing;
3991
3992     // Otherwise, return an error.
3993     Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
3994                                           << FileName << !ErrorStr.empty()
3995                                           << ErrorStr;
3996     return Failure;
3997
3998   case ModuleManager::OutOfDate:
3999     // We couldn't load the module file because it is out-of-date. If the
4000     // client can handle out-of-date, return it.
4001     if (ClientLoadCapabilities & ARR_OutOfDate)
4002       return OutOfDate;
4003
4004     // Otherwise, return an error.
4005     Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
4006                                             << FileName << !ErrorStr.empty()
4007                                             << ErrorStr;
4008     return Failure;
4009   }
4010
4011   assert(M && "Missing module file");
4012
4013   // FIXME: This seems rather a hack. Should CurrentDir be part of the
4014   // module?
4015   if (FileName != "-") {
4016     CurrentDir = llvm::sys::path::parent_path(FileName);
4017     if (CurrentDir.empty()) CurrentDir = ".";
4018   }
4019
4020   ModuleFile &F = *M;
4021   BitstreamCursor &Stream = F.Stream;
4022   Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
4023   F.SizeInBits = F.Buffer->getBufferSize() * 8;
4024
4025   // Sniff for the signature.
4026   if (!startsWithASTFileMagic(Stream)) {
4027     Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
4028                                         << FileName;
4029     return Failure;
4030   }
4031
4032   // This is used for compatibility with older PCH formats.
4033   bool HaveReadControlBlock = false;
4034   while (true) {
4035     llvm::BitstreamEntry Entry = Stream.advance();
4036
4037     switch (Entry.Kind) {
4038     case llvm::BitstreamEntry::Error:
4039     case llvm::BitstreamEntry::Record:
4040     case llvm::BitstreamEntry::EndBlock:
4041       Error("invalid record at top-level of AST file");
4042       return Failure;
4043
4044     case llvm::BitstreamEntry::SubBlock:
4045       break;
4046     }
4047
4048     switch (Entry.ID) {
4049     case CONTROL_BLOCK_ID:
4050       HaveReadControlBlock = true;
4051       switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
4052       case Success:
4053         // Check that we didn't try to load a non-module AST file as a module.
4054         //
4055         // FIXME: Should we also perform the converse check? Loading a module as
4056         // a PCH file sort of works, but it's a bit wonky.
4057         if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
4058              Type == MK_PrebuiltModule) &&
4059             F.ModuleName.empty()) {
4060           auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4061           if (Result != OutOfDate ||
4062               (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4063             Diag(diag::err_module_file_not_module) << FileName;
4064           return Result;
4065         }
4066         break;
4067
4068       case Failure: return Failure;
4069       case Missing: return Missing;
4070       case OutOfDate: return OutOfDate;
4071       case VersionMismatch: return VersionMismatch;
4072       case ConfigurationMismatch: return ConfigurationMismatch;
4073       case HadErrors: return HadErrors;
4074       }
4075       break;
4076
4077     case AST_BLOCK_ID:
4078       if (!HaveReadControlBlock) {
4079         if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
4080           Diag(diag::err_pch_version_too_old);
4081         return VersionMismatch;
4082       }
4083
4084       // Record that we've loaded this module.
4085       Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4086       return Success;
4087
4088     case UNHASHED_CONTROL_BLOCK_ID:
4089       // This block is handled using look-ahead during ReadControlBlock.  We
4090       // shouldn't get here!
4091       Error("malformed block record in AST file");
4092       return Failure;
4093
4094     default:
4095       if (Stream.SkipBlock()) {
4096         Error("malformed block record in AST file");
4097         return Failure;
4098       }
4099       break;
4100     }
4101   }
4102
4103   return Success;
4104 }
4105
4106 ASTReader::ASTReadResult
4107 ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4108                                     unsigned ClientLoadCapabilities) {
4109   const HeaderSearchOptions &HSOpts =
4110       PP.getHeaderSearchInfo().getHeaderSearchOpts();
4111   bool AllowCompatibleConfigurationMismatch =
4112       F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4113
4114   ASTReadResult Result = readUnhashedControlBlockImpl(
4115       &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4116       Listener.get(),
4117       WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4118
4119   // If F was directly imported by another module, it's implicitly validated by
4120   // the importing module.
4121   if (DisableValidation || WasImportedBy ||
4122       (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4123     return Success;
4124
4125   if (Result == Failure) {
4126     Error("malformed block record in AST file");
4127     return Failure;
4128   }
4129
4130   if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
4131     // If this module has already been finalized in the PCMCache, we're stuck
4132     // with it; we can only load a single version of each module.
4133     //
4134     // This can happen when a module is imported in two contexts: in one, as a
4135     // user module; in another, as a system module (due to an import from
4136     // another module marked with the [system] flag).  It usually indicates a
4137     // bug in the module map: this module should also be marked with [system].
4138     //
4139     // If -Wno-system-headers (the default), and the first import is as a
4140     // system module, then validation will fail during the as-user import,
4141     // since -Werror flags won't have been validated.  However, it's reasonable
4142     // to treat this consistently as a system module.
4143     //
4144     // If -Wsystem-headers, the PCM on disk was built with
4145     // -Wno-system-headers, and the first import is as a user module, then
4146     // validation will fail during the as-system import since the PCM on disk
4147     // doesn't guarantee that -Werror was respected.  However, the -Werror
4148     // flags were checked during the initial as-user import.
4149     if (PCMCache.isBufferFinal(F.FileName)) {
4150       Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4151       return Success;
4152     }
4153   }
4154
4155   return Result;
4156 }
4157
4158 ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4159     ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4160     bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4161     bool ValidateDiagnosticOptions) {
4162   // Initialize a stream.
4163   BitstreamCursor Stream(StreamData);
4164
4165   // Sniff for the signature.
4166   if (!startsWithASTFileMagic(Stream))
4167     return Failure;
4168
4169   // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4170   if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4171     return Failure;
4172
4173   // Read all of the records in the options block.
4174   RecordData Record;
4175   ASTReadResult Result = Success;
4176   while (1) {
4177     llvm::BitstreamEntry Entry = Stream.advance();
4178
4179     switch (Entry.Kind) {
4180     case llvm::BitstreamEntry::Error:
4181     case llvm::BitstreamEntry::SubBlock:
4182       return Failure;
4183
4184     case llvm::BitstreamEntry::EndBlock:
4185       return Result;
4186
4187     case llvm::BitstreamEntry::Record:
4188       // The interesting case.
4189       break;
4190     }
4191
4192     // Read and process a record.
4193     Record.clear();
4194     switch (
4195         (UnhashedControlBlockRecordTypes)Stream.readRecord(Entry.ID, Record)) {
4196     case SIGNATURE: {
4197       if (F)
4198         std::copy(Record.begin(), Record.end(), F->Signature.data());
4199       break;
4200     }
4201     case DIAGNOSTIC_OPTIONS: {
4202       bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4203       if (Listener && ValidateDiagnosticOptions &&
4204           !AllowCompatibleConfigurationMismatch &&
4205           ParseDiagnosticOptions(Record, Complain, *Listener))
4206         Result = OutOfDate; // Don't return early.  Read the signature.
4207       break;
4208     }
4209     case DIAG_PRAGMA_MAPPINGS:
4210       if (!F)
4211         break;
4212       if (F->PragmaDiagMappings.empty())
4213         F->PragmaDiagMappings.swap(Record);
4214       else
4215         F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4216                                      Record.begin(), Record.end());
4217       break;
4218     }
4219   }
4220 }
4221
4222 /// Parse a record and blob containing module file extension metadata.
4223 static bool parseModuleFileExtensionMetadata(
4224               const SmallVectorImpl<uint64_t> &Record,
4225               StringRef Blob,
4226               ModuleFileExtensionMetadata &Metadata) {
4227   if (Record.size() < 4) return true;
4228
4229   Metadata.MajorVersion = Record[0];
4230   Metadata.MinorVersion = Record[1];
4231
4232   unsigned BlockNameLen = Record[2];
4233   unsigned UserInfoLen = Record[3];
4234
4235   if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4236
4237   Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4238   Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4239                                   Blob.data() + BlockNameLen + UserInfoLen);
4240   return false;
4241 }
4242
4243 ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4244   BitstreamCursor &Stream = F.Stream;
4245
4246   RecordData Record;
4247   while (true) {
4248     llvm::BitstreamEntry Entry = Stream.advance();
4249     switch (Entry.Kind) {
4250     case llvm::BitstreamEntry::SubBlock:
4251       if (Stream.SkipBlock())
4252         return Failure;
4253
4254       continue;
4255
4256     case llvm::BitstreamEntry::EndBlock:
4257       return Success;
4258
4259     case llvm::BitstreamEntry::Error:
4260       return HadErrors;
4261
4262     case llvm::BitstreamEntry::Record:
4263       break;
4264     }
4265
4266     Record.clear();
4267     StringRef Blob;
4268     unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4269     switch (RecCode) {
4270     case EXTENSION_METADATA: {
4271       ModuleFileExtensionMetadata Metadata;
4272       if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4273         return Failure;
4274
4275       // Find a module file extension with this block name.
4276       auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4277       if (Known == ModuleFileExtensions.end()) break;
4278
4279       // Form a reader.
4280       if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4281                                                              F, Stream)) {
4282         F.ExtensionReaders.push_back(std::move(Reader));
4283       }
4284
4285       break;
4286     }
4287     }
4288   }
4289
4290   return Success;
4291 }
4292
4293 void ASTReader::InitializeContext() {
4294   // If there's a listener, notify them that we "read" the translation unit.
4295   if (DeserializationListener)
4296     DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
4297                                       Context.getTranslationUnitDecl());
4298
4299   // FIXME: Find a better way to deal with collisions between these
4300   // built-in types. Right now, we just ignore the problem.
4301
4302   // Load the special types.
4303   if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4304     if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4305       if (!Context.CFConstantStringTypeDecl)
4306         Context.setCFConstantStringType(GetType(String));
4307     }
4308
4309     if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4310       QualType FileType = GetType(File);
4311       if (FileType.isNull()) {
4312         Error("FILE type is NULL");
4313         return;
4314       }
4315
4316       if (!Context.FILEDecl) {
4317         if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
4318           Context.setFILEDecl(Typedef->getDecl());
4319         else {
4320           const TagType *Tag = FileType->getAs<TagType>();
4321           if (!Tag) {
4322             Error("Invalid FILE type in AST file");
4323             return;
4324           }
4325           Context.setFILEDecl(Tag->getDecl());
4326         }
4327       }
4328     }
4329
4330     if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4331       QualType Jmp_bufType = GetType(Jmp_buf);
4332       if (Jmp_bufType.isNull()) {
4333         Error("jmp_buf type is NULL");
4334         return;
4335       }
4336
4337       if (!Context.jmp_bufDecl) {
4338         if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4339           Context.setjmp_bufDecl(Typedef->getDecl());
4340         else {
4341           const TagType *Tag = Jmp_bufType->getAs<TagType>();
4342           if (!Tag) {
4343             Error("Invalid jmp_buf type in AST file");
4344             return;
4345           }
4346           Context.setjmp_bufDecl(Tag->getDecl());
4347         }
4348       }
4349     }
4350
4351     if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4352       QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4353       if (Sigjmp_bufType.isNull()) {
4354         Error("sigjmp_buf type is NULL");
4355         return;
4356       }
4357
4358       if (!Context.sigjmp_bufDecl) {
4359         if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4360           Context.setsigjmp_bufDecl(Typedef->getDecl());
4361         else {
4362           const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4363           assert(Tag && "Invalid sigjmp_buf type in AST file");
4364           Context.setsigjmp_bufDecl(Tag->getDecl());
4365         }
4366       }
4367     }
4368
4369     if (unsigned ObjCIdRedef
4370           = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4371       if (Context.ObjCIdRedefinitionType.isNull())
4372         Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4373     }
4374
4375     if (unsigned ObjCClassRedef
4376           = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4377       if (Context.ObjCClassRedefinitionType.isNull())
4378         Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4379     }
4380
4381     if (unsigned ObjCSelRedef
4382           = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4383       if (Context.ObjCSelRedefinitionType.isNull())
4384         Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4385     }
4386
4387     if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4388       QualType Ucontext_tType = GetType(Ucontext_t);
4389       if (Ucontext_tType.isNull()) {
4390         Error("ucontext_t type is NULL");
4391         return;
4392       }
4393
4394       if (!Context.ucontext_tDecl) {
4395         if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4396           Context.setucontext_tDecl(Typedef->getDecl());
4397         else {
4398           const TagType *Tag = Ucontext_tType->getAs<TagType>();
4399           assert(Tag && "Invalid ucontext_t type in AST file");
4400           Context.setucontext_tDecl(Tag->getDecl());
4401         }
4402       }
4403     }
4404   }
4405
4406   ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4407
4408   // If there were any CUDA special declarations, deserialize them.
4409   if (!CUDASpecialDeclRefs.empty()) {
4410     assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4411     Context.setcudaConfigureCallDecl(
4412                            cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4413   }
4414
4415   // Re-export any modules that were imported by a non-module AST file.
4416   // FIXME: This does not make macro-only imports visible again.
4417   for (auto &Import : ImportedModules) {
4418     if (Module *Imported = getSubmodule(Import.ID)) {
4419       makeModuleVisible(Imported, Module::AllVisible,
4420                         /*ImportLoc=*/Import.ImportLoc);
4421       if (Import.ImportLoc.isValid())
4422         PP.makeModuleVisible(Imported, Import.ImportLoc);
4423       // FIXME: should we tell Sema to make the module visible too?
4424     }
4425   }
4426   ImportedModules.clear();
4427 }
4428
4429 void ASTReader::finalizeForWriting() {
4430   // Nothing to do for now.
4431 }
4432
4433 /// \brief Reads and return the signature record from \p PCH's control block, or
4434 /// else returns 0.
4435 static ASTFileSignature readASTFileSignature(StringRef PCH) {
4436   BitstreamCursor Stream(PCH);
4437   if (!startsWithASTFileMagic(Stream))
4438     return ASTFileSignature();
4439
4440   // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4441   if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4442     return ASTFileSignature();
4443
4444   // Scan for SIGNATURE inside the diagnostic options block.
4445   ASTReader::RecordData Record;
4446   while (true) {
4447     llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4448     if (Entry.Kind != llvm::BitstreamEntry::Record)
4449       return ASTFileSignature();
4450
4451     Record.clear();
4452     StringRef Blob;
4453     if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4454       return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
4455                 (uint32_t)Record[3], (uint32_t)Record[4]}}};
4456   }
4457 }
4458
4459 /// \brief Retrieve the name of the original source file name
4460 /// directly from the AST file, without actually loading the AST
4461 /// file.
4462 std::string ASTReader::getOriginalSourceFile(
4463     const std::string &ASTFileName, FileManager &FileMgr,
4464     const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
4465   // Open the AST file.
4466   auto Buffer = FileMgr.getBufferForFile(ASTFileName);
4467   if (!Buffer) {
4468     Diags.Report(diag::err_fe_unable_to_read_pch_file)
4469         << ASTFileName << Buffer.getError().message();
4470     return std::string();
4471   }
4472
4473   // Initialize the stream
4474   BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
4475
4476   // Sniff for the signature.
4477   if (!startsWithASTFileMagic(Stream)) {
4478     Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4479     return std::string();
4480   }
4481
4482   // Scan for the CONTROL_BLOCK_ID block.
4483   if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
4484     Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4485     return std::string();
4486   }
4487
4488   // Scan for ORIGINAL_FILE inside the control block.
4489   RecordData Record;
4490   while (true) {
4491     llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4492     if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4493       return std::string();
4494
4495     if (Entry.Kind != llvm::BitstreamEntry::Record) {
4496       Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4497       return std::string();
4498     }
4499
4500     Record.clear();
4501     StringRef Blob;
4502     if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4503       return Blob.str();
4504   }
4505 }
4506
4507 namespace {
4508
4509   class SimplePCHValidator : public ASTReaderListener {
4510     const LangOptions &ExistingLangOpts;
4511     const TargetOptions &ExistingTargetOpts;
4512     const PreprocessorOptions &ExistingPPOpts;
4513     std::string ExistingModuleCachePath;
4514     FileManager &FileMgr;
4515
4516   public:
4517     SimplePCHValidator(const LangOptions &ExistingLangOpts,
4518                        const TargetOptions &ExistingTargetOpts,
4519                        const PreprocessorOptions &ExistingPPOpts,
4520                        StringRef ExistingModuleCachePath,
4521                        FileManager &FileMgr)
4522       : ExistingLangOpts(ExistingLangOpts),
4523         ExistingTargetOpts(ExistingTargetOpts),
4524         ExistingPPOpts(ExistingPPOpts),
4525         ExistingModuleCachePath(ExistingModuleCachePath),
4526         FileMgr(FileMgr)
4527     {
4528     }
4529
4530     bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4531                              bool AllowCompatibleDifferences) override {
4532       return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4533                                   AllowCompatibleDifferences);
4534     }
4535
4536     bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4537                            bool AllowCompatibleDifferences) override {
4538       return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4539                                 AllowCompatibleDifferences);
4540     }
4541
4542     bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4543                                  StringRef SpecificModuleCachePath,
4544                                  bool Complain) override {
4545       return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4546                                       ExistingModuleCachePath,
4547                                       nullptr, ExistingLangOpts);
4548     }
4549
4550     bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4551                                  bool Complain,
4552                                  std::string &SuggestedPredefines) override {
4553       return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
4554                                       SuggestedPredefines, ExistingLangOpts);
4555     }
4556   };
4557
4558 } // end anonymous namespace
4559
4560 bool ASTReader::readASTFileControlBlock(
4561     StringRef Filename, FileManager &FileMgr,
4562     const PCHContainerReader &PCHContainerRdr,
4563     bool FindModuleFileExtensions,
4564     ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
4565   // Open the AST file.
4566   // FIXME: This allows use of the VFS; we do not allow use of the
4567   // VFS when actually loading a module.
4568   auto Buffer = FileMgr.getBufferForFile(Filename);
4569   if (!Buffer) {
4570     return true;
4571   }
4572
4573   // Initialize the stream
4574   StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer);
4575   BitstreamCursor Stream(Bytes);
4576
4577   // Sniff for the signature.
4578   if (!startsWithASTFileMagic(Stream))
4579     return true;
4580
4581   // Scan for the CONTROL_BLOCK_ID block.
4582   if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4583     return true;
4584
4585   bool NeedsInputFiles = Listener.needsInputFileVisitation();
4586   bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
4587   bool NeedsImports = Listener.needsImportVisitation();
4588   BitstreamCursor InputFilesCursor;
4589
4590   RecordData Record;
4591   std::string ModuleDir;
4592   bool DoneWithControlBlock = false;
4593   while (!DoneWithControlBlock) {
4594     llvm::BitstreamEntry Entry = Stream.advance();
4595
4596     switch (Entry.Kind) {
4597     case llvm::BitstreamEntry::SubBlock: {
4598       switch (Entry.ID) {
4599       case OPTIONS_BLOCK_ID: {
4600         std::string IgnoredSuggestedPredefines;
4601         if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4602                              /*AllowCompatibleConfigurationMismatch*/ false,
4603                              Listener, IgnoredSuggestedPredefines) != Success)
4604           return true;
4605         break;
4606       }
4607
4608       case INPUT_FILES_BLOCK_ID:
4609         InputFilesCursor = Stream;
4610         if (Stream.SkipBlock() ||
4611             (NeedsInputFiles &&
4612              ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4613           return true;
4614         break;
4615
4616       default:
4617         if (Stream.SkipBlock())
4618           return true;
4619         break;
4620       }
4621
4622       continue;
4623     }
4624
4625     case llvm::BitstreamEntry::EndBlock:
4626       DoneWithControlBlock = true;
4627       break;
4628
4629     case llvm::BitstreamEntry::Error:
4630       return true;
4631
4632     case llvm::BitstreamEntry::Record:
4633       break;
4634     }
4635
4636     if (DoneWithControlBlock) break;
4637
4638     Record.clear();
4639     StringRef Blob;
4640     unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4641     switch ((ControlRecordTypes)RecCode) {
4642     case METADATA: {
4643       if (Record[0] != VERSION_MAJOR)
4644         return true;
4645
4646       if (Listener.ReadFullVersionInformation(Blob))
4647         return true;
4648
4649       break;
4650     }
4651     case MODULE_NAME:
4652       Listener.ReadModuleName(Blob);
4653       break;
4654     case MODULE_DIRECTORY:
4655       ModuleDir = Blob;
4656       break;
4657     case MODULE_MAP_FILE: {
4658       unsigned Idx = 0;
4659       auto Path = ReadString(Record, Idx);
4660       ResolveImportedPath(Path, ModuleDir);
4661       Listener.ReadModuleMapFile(Path);
4662       break;
4663     }
4664     case INPUT_FILE_OFFSETS: {
4665       if (!NeedsInputFiles)
4666         break;
4667
4668       unsigned NumInputFiles = Record[0];
4669       unsigned NumUserFiles = Record[1];
4670       const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
4671       for (unsigned I = 0; I != NumInputFiles; ++I) {
4672         // Go find this input file.
4673         bool isSystemFile = I >= NumUserFiles;
4674
4675         if (isSystemFile && !NeedsSystemInputFiles)
4676           break; // the rest are system input files
4677
4678         BitstreamCursor &Cursor = InputFilesCursor;
4679         SavedStreamPosition SavedPosition(Cursor);
4680         Cursor.JumpToBit(InputFileOffs[I]);
4681
4682         unsigned Code = Cursor.ReadCode();
4683         RecordData Record;
4684         StringRef Blob;
4685         bool shouldContinue = false;
4686         switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4687         case INPUT_FILE:
4688           bool Overridden = static_cast<bool>(Record[3]);
4689           std::string Filename = Blob;
4690           ResolveImportedPath(Filename, ModuleDir);
4691           shouldContinue = Listener.visitInputFile(
4692               Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
4693           break;
4694         }
4695         if (!shouldContinue)
4696           break;
4697       }
4698       break;
4699     }
4700
4701     case IMPORTS: {
4702       if (!NeedsImports)
4703         break;
4704
4705       unsigned Idx = 0, N = Record.size();
4706       while (Idx < N) {
4707         // Read information about the AST file.
4708         Idx += 5; // ImportLoc, Size, ModTime, Signature
4709         std::string Filename = ReadString(Record, Idx);
4710         ResolveImportedPath(Filename, ModuleDir);
4711         Listener.visitImport(Filename);
4712       }
4713       break;
4714     }
4715
4716     default:
4717       // No other validation to perform.
4718       break;
4719     }
4720   }
4721
4722   // Look for module file extension blocks, if requested.
4723   if (FindModuleFileExtensions) {
4724     BitstreamCursor SavedStream = Stream;
4725     while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4726       bool DoneWithExtensionBlock = false;
4727       while (!DoneWithExtensionBlock) {
4728        llvm::BitstreamEntry Entry = Stream.advance();
4729
4730        switch (Entry.Kind) {
4731        case llvm::BitstreamEntry::SubBlock:
4732          if (Stream.SkipBlock())
4733            return true;
4734
4735          continue;
4736
4737        case llvm::BitstreamEntry::EndBlock:
4738          DoneWithExtensionBlock = true;
4739          continue;
4740
4741        case llvm::BitstreamEntry::Error:
4742          return true;
4743
4744        case llvm::BitstreamEntry::Record:
4745          break;
4746        }
4747
4748        Record.clear();
4749        StringRef Blob;
4750        unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4751        switch (RecCode) {
4752        case EXTENSION_METADATA: {
4753          ModuleFileExtensionMetadata Metadata;
4754          if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4755            return true;
4756
4757          Listener.readModuleFileExtension(Metadata);
4758          break;
4759        }
4760        }
4761       }
4762     }
4763     Stream = SavedStream;
4764   }
4765
4766   // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4767   if (readUnhashedControlBlockImpl(
4768           nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
4769           /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
4770           ValidateDiagnosticOptions) != Success)
4771     return true;
4772
4773   return false;
4774 }
4775
4776 bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
4777                                     const PCHContainerReader &PCHContainerRdr,
4778                                     const LangOptions &LangOpts,
4779                                     const TargetOptions &TargetOpts,
4780                                     const PreprocessorOptions &PPOpts,
4781                                     StringRef ExistingModuleCachePath) {
4782   SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4783                                ExistingModuleCachePath, FileMgr);
4784   return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
4785                                   /*FindModuleFileExtensions=*/false,
4786                                   validator,
4787                                   /*ValidateDiagnosticOptions=*/true);
4788 }
4789
4790 ASTReader::ASTReadResult
4791 ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
4792   // Enter the submodule block.
4793   if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4794     Error("malformed submodule block record in AST file");
4795     return Failure;
4796   }
4797
4798   ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4799   bool First = true;
4800   Module *CurrentModule = nullptr;
4801   Module::ModuleKind ModuleKind = Module::ModuleMapModule;
4802   RecordData Record;
4803   while (true) {
4804     llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
4805
4806     switch (Entry.Kind) {
4807     case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4808     case llvm::BitstreamEntry::Error:
4809       Error("malformed block record in AST file");
4810       return Failure;
4811     case llvm::BitstreamEntry::EndBlock:
4812       return Success;
4813     case llvm::BitstreamEntry::Record:
4814       // The interesting case.
4815       break;
4816     }
4817
4818     // Read a record.
4819     StringRef Blob;
4820     Record.clear();
4821     auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4822
4823     if ((Kind == SUBMODULE_METADATA) != First) {
4824       Error("submodule metadata record should be at beginning of block");
4825       return Failure;
4826     }
4827     First = false;
4828
4829     // Submodule information is only valid if we have a current module.
4830     // FIXME: Should we error on these cases?
4831     if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4832         Kind != SUBMODULE_DEFINITION)
4833       continue;
4834
4835     switch (Kind) {
4836     default:  // Default behavior: ignore.
4837       break;
4838
4839     case SUBMODULE_DEFINITION: {
4840       if (Record.size() < 8) {
4841         Error("malformed module definition");
4842         return Failure;
4843       }
4844
4845       StringRef Name = Blob;
4846       unsigned Idx = 0;
4847       SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4848       SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4849       bool IsFramework = Record[Idx++];
4850       bool IsExplicit = Record[Idx++];
4851       bool IsSystem = Record[Idx++];
4852       bool IsExternC = Record[Idx++];
4853       bool InferSubmodules = Record[Idx++];
4854       bool InferExplicitSubmodules = Record[Idx++];
4855       bool InferExportWildcard = Record[Idx++];
4856       bool ConfigMacrosExhaustive = Record[Idx++];
4857
4858       Module *ParentModule = nullptr;
4859       if (Parent)
4860         ParentModule = getSubmodule(Parent);
4861
4862       // Retrieve this (sub)module from the module map, creating it if
4863       // necessary.
4864       CurrentModule =
4865           ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
4866               .first;
4867
4868       // FIXME: set the definition loc for CurrentModule, or call
4869       // ModMap.setInferredModuleAllowedBy()
4870
4871       SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4872       if (GlobalIndex >= SubmodulesLoaded.size() ||
4873           SubmodulesLoaded[GlobalIndex]) {
4874         Error("too many submodules");
4875         return Failure;
4876       }
4877
4878       if (!ParentModule) {
4879         if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4880           if (CurFile != F.File) {
4881             if (!Diags.isDiagnosticInFlight()) {
4882               Diag(diag::err_module_file_conflict)
4883                 << CurrentModule->getTopLevelModuleName()
4884                 << CurFile->getName()
4885                 << F.File->getName();
4886             }
4887             return Failure;
4888           }
4889         }
4890
4891         CurrentModule->setASTFile(F.File);
4892       }
4893
4894       CurrentModule->Kind = ModuleKind;
4895       CurrentModule->Signature = F.Signature;
4896       CurrentModule->IsFromModuleFile = true;
4897       CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
4898       CurrentModule->IsExternC = IsExternC;
4899       CurrentModule->InferSubmodules = InferSubmodules;
4900       CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4901       CurrentModule->InferExportWildcard = InferExportWildcard;
4902       CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
4903       if (DeserializationListener)
4904         DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4905
4906       SubmodulesLoaded[GlobalIndex] = CurrentModule;
4907
4908       // Clear out data that will be replaced by what is in the module file.
4909       CurrentModule->LinkLibraries.clear();
4910       CurrentModule->ConfigMacros.clear();
4911       CurrentModule->UnresolvedConflicts.clear();
4912       CurrentModule->Conflicts.clear();
4913
4914       // The module is available unless it's missing a requirement; relevant
4915       // requirements will be (re-)added by SUBMODULE_REQUIRES records.
4916       // Missing headers that were present when the module was built do not
4917       // make it unavailable -- if we got this far, this must be an explicitly
4918       // imported module file.
4919       CurrentModule->Requirements.clear();
4920       CurrentModule->MissingHeaders.clear();
4921       CurrentModule->IsMissingRequirement =
4922           ParentModule && ParentModule->IsMissingRequirement;
4923       CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
4924       break;
4925     }
4926
4927     case SUBMODULE_UMBRELLA_HEADER: {
4928       std::string Filename = Blob;
4929       ResolveImportedPath(F, Filename);
4930       if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
4931         if (!CurrentModule->getUmbrellaHeader())
4932           ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4933         else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
4934           if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4935             Error("mismatched umbrella headers in submodule");
4936           return OutOfDate;
4937         }
4938       }
4939       break;
4940     }
4941
4942     case SUBMODULE_HEADER:
4943     case SUBMODULE_EXCLUDED_HEADER:
4944     case SUBMODULE_PRIVATE_HEADER:
4945       // We lazily associate headers with their modules via the HeaderInfo table.
4946       // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4947       // of complete filenames or remove it entirely.
4948       break;
4949
4950     case SUBMODULE_TEXTUAL_HEADER:
4951     case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4952       // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4953       // them here.
4954       break;
4955
4956     case SUBMODULE_TOPHEADER: {
4957       CurrentModule->addTopHeaderFilename(Blob);
4958       break;
4959     }
4960
4961     case SUBMODULE_UMBRELLA_DIR: {
4962       std::string Dirname = Blob;
4963       ResolveImportedPath(F, Dirname);
4964       if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
4965         if (!CurrentModule->getUmbrellaDir())
4966           ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4967         else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
4968           if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4969             Error("mismatched umbrella directories in submodule");
4970           return OutOfDate;
4971         }
4972       }
4973       break;
4974     }
4975
4976     case SUBMODULE_METADATA: {
4977       F.BaseSubmoduleID = getTotalNumSubmodules();
4978       F.LocalNumSubmodules = Record[0];
4979       unsigned LocalBaseSubmoduleID = Record[1];
4980       if (F.LocalNumSubmodules > 0) {
4981         // Introduce the global -> local mapping for submodules within this
4982         // module.
4983         GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4984
4985         // Introduce the local -> global mapping for submodules within this
4986         // module.
4987         F.SubmoduleRemap.insertOrReplace(
4988           std::make_pair(LocalBaseSubmoduleID,
4989                          F.BaseSubmoduleID - LocalBaseSubmoduleID));
4990
4991         SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4992       }
4993       ModuleKind = (Module::ModuleKind)Record[2];
4994       break;
4995     }
4996
4997     case SUBMODULE_IMPORTS: {
4998       for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
4999         UnresolvedModuleRef Unresolved;
5000         Unresolved.File = &F;
5001         Unresolved.Mod = CurrentModule;
5002         Unresolved.ID = Record[Idx];
5003         Unresolved.Kind = UnresolvedModuleRef::Import;
5004         Unresolved.IsWildcard = false;
5005         UnresolvedModuleRefs.push_back(Unresolved);
5006       }
5007       break;
5008     }
5009
5010     case SUBMODULE_EXPORTS: {
5011       for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
5012         UnresolvedModuleRef Unresolved;
5013         Unresolved.File = &F;
5014         Unresolved.Mod = CurrentModule;
5015         Unresolved.ID = Record[Idx];
5016         Unresolved.Kind = UnresolvedModuleRef::Export;
5017         Unresolved.IsWildcard = Record[Idx + 1];
5018         UnresolvedModuleRefs.push_back(Unresolved);
5019       }
5020
5021       // Once we've loaded the set of exports, there's no reason to keep
5022       // the parsed, unresolved exports around.
5023       CurrentModule->UnresolvedExports.clear();
5024       break;
5025     }
5026     case SUBMODULE_REQUIRES: {
5027       CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
5028                                     Context.getTargetInfo());
5029       break;
5030     }
5031
5032     case SUBMODULE_LINK_LIBRARY:
5033       CurrentModule->LinkLibraries.push_back(
5034                                          Module::LinkLibrary(Blob, Record[0]));
5035       break;
5036
5037     case SUBMODULE_CONFIG_MACRO:
5038       CurrentModule->ConfigMacros.push_back(Blob.str());
5039       break;
5040
5041     case SUBMODULE_CONFLICT: {
5042       UnresolvedModuleRef Unresolved;
5043       Unresolved.File = &F;
5044       Unresolved.Mod = CurrentModule;
5045       Unresolved.ID = Record[0];
5046       Unresolved.Kind = UnresolvedModuleRef::Conflict;
5047       Unresolved.IsWildcard = false;
5048       Unresolved.String = Blob;
5049       UnresolvedModuleRefs.push_back(Unresolved);
5050       break;
5051     }
5052
5053     case SUBMODULE_INITIALIZERS:
5054       SmallVector<uint32_t, 16> Inits;
5055       for (auto &ID : Record)
5056         Inits.push_back(getGlobalDeclID(F, ID));
5057       Context.addLazyModuleInitializers(CurrentModule, Inits);
5058       break;
5059     }
5060   }
5061 }
5062
5063 /// \brief Parse the record that corresponds to a LangOptions data
5064 /// structure.
5065 ///
5066 /// This routine parses the language options from the AST file and then gives
5067 /// them to the AST listener if one is set.
5068 ///
5069 /// \returns true if the listener deems the file unacceptable, false otherwise.
5070 bool ASTReader::ParseLanguageOptions(const RecordData &Record,
5071                                      bool Complain,
5072                                      ASTReaderListener &Listener,
5073                                      bool AllowCompatibleDifferences) {
5074   LangOptions LangOpts;
5075   unsigned Idx = 0;
5076 #define LANGOPT(Name, Bits, Default, Description) \
5077   LangOpts.Name = Record[Idx++];
5078 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
5079   LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
5080 #include "clang/Basic/LangOptions.def"
5081 #define SANITIZER(NAME, ID)                                                    \
5082   LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
5083 #include "clang/Basic/Sanitizers.def"
5084
5085   for (unsigned N = Record[Idx++]; N; --N)
5086     LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
5087
5088   ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
5089   VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
5090   LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
5091
5092   LangOpts.CurrentModule = ReadString(Record, Idx);
5093
5094   // Comment options.
5095   for (unsigned N = Record[Idx++]; N; --N) {
5096     LangOpts.CommentOpts.BlockCommandNames.push_back(
5097       ReadString(Record, Idx));
5098   }
5099   LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
5100
5101   // OpenMP offloading options.
5102   for (unsigned N = Record[Idx++]; N; --N) {
5103     LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
5104   }
5105
5106   LangOpts.OMPHostIRFile = ReadString(Record, Idx);
5107
5108   return Listener.ReadLanguageOptions(LangOpts, Complain,
5109                                       AllowCompatibleDifferences);
5110 }
5111
5112 bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
5113                                    ASTReaderListener &Listener,
5114                                    bool AllowCompatibleDifferences) {
5115   unsigned Idx = 0;
5116   TargetOptions TargetOpts;
5117   TargetOpts.Triple = ReadString(Record, Idx);
5118   TargetOpts.CPU = ReadString(Record, Idx);
5119   TargetOpts.ABI = ReadString(Record, Idx);
5120   for (unsigned N = Record[Idx++]; N; --N) {
5121     TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
5122   }
5123   for (unsigned N = Record[Idx++]; N; --N) {
5124     TargetOpts.Features.push_back(ReadString(Record, Idx));
5125   }
5126
5127   return Listener.ReadTargetOptions(TargetOpts, Complain,
5128                                     AllowCompatibleDifferences);
5129 }
5130
5131 bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
5132                                        ASTReaderListener &Listener) {
5133   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
5134   unsigned Idx = 0;
5135 #define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
5136 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
5137   DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
5138 #include "clang/Basic/DiagnosticOptions.def"
5139
5140   for (unsigned N = Record[Idx++]; N; --N)
5141     DiagOpts->Warnings.push_back(ReadString(Record, Idx));
5142   for (unsigned N = Record[Idx++]; N; --N)
5143     DiagOpts->Remarks.push_back(ReadString(Record, Idx));
5144
5145   return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
5146 }
5147
5148 bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
5149                                        ASTReaderListener &Listener) {
5150   FileSystemOptions FSOpts;
5151   unsigned Idx = 0;
5152   FSOpts.WorkingDir = ReadString(Record, Idx);
5153   return Listener.ReadFileSystemOptions(FSOpts, Complain);
5154 }
5155
5156 bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
5157                                          bool Complain,
5158                                          ASTReaderListener &Listener) {
5159   HeaderSearchOptions HSOpts;
5160   unsigned Idx = 0;
5161   HSOpts.Sysroot = ReadString(Record, Idx);
5162
5163   // Include entries.
5164   for (unsigned N = Record[Idx++]; N; --N) {
5165     std::string Path = ReadString(Record, Idx);
5166     frontend::IncludeDirGroup Group
5167       = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
5168     bool IsFramework = Record[Idx++];
5169     bool IgnoreSysRoot = Record[Idx++];
5170     HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
5171                                     IgnoreSysRoot);
5172   }
5173
5174   // System header prefixes.
5175   for (unsigned N = Record[Idx++]; N; --N) {
5176     std::string Prefix = ReadString(Record, Idx);
5177     bool IsSystemHeader = Record[Idx++];
5178     HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
5179   }
5180
5181   HSOpts.ResourceDir = ReadString(Record, Idx);
5182   HSOpts.ModuleCachePath = ReadString(Record, Idx);
5183   HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
5184   HSOpts.DisableModuleHash = Record[Idx++];
5185   HSOpts.UseBuiltinIncludes = Record[Idx++];
5186   HSOpts.UseStandardSystemIncludes = Record[Idx++];
5187   HSOpts.UseStandardCXXIncludes = Record[Idx++];
5188   HSOpts.UseLibcxx = Record[Idx++];
5189   std::string SpecificModuleCachePath = ReadString(Record, Idx);
5190
5191   return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5192                                           Complain);
5193 }
5194
5195 bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5196                                          bool Complain,
5197                                          ASTReaderListener &Listener,
5198                                          std::string &SuggestedPredefines) {
5199   PreprocessorOptions PPOpts;
5200   unsigned Idx = 0;
5201
5202   // Macro definitions/undefs
5203   for (unsigned N = Record[Idx++]; N; --N) {
5204     std::string Macro = ReadString(Record, Idx);
5205     bool IsUndef = Record[Idx++];
5206     PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5207   }
5208
5209   // Includes
5210   for (unsigned N = Record[Idx++]; N; --N) {
5211     PPOpts.Includes.push_back(ReadString(Record, Idx));
5212   }
5213
5214   // Macro Includes
5215   for (unsigned N = Record[Idx++]; N; --N) {
5216     PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5217   }
5218
5219   PPOpts.UsePredefines = Record[Idx++];
5220   PPOpts.DetailedRecord = Record[Idx++];
5221   PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
5222   PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
5223   PPOpts.ObjCXXARCStandardLibrary =
5224     static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5225   SuggestedPredefines.clear();
5226   return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5227                                           SuggestedPredefines);
5228 }
5229
5230 std::pair<ModuleFile *, unsigned>
5231 ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5232   GlobalPreprocessedEntityMapType::iterator
5233   I = GlobalPreprocessedEntityMap.find(GlobalIndex);
5234   assert(I != GlobalPreprocessedEntityMap.end() &&
5235          "Corrupted global preprocessed entity map");
5236   ModuleFile *M = I->second;
5237   unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5238   return std::make_pair(M, LocalIndex);
5239 }
5240
5241 llvm::iterator_range<PreprocessingRecord::iterator>
5242 ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5243   if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5244     return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5245                                              Mod.NumPreprocessedEntities);
5246
5247   return llvm::make_range(PreprocessingRecord::iterator(),
5248                           PreprocessingRecord::iterator());
5249 }
5250
5251 llvm::iterator_range<ASTReader::ModuleDeclIterator>
5252 ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
5253   return llvm::make_range(
5254       ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5255       ModuleDeclIterator(this, &Mod,
5256                          Mod.FileSortedDecls + Mod.NumFileSortedDecls));
5257 }
5258
5259 PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5260   PreprocessedEntityID PPID = Index+1;
5261   std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5262   ModuleFile &M = *PPInfo.first;
5263   unsigned LocalIndex = PPInfo.second;
5264   const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5265
5266   if (!PP.getPreprocessingRecord()) {
5267     Error("no preprocessing record");
5268     return nullptr;
5269   }
5270
5271   SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
5272   M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
5273
5274   llvm::BitstreamEntry Entry =
5275     M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5276   if (Entry.Kind != llvm::BitstreamEntry::Record)
5277     return nullptr;
5278
5279   // Read the record.
5280   SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5281                     TranslateSourceLocation(M, PPOffs.getEnd()));
5282   PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
5283   StringRef Blob;
5284   RecordData Record;
5285   PreprocessorDetailRecordTypes RecType =
5286     (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
5287                                           Entry.ID, Record, &Blob);
5288   switch (RecType) {
5289   case PPD_MACRO_EXPANSION: {
5290     bool isBuiltin = Record[0];
5291     IdentifierInfo *Name = nullptr;
5292     MacroDefinitionRecord *Def = nullptr;
5293     if (isBuiltin)
5294       Name = getLocalIdentifier(M, Record[1]);
5295     else {
5296       PreprocessedEntityID GlobalID =
5297           getGlobalPreprocessedEntityID(M, Record[1]);
5298       Def = cast<MacroDefinitionRecord>(
5299           PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
5300     }
5301
5302     MacroExpansion *ME;
5303     if (isBuiltin)
5304       ME = new (PPRec) MacroExpansion(Name, Range);
5305     else
5306       ME = new (PPRec) MacroExpansion(Def, Range);
5307
5308     return ME;
5309   }
5310
5311   case PPD_MACRO_DEFINITION: {
5312     // Decode the identifier info and then check again; if the macro is
5313     // still defined and associated with the identifier,
5314     IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
5315     MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
5316
5317     if (DeserializationListener)
5318       DeserializationListener->MacroDefinitionRead(PPID, MD);
5319
5320     return MD;
5321   }
5322
5323   case PPD_INCLUSION_DIRECTIVE: {
5324     const char *FullFileNameStart = Blob.data() + Record[0];
5325     StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
5326     const FileEntry *File = nullptr;
5327     if (!FullFileName.empty())
5328       File = PP.getFileManager().getFile(FullFileName);
5329
5330     // FIXME: Stable encoding
5331     InclusionDirective::InclusionKind Kind
5332       = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5333     InclusionDirective *ID
5334       = new (PPRec) InclusionDirective(PPRec, Kind,
5335                                        StringRef(Blob.data(), Record[0]),
5336                                        Record[1], Record[3],
5337                                        File,
5338                                        Range);
5339     return ID;
5340   }
5341   }
5342
5343   llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5344 }
5345
5346 /// \brief \arg SLocMapI points at a chunk of a module that contains no
5347 /// preprocessed entities or the entities it contains are not the ones we are
5348 /// looking for. Find the next module that contains entities and return the ID
5349 /// of the first entry.
5350 PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5351                        GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5352   ++SLocMapI;
5353   for (GlobalSLocOffsetMapType::const_iterator
5354          EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5355     ModuleFile &M = *SLocMapI->second;
5356     if (M.NumPreprocessedEntities)
5357       return M.BasePreprocessedEntityID;
5358   }
5359
5360   return getTotalNumPreprocessedEntities();
5361 }
5362
5363 namespace {
5364
5365 struct PPEntityComp {
5366   const ASTReader &Reader;
5367   ModuleFile &M;
5368
5369   PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
5370
5371   bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5372     SourceLocation LHS = getLoc(L);
5373     SourceLocation RHS = getLoc(R);
5374     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5375   }
5376
5377   bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5378     SourceLocation LHS = getLoc(L);
5379     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5380   }
5381
5382   bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5383     SourceLocation RHS = getLoc(R);
5384     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5385   }
5386
5387   SourceLocation getLoc(const PPEntityOffset &PPE) const {
5388     return Reader.TranslateSourceLocation(M, PPE.getBegin());
5389   }
5390 };
5391
5392 } // end anonymous namespace
5393
5394 PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5395                                                        bool EndsAfter) const {
5396   if (SourceMgr.isLocalSourceLocation(Loc))
5397     return getTotalNumPreprocessedEntities();
5398
5399   GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5400       SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
5401   assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5402          "Corrupted global sloc offset map");
5403
5404   if (SLocMapI->second->NumPreprocessedEntities == 0)
5405     return findNextPreprocessedEntity(SLocMapI);
5406
5407   ModuleFile &M = *SLocMapI->second;
5408   typedef const PPEntityOffset *pp_iterator;
5409   pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5410   pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5411
5412   size_t Count = M.NumPreprocessedEntities;
5413   size_t Half;
5414   pp_iterator First = pp_begin;
5415   pp_iterator PPI;
5416
5417   if (EndsAfter) {
5418     PPI = std::upper_bound(pp_begin, pp_end, Loc,
5419                            PPEntityComp(*this, M));
5420   } else {
5421     // Do a binary search manually instead of using std::lower_bound because
5422     // The end locations of entities may be unordered (when a macro expansion
5423     // is inside another macro argument), but for this case it is not important
5424     // whether we get the first macro expansion or its containing macro.
5425     while (Count > 0) {
5426       Half = Count / 2;
5427       PPI = First;
5428       std::advance(PPI, Half);
5429       if (SourceMgr.isBeforeInTranslationUnit(
5430               TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
5431         First = PPI;
5432         ++First;
5433         Count = Count - Half - 1;
5434       } else
5435         Count = Half;
5436     }
5437   }
5438
5439   if (PPI == pp_end)
5440     return findNextPreprocessedEntity(SLocMapI);
5441
5442   return M.BasePreprocessedEntityID + (PPI - pp_begin);
5443 }
5444
5445 /// \brief Returns a pair of [Begin, End) indices of preallocated
5446 /// preprocessed entities that \arg Range encompasses.
5447 std::pair<unsigned, unsigned>
5448     ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5449   if (Range.isInvalid())
5450     return std::make_pair(0,0);
5451   assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5452
5453   PreprocessedEntityID BeginID =
5454       findPreprocessedEntity(Range.getBegin(), false);
5455   PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
5456   return std::make_pair(BeginID, EndID);
5457 }
5458
5459 /// \brief Optionally returns true or false if the preallocated preprocessed
5460 /// entity with index \arg Index came from file \arg FID.
5461 Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
5462                                                              FileID FID) {
5463   if (FID.isInvalid())
5464     return false;
5465
5466   std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5467   ModuleFile &M = *PPInfo.first;
5468   unsigned LocalIndex = PPInfo.second;
5469   const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5470
5471   SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
5472   if (Loc.isInvalid())
5473     return false;
5474
5475   if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5476     return true;
5477   else
5478     return false;
5479 }
5480
5481 namespace {
5482
5483   /// \brief Visitor used to search for information about a header file.
5484   class HeaderFileInfoVisitor {
5485     const FileEntry *FE;
5486
5487     Optional<HeaderFileInfo> HFI;
5488
5489   public:
5490     explicit HeaderFileInfoVisitor(const FileEntry *FE)
5491       : FE(FE) { }
5492
5493     bool operator()(ModuleFile &M) {
5494       HeaderFileInfoLookupTable *Table
5495         = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5496       if (!Table)
5497         return false;
5498
5499       // Look in the on-disk hash table for an entry for this file name.
5500       HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
5501       if (Pos == Table->end())
5502         return false;
5503
5504       HFI = *Pos;
5505       return true;
5506     }
5507
5508     Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
5509   };
5510
5511 } // end anonymous namespace
5512
5513 HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
5514   HeaderFileInfoVisitor Visitor(FE);
5515   ModuleMgr.visit(Visitor);
5516   if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
5517     return *HFI;
5518
5519   return HeaderFileInfo();
5520 }
5521
5522 void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
5523   using DiagState = DiagnosticsEngine::DiagState;
5524   SmallVector<DiagState *, 32> DiagStates;
5525
5526   for (ModuleFile &F : ModuleMgr) {
5527     unsigned Idx = 0;
5528     auto &Record = F.PragmaDiagMappings;
5529     if (Record.empty())
5530       continue;
5531
5532     DiagStates.clear();
5533
5534     auto ReadDiagState =
5535         [&](const DiagState &BasedOn, SourceLocation Loc,
5536             bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
5537       unsigned BackrefID = Record[Idx++];
5538       if (BackrefID != 0)
5539         return DiagStates[BackrefID - 1];
5540
5541       // A new DiagState was created here.
5542       Diag.DiagStates.push_back(BasedOn);
5543       DiagState *NewState = &Diag.DiagStates.back();
5544       DiagStates.push_back(NewState);
5545       unsigned Size = Record[Idx++];
5546       assert(Idx + Size * 2 <= Record.size() &&
5547              "Invalid data, not enough diag/map pairs");
5548       while (Size--) {
5549         unsigned DiagID = Record[Idx++];
5550         DiagnosticMapping NewMapping =
5551             DiagnosticMapping::deserialize(Record[Idx++]);
5552         if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
5553           continue;
5554
5555         DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
5556
5557         // If this mapping was specified as a warning but the severity was
5558         // upgraded due to diagnostic settings, simulate the current diagnostic
5559         // settings (and use a warning).
5560         if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
5561           NewMapping.setSeverity(diag::Severity::Warning);
5562           NewMapping.setUpgradedFromWarning(false);
5563         }
5564
5565         Mapping = NewMapping;
5566       }
5567       return NewState;
5568     };
5569
5570     // Read the first state.
5571     DiagState *FirstState;
5572     if (F.Kind == MK_ImplicitModule) {
5573       // Implicitly-built modules are reused with different diagnostic
5574       // settings.  Use the initial diagnostic state from Diag to simulate this
5575       // compilation's diagnostic settings.
5576       FirstState = Diag.DiagStatesByLoc.FirstDiagState;
5577       DiagStates.push_back(FirstState);
5578
5579       // Skip the initial diagnostic state from the serialized module.
5580       assert(Record[1] == 0 &&
5581              "Invalid data, unexpected backref in initial state");
5582       Idx = 3 + Record[2] * 2;
5583       assert(Idx < Record.size() &&
5584              "Invalid data, not enough state change pairs in initial state");
5585     } else if (F.isModule()) {
5586       // For an explicit module, preserve the flags from the module build
5587       // command line (-w, -Weverything, -Werror, ...) along with any explicit
5588       // -Wblah flags.
5589       unsigned Flags = Record[Idx++];
5590       DiagState Initial;
5591       Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
5592       Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
5593       Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
5594       Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
5595       Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
5596       Initial.ExtBehavior = (diag::Severity)Flags;
5597       FirstState = ReadDiagState(Initial, SourceLocation(), true);
5598
5599       // Set up the root buffer of the module to start with the initial
5600       // diagnostic state of the module itself, to cover files that contain no
5601       // explicit transitions (for which we did not serialize anything).
5602       Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
5603           .StateTransitions.push_back({FirstState, 0});
5604     } else {
5605       // For prefix ASTs, start with whatever the user configured on the
5606       // command line.
5607       Idx++; // Skip flags.
5608       FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState,
5609                                  SourceLocation(), false);
5610     }
5611
5612     // Read the state transitions.
5613     unsigned NumLocations = Record[Idx++];
5614     while (NumLocations--) {
5615       assert(Idx < Record.size() &&
5616              "Invalid data, missing pragma diagnostic states");
5617       SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
5618       auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
5619       assert(IDAndOffset.second == 0 && "not a start location for a FileID");
5620       unsigned Transitions = Record[Idx++];
5621
5622       // Note that we don't need to set up Parent/ParentOffset here, because
5623       // we won't be changing the diagnostic state within imported FileIDs
5624       // (other than perhaps appending to the main source file, which has no
5625       // parent).
5626       auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
5627       F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
5628       for (unsigned I = 0; I != Transitions; ++I) {
5629         unsigned Offset = Record[Idx++];
5630         auto *State =
5631             ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
5632         F.StateTransitions.push_back({State, Offset});
5633       }
5634     }
5635
5636     // Read the final state.
5637     assert(Idx < Record.size() &&
5638            "Invalid data, missing final pragma diagnostic state");
5639     SourceLocation CurStateLoc =
5640         ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5641     auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
5642
5643     if (!F.isModule()) {
5644       Diag.DiagStatesByLoc.CurDiagState = CurState;
5645       Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
5646
5647       // Preserve the property that the imaginary root file describes the
5648       // current state.
5649       auto &T = Diag.DiagStatesByLoc.Files[FileID()].StateTransitions;
5650       if (T.empty())
5651         T.push_back({CurState, 0});
5652       else
5653         T[0].State = CurState;
5654     }
5655
5656     // Don't try to read these mappings again.
5657     Record.clear();
5658   }
5659 }
5660
5661 /// \brief Get the correct cursor and offset for loading a type.
5662 ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5663   GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5664   assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5665   ModuleFile *M = I->second;
5666   return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5667 }
5668
5669 /// \brief Read and return the type with the given index..
5670 ///
5671 /// The index is the type ID, shifted and minus the number of predefs. This
5672 /// routine actually reads the record corresponding to the type at the given
5673 /// location. It is a helper routine for GetType, which deals with reading type
5674 /// IDs.
5675 QualType ASTReader::readTypeRecord(unsigned Index) {
5676   RecordLocation Loc = TypeCursorForIndex(Index);
5677   BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
5678
5679   // Keep track of where we are in the stream, then jump back there
5680   // after reading this type.
5681   SavedStreamPosition SavedPosition(DeclsCursor);
5682
5683   ReadingKindTracker ReadingKind(Read_Type, *this);
5684
5685   // Note that we are loading a type record.
5686   Deserializing AType(this);
5687
5688   unsigned Idx = 0;
5689   DeclsCursor.JumpToBit(Loc.Offset);
5690   RecordData Record;
5691   unsigned Code = DeclsCursor.ReadCode();
5692   switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
5693   case TYPE_EXT_QUAL: {
5694     if (Record.size() != 2) {
5695       Error("Incorrect encoding of extended qualifier type");
5696       return QualType();
5697     }
5698     QualType Base = readType(*Loc.F, Record, Idx);
5699     Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5700     return Context.getQualifiedType(Base, Quals);
5701   }
5702
5703   case TYPE_COMPLEX: {
5704     if (Record.size() != 1) {
5705       Error("Incorrect encoding of complex type");
5706       return QualType();
5707     }
5708     QualType ElemType = readType(*Loc.F, Record, Idx);
5709     return Context.getComplexType(ElemType);
5710   }
5711
5712   case TYPE_POINTER: {
5713     if (Record.size() != 1) {
5714       Error("Incorrect encoding of pointer type");
5715       return QualType();
5716     }
5717     QualType PointeeType = readType(*Loc.F, Record, Idx);
5718     return Context.getPointerType(PointeeType);
5719   }
5720
5721   case TYPE_DECAYED: {
5722     if (Record.size() != 1) {
5723       Error("Incorrect encoding of decayed type");
5724       return QualType();
5725     }
5726     QualType OriginalType = readType(*Loc.F, Record, Idx);
5727     QualType DT = Context.getAdjustedParameterType(OriginalType);
5728     if (!isa<DecayedType>(DT))
5729       Error("Decayed type does not decay");
5730     return DT;
5731   }
5732
5733   case TYPE_ADJUSTED: {
5734     if (Record.size() != 2) {
5735       Error("Incorrect encoding of adjusted type");
5736       return QualType();
5737     }
5738     QualType OriginalTy = readType(*Loc.F, Record, Idx);
5739     QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5740     return Context.getAdjustedType(OriginalTy, AdjustedTy);
5741   }
5742
5743   case TYPE_BLOCK_POINTER: {
5744     if (Record.size() != 1) {
5745       Error("Incorrect encoding of block pointer type");
5746       return QualType();
5747     }
5748     QualType PointeeType = readType(*Loc.F, Record, Idx);
5749     return Context.getBlockPointerType(PointeeType);
5750   }
5751
5752   case TYPE_LVALUE_REFERENCE: {
5753     if (Record.size() != 2) {
5754       Error("Incorrect encoding of lvalue reference type");
5755       return QualType();
5756     }
5757     QualType PointeeType = readType(*Loc.F, Record, Idx);
5758     return Context.getLValueReferenceType(PointeeType, Record[1]);
5759   }
5760
5761   case TYPE_RVALUE_REFERENCE: {
5762     if (Record.size() != 1) {
5763       Error("Incorrect encoding of rvalue reference type");
5764       return QualType();
5765     }
5766     QualType PointeeType = readType(*Loc.F, Record, Idx);
5767     return Context.getRValueReferenceType(PointeeType);
5768   }
5769
5770   case TYPE_MEMBER_POINTER: {
5771     if (Record.size() != 2) {
5772       Error("Incorrect encoding of member pointer type");
5773       return QualType();
5774     }
5775     QualType PointeeType = readType(*Loc.F, Record, Idx);
5776     QualType ClassType = readType(*Loc.F, Record, Idx);
5777     if (PointeeType.isNull() || ClassType.isNull())
5778       return QualType();
5779
5780     return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5781   }
5782
5783   case TYPE_CONSTANT_ARRAY: {
5784     QualType ElementType = readType(*Loc.F, Record, Idx);
5785     ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5786     unsigned IndexTypeQuals = Record[2];
5787     unsigned Idx = 3;
5788     llvm::APInt Size = ReadAPInt(Record, Idx);
5789     return Context.getConstantArrayType(ElementType, Size,
5790                                          ASM, IndexTypeQuals);
5791   }
5792
5793   case TYPE_INCOMPLETE_ARRAY: {
5794     QualType ElementType = readType(*Loc.F, Record, Idx);
5795     ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5796     unsigned IndexTypeQuals = Record[2];
5797     return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5798   }
5799
5800   case TYPE_VARIABLE_ARRAY: {
5801     QualType ElementType = readType(*Loc.F, Record, Idx);
5802     ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5803     unsigned IndexTypeQuals = Record[2];
5804     SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5805     SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5806     return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5807                                          ASM, IndexTypeQuals,
5808                                          SourceRange(LBLoc, RBLoc));
5809   }
5810
5811   case TYPE_VECTOR: {
5812     if (Record.size() != 3) {
5813       Error("incorrect encoding of vector type in AST file");
5814       return QualType();
5815     }
5816
5817     QualType ElementType = readType(*Loc.F, Record, Idx);
5818     unsigned NumElements = Record[1];
5819     unsigned VecKind = Record[2];
5820     return Context.getVectorType(ElementType, NumElements,
5821                                   (VectorType::VectorKind)VecKind);
5822   }
5823
5824   case TYPE_EXT_VECTOR: {
5825     if (Record.size() != 3) {
5826       Error("incorrect encoding of extended vector type in AST file");
5827       return QualType();
5828     }
5829
5830     QualType ElementType = readType(*Loc.F, Record, Idx);
5831     unsigned NumElements = Record[1];
5832     return Context.getExtVectorType(ElementType, NumElements);
5833   }
5834
5835   case TYPE_FUNCTION_NO_PROTO: {
5836     if (Record.size() != 7) {
5837       Error("incorrect encoding of no-proto function type");
5838       return QualType();
5839     }
5840     QualType ResultType = readType(*Loc.F, Record, Idx);
5841     FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5842                                (CallingConv)Record[4], Record[5], Record[6]);
5843     return Context.getFunctionNoProtoType(ResultType, Info);
5844   }
5845
5846   case TYPE_FUNCTION_PROTO: {
5847     QualType ResultType = readType(*Loc.F, Record, Idx);
5848
5849     FunctionProtoType::ExtProtoInfo EPI;
5850     EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5851                                         /*hasregparm*/ Record[2],
5852                                         /*regparm*/ Record[3],
5853                                         static_cast<CallingConv>(Record[4]),
5854                                         /*produces*/ Record[5],
5855                                         /*nocallersavedregs*/ Record[6]);
5856
5857     unsigned Idx = 7;
5858
5859     EPI.Variadic = Record[Idx++];
5860     EPI.HasTrailingReturn = Record[Idx++];
5861     EPI.TypeQuals = Record[Idx++];
5862     EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
5863     SmallVector<QualType, 8> ExceptionStorage;
5864     readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
5865
5866     unsigned NumParams = Record[Idx++];
5867     SmallVector<QualType, 16> ParamTypes;
5868     for (unsigned I = 0; I != NumParams; ++I)
5869       ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5870
5871     SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
5872     if (Idx != Record.size()) {
5873       for (unsigned I = 0; I != NumParams; ++I)
5874         ExtParameterInfos.push_back(
5875           FunctionProtoType::ExtParameterInfo
5876                            ::getFromOpaqueValue(Record[Idx++]));
5877       EPI.ExtParameterInfos = ExtParameterInfos.data();
5878     }
5879
5880     assert(Idx == Record.size());
5881
5882     return Context.getFunctionType(ResultType, ParamTypes, EPI);
5883   }
5884
5885   case TYPE_UNRESOLVED_USING: {
5886     unsigned Idx = 0;
5887     return Context.getTypeDeclType(
5888                   ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5889   }
5890
5891   case TYPE_TYPEDEF: {
5892     if (Record.size() != 2) {
5893       Error("incorrect encoding of typedef type");
5894       return QualType();
5895     }
5896     unsigned Idx = 0;
5897     TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5898     QualType Canonical = readType(*Loc.F, Record, Idx);
5899     if (!Canonical.isNull())
5900       Canonical = Context.getCanonicalType(Canonical);
5901     return Context.getTypedefType(Decl, Canonical);
5902   }
5903
5904   case TYPE_TYPEOF_EXPR:
5905     return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5906
5907   case TYPE_TYPEOF: {
5908     if (Record.size() != 1) {
5909       Error("incorrect encoding of typeof(type) in AST file");
5910       return QualType();
5911     }
5912     QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5913     return Context.getTypeOfType(UnderlyingType);
5914   }
5915
5916   case TYPE_DECLTYPE: {
5917     QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5918     return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5919   }
5920
5921   case TYPE_UNARY_TRANSFORM: {
5922     QualType BaseType = readType(*Loc.F, Record, Idx);
5923     QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5924     UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5925     return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5926   }
5927
5928   case TYPE_AUTO: {
5929     QualType Deduced = readType(*Loc.F, Record, Idx);
5930     AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
5931     bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
5932     return Context.getAutoType(Deduced, Keyword, IsDependent);
5933   }
5934
5935   case TYPE_DEDUCED_TEMPLATE_SPECIALIZATION: {
5936     TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5937     QualType Deduced = readType(*Loc.F, Record, Idx);
5938     bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
5939     return Context.getDeducedTemplateSpecializationType(Name, Deduced,
5940                                                         IsDependent);
5941   }
5942
5943   case TYPE_RECORD: {
5944     if (Record.size() != 2) {
5945       Error("incorrect encoding of record type");
5946       return QualType();
5947     }
5948     unsigned Idx = 0;
5949     bool IsDependent = Record[Idx++];
5950     RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5951     RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5952     QualType T = Context.getRecordType(RD);
5953     const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5954     return T;
5955   }
5956
5957   case TYPE_ENUM: {
5958     if (Record.size() != 2) {
5959       Error("incorrect encoding of enum type");
5960       return QualType();
5961     }
5962     unsigned Idx = 0;
5963     bool IsDependent = Record[Idx++];
5964     QualType T
5965       = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5966     const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5967     return T;
5968   }
5969
5970   case TYPE_ATTRIBUTED: {
5971     if (Record.size() != 3) {
5972       Error("incorrect encoding of attributed type");
5973       return QualType();
5974     }
5975     QualType modifiedType = readType(*Loc.F, Record, Idx);
5976     QualType equivalentType = readType(*Loc.F, Record, Idx);
5977     AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5978     return Context.getAttributedType(kind, modifiedType, equivalentType);
5979   }
5980
5981   case TYPE_PAREN: {
5982     if (Record.size() != 1) {
5983       Error("incorrect encoding of paren type");
5984       return QualType();
5985     }
5986     QualType InnerType = readType(*Loc.F, Record, Idx);
5987     return Context.getParenType(InnerType);
5988   }
5989
5990   case TYPE_PACK_EXPANSION: {
5991     if (Record.size() != 2) {
5992       Error("incorrect encoding of pack expansion type");
5993       return QualType();
5994     }
5995     QualType Pattern = readType(*Loc.F, Record, Idx);
5996     if (Pattern.isNull())
5997       return QualType();
5998     Optional<unsigned> NumExpansions;
5999     if (Record[1])
6000       NumExpansions = Record[1] - 1;
6001     return Context.getPackExpansionType(Pattern, NumExpansions);
6002   }
6003
6004   case TYPE_ELABORATED: {
6005     unsigned Idx = 0;
6006     ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
6007     NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
6008     QualType NamedType = readType(*Loc.F, Record, Idx);
6009     return Context.getElaboratedType(Keyword, NNS, NamedType);
6010   }
6011
6012   case TYPE_OBJC_INTERFACE: {
6013     unsigned Idx = 0;
6014     ObjCInterfaceDecl *ItfD
6015       = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
6016     return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
6017   }
6018
6019   case TYPE_OBJC_TYPE_PARAM: {
6020     unsigned Idx = 0;
6021     ObjCTypeParamDecl *Decl
6022       = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
6023     unsigned NumProtos = Record[Idx++];
6024     SmallVector<ObjCProtocolDecl*, 4> Protos;
6025     for (unsigned I = 0; I != NumProtos; ++I)
6026       Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
6027     return Context.getObjCTypeParamType(Decl, Protos);
6028   }
6029   case TYPE_OBJC_OBJECT: {
6030     unsigned Idx = 0;
6031     QualType Base = readType(*Loc.F, Record, Idx);
6032     unsigned NumTypeArgs = Record[Idx++];
6033     SmallVector<QualType, 4> TypeArgs;
6034     for (unsigned I = 0; I != NumTypeArgs; ++I)
6035       TypeArgs.push_back(readType(*Loc.F, Record, Idx));
6036     unsigned NumProtos = Record[Idx++];
6037     SmallVector<ObjCProtocolDecl*, 4> Protos;
6038     for (unsigned I = 0; I != NumProtos; ++I)
6039       Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
6040     bool IsKindOf = Record[Idx++];
6041     return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
6042   }
6043
6044   case TYPE_OBJC_OBJECT_POINTER: {
6045     unsigned Idx = 0;
6046     QualType Pointee = readType(*Loc.F, Record, Idx);
6047     return Context.getObjCObjectPointerType(Pointee);
6048   }
6049
6050   case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
6051     unsigned Idx = 0;
6052     QualType Parm = readType(*Loc.F, Record, Idx);
6053     QualType Replacement = readType(*Loc.F, Record, Idx);
6054     return Context.getSubstTemplateTypeParmType(
6055         cast<TemplateTypeParmType>(Parm),
6056         Context.getCanonicalType(Replacement));
6057   }
6058
6059   case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
6060     unsigned Idx = 0;
6061     QualType Parm = readType(*Loc.F, Record, Idx);
6062     TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
6063     return Context.getSubstTemplateTypeParmPackType(
6064                                                cast<TemplateTypeParmType>(Parm),
6065                                                      ArgPack);
6066   }
6067
6068   case TYPE_INJECTED_CLASS_NAME: {
6069     CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
6070     QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
6071     // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
6072     // for AST reading, too much interdependencies.
6073     const Type *T = nullptr;
6074     for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
6075       if (const Type *Existing = DI->getTypeForDecl()) {
6076         T = Existing;
6077         break;
6078       }
6079     }
6080     if (!T) {
6081       T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
6082       for (auto *DI = D; DI; DI = DI->getPreviousDecl())
6083         DI->setTypeForDecl(T);
6084     }
6085     return QualType(T, 0);
6086   }
6087
6088   case TYPE_TEMPLATE_TYPE_PARM: {
6089     unsigned Idx = 0;
6090     unsigned Depth = Record[Idx++];
6091     unsigned Index = Record[Idx++];
6092     bool Pack = Record[Idx++];
6093     TemplateTypeParmDecl *D
6094       = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
6095     return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
6096   }
6097
6098   case TYPE_DEPENDENT_NAME: {
6099     unsigned Idx = 0;
6100     ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
6101     NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
6102     const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
6103     QualType Canon = readType(*Loc.F, Record, Idx);
6104     if (!Canon.isNull())
6105       Canon = Context.getCanonicalType(Canon);
6106     return Context.getDependentNameType(Keyword, NNS, Name, Canon);
6107   }
6108
6109   case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
6110     unsigned Idx = 0;
6111     ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
6112     NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
6113     const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
6114     unsigned NumArgs = Record[Idx++];
6115     SmallVector<TemplateArgument, 8> Args;
6116     Args.reserve(NumArgs);
6117     while (NumArgs--)
6118       Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
6119     return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
6120                                                           Args);
6121   }
6122
6123   case TYPE_DEPENDENT_SIZED_ARRAY: {
6124     unsigned Idx = 0;
6125
6126     // ArrayType
6127     QualType ElementType = readType(*Loc.F, Record, Idx);
6128     ArrayType::ArraySizeModifier ASM
6129       = (ArrayType::ArraySizeModifier)Record[Idx++];
6130     unsigned IndexTypeQuals = Record[Idx++];
6131
6132     // DependentSizedArrayType
6133     Expr *NumElts = ReadExpr(*Loc.F);
6134     SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
6135
6136     return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
6137                                                IndexTypeQuals, Brackets);
6138   }
6139
6140   case TYPE_TEMPLATE_SPECIALIZATION: {
6141     unsigned Idx = 0;
6142     bool IsDependent = Record[Idx++];
6143     TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6144     SmallVector<TemplateArgument, 8> Args;
6145     ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
6146     QualType Underlying = readType(*Loc.F, Record, Idx);
6147     QualType T;
6148     if (Underlying.isNull())
6149       T = Context.getCanonicalTemplateSpecializationType(Name, Args);
6150     else
6151       T = Context.getTemplateSpecializationType(Name, Args, Underlying);
6152     const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6153     return T;
6154   }
6155
6156   case TYPE_ATOMIC: {
6157     if (Record.size() != 1) {
6158       Error("Incorrect encoding of atomic type");
6159       return QualType();
6160     }
6161     QualType ValueType = readType(*Loc.F, Record, Idx);
6162     return Context.getAtomicType(ValueType);
6163   }
6164
6165   case TYPE_PIPE: {
6166     if (Record.size() != 2) {
6167       Error("Incorrect encoding of pipe type");
6168       return QualType();
6169     }
6170
6171     // Reading the pipe element type.
6172     QualType ElementType = readType(*Loc.F, Record, Idx);
6173     unsigned ReadOnly = Record[1];
6174     return Context.getPipeType(ElementType, ReadOnly);
6175   }
6176
6177   case TYPE_DEPENDENT_SIZED_EXT_VECTOR: {
6178     unsigned Idx = 0;
6179
6180     // DependentSizedExtVectorType
6181     QualType ElementType = readType(*Loc.F, Record, Idx);
6182     Expr *SizeExpr = ReadExpr(*Loc.F);
6183     SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6184
6185     return Context.getDependentSizedExtVectorType(ElementType, SizeExpr,
6186                                                   AttrLoc);
6187   }
6188   }
6189   llvm_unreachable("Invalid TypeCode!");
6190 }
6191
6192 void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
6193                                   SmallVectorImpl<QualType> &Exceptions,
6194                                   FunctionProtoType::ExceptionSpecInfo &ESI,
6195                                   const RecordData &Record, unsigned &Idx) {
6196   ExceptionSpecificationType EST =
6197       static_cast<ExceptionSpecificationType>(Record[Idx++]);
6198   ESI.Type = EST;
6199   if (EST == EST_Dynamic) {
6200     for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
6201       Exceptions.push_back(readType(ModuleFile, Record, Idx));
6202     ESI.Exceptions = Exceptions;
6203   } else if (EST == EST_ComputedNoexcept) {
6204     ESI.NoexceptExpr = ReadExpr(ModuleFile);
6205   } else if (EST == EST_Uninstantiated) {
6206     ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
6207     ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
6208   } else if (EST == EST_Unevaluated) {
6209     ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
6210   }
6211 }
6212
6213 class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
6214   ModuleFile *F;
6215   ASTReader *Reader;
6216   const ASTReader::RecordData &Record;
6217   unsigned &Idx;
6218
6219   SourceLocation ReadSourceLocation() {
6220     return Reader->ReadSourceLocation(*F, Record, Idx);
6221   }
6222
6223   TypeSourceInfo *GetTypeSourceInfo() {
6224     return Reader->GetTypeSourceInfo(*F, Record, Idx);
6225   }
6226
6227   NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6228     return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
6229   }
6230
6231 public:
6232   TypeLocReader(ModuleFile &F, ASTReader &Reader,
6233                 const ASTReader::RecordData &Record, unsigned &Idx)
6234       : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
6235
6236   // We want compile-time assurance that we've enumerated all of
6237   // these, so unfortunately we have to declare them first, then
6238   // define them out-of-line.
6239 #define ABSTRACT_TYPELOC(CLASS, PARENT)
6240 #define TYPELOC(CLASS, PARENT) \
6241   void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6242 #include "clang/AST/TypeLocNodes.def"
6243
6244   void VisitFunctionTypeLoc(FunctionTypeLoc);
6245   void VisitArrayTypeLoc(ArrayTypeLoc);
6246 };
6247
6248 void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6249   // nothing to do
6250 }
6251
6252 void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6253   TL.setBuiltinLoc(ReadSourceLocation());
6254   if (TL.needsExtraLocalData()) {
6255     TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
6256     TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
6257     TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
6258     TL.setModeAttr(Record[Idx++]);
6259   }
6260 }
6261
6262 void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
6263   TL.setNameLoc(ReadSourceLocation());
6264 }
6265
6266 void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
6267   TL.setStarLoc(ReadSourceLocation());
6268 }
6269
6270 void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6271   // nothing to do
6272 }
6273
6274 void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6275   // nothing to do
6276 }
6277
6278 void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6279   TL.setCaretLoc(ReadSourceLocation());
6280 }
6281
6282 void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6283   TL.setAmpLoc(ReadSourceLocation());
6284 }
6285
6286 void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6287   TL.setAmpAmpLoc(ReadSourceLocation());
6288 }
6289
6290 void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6291   TL.setStarLoc(ReadSourceLocation());
6292   TL.setClassTInfo(GetTypeSourceInfo());
6293 }
6294
6295 void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
6296   TL.setLBracketLoc(ReadSourceLocation());
6297   TL.setRBracketLoc(ReadSourceLocation());
6298   if (Record[Idx++])
6299     TL.setSizeExpr(Reader->ReadExpr(*F));
6300   else
6301     TL.setSizeExpr(nullptr);
6302 }
6303
6304 void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6305   VisitArrayTypeLoc(TL);
6306 }
6307
6308 void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6309   VisitArrayTypeLoc(TL);
6310 }
6311
6312 void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6313   VisitArrayTypeLoc(TL);
6314 }
6315
6316 void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6317                                             DependentSizedArrayTypeLoc TL) {
6318   VisitArrayTypeLoc(TL);
6319 }
6320
6321 void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6322                                         DependentSizedExtVectorTypeLoc TL) {
6323   TL.setNameLoc(ReadSourceLocation());
6324 }
6325
6326 void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
6327   TL.setNameLoc(ReadSourceLocation());
6328 }
6329
6330 void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6331   TL.setNameLoc(ReadSourceLocation());
6332 }
6333
6334 void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
6335   TL.setLocalRangeBegin(ReadSourceLocation());
6336   TL.setLParenLoc(ReadSourceLocation());
6337   TL.setRParenLoc(ReadSourceLocation());
6338   TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx),
6339                                        Reader->ReadSourceLocation(*F, Record, Idx)));
6340   TL.setLocalRangeEnd(ReadSourceLocation());
6341   for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
6342     TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx));
6343   }
6344 }
6345
6346 void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6347   VisitFunctionTypeLoc(TL);
6348 }
6349
6350 void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6351   VisitFunctionTypeLoc(TL);
6352 }
6353 void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
6354   TL.setNameLoc(ReadSourceLocation());
6355 }
6356 void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
6357   TL.setNameLoc(ReadSourceLocation());
6358 }
6359 void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6360   TL.setTypeofLoc(ReadSourceLocation());
6361   TL.setLParenLoc(ReadSourceLocation());
6362   TL.setRParenLoc(ReadSourceLocation());
6363 }
6364 void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6365   TL.setTypeofLoc(ReadSourceLocation());
6366   TL.setLParenLoc(ReadSourceLocation());
6367   TL.setRParenLoc(ReadSourceLocation());
6368   TL.setUnderlyingTInfo(GetTypeSourceInfo());
6369 }
6370 void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6371   TL.setNameLoc(ReadSourceLocation());
6372 }
6373
6374 void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6375   TL.setKWLoc(ReadSourceLocation());
6376   TL.setLParenLoc(ReadSourceLocation());
6377   TL.setRParenLoc(ReadSourceLocation());
6378   TL.setUnderlyingTInfo(GetTypeSourceInfo());
6379 }
6380
6381 void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
6382   TL.setNameLoc(ReadSourceLocation());
6383 }
6384
6385 void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6386     DeducedTemplateSpecializationTypeLoc TL) {
6387   TL.setTemplateNameLoc(ReadSourceLocation());
6388 }
6389
6390 void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
6391   TL.setNameLoc(ReadSourceLocation());
6392 }
6393
6394 void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
6395   TL.setNameLoc(ReadSourceLocation());
6396 }
6397
6398 void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6399   TL.setAttrNameLoc(ReadSourceLocation());
6400   if (TL.hasAttrOperand()) {
6401     SourceRange range;
6402     range.setBegin(ReadSourceLocation());
6403     range.setEnd(ReadSourceLocation());
6404     TL.setAttrOperandParensRange(range);
6405   }
6406   if (TL.hasAttrExprOperand()) {
6407     if (Record[Idx++])
6408       TL.setAttrExprOperand(Reader->ReadExpr(*F));
6409     else
6410       TL.setAttrExprOperand(nullptr);
6411   } else if (TL.hasAttrEnumOperand())
6412     TL.setAttrEnumOperandLoc(ReadSourceLocation());
6413 }
6414
6415 void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
6416   TL.setNameLoc(ReadSourceLocation());
6417 }
6418
6419 void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6420                                             SubstTemplateTypeParmTypeLoc TL) {
6421   TL.setNameLoc(ReadSourceLocation());
6422 }
6423 void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6424                                           SubstTemplateTypeParmPackTypeLoc TL) {
6425   TL.setNameLoc(ReadSourceLocation());
6426 }
6427 void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6428                                            TemplateSpecializationTypeLoc TL) {
6429   TL.setTemplateKeywordLoc(ReadSourceLocation());
6430   TL.setTemplateNameLoc(ReadSourceLocation());
6431   TL.setLAngleLoc(ReadSourceLocation());
6432   TL.setRAngleLoc(ReadSourceLocation());
6433   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
6434     TL.setArgLocInfo(
6435         i,
6436         Reader->GetTemplateArgumentLocInfo(
6437             *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx));
6438 }
6439 void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
6440   TL.setLParenLoc(ReadSourceLocation());
6441   TL.setRParenLoc(ReadSourceLocation());
6442 }
6443
6444 void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
6445   TL.setElaboratedKeywordLoc(ReadSourceLocation());
6446   TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6447 }
6448
6449 void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
6450   TL.setNameLoc(ReadSourceLocation());
6451 }
6452
6453 void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6454   TL.setElaboratedKeywordLoc(ReadSourceLocation());
6455   TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6456   TL.setNameLoc(ReadSourceLocation());
6457 }
6458
6459 void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6460        DependentTemplateSpecializationTypeLoc TL) {
6461   TL.setElaboratedKeywordLoc(ReadSourceLocation());
6462   TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6463   TL.setTemplateKeywordLoc(ReadSourceLocation());
6464   TL.setTemplateNameLoc(ReadSourceLocation());
6465   TL.setLAngleLoc(ReadSourceLocation());
6466   TL.setRAngleLoc(ReadSourceLocation());
6467   for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
6468     TL.setArgLocInfo(
6469         I,
6470         Reader->GetTemplateArgumentLocInfo(
6471             *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx));
6472 }
6473
6474 void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
6475   TL.setEllipsisLoc(ReadSourceLocation());
6476 }
6477
6478 void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
6479   TL.setNameLoc(ReadSourceLocation());
6480 }
6481
6482 void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6483   if (TL.getNumProtocols()) {
6484     TL.setProtocolLAngleLoc(ReadSourceLocation());
6485     TL.setProtocolRAngleLoc(ReadSourceLocation());
6486   }
6487   for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
6488     TL.setProtocolLoc(i, ReadSourceLocation());
6489 }
6490
6491 void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
6492   TL.setHasBaseTypeAsWritten(Record[Idx++]);
6493   TL.setTypeArgsLAngleLoc(ReadSourceLocation());
6494   TL.setTypeArgsRAngleLoc(ReadSourceLocation());
6495   for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
6496     TL.setTypeArgTInfo(i, GetTypeSourceInfo());
6497   TL.setProtocolLAngleLoc(ReadSourceLocation());
6498   TL.setProtocolRAngleLoc(ReadSourceLocation());
6499   for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
6500     TL.setProtocolLoc(i, ReadSourceLocation());
6501 }
6502
6503 void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6504   TL.setStarLoc(ReadSourceLocation());
6505 }
6506
6507 void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6508   TL.setKWLoc(ReadSourceLocation());
6509   TL.setLParenLoc(ReadSourceLocation());
6510   TL.setRParenLoc(ReadSourceLocation());
6511 }
6512
6513 void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
6514   TL.setKWLoc(ReadSourceLocation());
6515 }
6516
6517 TypeSourceInfo *
6518 ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record,
6519                              unsigned &Idx) {
6520   QualType InfoTy = readType(F, Record, Idx);
6521   if (InfoTy.isNull())
6522     return nullptr;
6523
6524   TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
6525   TypeLocReader TLR(F, *this, Record, Idx);
6526   for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
6527     TLR.Visit(TL);
6528   return TInfo;
6529 }
6530
6531 QualType ASTReader::GetType(TypeID ID) {
6532   unsigned FastQuals = ID & Qualifiers::FastMask;
6533   unsigned Index = ID >> Qualifiers::FastWidth;
6534
6535   if (Index < NUM_PREDEF_TYPE_IDS) {
6536     QualType T;
6537     switch ((PredefinedTypeIDs)Index) {
6538     case PREDEF_TYPE_NULL_ID:
6539       return QualType();
6540     case PREDEF_TYPE_VOID_ID:
6541       T = Context.VoidTy;
6542       break;
6543     case PREDEF_TYPE_BOOL_ID:
6544       T = Context.BoolTy;
6545       break;
6546
6547     case PREDEF_TYPE_CHAR_U_ID:
6548     case PREDEF_TYPE_CHAR_S_ID:
6549       // FIXME: Check that the signedness of CharTy is correct!
6550       T = Context.CharTy;
6551       break;
6552
6553     case PREDEF_TYPE_UCHAR_ID:
6554       T = Context.UnsignedCharTy;
6555       break;
6556     case PREDEF_TYPE_USHORT_ID:
6557       T = Context.UnsignedShortTy;
6558       break;
6559     case PREDEF_TYPE_UINT_ID:
6560       T = Context.UnsignedIntTy;
6561       break;
6562     case PREDEF_TYPE_ULONG_ID:
6563       T = Context.UnsignedLongTy;
6564       break;
6565     case PREDEF_TYPE_ULONGLONG_ID:
6566       T = Context.UnsignedLongLongTy;
6567       break;
6568     case PREDEF_TYPE_UINT128_ID:
6569       T = Context.UnsignedInt128Ty;
6570       break;
6571     case PREDEF_TYPE_SCHAR_ID:
6572       T = Context.SignedCharTy;
6573       break;
6574     case PREDEF_TYPE_WCHAR_ID:
6575       T = Context.WCharTy;
6576       break;
6577     case PREDEF_TYPE_SHORT_ID:
6578       T = Context.ShortTy;
6579       break;
6580     case PREDEF_TYPE_INT_ID:
6581       T = Context.IntTy;
6582       break;
6583     case PREDEF_TYPE_LONG_ID:
6584       T = Context.LongTy;
6585       break;
6586     case PREDEF_TYPE_LONGLONG_ID:
6587       T = Context.LongLongTy;
6588       break;
6589     case PREDEF_TYPE_INT128_ID:
6590       T = Context.Int128Ty;
6591       break;
6592     case PREDEF_TYPE_HALF_ID:
6593       T = Context.HalfTy;
6594       break;
6595     case PREDEF_TYPE_FLOAT_ID:
6596       T = Context.FloatTy;
6597       break;
6598     case PREDEF_TYPE_DOUBLE_ID:
6599       T = Context.DoubleTy;
6600       break;
6601     case PREDEF_TYPE_LONGDOUBLE_ID:
6602       T = Context.LongDoubleTy;
6603       break;
6604     case PREDEF_TYPE_FLOAT128_ID:
6605       T = Context.Float128Ty;
6606       break;
6607     case PREDEF_TYPE_OVERLOAD_ID:
6608       T = Context.OverloadTy;
6609       break;
6610     case PREDEF_TYPE_BOUND_MEMBER:
6611       T = Context.BoundMemberTy;
6612       break;
6613     case PREDEF_TYPE_PSEUDO_OBJECT:
6614       T = Context.PseudoObjectTy;
6615       break;
6616     case PREDEF_TYPE_DEPENDENT_ID:
6617       T = Context.DependentTy;
6618       break;
6619     case PREDEF_TYPE_UNKNOWN_ANY:
6620       T = Context.UnknownAnyTy;
6621       break;
6622     case PREDEF_TYPE_NULLPTR_ID:
6623       T = Context.NullPtrTy;
6624       break;
6625     case PREDEF_TYPE_CHAR16_ID:
6626       T = Context.Char16Ty;
6627       break;
6628     case PREDEF_TYPE_CHAR32_ID:
6629       T = Context.Char32Ty;
6630       break;
6631     case PREDEF_TYPE_OBJC_ID:
6632       T = Context.ObjCBuiltinIdTy;
6633       break;
6634     case PREDEF_TYPE_OBJC_CLASS:
6635       T = Context.ObjCBuiltinClassTy;
6636       break;
6637     case PREDEF_TYPE_OBJC_SEL:
6638       T = Context.ObjCBuiltinSelTy;
6639       break;
6640 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6641     case PREDEF_TYPE_##Id##_ID: \
6642       T = Context.SingletonId; \
6643       break;
6644 #include "clang/Basic/OpenCLImageTypes.def"
6645     case PREDEF_TYPE_SAMPLER_ID:
6646       T = Context.OCLSamplerTy;
6647       break;
6648     case PREDEF_TYPE_EVENT_ID:
6649       T = Context.OCLEventTy;
6650       break;
6651     case PREDEF_TYPE_CLK_EVENT_ID:
6652       T = Context.OCLClkEventTy;
6653       break;
6654     case PREDEF_TYPE_QUEUE_ID:
6655       T = Context.OCLQueueTy;
6656       break;
6657     case PREDEF_TYPE_RESERVE_ID_ID:
6658       T = Context.OCLReserveIDTy;
6659       break;
6660     case PREDEF_TYPE_AUTO_DEDUCT:
6661       T = Context.getAutoDeductType();
6662       break;
6663
6664     case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6665       T = Context.getAutoRRefDeductType();
6666       break;
6667
6668     case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6669       T = Context.ARCUnbridgedCastTy;
6670       break;
6671
6672     case PREDEF_TYPE_BUILTIN_FN:
6673       T = Context.BuiltinFnTy;
6674       break;
6675
6676     case PREDEF_TYPE_OMP_ARRAY_SECTION:
6677       T = Context.OMPArraySectionTy;
6678       break;
6679     }
6680
6681     assert(!T.isNull() && "Unknown predefined type");
6682     return T.withFastQualifiers(FastQuals);
6683   }
6684
6685   Index -= NUM_PREDEF_TYPE_IDS;
6686   assert(Index < TypesLoaded.size() && "Type index out-of-range");
6687   if (TypesLoaded[Index].isNull()) {
6688     TypesLoaded[Index] = readTypeRecord(Index);
6689     if (TypesLoaded[Index].isNull())
6690       return QualType();
6691
6692     TypesLoaded[Index]->setFromAST();
6693     if (DeserializationListener)
6694       DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6695                                         TypesLoaded[Index]);
6696   }
6697
6698   return TypesLoaded[Index].withFastQualifiers(FastQuals);
6699 }
6700
6701 QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6702   return GetType(getGlobalTypeID(F, LocalID));
6703 }
6704
6705 serialization::TypeID
6706 ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6707   unsigned FastQuals = LocalID & Qualifiers::FastMask;
6708   unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
6709
6710   if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6711     return LocalID;
6712
6713   if (!F.ModuleOffsetMap.empty())
6714     ReadModuleOffsetMap(F);
6715
6716   ContinuousRangeMap<uint32_t, int, 2>::iterator I
6717     = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6718   assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
6719
6720   unsigned GlobalIndex = LocalIndex + I->second;
6721   return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6722 }
6723
6724 TemplateArgumentLocInfo
6725 ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6726                                       TemplateArgument::ArgKind Kind,
6727                                       const RecordData &Record,
6728                                       unsigned &Index) {
6729   switch (Kind) {
6730   case TemplateArgument::Expression:
6731     return ReadExpr(F);
6732   case TemplateArgument::Type:
6733     return GetTypeSourceInfo(F, Record, Index);
6734   case TemplateArgument::Template: {
6735     NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6736                                                                      Index);
6737     SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6738     return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6739                                    SourceLocation());
6740   }
6741   case TemplateArgument::TemplateExpansion: {
6742     NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
6743                                                                      Index);
6744     SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6745     SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
6746     return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6747                                    EllipsisLoc);
6748   }
6749   case TemplateArgument::Null:
6750   case TemplateArgument::Integral:
6751   case TemplateArgument::Declaration:
6752   case TemplateArgument::NullPtr:
6753   case TemplateArgument::Pack:
6754     // FIXME: Is this right?
6755     return TemplateArgumentLocInfo();
6756   }
6757   llvm_unreachable("unexpected template argument loc");
6758 }
6759
6760 TemplateArgumentLoc
6761 ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6762                                    const RecordData &Record, unsigned &Index) {
6763   TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6764
6765   if (Arg.getKind() == TemplateArgument::Expression) {
6766     if (Record[Index++]) // bool InfoHasSameExpr.
6767       return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6768   }
6769   return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6770                                                              Record, Index));
6771 }
6772
6773 const ASTTemplateArgumentListInfo*
6774 ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6775                                            const RecordData &Record,
6776                                            unsigned &Index) {
6777   SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6778   SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6779   unsigned NumArgsAsWritten = Record[Index++];
6780   TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6781   for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6782     TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6783   return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6784 }
6785
6786 Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6787   return GetDecl(ID);
6788 }
6789
6790 void ASTReader::CompleteRedeclChain(const Decl *D) {
6791   if (NumCurrentElementsDeserializing) {
6792     // We arrange to not care about the complete redeclaration chain while we're
6793     // deserializing. Just remember that the AST has marked this one as complete
6794     // but that it's not actually complete yet, so we know we still need to
6795     // complete it later.
6796     PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6797     return;
6798   }
6799
6800   const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6801
6802   // If this is a named declaration, complete it by looking it up
6803   // within its context.
6804   //
6805   // FIXME: Merging a function definition should merge
6806   // all mergeable entities within it.
6807   if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6808       isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6809     if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
6810       if (!getContext().getLangOpts().CPlusPlus &&
6811           isa<TranslationUnitDecl>(DC)) {
6812         // Outside of C++, we don't have a lookup table for the TU, so update
6813         // the identifier instead. (For C++ modules, we don't store decls
6814         // in the serialized identifier table, so we do the lookup in the TU.)
6815         auto *II = Name.getAsIdentifierInfo();
6816         assert(II && "non-identifier name in C?");
6817         if (II->isOutOfDate())
6818           updateOutOfDateIdentifier(*II);
6819       } else
6820         DC->lookup(Name);
6821     } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
6822       // Find all declarations of this kind from the relevant context.
6823       for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6824         auto *DC = cast<DeclContext>(DCDecl);
6825         SmallVector<Decl*, 8> Decls;
6826         FindExternalLexicalDecls(
6827             DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6828       }
6829     }
6830   }
6831
6832   if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6833     CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6834   if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6835     VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6836   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6837     if (auto *Template = FD->getPrimaryTemplate())
6838       Template->LoadLazySpecializations();
6839   }
6840 }
6841
6842 CXXCtorInitializer **
6843 ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6844   RecordLocation Loc = getLocalBitOffset(Offset);
6845   BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6846   SavedStreamPosition SavedPosition(Cursor);
6847   Cursor.JumpToBit(Loc.Offset);
6848   ReadingKindTracker ReadingKind(Read_Decl, *this);
6849
6850   RecordData Record;
6851   unsigned Code = Cursor.ReadCode();
6852   unsigned RecCode = Cursor.readRecord(Code, Record);
6853   if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6854     Error("malformed AST file: missing C++ ctor initializers");
6855     return nullptr;
6856   }
6857
6858   unsigned Idx = 0;
6859   return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6860 }
6861
6862 CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6863   RecordLocation Loc = getLocalBitOffset(Offset);
6864   BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6865   SavedStreamPosition SavedPosition(Cursor);
6866   Cursor.JumpToBit(Loc.Offset);
6867   ReadingKindTracker ReadingKind(Read_Decl, *this);
6868   RecordData Record;
6869   unsigned Code = Cursor.ReadCode();
6870   unsigned RecCode = Cursor.readRecord(Code, Record);
6871   if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
6872     Error("malformed AST file: missing C++ base specifiers");
6873     return nullptr;
6874   }
6875
6876   unsigned Idx = 0;
6877   unsigned NumBases = Record[Idx++];
6878   void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6879   CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6880   for (unsigned I = 0; I != NumBases; ++I)
6881     Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6882   return Bases;
6883 }
6884
6885 serialization::DeclID
6886 ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6887   if (LocalID < NUM_PREDEF_DECL_IDS)
6888     return LocalID;
6889
6890   if (!F.ModuleOffsetMap.empty())
6891     ReadModuleOffsetMap(F);
6892
6893   ContinuousRangeMap<uint32_t, int, 2>::iterator I
6894     = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6895   assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
6896
6897   return LocalID + I->second;
6898 }
6899
6900 bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6901                                    ModuleFile &M) const {
6902   // Predefined decls aren't from any module.
6903   if (ID < NUM_PREDEF_DECL_IDS)
6904     return false;
6905
6906   return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
6907          ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
6908 }
6909
6910 ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
6911   if (!D->isFromASTFile())
6912     return nullptr;
6913   GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6914   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6915   return I->second;
6916 }
6917
6918 SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6919   if (ID < NUM_PREDEF_DECL_IDS)
6920     return SourceLocation();
6921
6922   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6923
6924   if (Index > DeclsLoaded.size()) {
6925     Error("declaration ID out-of-range for AST file");
6926     return SourceLocation();
6927   }
6928
6929   if (Decl *D = DeclsLoaded[Index])
6930     return D->getLocation();
6931
6932   SourceLocation Loc;
6933   DeclCursorForID(ID, Loc);
6934   return Loc;
6935 }
6936
6937 static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6938   switch (ID) {
6939   case PREDEF_DECL_NULL_ID:
6940     return nullptr;
6941
6942   case PREDEF_DECL_TRANSLATION_UNIT_ID:
6943     return Context.getTranslationUnitDecl();
6944
6945   case PREDEF_DECL_OBJC_ID_ID:
6946     return Context.getObjCIdDecl();
6947
6948   case PREDEF_DECL_OBJC_SEL_ID:
6949     return Context.getObjCSelDecl();
6950
6951   case PREDEF_DECL_OBJC_CLASS_ID:
6952     return Context.getObjCClassDecl();
6953
6954   case PREDEF_DECL_OBJC_PROTOCOL_ID:
6955     return Context.getObjCProtocolDecl();
6956
6957   case PREDEF_DECL_INT_128_ID:
6958     return Context.getInt128Decl();
6959
6960   case PREDEF_DECL_UNSIGNED_INT_128_ID:
6961     return Context.getUInt128Decl();
6962
6963   case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6964     return Context.getObjCInstanceTypeDecl();
6965
6966   case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6967     return Context.getBuiltinVaListDecl();
6968
6969   case PREDEF_DECL_VA_LIST_TAG:
6970     return Context.getVaListTagDecl();
6971
6972   case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
6973     return Context.getBuiltinMSVaListDecl();
6974
6975   case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6976     return Context.getExternCContextDecl();
6977
6978   case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
6979     return Context.getMakeIntegerSeqDecl();
6980
6981   case PREDEF_DECL_CF_CONSTANT_STRING_ID:
6982     return Context.getCFConstantStringDecl();
6983
6984   case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
6985     return Context.getCFConstantStringTagDecl();
6986
6987   case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
6988     return Context.getTypePackElementDecl();
6989   }
6990   llvm_unreachable("PredefinedDeclIDs unknown enum value");
6991 }
6992
6993 Decl *ASTReader::GetExistingDecl(DeclID ID) {
6994   if (ID < NUM_PREDEF_DECL_IDS) {
6995     Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6996     if (D) {
6997       // Track that we have merged the declaration with ID \p ID into the
6998       // pre-existing predefined declaration \p D.
6999       auto &Merged = KeyDecls[D->getCanonicalDecl()];
7000       if (Merged.empty())
7001         Merged.push_back(ID);
7002     }
7003     return D;
7004   }
7005
7006   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7007
7008   if (Index >= DeclsLoaded.size()) {
7009     assert(0 && "declaration ID out-of-range for AST file");
7010     Error("declaration ID out-of-range for AST file");
7011     return nullptr;
7012   }
7013
7014   return DeclsLoaded[Index];
7015 }
7016
7017 Decl *ASTReader::GetDecl(DeclID ID) {
7018   if (ID < NUM_PREDEF_DECL_IDS)
7019     return GetExistingDecl(ID);
7020
7021   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7022
7023   if (Index >= DeclsLoaded.size()) {
7024     assert(0 && "declaration ID out-of-range for AST file");
7025     Error("declaration ID out-of-range for AST file");
7026     return nullptr;
7027   }
7028
7029   if (!DeclsLoaded[Index]) {
7030     ReadDeclRecord(ID);
7031     if (DeserializationListener)
7032       DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7033   }
7034
7035   return DeclsLoaded[Index];
7036 }
7037
7038 DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
7039                                                   DeclID GlobalID) {
7040   if (GlobalID < NUM_PREDEF_DECL_IDS)
7041     return GlobalID;
7042
7043   GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7044   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7045   ModuleFile *Owner = I->second;
7046
7047   llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
7048     = M.GlobalToLocalDeclIDs.find(Owner);
7049   if (Pos == M.GlobalToLocalDeclIDs.end())
7050     return 0;
7051
7052   return GlobalID - Owner->BaseDeclID + Pos->second;
7053 }
7054
7055 serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
7056                                             const RecordData &Record,
7057                                             unsigned &Idx) {
7058   if (Idx >= Record.size()) {
7059     Error("Corrupted AST file");
7060     return 0;
7061   }
7062
7063   return getGlobalDeclID(F, Record[Idx++]);
7064 }
7065
7066 /// \brief Resolve the offset of a statement into a statement.
7067 ///
7068 /// This operation will read a new statement from the external
7069 /// source each time it is called, and is meant to be used via a
7070 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7071 Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
7072   // Switch case IDs are per Decl.
7073   ClearSwitchCaseIDs();
7074
7075   // Offset here is a global offset across the entire chain.
7076   RecordLocation Loc = getLocalBitOffset(Offset);
7077   Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
7078   assert(NumCurrentElementsDeserializing == 0 &&
7079          "should not be called while already deserializing");
7080   Deserializing D(this);
7081   return ReadStmtFromStream(*Loc.F);
7082 }
7083
7084 void ASTReader::FindExternalLexicalDecls(
7085     const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7086     SmallVectorImpl<Decl *> &Decls) {
7087   bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7088
7089   auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
7090     assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7091     for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7092       auto K = (Decl::Kind)+LexicalDecls[I];
7093       if (!IsKindWeWant(K))
7094         continue;
7095
7096       auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
7097
7098       // Don't add predefined declarations to the lexical context more
7099       // than once.
7100       if (ID < NUM_PREDEF_DECL_IDS) {
7101         if (PredefsVisited[ID])
7102           continue;
7103
7104         PredefsVisited[ID] = true;
7105       }
7106
7107       if (Decl *D = GetLocalDecl(*M, ID)) {
7108         assert(D->getKind() == K && "wrong kind for lexical decl");
7109         if (!DC->isDeclInLexicalTraversal(D))
7110           Decls.push_back(D);
7111       }
7112     }
7113   };
7114
7115   if (isa<TranslationUnitDecl>(DC)) {
7116     for (auto Lexical : TULexicalDecls)
7117       Visit(Lexical.first, Lexical.second);
7118   } else {
7119     auto I = LexicalDecls.find(DC);
7120     if (I != LexicalDecls.end())
7121       Visit(I->second.first, I->second.second);
7122   }
7123
7124   ++NumLexicalDeclContextsRead;
7125 }
7126
7127 namespace {
7128
7129 class DeclIDComp {
7130   ASTReader &Reader;
7131   ModuleFile &Mod;
7132
7133 public:
7134   DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7135
7136   bool operator()(LocalDeclID L, LocalDeclID R) const {
7137     SourceLocation LHS = getLocation(L);
7138     SourceLocation RHS = getLocation(R);
7139     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7140   }
7141
7142   bool operator()(SourceLocation LHS, LocalDeclID R) const {
7143     SourceLocation RHS = getLocation(R);
7144     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7145   }
7146
7147   bool operator()(LocalDeclID L, SourceLocation RHS) const {
7148     SourceLocation LHS = getLocation(L);
7149     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7150   }
7151
7152   SourceLocation getLocation(LocalDeclID ID) const {
7153     return Reader.getSourceManager().getFileLoc(
7154             Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7155   }
7156 };
7157
7158 } // end anonymous namespace
7159
7160 void ASTReader::FindFileRegionDecls(FileID File,
7161                                     unsigned Offset, unsigned Length,
7162                                     SmallVectorImpl<Decl *> &Decls) {
7163   SourceManager &SM = getSourceManager();
7164
7165   llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7166   if (I == FileDeclIDs.end())
7167     return;
7168
7169   FileDeclsInfo &DInfo = I->second;
7170   if (DInfo.Decls.empty())
7171     return;
7172
7173   SourceLocation
7174     BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7175   SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7176
7177   DeclIDComp DIDComp(*this, *DInfo.Mod);
7178   ArrayRef<serialization::LocalDeclID>::iterator
7179     BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7180                                BeginLoc, DIDComp);
7181   if (BeginIt != DInfo.Decls.begin())
7182     --BeginIt;
7183
7184   // If we are pointing at a top-level decl inside an objc container, we need
7185   // to backtrack until we find it otherwise we will fail to report that the
7186   // region overlaps with an objc container.
7187   while (BeginIt != DInfo.Decls.begin() &&
7188          GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7189              ->isTopLevelDeclInObjCContainer())
7190     --BeginIt;
7191
7192   ArrayRef<serialization::LocalDeclID>::iterator
7193     EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7194                              EndLoc, DIDComp);
7195   if (EndIt != DInfo.Decls.end())
7196     ++EndIt;
7197
7198   for (ArrayRef<serialization::LocalDeclID>::iterator
7199          DIt = BeginIt; DIt != EndIt; ++DIt)
7200     Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7201 }
7202
7203 bool
7204 ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
7205                                           DeclarationName Name) {
7206   assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
7207          "DeclContext has no visible decls in storage");
7208   if (!Name)
7209     return false;
7210
7211   auto It = Lookups.find(DC);
7212   if (It == Lookups.end())
7213     return false;
7214
7215   Deserializing LookupResults(this);
7216
7217   // Load the list of declarations.
7218   SmallVector<NamedDecl *, 64> Decls;
7219   for (DeclID ID : It->second.Table.find(Name)) {
7220     NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7221     if (ND->getDeclName() == Name)
7222       Decls.push_back(ND);
7223   }
7224
7225   ++NumVisibleDeclContextsRead;
7226   SetExternalVisibleDeclsForName(DC, Name, Decls);
7227   return !Decls.empty();
7228 }
7229
7230 void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
7231   if (!DC->hasExternalVisibleStorage())
7232     return;
7233
7234   auto It = Lookups.find(DC);
7235   assert(It != Lookups.end() &&
7236          "have external visible storage but no lookup tables");
7237
7238   DeclsMap Decls;
7239
7240   for (DeclID ID : It->second.Table.findAll()) {
7241     NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7242     Decls[ND->getDeclName()].push_back(ND);
7243   }
7244
7245   ++NumVisibleDeclContextsRead;
7246
7247   for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
7248     SetExternalVisibleDeclsForName(DC, I->first, I->second);
7249   }
7250   const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
7251 }
7252
7253 const serialization::reader::DeclContextLookupTable *
7254 ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
7255   auto I = Lookups.find(Primary);
7256   return I == Lookups.end() ? nullptr : &I->second;
7257 }
7258
7259 /// \brief Under non-PCH compilation the consumer receives the objc methods
7260 /// before receiving the implementation, and codegen depends on this.
7261 /// We simulate this by deserializing and passing to consumer the methods of the
7262 /// implementation before passing the deserialized implementation decl.
7263 static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
7264                                        ASTConsumer *Consumer) {
7265   assert(ImplD && Consumer);
7266
7267   for (auto *I : ImplD->methods())
7268     Consumer->HandleInterestingDecl(DeclGroupRef(I));
7269
7270   Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
7271 }
7272
7273 void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
7274   if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
7275     PassObjCImplDeclToConsumer(ImplD, Consumer);
7276   else
7277     Consumer->HandleInterestingDecl(DeclGroupRef(D));
7278 }
7279
7280 void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7281   this->Consumer = Consumer;
7282
7283   if (Consumer)
7284     PassInterestingDeclsToConsumer();
7285
7286   if (DeserializationListener)
7287     DeserializationListener->ReaderInitialized(this);
7288 }
7289
7290 void ASTReader::PrintStats() {
7291   std::fprintf(stderr, "*** AST File Statistics:\n");
7292
7293   unsigned NumTypesLoaded
7294     = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
7295                                       QualType());
7296   unsigned NumDeclsLoaded
7297     = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
7298                                       (Decl *)nullptr);
7299   unsigned NumIdentifiersLoaded
7300     = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
7301                                             IdentifiersLoaded.end(),
7302                                             (IdentifierInfo *)nullptr);
7303   unsigned NumMacrosLoaded
7304     = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
7305                                        MacrosLoaded.end(),
7306                                        (MacroInfo *)nullptr);
7307   unsigned NumSelectorsLoaded
7308     = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
7309                                           SelectorsLoaded.end(),
7310                                           Selector());
7311
7312   if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7313     std::fprintf(stderr, "  %u/%u source location entries read (%f%%)\n",
7314                  NumSLocEntriesRead, TotalNumSLocEntries,
7315                  ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7316   if (!TypesLoaded.empty())
7317     std::fprintf(stderr, "  %u/%u types read (%f%%)\n",
7318                  NumTypesLoaded, (unsigned)TypesLoaded.size(),
7319                  ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7320   if (!DeclsLoaded.empty())
7321     std::fprintf(stderr, "  %u/%u declarations read (%f%%)\n",
7322                  NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7323                  ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7324   if (!IdentifiersLoaded.empty())
7325     std::fprintf(stderr, "  %u/%u identifiers read (%f%%)\n",
7326                  NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7327                  ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7328   if (!MacrosLoaded.empty())
7329     std::fprintf(stderr, "  %u/%u macros read (%f%%)\n",
7330                  NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7331                  ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7332   if (!SelectorsLoaded.empty())
7333     std::fprintf(stderr, "  %u/%u selectors read (%f%%)\n",
7334                  NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7335                  ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7336   if (TotalNumStatements)
7337     std::fprintf(stderr, "  %u/%u statements read (%f%%)\n",
7338                  NumStatementsRead, TotalNumStatements,
7339                  ((float)NumStatementsRead/TotalNumStatements * 100));
7340   if (TotalNumMacros)
7341     std::fprintf(stderr, "  %u/%u macros read (%f%%)\n",
7342                  NumMacrosRead, TotalNumMacros,
7343                  ((float)NumMacrosRead/TotalNumMacros * 100));
7344   if (TotalLexicalDeclContexts)
7345     std::fprintf(stderr, "  %u/%u lexical declcontexts read (%f%%)\n",
7346                  NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7347                  ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7348                   * 100));
7349   if (TotalVisibleDeclContexts)
7350     std::fprintf(stderr, "  %u/%u visible declcontexts read (%f%%)\n",
7351                  NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7352                  ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7353                   * 100));
7354   if (TotalNumMethodPoolEntries) {
7355     std::fprintf(stderr, "  %u/%u method pool entries read (%f%%)\n",
7356                  NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7357                  ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7358                   * 100));
7359   }
7360   if (NumMethodPoolLookups) {
7361     std::fprintf(stderr, "  %u/%u method pool lookups succeeded (%f%%)\n",
7362                  NumMethodPoolHits, NumMethodPoolLookups,
7363                  ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
7364   }
7365   if (NumMethodPoolTableLookups) {
7366     std::fprintf(stderr, "  %u/%u method pool table lookups succeeded (%f%%)\n",
7367                  NumMethodPoolTableHits, NumMethodPoolTableLookups,
7368                  ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7369                   * 100.0));
7370   }
7371
7372   if (NumIdentifierLookupHits) {
7373     std::fprintf(stderr,
7374                  "  %u / %u identifier table lookups succeeded (%f%%)\n",
7375                  NumIdentifierLookupHits, NumIdentifierLookups,
7376                  (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
7377   }
7378
7379   if (GlobalIndex) {
7380     std::fprintf(stderr, "\n");
7381     GlobalIndex->printStats();
7382   }
7383
7384   std::fprintf(stderr, "\n");
7385   dump();
7386   std::fprintf(stderr, "\n");
7387 }
7388
7389 template<typename Key, typename ModuleFile, unsigned InitialCapacity>
7390 LLVM_DUMP_METHOD static void
7391 dumpModuleIDMap(StringRef Name,
7392                 const ContinuousRangeMap<Key, ModuleFile *,
7393                                          InitialCapacity> &Map) {
7394   if (Map.begin() == Map.end())
7395     return;
7396
7397   typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
7398   llvm::errs() << Name << ":\n";
7399   for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
7400        I != IEnd; ++I) {
7401     llvm::errs() << "  " << I->first << " -> " << I->second->FileName
7402       << "\n";
7403   }
7404 }
7405
7406 LLVM_DUMP_METHOD void ASTReader::dump() {
7407   llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7408   dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7409   dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7410   dumpModuleIDMap("Global type map", GlobalTypeMap);
7411   dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7412   dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7413   dumpModuleIDMap("Global macro map", GlobalMacroMap);
7414   dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7415   dumpModuleIDMap("Global selector map", GlobalSelectorMap);
7416   dumpModuleIDMap("Global preprocessed entity map",
7417                   GlobalPreprocessedEntityMap);
7418
7419   llvm::errs() << "\n*** PCH/Modules Loaded:";
7420   for (ModuleFile &M : ModuleMgr)
7421     M.dump();
7422 }
7423
7424 /// Return the amount of memory used by memory buffers, breaking down
7425 /// by heap-backed versus mmap'ed memory.
7426 void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
7427   for (ModuleFile &I : ModuleMgr) {
7428     if (llvm::MemoryBuffer *buf = I.Buffer) {
7429       size_t bytes = buf->getBufferSize();
7430       switch (buf->getBufferKind()) {
7431         case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7432           sizes.malloc_bytes += bytes;
7433           break;
7434         case llvm::MemoryBuffer::MemoryBuffer_MMap:
7435           sizes.mmap_bytes += bytes;
7436           break;
7437       }
7438     }
7439   }
7440 }
7441
7442 void ASTReader::InitializeSema(Sema &S) {
7443   SemaObj = &S;
7444   S.addExternalSource(this);
7445
7446   // Makes sure any declarations that were deserialized "too early"
7447   // still get added to the identifier's declaration chains.
7448   for (uint64_t ID : PreloadedDeclIDs) {
7449     NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7450     pushExternalDeclIntoScope(D, D->getDeclName());
7451   }
7452   PreloadedDeclIDs.clear();
7453
7454   // FIXME: What happens if these are changed by a module import?
7455   if (!FPPragmaOptions.empty()) {
7456     assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
7457     SemaObj->FPFeatures = FPOptions(FPPragmaOptions[0]);
7458   }
7459
7460   SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
7461   SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
7462   SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
7463
7464   UpdateSema();
7465 }
7466
7467 void ASTReader::UpdateSema() {
7468   assert(SemaObj && "no Sema to update");
7469
7470   // Load the offsets of the declarations that Sema references.
7471   // They will be lazily deserialized when needed.
7472   if (!SemaDeclRefs.empty()) {
7473     assert(SemaDeclRefs.size() % 3 == 0);
7474     for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
7475       if (!SemaObj->StdNamespace)
7476         SemaObj->StdNamespace = SemaDeclRefs[I];
7477       if (!SemaObj->StdBadAlloc)
7478         SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
7479       if (!SemaObj->StdAlignValT)
7480         SemaObj->StdAlignValT = SemaDeclRefs[I+2];
7481     }
7482     SemaDeclRefs.clear();
7483   }
7484
7485   // Update the state of pragmas. Use the same API as if we had encountered the
7486   // pragma in the source.
7487   if(OptimizeOffPragmaLocation.isValid())
7488     SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
7489   if (PragmaMSStructState != -1)
7490     SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
7491   if (PointersToMembersPragmaLocation.isValid()) {
7492     SemaObj->ActOnPragmaMSPointersToMembers(
7493         (LangOptions::PragmaMSPointersToMembersKind)
7494             PragmaMSPointersToMembersState,
7495         PointersToMembersPragmaLocation);
7496   }
7497   SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
7498
7499   if (PragmaPackCurrentValue) {
7500     // The bottom of the stack might have a default value. It must be adjusted
7501     // to the current value to ensure that the packing state is preserved after
7502     // popping entries that were included/imported from a PCH/module.
7503     bool DropFirst = false;
7504     if (!PragmaPackStack.empty() &&
7505         PragmaPackStack.front().Location.isInvalid()) {
7506       assert(PragmaPackStack.front().Value == SemaObj->PackStack.DefaultValue &&
7507              "Expected a default alignment value");
7508       SemaObj->PackStack.Stack.emplace_back(
7509           PragmaPackStack.front().SlotLabel, SemaObj->PackStack.CurrentValue,
7510           SemaObj->PackStack.CurrentPragmaLocation);
7511       DropFirst = true;
7512     }
7513     for (const auto &Entry :
7514          llvm::makeArrayRef(PragmaPackStack).drop_front(DropFirst ? 1 : 0))
7515       SemaObj->PackStack.Stack.emplace_back(Entry.SlotLabel, Entry.Value,
7516                                             Entry.Location);
7517     if (PragmaPackCurrentLocation.isInvalid()) {
7518       assert(*PragmaPackCurrentValue == SemaObj->PackStack.DefaultValue &&
7519              "Expected a default alignment value");
7520       // Keep the current values.
7521     } else {
7522       SemaObj->PackStack.CurrentValue = *PragmaPackCurrentValue;
7523       SemaObj->PackStack.CurrentPragmaLocation = PragmaPackCurrentLocation;
7524     }
7525   }
7526 }
7527
7528 IdentifierInfo *ASTReader::get(StringRef Name) {
7529   // Note that we are loading an identifier.
7530   Deserializing AnIdentifier(this);
7531
7532   IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
7533                                   NumIdentifierLookups,
7534                                   NumIdentifierLookupHits);
7535
7536   // We don't need to do identifier table lookups in C++ modules (we preload
7537   // all interesting declarations, and don't need to use the scope for name
7538   // lookups). Perform the lookup in PCH files, though, since we don't build
7539   // a complete initial identifier table if we're carrying on from a PCH.
7540   if (Context.getLangOpts().CPlusPlus) {
7541     for (auto F : ModuleMgr.pch_modules())
7542       if (Visitor(*F))
7543         break;
7544   } else {
7545     // If there is a global index, look there first to determine which modules
7546     // provably do not have any results for this identifier.
7547     GlobalModuleIndex::HitSet Hits;
7548     GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7549     if (!loadGlobalIndex()) {
7550       if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7551         HitsPtr = &Hits;
7552       }
7553     }
7554
7555     ModuleMgr.visit(Visitor, HitsPtr);
7556   }
7557
7558   IdentifierInfo *II = Visitor.getIdentifierInfo();
7559   markIdentifierUpToDate(II);
7560   return II;
7561 }
7562
7563 namespace clang {
7564
7565   /// \brief An identifier-lookup iterator that enumerates all of the
7566   /// identifiers stored within a set of AST files.
7567   class ASTIdentifierIterator : public IdentifierIterator {
7568     /// \brief The AST reader whose identifiers are being enumerated.
7569     const ASTReader &Reader;
7570
7571     /// \brief The current index into the chain of AST files stored in
7572     /// the AST reader.
7573     unsigned Index;
7574
7575     /// \brief The current position within the identifier lookup table
7576     /// of the current AST file.
7577     ASTIdentifierLookupTable::key_iterator Current;
7578
7579     /// \brief The end position within the identifier lookup table of
7580     /// the current AST file.
7581     ASTIdentifierLookupTable::key_iterator End;
7582
7583     /// \brief Whether to skip any modules in the ASTReader.
7584     bool SkipModules;
7585
7586   public:
7587     explicit ASTIdentifierIterator(const ASTReader &Reader,
7588                                    bool SkipModules = false);
7589
7590     StringRef Next() override;
7591   };
7592
7593 } // end namespace clang
7594
7595 ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7596                                              bool SkipModules)
7597     : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
7598 }
7599
7600 StringRef ASTIdentifierIterator::Next() {
7601   while (Current == End) {
7602     // If we have exhausted all of our AST files, we're done.
7603     if (Index == 0)
7604       return StringRef();
7605
7606     --Index;
7607     ModuleFile &F = Reader.ModuleMgr[Index];
7608     if (SkipModules && F.isModule())
7609       continue;
7610
7611     ASTIdentifierLookupTable *IdTable =
7612         (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
7613     Current = IdTable->key_begin();
7614     End = IdTable->key_end();
7615   }
7616
7617   // We have any identifiers remaining in the current AST file; return
7618   // the next one.
7619   StringRef Result = *Current;
7620   ++Current;
7621   return Result;
7622 }
7623
7624 namespace {
7625
7626 /// A utility for appending two IdentifierIterators.
7627 class ChainedIdentifierIterator : public IdentifierIterator {
7628   std::unique_ptr<IdentifierIterator> Current;
7629   std::unique_ptr<IdentifierIterator> Queued;
7630
7631 public:
7632   ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7633                             std::unique_ptr<IdentifierIterator> Second)
7634       : Current(std::move(First)), Queued(std::move(Second)) {}
7635
7636   StringRef Next() override {
7637     if (!Current)
7638       return StringRef();
7639
7640     StringRef result = Current->Next();
7641     if (!result.empty())
7642       return result;
7643
7644     // Try the queued iterator, which may itself be empty.
7645     Current.reset();
7646     std::swap(Current, Queued);
7647     return Next();
7648   }
7649 };
7650
7651 } // end anonymous namespace.
7652
7653 IdentifierIterator *ASTReader::getIdentifiers() {
7654   if (!loadGlobalIndex()) {
7655     std::unique_ptr<IdentifierIterator> ReaderIter(
7656         new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7657     std::unique_ptr<IdentifierIterator> ModulesIter(
7658         GlobalIndex->createIdentifierIterator());
7659     return new ChainedIdentifierIterator(std::move(ReaderIter),
7660                                          std::move(ModulesIter));
7661   }
7662
7663   return new ASTIdentifierIterator(*this);
7664 }
7665
7666 namespace clang {
7667 namespace serialization {
7668
7669   class ReadMethodPoolVisitor {
7670     ASTReader &Reader;
7671     Selector Sel;
7672     unsigned PriorGeneration;
7673     unsigned InstanceBits;
7674     unsigned FactoryBits;
7675     bool InstanceHasMoreThanOneDecl;
7676     bool FactoryHasMoreThanOneDecl;
7677     SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7678     SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
7679
7680   public:
7681     ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
7682                           unsigned PriorGeneration)
7683         : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
7684           InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7685           FactoryHasMoreThanOneDecl(false) {}
7686
7687     bool operator()(ModuleFile &M) {
7688       if (!M.SelectorLookupTable)
7689         return false;
7690
7691       // If we've already searched this module file, skip it now.
7692       if (M.Generation <= PriorGeneration)
7693         return true;
7694
7695       ++Reader.NumMethodPoolTableLookups;
7696       ASTSelectorLookupTable *PoolTable
7697         = (ASTSelectorLookupTable*)M.SelectorLookupTable;
7698       ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
7699       if (Pos == PoolTable->end())
7700         return false;
7701
7702       ++Reader.NumMethodPoolTableHits;
7703       ++Reader.NumSelectorsRead;
7704       // FIXME: Not quite happy with the statistics here. We probably should
7705       // disable this tracking when called via LoadSelector.
7706       // Also, should entries without methods count as misses?
7707       ++Reader.NumMethodPoolEntriesRead;
7708       ASTSelectorLookupTrait::data_type Data = *Pos;
7709       if (Reader.DeserializationListener)
7710         Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
7711
7712       InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7713       FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7714       InstanceBits = Data.InstanceBits;
7715       FactoryBits = Data.FactoryBits;
7716       InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7717       FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
7718       return true;
7719     }
7720
7721     /// \brief Retrieve the instance methods found by this visitor.
7722     ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7723       return InstanceMethods;
7724     }
7725
7726     /// \brief Retrieve the instance methods found by this visitor.
7727     ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
7728       return FactoryMethods;
7729     }
7730
7731     unsigned getInstanceBits() const { return InstanceBits; }
7732     unsigned getFactoryBits() const { return FactoryBits; }
7733     bool instanceHasMoreThanOneDecl() const {
7734       return InstanceHasMoreThanOneDecl;
7735     }
7736     bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
7737   };
7738
7739 } // end namespace serialization
7740 } // end namespace clang
7741
7742 /// \brief Add the given set of methods to the method list.
7743 static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7744                              ObjCMethodList &List) {
7745   for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7746     S.addMethodToGlobalList(&List, Methods[I]);
7747   }
7748 }
7749
7750 void ASTReader::ReadMethodPool(Selector Sel) {
7751   // Get the selector generation and update it to the current generation.
7752   unsigned &Generation = SelectorGeneration[Sel];
7753   unsigned PriorGeneration = Generation;
7754   Generation = getGeneration();
7755   SelectorOutOfDate[Sel] = false;
7756
7757   // Search for methods defined with this selector.
7758   ++NumMethodPoolLookups;
7759   ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
7760   ModuleMgr.visit(Visitor);
7761
7762   if (Visitor.getInstanceMethods().empty() &&
7763       Visitor.getFactoryMethods().empty())
7764     return;
7765
7766   ++NumMethodPoolHits;
7767
7768   if (!getSema())
7769     return;
7770
7771   Sema &S = *getSema();
7772   Sema::GlobalMethodPool::iterator Pos
7773     = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
7774
7775   Pos->second.first.setBits(Visitor.getInstanceBits());
7776   Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
7777   Pos->second.second.setBits(Visitor.getFactoryBits());
7778   Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
7779
7780   // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7781   // when building a module we keep every method individually and may need to
7782   // update hasMoreThanOneDecl as we add the methods.
7783   addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7784   addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
7785 }
7786
7787 void ASTReader::updateOutOfDateSelector(Selector Sel) {
7788   if (SelectorOutOfDate[Sel])
7789     ReadMethodPool(Sel);
7790 }
7791
7792 void ASTReader::ReadKnownNamespaces(
7793                           SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7794   Namespaces.clear();
7795
7796   for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
7797     if (NamespaceDecl *Namespace
7798                 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7799       Namespaces.push_back(Namespace);
7800   }
7801 }
7802
7803 void ASTReader::ReadUndefinedButUsed(
7804     llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
7805   for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7806     NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
7807     SourceLocation Loc =
7808         SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
7809     Undefined.insert(std::make_pair(D, Loc));
7810   }
7811 }
7812
7813 void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7814     FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7815                                                      Exprs) {
7816   for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7817     FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7818     uint64_t Count = DelayedDeleteExprs[Idx++];
7819     for (uint64_t C = 0; C < Count; ++C) {
7820       SourceLocation DeleteLoc =
7821           SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7822       const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7823       Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7824     }
7825   }
7826 }
7827
7828 void ASTReader::ReadTentativeDefinitions(
7829                   SmallVectorImpl<VarDecl *> &TentativeDefs) {
7830   for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7831     VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7832     if (Var)
7833       TentativeDefs.push_back(Var);
7834   }
7835   TentativeDefinitions.clear();
7836 }
7837
7838 void ASTReader::ReadUnusedFileScopedDecls(
7839                                SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7840   for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7841     DeclaratorDecl *D
7842       = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7843     if (D)
7844       Decls.push_back(D);
7845   }
7846   UnusedFileScopedDecls.clear();
7847 }
7848
7849 void ASTReader::ReadDelegatingConstructors(
7850                                  SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7851   for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7852     CXXConstructorDecl *D
7853       = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7854     if (D)
7855       Decls.push_back(D);
7856   }
7857   DelegatingCtorDecls.clear();
7858 }
7859
7860 void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7861   for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7862     TypedefNameDecl *D
7863       = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7864     if (D)
7865       Decls.push_back(D);
7866   }
7867   ExtVectorDecls.clear();
7868 }
7869
7870 void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7871     llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7872   for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7873        ++I) {
7874     TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7875         GetDecl(UnusedLocalTypedefNameCandidates[I]));
7876     if (D)
7877       Decls.insert(D);
7878   }
7879   UnusedLocalTypedefNameCandidates.clear();
7880 }
7881
7882 void ASTReader::ReadReferencedSelectors(
7883        SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7884   if (ReferencedSelectorsData.empty())
7885     return;
7886
7887   // If there are @selector references added them to its pool. This is for
7888   // implementation of -Wselector.
7889   unsigned int DataSize = ReferencedSelectorsData.size()-1;
7890   unsigned I = 0;
7891   while (I < DataSize) {
7892     Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7893     SourceLocation SelLoc
7894       = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7895     Sels.push_back(std::make_pair(Sel, SelLoc));
7896   }
7897   ReferencedSelectorsData.clear();
7898 }
7899
7900 void ASTReader::ReadWeakUndeclaredIdentifiers(
7901        SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7902   if (WeakUndeclaredIdentifiers.empty())
7903     return;
7904
7905   for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
7906     IdentifierInfo *WeakId
7907       = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7908     IdentifierInfo *AliasId
7909       = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7910     SourceLocation Loc
7911       = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7912     bool Used = WeakUndeclaredIdentifiers[I++];
7913     WeakInfo WI(AliasId, Loc);
7914     WI.setUsed(Used);
7915     WeakIDs.push_back(std::make_pair(WeakId, WI));
7916   }
7917   WeakUndeclaredIdentifiers.clear();
7918 }
7919
7920 void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7921   for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7922     ExternalVTableUse VT;
7923     VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7924     VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7925     VT.DefinitionRequired = VTableUses[Idx++];
7926     VTables.push_back(VT);
7927   }
7928
7929   VTableUses.clear();
7930 }
7931
7932 void ASTReader::ReadPendingInstantiations(
7933        SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7934   for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7935     ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7936     SourceLocation Loc
7937       = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7938
7939     Pending.push_back(std::make_pair(D, Loc));
7940   }
7941   PendingInstantiations.clear();
7942 }
7943
7944 void ASTReader::ReadLateParsedTemplates(
7945     llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
7946         &LPTMap) {
7947   for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7948        /* In loop */) {
7949     FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7950
7951     auto LT = llvm::make_unique<LateParsedTemplate>();
7952     LT->D = GetDecl(LateParsedTemplates[Idx++]);
7953
7954     ModuleFile *F = getOwningModuleFile(LT->D);
7955     assert(F && "No module");
7956
7957     unsigned TokN = LateParsedTemplates[Idx++];
7958     LT->Toks.reserve(TokN);
7959     for (unsigned T = 0; T < TokN; ++T)
7960       LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7961
7962     LPTMap.insert(std::make_pair(FD, std::move(LT)));
7963   }
7964
7965   LateParsedTemplates.clear();
7966 }
7967
7968 void ASTReader::LoadSelector(Selector Sel) {
7969   // It would be complicated to avoid reading the methods anyway. So don't.
7970   ReadMethodPool(Sel);
7971 }
7972
7973 void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7974   assert(ID && "Non-zero identifier ID required");
7975   assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7976   IdentifiersLoaded[ID - 1] = II;
7977   if (DeserializationListener)
7978     DeserializationListener->IdentifierRead(ID, II);
7979 }
7980
7981 /// \brief Set the globally-visible declarations associated with the given
7982 /// identifier.
7983 ///
7984 /// If the AST reader is currently in a state where the given declaration IDs
7985 /// cannot safely be resolved, they are queued until it is safe to resolve
7986 /// them.
7987 ///
7988 /// \param II an IdentifierInfo that refers to one or more globally-visible
7989 /// declarations.
7990 ///
7991 /// \param DeclIDs the set of declaration IDs with the name @p II that are
7992 /// visible at global scope.
7993 ///
7994 /// \param Decls if non-null, this vector will be populated with the set of
7995 /// deserialized declarations. These declarations will not be pushed into
7996 /// scope.
7997 void
7998 ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7999                               const SmallVectorImpl<uint32_t> &DeclIDs,
8000                                    SmallVectorImpl<Decl *> *Decls) {
8001   if (NumCurrentElementsDeserializing && !Decls) {
8002     PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
8003     return;
8004   }
8005
8006   for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
8007     if (!SemaObj) {
8008       // Queue this declaration so that it will be added to the
8009       // translation unit scope and identifier's declaration chain
8010       // once a Sema object is known.
8011       PreloadedDeclIDs.push_back(DeclIDs[I]);
8012       continue;
8013     }
8014
8015     NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
8016
8017     // If we're simply supposed to record the declarations, do so now.
8018     if (Decls) {
8019       Decls->push_back(D);
8020       continue;
8021     }
8022
8023     // Introduce this declaration into the translation-unit scope
8024     // and add it to the declaration chain for this identifier, so
8025     // that (unqualified) name lookup will find it.
8026     pushExternalDeclIntoScope(D, II);
8027   }
8028 }
8029
8030 IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
8031   if (ID == 0)
8032     return nullptr;
8033
8034   if (IdentifiersLoaded.empty()) {
8035     Error("no identifier table in AST file");
8036     return nullptr;
8037   }
8038
8039   ID -= 1;
8040   if (!IdentifiersLoaded[ID]) {
8041     GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8042     assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8043     ModuleFile *M = I->second;
8044     unsigned Index = ID - M->BaseIdentifierID;
8045     const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
8046
8047     // All of the strings in the AST file are preceded by a 16-bit length.
8048     // Extract that 16-bit length to avoid having to execute strlen().
8049     // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
8050     //  unsigned integers.  This is important to avoid integer overflow when
8051     //  we cast them to 'unsigned'.
8052     const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
8053     unsigned StrLen = (((unsigned) StrLenPtr[0])
8054                        | (((unsigned) StrLenPtr[1]) << 8)) - 1;
8055     auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
8056     IdentifiersLoaded[ID] = &II;
8057     markIdentifierFromAST(*this,  II);
8058     if (DeserializationListener)
8059       DeserializationListener->IdentifierRead(ID + 1, &II);
8060   }
8061
8062   return IdentifiersLoaded[ID];
8063 }
8064
8065 IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
8066   return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
8067 }
8068
8069 IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
8070   if (LocalID < NUM_PREDEF_IDENT_IDS)
8071     return LocalID;
8072
8073   if (!M.ModuleOffsetMap.empty())
8074     ReadModuleOffsetMap(M);
8075
8076   ContinuousRangeMap<uint32_t, int, 2>::iterator I
8077     = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
8078   assert(I != M.IdentifierRemap.end()
8079          && "Invalid index into identifier index remap");
8080
8081   return LocalID + I->second;
8082 }
8083
8084 MacroInfo *ASTReader::getMacro(MacroID ID) {
8085   if (ID == 0)
8086     return nullptr;
8087
8088   if (MacrosLoaded.empty()) {
8089     Error("no macro table in AST file");
8090     return nullptr;
8091   }
8092
8093   ID -= NUM_PREDEF_MACRO_IDS;
8094   if (!MacrosLoaded[ID]) {
8095     GlobalMacroMapType::iterator I
8096       = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8097     assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8098     ModuleFile *M = I->second;
8099     unsigned Index = ID - M->BaseMacroID;
8100     MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
8101
8102     if (DeserializationListener)
8103       DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8104                                          MacrosLoaded[ID]);
8105   }
8106
8107   return MacrosLoaded[ID];
8108 }
8109
8110 MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
8111   if (LocalID < NUM_PREDEF_MACRO_IDS)
8112     return LocalID;
8113
8114   if (!M.ModuleOffsetMap.empty())
8115     ReadModuleOffsetMap(M);
8116
8117   ContinuousRangeMap<uint32_t, int, 2>::iterator I
8118     = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8119   assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8120
8121   return LocalID + I->second;
8122 }
8123
8124 serialization::SubmoduleID
8125 ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
8126   if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8127     return LocalID;
8128
8129   if (!M.ModuleOffsetMap.empty())
8130     ReadModuleOffsetMap(M);
8131
8132   ContinuousRangeMap<uint32_t, int, 2>::iterator I
8133     = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
8134   assert(I != M.SubmoduleRemap.end()
8135          && "Invalid index into submodule index remap");
8136
8137   return LocalID + I->second;
8138 }
8139
8140 Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
8141   if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8142     assert(GlobalID == 0 && "Unhandled global submodule ID");
8143     return nullptr;
8144   }
8145
8146   if (GlobalID > SubmodulesLoaded.size()) {
8147     Error("submodule ID out of range in AST file");
8148     return nullptr;
8149   }
8150
8151   return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8152 }
8153
8154 Module *ASTReader::getModule(unsigned ID) {
8155   return getSubmodule(ID);
8156 }
8157
8158 ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
8159   if (ID & 1) {
8160     // It's a module, look it up by submodule ID.
8161     auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
8162     return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
8163   } else {
8164     // It's a prefix (preamble, PCH, ...). Look it up by index.
8165     unsigned IndexFromEnd = ID >> 1;
8166     assert(IndexFromEnd && "got reference to unknown module file");
8167     return getModuleManager().pch_modules().end()[-IndexFromEnd];
8168   }
8169 }
8170
8171 unsigned ASTReader::getModuleFileID(ModuleFile *F) {
8172   if (!F)
8173     return 1;
8174
8175   // For a file representing a module, use the submodule ID of the top-level
8176   // module as the file ID. For any other kind of file, the number of such
8177   // files loaded beforehand will be the same on reload.
8178   // FIXME: Is this true even if we have an explicit module file and a PCH?
8179   if (F->isModule())
8180     return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
8181
8182   auto PCHModules = getModuleManager().pch_modules();
8183   auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
8184   assert(I != PCHModules.end() && "emitting reference to unknown file");
8185   return (I - PCHModules.end()) << 1;
8186 }
8187
8188 llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
8189 ASTReader::getSourceDescriptor(unsigned ID) {
8190   if (const Module *M = getSubmodule(ID))
8191     return ExternalASTSource::ASTSourceDescriptor(*M);
8192
8193   // If there is only a single PCH, return it instead.
8194   // Chained PCH are not suported.
8195   const auto &PCHChain = ModuleMgr.pch_modules();
8196   if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
8197     ModuleFile &MF = ModuleMgr.getPrimaryModule();
8198     StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
8199     StringRef FileName = llvm::sys::path::filename(MF.FileName);
8200     return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
8201                                           MF.Signature);
8202   }
8203   return None;
8204 }
8205
8206 ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
8207   auto I = BodySource.find(FD);
8208   if (I == BodySource.end())
8209     return EK_ReplyHazy;
8210   return I->second ? EK_Never : EK_Always;
8211 }
8212
8213 Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
8214   return DecodeSelector(getGlobalSelectorID(M, LocalID));
8215 }
8216
8217 Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
8218   if (ID == 0)
8219     return Selector();
8220
8221   if (ID > SelectorsLoaded.size()) {
8222     Error("selector ID out of range in AST file");
8223     return Selector();
8224   }
8225
8226   if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
8227     // Load this selector from the selector table.
8228     GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
8229     assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
8230     ModuleFile &M = *I->second;
8231     ASTSelectorLookupTrait Trait(*this, M);
8232     unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
8233     SelectorsLoaded[ID - 1] =
8234       Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
8235     if (DeserializationListener)
8236       DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
8237   }
8238
8239   return SelectorsLoaded[ID - 1];
8240 }
8241
8242 Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
8243   return DecodeSelector(ID);
8244 }
8245
8246 uint32_t ASTReader::GetNumExternalSelectors() {
8247   // ID 0 (the null selector) is considered an external selector.
8248   return getTotalNumSelectors() + 1;
8249 }
8250
8251 serialization::SelectorID
8252 ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
8253   if (LocalID < NUM_PREDEF_SELECTOR_IDS)
8254     return LocalID;
8255
8256   if (!M.ModuleOffsetMap.empty())
8257     ReadModuleOffsetMap(M);
8258
8259   ContinuousRangeMap<uint32_t, int, 2>::iterator I
8260     = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
8261   assert(I != M.SelectorRemap.end()
8262          && "Invalid index into selector index remap");
8263
8264   return LocalID + I->second;
8265 }
8266
8267 DeclarationName
8268 ASTReader::ReadDeclarationName(ModuleFile &F,
8269                                const RecordData &Record, unsigned &Idx) {
8270   DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
8271   switch (Kind) {
8272   case DeclarationName::Identifier:
8273     return DeclarationName(GetIdentifierInfo(F, Record, Idx));
8274
8275   case DeclarationName::ObjCZeroArgSelector:
8276   case DeclarationName::ObjCOneArgSelector:
8277   case DeclarationName::ObjCMultiArgSelector:
8278     return DeclarationName(ReadSelector(F, Record, Idx));
8279
8280   case DeclarationName::CXXConstructorName:
8281     return Context.DeclarationNames.getCXXConstructorName(
8282                           Context.getCanonicalType(readType(F, Record, Idx)));
8283
8284   case DeclarationName::CXXDestructorName:
8285     return Context.DeclarationNames.getCXXDestructorName(
8286                           Context.getCanonicalType(readType(F, Record, Idx)));
8287
8288   case DeclarationName::CXXDeductionGuideName:
8289     return Context.DeclarationNames.getCXXDeductionGuideName(
8290                           ReadDeclAs<TemplateDecl>(F, Record, Idx));
8291
8292   case DeclarationName::CXXConversionFunctionName:
8293     return Context.DeclarationNames.getCXXConversionFunctionName(
8294                           Context.getCanonicalType(readType(F, Record, Idx)));
8295
8296   case DeclarationName::CXXOperatorName:
8297     return Context.DeclarationNames.getCXXOperatorName(
8298                                        (OverloadedOperatorKind)Record[Idx++]);
8299
8300   case DeclarationName::CXXLiteralOperatorName:
8301     return Context.DeclarationNames.getCXXLiteralOperatorName(
8302                                        GetIdentifierInfo(F, Record, Idx));
8303
8304   case DeclarationName::CXXUsingDirective:
8305     return DeclarationName::getUsingDirectiveName();
8306   }
8307
8308   llvm_unreachable("Invalid NameKind!");
8309 }
8310
8311 void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
8312                                        DeclarationNameLoc &DNLoc,
8313                                        DeclarationName Name,
8314                                       const RecordData &Record, unsigned &Idx) {
8315   switch (Name.getNameKind()) {
8316   case DeclarationName::CXXConstructorName:
8317   case DeclarationName::CXXDestructorName:
8318   case DeclarationName::CXXConversionFunctionName:
8319     DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
8320     break;
8321
8322   case DeclarationName::CXXOperatorName:
8323     DNLoc.CXXOperatorName.BeginOpNameLoc
8324         = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8325     DNLoc.CXXOperatorName.EndOpNameLoc
8326         = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8327     break;
8328
8329   case DeclarationName::CXXLiteralOperatorName:
8330     DNLoc.CXXLiteralOperatorName.OpNameLoc
8331         = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8332     break;
8333
8334   case DeclarationName::Identifier:
8335   case DeclarationName::ObjCZeroArgSelector:
8336   case DeclarationName::ObjCOneArgSelector:
8337   case DeclarationName::ObjCMultiArgSelector:
8338   case DeclarationName::CXXUsingDirective:
8339   case DeclarationName::CXXDeductionGuideName:
8340     break;
8341   }
8342 }
8343
8344 void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
8345                                         DeclarationNameInfo &NameInfo,
8346                                       const RecordData &Record, unsigned &Idx) {
8347   NameInfo.setName(ReadDeclarationName(F, Record, Idx));
8348   NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
8349   DeclarationNameLoc DNLoc;
8350   ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
8351   NameInfo.setInfo(DNLoc);
8352 }
8353
8354 void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
8355                                   const RecordData &Record, unsigned &Idx) {
8356   Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
8357   unsigned NumTPLists = Record[Idx++];
8358   Info.NumTemplParamLists = NumTPLists;
8359   if (NumTPLists) {
8360     Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
8361     for (unsigned i = 0; i != NumTPLists; ++i)
8362       Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
8363   }
8364 }
8365
8366 TemplateName
8367 ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
8368                             unsigned &Idx) {
8369   TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
8370   switch (Kind) {
8371   case TemplateName::Template:
8372       return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
8373
8374   case TemplateName::OverloadedTemplate: {
8375     unsigned size = Record[Idx++];
8376     UnresolvedSet<8> Decls;
8377     while (size--)
8378       Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
8379
8380     return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
8381   }
8382
8383   case TemplateName::QualifiedTemplate: {
8384     NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8385     bool hasTemplKeyword = Record[Idx++];
8386     TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
8387     return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
8388   }
8389
8390   case TemplateName::DependentTemplate: {
8391     NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8392     if (Record[Idx++])  // isIdentifier
8393       return Context.getDependentTemplateName(NNS,
8394                                                GetIdentifierInfo(F, Record,
8395                                                                  Idx));
8396     return Context.getDependentTemplateName(NNS,
8397                                          (OverloadedOperatorKind)Record[Idx++]);
8398   }
8399
8400   case TemplateName::SubstTemplateTemplateParm: {
8401     TemplateTemplateParmDecl *param
8402       = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8403     if (!param) return TemplateName();
8404     TemplateName replacement = ReadTemplateName(F, Record, Idx);
8405     return Context.getSubstTemplateTemplateParm(param, replacement);
8406   }
8407
8408   case TemplateName::SubstTemplateTemplateParmPack: {
8409     TemplateTemplateParmDecl *Param
8410       = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8411     if (!Param)
8412       return TemplateName();
8413
8414     TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
8415     if (ArgPack.getKind() != TemplateArgument::Pack)
8416       return TemplateName();
8417
8418     return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
8419   }
8420   }
8421
8422   llvm_unreachable("Unhandled template name kind!");
8423 }
8424
8425 TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
8426                                                  const RecordData &Record,
8427                                                  unsigned &Idx,
8428                                                  bool Canonicalize) {
8429   if (Canonicalize) {
8430     // The caller wants a canonical template argument. Sometimes the AST only
8431     // wants template arguments in canonical form (particularly as the template
8432     // argument lists of template specializations) so ensure we preserve that
8433     // canonical form across serialization.
8434     TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
8435     return Context.getCanonicalTemplateArgument(Arg);
8436   }
8437
8438   TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
8439   switch (Kind) {
8440   case TemplateArgument::Null:
8441     return TemplateArgument();
8442   case TemplateArgument::Type:
8443     return TemplateArgument(readType(F, Record, Idx));
8444   case TemplateArgument::Declaration: {
8445     ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
8446     return TemplateArgument(D, readType(F, Record, Idx));
8447   }
8448   case TemplateArgument::NullPtr:
8449     return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
8450   case TemplateArgument::Integral: {
8451     llvm::APSInt Value = ReadAPSInt(Record, Idx);
8452     QualType T = readType(F, Record, Idx);
8453     return TemplateArgument(Context, Value, T);
8454   }
8455   case TemplateArgument::Template:
8456     return TemplateArgument(ReadTemplateName(F, Record, Idx));
8457   case TemplateArgument::TemplateExpansion: {
8458     TemplateName Name = ReadTemplateName(F, Record, Idx);
8459     Optional<unsigned> NumTemplateExpansions;
8460     if (unsigned NumExpansions = Record[Idx++])
8461       NumTemplateExpansions = NumExpansions - 1;
8462     return TemplateArgument(Name, NumTemplateExpansions);
8463   }
8464   case TemplateArgument::Expression:
8465     return TemplateArgument(ReadExpr(F));
8466   case TemplateArgument::Pack: {
8467     unsigned NumArgs = Record[Idx++];
8468     TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
8469     for (unsigned I = 0; I != NumArgs; ++I)
8470       Args[I] = ReadTemplateArgument(F, Record, Idx);
8471     return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
8472   }
8473   }
8474
8475   llvm_unreachable("Unhandled template argument kind!");
8476 }
8477
8478 TemplateParameterList *
8479 ASTReader::ReadTemplateParameterList(ModuleFile &F,
8480                                      const RecordData &Record, unsigned &Idx) {
8481   SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
8482   SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
8483   SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
8484
8485   unsigned NumParams = Record[Idx++];
8486   SmallVector<NamedDecl *, 16> Params;
8487   Params.reserve(NumParams);
8488   while (NumParams--)
8489     Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
8490
8491   // TODO: Concepts
8492   TemplateParameterList* TemplateParams =
8493     TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
8494                                   Params, RAngleLoc, nullptr);
8495   return TemplateParams;
8496 }
8497
8498 void
8499 ASTReader::
8500 ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
8501                          ModuleFile &F, const RecordData &Record,
8502                          unsigned &Idx, bool Canonicalize) {
8503   unsigned NumTemplateArgs = Record[Idx++];
8504   TemplArgs.reserve(NumTemplateArgs);
8505   while (NumTemplateArgs--)
8506     TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
8507 }
8508
8509 /// \brief Read a UnresolvedSet structure.
8510 void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
8511                                   const RecordData &Record, unsigned &Idx) {
8512   unsigned NumDecls = Record[Idx++];
8513   Set.reserve(Context, NumDecls);
8514   while (NumDecls--) {
8515     DeclID ID = ReadDeclID(F, Record, Idx);
8516     AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
8517     Set.addLazyDecl(Context, ID, AS);
8518   }
8519 }
8520
8521 CXXBaseSpecifier
8522 ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
8523                                 const RecordData &Record, unsigned &Idx) {
8524   bool isVirtual = static_cast<bool>(Record[Idx++]);
8525   bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
8526   AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
8527   bool inheritConstructors = static_cast<bool>(Record[Idx++]);
8528   TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
8529   SourceRange Range = ReadSourceRange(F, Record, Idx);
8530   SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
8531   CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
8532                           EllipsisLoc);
8533   Result.setInheritConstructors(inheritConstructors);
8534   return Result;
8535 }
8536
8537 CXXCtorInitializer **
8538 ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
8539                                    unsigned &Idx) {
8540   unsigned NumInitializers = Record[Idx++];
8541   assert(NumInitializers && "wrote ctor initializers but have no inits");
8542   auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
8543   for (unsigned i = 0; i != NumInitializers; ++i) {
8544     TypeSourceInfo *TInfo = nullptr;
8545     bool IsBaseVirtual = false;
8546     FieldDecl *Member = nullptr;
8547     IndirectFieldDecl *IndirectMember = nullptr;
8548
8549     CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
8550     switch (Type) {
8551     case CTOR_INITIALIZER_BASE:
8552       TInfo = GetTypeSourceInfo(F, Record, Idx);
8553       IsBaseVirtual = Record[Idx++];
8554       break;
8555
8556     case CTOR_INITIALIZER_DELEGATING:
8557       TInfo = GetTypeSourceInfo(F, Record, Idx);
8558       break;
8559
8560      case CTOR_INITIALIZER_MEMBER:
8561       Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
8562       break;
8563
8564      case CTOR_INITIALIZER_INDIRECT_MEMBER:
8565       IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
8566       break;
8567     }
8568
8569     SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
8570     Expr *Init = ReadExpr(F);
8571     SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
8572     SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
8573
8574     CXXCtorInitializer *BOMInit;
8575     if (Type == CTOR_INITIALIZER_BASE)
8576       BOMInit = new (Context)
8577           CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8578                              RParenLoc, MemberOrEllipsisLoc);
8579     else if (Type == CTOR_INITIALIZER_DELEGATING)
8580       BOMInit = new (Context)
8581           CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
8582     else if (Member)
8583       BOMInit = new (Context)
8584           CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8585                              Init, RParenLoc);
8586     else
8587       BOMInit = new (Context)
8588           CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8589                              LParenLoc, Init, RParenLoc);
8590
8591     if (/*IsWritten*/Record[Idx++]) {
8592       unsigned SourceOrder = Record[Idx++];
8593       BOMInit->setSourceOrder(SourceOrder);
8594     }
8595
8596     CtorInitializers[i] = BOMInit;
8597   }
8598
8599   return CtorInitializers;
8600 }
8601
8602 NestedNameSpecifier *
8603 ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8604                                    const RecordData &Record, unsigned &Idx) {
8605   unsigned N = Record[Idx++];
8606   NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
8607   for (unsigned I = 0; I != N; ++I) {
8608     NestedNameSpecifier::SpecifierKind Kind
8609       = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8610     switch (Kind) {
8611     case NestedNameSpecifier::Identifier: {
8612       IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8613       NNS = NestedNameSpecifier::Create(Context, Prev, II);
8614       break;
8615     }
8616
8617     case NestedNameSpecifier::Namespace: {
8618       NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8619       NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8620       break;
8621     }
8622
8623     case NestedNameSpecifier::NamespaceAlias: {
8624       NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8625       NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8626       break;
8627     }
8628
8629     case NestedNameSpecifier::TypeSpec:
8630     case NestedNameSpecifier::TypeSpecWithTemplate: {
8631       const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8632       if (!T)
8633         return nullptr;
8634
8635       bool Template = Record[Idx++];
8636       NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8637       break;
8638     }
8639
8640     case NestedNameSpecifier::Global: {
8641       NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8642       // No associated value, and there can't be a prefix.
8643       break;
8644     }
8645
8646     case NestedNameSpecifier::Super: {
8647       CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8648       NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8649       break;
8650     }
8651     }
8652     Prev = NNS;
8653   }
8654   return NNS;
8655 }
8656
8657 NestedNameSpecifierLoc
8658 ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
8659                                       unsigned &Idx) {
8660   unsigned N = Record[Idx++];
8661   NestedNameSpecifierLocBuilder Builder;
8662   for (unsigned I = 0; I != N; ++I) {
8663     NestedNameSpecifier::SpecifierKind Kind
8664       = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8665     switch (Kind) {
8666     case NestedNameSpecifier::Identifier: {
8667       IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8668       SourceRange Range = ReadSourceRange(F, Record, Idx);
8669       Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8670       break;
8671     }
8672
8673     case NestedNameSpecifier::Namespace: {
8674       NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8675       SourceRange Range = ReadSourceRange(F, Record, Idx);
8676       Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8677       break;
8678     }
8679
8680     case NestedNameSpecifier::NamespaceAlias: {
8681       NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8682       SourceRange Range = ReadSourceRange(F, Record, Idx);
8683       Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8684       break;
8685     }
8686
8687     case NestedNameSpecifier::TypeSpec:
8688     case NestedNameSpecifier::TypeSpecWithTemplate: {
8689       bool Template = Record[Idx++];
8690       TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8691       if (!T)
8692         return NestedNameSpecifierLoc();
8693       SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8694
8695       // FIXME: 'template' keyword location not saved anywhere, so we fake it.
8696       Builder.Extend(Context,
8697                      Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8698                      T->getTypeLoc(), ColonColonLoc);
8699       break;
8700     }
8701
8702     case NestedNameSpecifier::Global: {
8703       SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8704       Builder.MakeGlobal(Context, ColonColonLoc);
8705       break;
8706     }
8707
8708     case NestedNameSpecifier::Super: {
8709       CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8710       SourceRange Range = ReadSourceRange(F, Record, Idx);
8711       Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8712       break;
8713     }
8714     }
8715   }
8716
8717   return Builder.getWithLocInContext(Context);
8718 }
8719
8720 SourceRange
8721 ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8722                            unsigned &Idx) {
8723   SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8724   SourceLocation end = ReadSourceLocation(F, Record, Idx);
8725   return SourceRange(beg, end);
8726 }
8727
8728 /// \brief Read an integral value
8729 llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8730   unsigned BitWidth = Record[Idx++];
8731   unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8732   llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8733   Idx += NumWords;
8734   return Result;
8735 }
8736
8737 /// \brief Read a signed integral value
8738 llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8739   bool isUnsigned = Record[Idx++];
8740   return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8741 }
8742
8743 /// \brief Read a floating-point value
8744 llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8745                                      const llvm::fltSemantics &Sem,
8746                                      unsigned &Idx) {
8747   return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
8748 }
8749
8750 // \brief Read a string
8751 std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8752   unsigned Len = Record[Idx++];
8753   std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8754   Idx += Len;
8755   return Result;
8756 }
8757
8758 std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8759                                 unsigned &Idx) {
8760   std::string Filename = ReadString(Record, Idx);
8761   ResolveImportedPath(F, Filename);
8762   return Filename;
8763 }
8764
8765 VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
8766                                          unsigned &Idx) {
8767   unsigned Major = Record[Idx++];
8768   unsigned Minor = Record[Idx++];
8769   unsigned Subminor = Record[Idx++];
8770   if (Minor == 0)
8771     return VersionTuple(Major);
8772   if (Subminor == 0)
8773     return VersionTuple(Major, Minor - 1);
8774   return VersionTuple(Major, Minor - 1, Subminor - 1);
8775 }
8776
8777 CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
8778                                           const RecordData &Record,
8779                                           unsigned &Idx) {
8780   CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8781   return CXXTemporary::Create(Context, Decl);
8782 }
8783
8784 DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
8785   return Diag(CurrentImportLoc, DiagID);
8786 }
8787
8788 DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
8789   return Diags.Report(Loc, DiagID);
8790 }
8791
8792 /// \brief Retrieve the identifier table associated with the
8793 /// preprocessor.
8794 IdentifierTable &ASTReader::getIdentifierTable() {
8795   return PP.getIdentifierTable();
8796 }
8797
8798 /// \brief Record that the given ID maps to the given switch-case
8799 /// statement.
8800 void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
8801   assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
8802          "Already have a SwitchCase with this ID");
8803   (*CurrSwitchCaseStmts)[ID] = SC;
8804 }
8805
8806 /// \brief Retrieve the switch-case statement with the given ID.
8807 SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
8808   assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
8809   return (*CurrSwitchCaseStmts)[ID];
8810 }
8811
8812 void ASTReader::ClearSwitchCaseIDs() {
8813   CurrSwitchCaseStmts->clear();
8814 }
8815
8816 void ASTReader::ReadComments() {
8817   std::vector<RawComment *> Comments;
8818   for (SmallVectorImpl<std::pair<BitstreamCursor,
8819                                  serialization::ModuleFile *> >::iterator
8820        I = CommentsCursors.begin(),
8821        E = CommentsCursors.end();
8822        I != E; ++I) {
8823     Comments.clear();
8824     BitstreamCursor &Cursor = I->first;
8825     serialization::ModuleFile &F = *I->second;
8826     SavedStreamPosition SavedPosition(Cursor);
8827
8828     RecordData Record;
8829     while (true) {
8830       llvm::BitstreamEntry Entry =
8831         Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
8832
8833       switch (Entry.Kind) {
8834       case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8835       case llvm::BitstreamEntry::Error:
8836         Error("malformed block record in AST file");
8837         return;
8838       case llvm::BitstreamEntry::EndBlock:
8839         goto NextCursor;
8840       case llvm::BitstreamEntry::Record:
8841         // The interesting case.
8842         break;
8843       }
8844
8845       // Read a record.
8846       Record.clear();
8847       switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
8848       case COMMENTS_RAW_COMMENT: {
8849         unsigned Idx = 0;
8850         SourceRange SR = ReadSourceRange(F, Record, Idx);
8851         RawComment::CommentKind Kind =
8852             (RawComment::CommentKind) Record[Idx++];
8853         bool IsTrailingComment = Record[Idx++];
8854         bool IsAlmostTrailingComment = Record[Idx++];
8855         Comments.push_back(new (Context) RawComment(
8856             SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8857             Context.getLangOpts().CommentOpts.ParseAllComments));
8858         break;
8859       }
8860       }
8861     }
8862   NextCursor:
8863     // De-serialized SourceLocations get negative FileIDs for other modules,
8864     // potentially invalidating the original order. Sort it again.
8865     std::sort(Comments.begin(), Comments.end(),
8866               BeforeThanCompare<RawComment>(SourceMgr));
8867     Context.Comments.addDeserializedComments(Comments);
8868   }
8869 }
8870
8871 void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
8872                                 bool IncludeSystem, bool Complain,
8873                     llvm::function_ref<void(const serialization::InputFile &IF,
8874                                             bool isSystem)> Visitor) {
8875   unsigned NumUserInputs = MF.NumUserInputFiles;
8876   unsigned NumInputs = MF.InputFilesLoaded.size();
8877   assert(NumUserInputs <= NumInputs);
8878   unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
8879   for (unsigned I = 0; I < N; ++I) {
8880     bool IsSystem = I >= NumUserInputs;
8881     InputFile IF = getInputFile(MF, I+1, Complain);
8882     Visitor(IF, IsSystem);
8883   }
8884 }
8885
8886 std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8887   // If we know the owning module, use it.
8888   if (Module *M = D->getImportedOwningModule())
8889     return M->getFullModuleName();
8890
8891   // Otherwise, use the name of the top-level module the decl is within.
8892   if (ModuleFile *M = getOwningModuleFile(D))
8893     return M->ModuleName;
8894
8895   // Not from a module.
8896   return "";
8897 }
8898
8899 void ASTReader::finishPendingActions() {
8900   while (!PendingIdentifierInfos.empty() ||
8901          !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
8902          !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
8903          !PendingUpdateRecords.empty()) {
8904     // If any identifiers with corresponding top-level declarations have
8905     // been loaded, load those declarations now.
8906     typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8907       TopLevelDeclsMap;
8908     TopLevelDeclsMap TopLevelDecls;
8909
8910     while (!PendingIdentifierInfos.empty()) {
8911       IdentifierInfo *II = PendingIdentifierInfos.back().first;
8912       SmallVector<uint32_t, 4> DeclIDs =
8913           std::move(PendingIdentifierInfos.back().second);
8914       PendingIdentifierInfos.pop_back();
8915
8916       SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
8917     }
8918
8919     // For each decl chain that we wanted to complete while deserializing, mark
8920     // it as "still needs to be completed".
8921     for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8922       markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8923     }
8924     PendingIncompleteDeclChains.clear();
8925
8926     // Load pending declaration chains.
8927     for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
8928       loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
8929     PendingDeclChains.clear();
8930
8931     // Make the most recent of the top-level declarations visible.
8932     for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8933            TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
8934       IdentifierInfo *II = TLD->first;
8935       for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
8936         pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
8937       }
8938     }
8939
8940     // Load any pending macro definitions.
8941     for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
8942       IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8943       SmallVector<PendingMacroInfo, 2> GlobalIDs;
8944       GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8945       // Initialize the macro history from chained-PCHs ahead of module imports.
8946       for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
8947            ++IDIdx) {
8948         const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8949         if (!Info.M->isModule())
8950           resolvePendingMacro(II, Info);
8951       }
8952       // Handle module imports.
8953       for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
8954            ++IDIdx) {
8955         const PendingMacroInfo &Info = GlobalIDs[IDIdx];
8956         if (Info.M->isModule())
8957           resolvePendingMacro(II, Info);
8958       }
8959     }
8960     PendingMacroIDs.clear();
8961
8962     // Wire up the DeclContexts for Decls that we delayed setting until
8963     // recursive loading is completed.
8964     while (!PendingDeclContextInfos.empty()) {
8965       PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8966       PendingDeclContextInfos.pop_front();
8967       DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8968       DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8969       Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8970     }
8971
8972     // Perform any pending declaration updates.
8973     while (!PendingUpdateRecords.empty()) {
8974       auto Update = PendingUpdateRecords.pop_back_val();
8975       ReadingKindTracker ReadingKind(Read_Decl, *this);
8976       loadDeclUpdateRecords(Update);
8977     }
8978   }
8979
8980   // At this point, all update records for loaded decls are in place, so any
8981   // fake class definitions should have become real.
8982   assert(PendingFakeDefinitionData.empty() &&
8983          "faked up a class definition but never saw the real one");
8984
8985   // If we deserialized any C++ or Objective-C class definitions, any
8986   // Objective-C protocol definitions, or any redeclarable templates, make sure
8987   // that all redeclarations point to the definitions. Note that this can only
8988   // happen now, after the redeclaration chains have been fully wired.
8989   for (Decl *D : PendingDefinitions) {
8990     if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
8991       if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
8992         // Make sure that the TagType points at the definition.
8993         const_cast<TagType*>(TagT)->decl = TD;
8994       }
8995
8996       if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
8997         for (auto *R = getMostRecentExistingDecl(RD); R;
8998              R = R->getPreviousDecl()) {
8999           assert((R == D) ==
9000                      cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
9001                  "declaration thinks it's the definition but it isn't");
9002           cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
9003         }
9004       }
9005
9006       continue;
9007     }
9008
9009     if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
9010       // Make sure that the ObjCInterfaceType points at the definition.
9011       const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9012         ->Decl = ID;
9013
9014       for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9015         cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9016
9017       continue;
9018     }
9019
9020     if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
9021       for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9022         cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9023
9024       continue;
9025     }
9026
9027     auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
9028     for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9029       cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
9030   }
9031   PendingDefinitions.clear();
9032
9033   // Load the bodies of any functions or methods we've encountered. We do
9034   // this now (delayed) so that we can be sure that the declaration chains
9035   // have been fully wired up (hasBody relies on this).
9036   // FIXME: We shouldn't require complete redeclaration chains here.
9037   for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9038                                PBEnd = PendingBodies.end();
9039        PB != PBEnd; ++PB) {
9040     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
9041       // FIXME: Check for =delete/=default?
9042       // FIXME: Complain about ODR violations here?
9043       const FunctionDecl *Defn = nullptr;
9044       if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
9045         FD->setLazyBody(PB->second);
9046       } else
9047         mergeDefinitionVisibility(const_cast<FunctionDecl*>(Defn), FD);
9048       continue;
9049     }
9050
9051     ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
9052     if (!getContext().getLangOpts().Modules || !MD->hasBody())
9053       MD->setLazyBody(PB->second);
9054   }
9055   PendingBodies.clear();
9056
9057   // Do some cleanup.
9058   for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9059     getContext().deduplicateMergedDefinitonsFor(ND);
9060   PendingMergedDefinitionsToDeduplicate.clear();
9061 }
9062
9063 void ASTReader::diagnoseOdrViolations() {
9064   if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
9065     return;
9066
9067   // Trigger the import of the full definition of each class that had any
9068   // odr-merging problems, so we can produce better diagnostics for them.
9069   // These updates may in turn find and diagnose some ODR failures, so take
9070   // ownership of the set first.
9071   auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
9072   PendingOdrMergeFailures.clear();
9073   for (auto &Merge : OdrMergeFailures) {
9074     Merge.first->buildLookup();
9075     Merge.first->decls_begin();
9076     Merge.first->bases_begin();
9077     Merge.first->vbases_begin();
9078     for (auto *RD : Merge.second) {
9079       RD->decls_begin();
9080       RD->bases_begin();
9081       RD->vbases_begin();
9082     }
9083   }
9084
9085   // For each declaration from a merged context, check that the canonical
9086   // definition of that context also contains a declaration of the same
9087   // entity.
9088   //
9089   // Caution: this loop does things that might invalidate iterators into
9090   // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
9091   while (!PendingOdrMergeChecks.empty()) {
9092     NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
9093
9094     // FIXME: Skip over implicit declarations for now. This matters for things
9095     // like implicitly-declared special member functions. This isn't entirely
9096     // correct; we can end up with multiple unmerged declarations of the same
9097     // implicit entity.
9098     if (D->isImplicit())
9099       continue;
9100
9101     DeclContext *CanonDef = D->getDeclContext();
9102
9103     bool Found = false;
9104     const Decl *DCanon = D->getCanonicalDecl();
9105
9106     for (auto RI : D->redecls()) {
9107       if (RI->getLexicalDeclContext() == CanonDef) {
9108         Found = true;
9109         break;
9110       }
9111     }
9112     if (Found)
9113       continue;
9114
9115     // Quick check failed, time to do the slow thing. Note, we can't just
9116     // look up the name of D in CanonDef here, because the member that is
9117     // in CanonDef might not be found by name lookup (it might have been
9118     // replaced by a more recent declaration in the lookup table), and we
9119     // can't necessarily find it in the redeclaration chain because it might
9120     // be merely mergeable, not redeclarable.
9121     llvm::SmallVector<const NamedDecl*, 4> Candidates;
9122     for (auto *CanonMember : CanonDef->decls()) {
9123       if (CanonMember->getCanonicalDecl() == DCanon) {
9124         // This can happen if the declaration is merely mergeable and not
9125         // actually redeclarable (we looked for redeclarations earlier).
9126         //
9127         // FIXME: We should be able to detect this more efficiently, without
9128         // pulling in all of the members of CanonDef.
9129         Found = true;
9130         break;
9131       }
9132       if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
9133         if (ND->getDeclName() == D->getDeclName())
9134           Candidates.push_back(ND);
9135     }
9136
9137     if (!Found) {
9138       // The AST doesn't like TagDecls becoming invalid after they've been
9139       // completed. We only really need to mark FieldDecls as invalid here.
9140       if (!isa<TagDecl>(D))
9141         D->setInvalidDecl();
9142
9143       // Ensure we don't accidentally recursively enter deserialization while
9144       // we're producing our diagnostic.
9145       Deserializing RecursionGuard(this);
9146
9147       std::string CanonDefModule =
9148           getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
9149       Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9150         << D << getOwningModuleNameForDiagnostic(D)
9151         << CanonDef << CanonDefModule.empty() << CanonDefModule;
9152
9153       if (Candidates.empty())
9154         Diag(cast<Decl>(CanonDef)->getLocation(),
9155              diag::note_module_odr_violation_no_possible_decls) << D;
9156       else {
9157         for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
9158           Diag(Candidates[I]->getLocation(),
9159                diag::note_module_odr_violation_possible_decl)
9160             << Candidates[I];
9161       }
9162
9163       DiagnosedOdrMergeFailures.insert(CanonDef);
9164     }
9165   }
9166
9167   if (OdrMergeFailures.empty())
9168     return;
9169
9170   // Ensure we don't accidentally recursively enter deserialization while
9171   // we're producing our diagnostics.
9172   Deserializing RecursionGuard(this);
9173
9174   // Issue any pending ODR-failure diagnostics.
9175   for (auto &Merge : OdrMergeFailures) {
9176     // If we've already pointed out a specific problem with this class, don't
9177     // bother issuing a general "something's different" diagnostic.
9178     if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
9179       continue;
9180
9181     bool Diagnosed = false;
9182     CXXRecordDecl *FirstRecord = Merge.first;
9183     std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
9184     for (CXXRecordDecl *SecondRecord : Merge.second) {
9185       // Multiple different declarations got merged together; tell the user
9186       // where they came from.
9187       if (FirstRecord == SecondRecord)
9188         continue;
9189
9190       std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
9191       using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
9192       DeclHashes FirstHashes;
9193       DeclHashes SecondHashes;
9194       ODRHash Hash;
9195
9196       auto PopulateHashes = [&Hash, FirstRecord](DeclHashes &Hashes,
9197                                                  CXXRecordDecl *Record) {
9198         for (auto *D : Record->decls()) {
9199           // Due to decl merging, the first CXXRecordDecl is the parent of
9200           // Decls in both records.
9201           if (!ODRHash::isWhitelistedDecl(D, FirstRecord))
9202             continue;
9203           Hash.clear();
9204           Hash.AddSubDecl(D);
9205           Hashes.emplace_back(D, Hash.CalculateHash());
9206         }
9207       };
9208       PopulateHashes(FirstHashes, FirstRecord);
9209       PopulateHashes(SecondHashes, SecondRecord);
9210
9211       // Used with err_module_odr_violation_mismatch_decl and
9212       // note_module_odr_violation_mismatch_decl
9213       enum {
9214         EndOfClass,
9215         PublicSpecifer,
9216         PrivateSpecifer,
9217         ProtectedSpecifer,
9218         StaticAssert,
9219         Field,
9220         CXXMethod,
9221         Other
9222       } FirstDiffType = Other,
9223         SecondDiffType = Other;
9224
9225       auto DifferenceSelector = [](Decl *D) {
9226         assert(D && "valid Decl required");
9227         switch (D->getKind()) {
9228         default:
9229           return Other;
9230         case Decl::AccessSpec:
9231           switch (D->getAccess()) {
9232           case AS_public:
9233             return PublicSpecifer;
9234           case AS_private:
9235             return PrivateSpecifer;
9236           case AS_protected:
9237             return ProtectedSpecifer;
9238           case AS_none:
9239             break;
9240           }
9241           llvm_unreachable("Invalid access specifier");
9242         case Decl::StaticAssert:
9243           return StaticAssert;
9244         case Decl::Field:
9245           return Field;
9246         case Decl::CXXMethod:
9247           return CXXMethod;
9248         }
9249       };
9250
9251       Decl *FirstDecl = nullptr;
9252       Decl *SecondDecl = nullptr;
9253       auto FirstIt = FirstHashes.begin();
9254       auto SecondIt = SecondHashes.begin();
9255
9256       // If there is a diagnoseable difference, FirstDiffType and
9257       // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
9258       // filled in if not EndOfClass.
9259       while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
9260         if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
9261             FirstIt->second == SecondIt->second) {
9262           ++FirstIt;
9263           ++SecondIt;
9264           continue;
9265         }
9266
9267         FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
9268         SecondDecl = SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
9269
9270         FirstDiffType = FirstDecl ? DifferenceSelector(FirstDecl) : EndOfClass;
9271         SecondDiffType =
9272             SecondDecl ? DifferenceSelector(SecondDecl) : EndOfClass;
9273
9274         break;
9275       }
9276
9277       if (FirstDiffType == Other || SecondDiffType == Other) {
9278         // Reaching this point means an unexpected Decl was encountered
9279         // or no difference was detected.  This causes a generic error
9280         // message to be emitted.
9281         Diag(FirstRecord->getLocation(),
9282              diag::err_module_odr_violation_different_definitions)
9283             << FirstRecord << FirstModule.empty() << FirstModule;
9284
9285         Diag(SecondRecord->getLocation(),
9286              diag::note_module_odr_violation_different_definitions)
9287             << SecondModule;
9288         Diagnosed = true;
9289         break;
9290       }
9291
9292       if (FirstDiffType != SecondDiffType) {
9293         SourceLocation FirstLoc;
9294         SourceRange FirstRange;
9295         if (FirstDiffType == EndOfClass) {
9296           FirstLoc = FirstRecord->getBraceRange().getEnd();
9297         } else {
9298           FirstLoc = FirstIt->first->getLocation();
9299           FirstRange = FirstIt->first->getSourceRange();
9300         }
9301         Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
9302             << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
9303             << FirstDiffType;
9304
9305         SourceLocation SecondLoc;
9306         SourceRange SecondRange;
9307         if (SecondDiffType == EndOfClass) {
9308           SecondLoc = SecondRecord->getBraceRange().getEnd();
9309         } else {
9310           SecondLoc = SecondDecl->getLocation();
9311           SecondRange = SecondDecl->getSourceRange();
9312         }
9313         Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
9314             << SecondModule << SecondRange << SecondDiffType;
9315         Diagnosed = true;
9316         break;
9317       }
9318
9319       assert(FirstDiffType == SecondDiffType);
9320
9321       // Used with err_module_odr_violation_mismatch_decl_diff and
9322       // note_module_odr_violation_mismatch_decl_diff
9323       enum ODRDeclDifference{
9324         StaticAssertCondition,
9325         StaticAssertMessage,
9326         StaticAssertOnlyMessage,
9327         FieldName,
9328         FieldTypeName,
9329         FieldSingleBitField,
9330         FieldDifferentWidthBitField,
9331         FieldSingleMutable,
9332         FieldSingleInitializer,
9333         FieldDifferentInitializers,
9334         MethodName,
9335         MethodDeleted,
9336         MethodVirtual,
9337         MethodStatic,
9338         MethodVolatile,
9339         MethodConst,
9340         MethodInline,
9341         MethodNumberParameters,
9342         MethodParameterType,
9343         MethodParameterName,
9344       };
9345
9346       // These lambdas have the common portions of the ODR diagnostics.  This
9347       // has the same return as Diag(), so addition parameters can be passed
9348       // in with operator<<
9349       auto ODRDiagError = [FirstRecord, &FirstModule, this](
9350           SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9351         return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
9352                << FirstRecord << FirstModule.empty() << FirstModule << Range
9353                << DiffType;
9354       };
9355       auto ODRDiagNote = [&SecondModule, this](
9356           SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9357         return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
9358                << SecondModule << Range << DiffType;
9359       };
9360
9361       auto ComputeODRHash = [&Hash](const Stmt* S) {
9362         assert(S);
9363         Hash.clear();
9364         Hash.AddStmt(S);
9365         return Hash.CalculateHash();
9366       };
9367
9368       auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
9369         Hash.clear();
9370         Hash.AddQualType(Ty);
9371         return Hash.CalculateHash();
9372       };
9373
9374       switch (FirstDiffType) {
9375       case Other:
9376       case EndOfClass:
9377       case PublicSpecifer:
9378       case PrivateSpecifer:
9379       case ProtectedSpecifer:
9380         llvm_unreachable("Invalid diff type");
9381
9382       case StaticAssert: {
9383         StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
9384         StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
9385
9386         Expr *FirstExpr = FirstSA->getAssertExpr();
9387         Expr *SecondExpr = SecondSA->getAssertExpr();
9388         unsigned FirstODRHash = ComputeODRHash(FirstExpr);
9389         unsigned SecondODRHash = ComputeODRHash(SecondExpr);
9390         if (FirstODRHash != SecondODRHash) {
9391           ODRDiagError(FirstExpr->getLocStart(), FirstExpr->getSourceRange(),
9392                        StaticAssertCondition);
9393           ODRDiagNote(SecondExpr->getLocStart(),
9394                       SecondExpr->getSourceRange(), StaticAssertCondition);
9395           Diagnosed = true;
9396           break;
9397         }
9398
9399         StringLiteral *FirstStr = FirstSA->getMessage();
9400         StringLiteral *SecondStr = SecondSA->getMessage();
9401         assert((FirstStr || SecondStr) && "Both messages cannot be empty");
9402         if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
9403           SourceLocation FirstLoc, SecondLoc;
9404           SourceRange FirstRange, SecondRange;
9405           if (FirstStr) {
9406             FirstLoc = FirstStr->getLocStart();
9407             FirstRange = FirstStr->getSourceRange();
9408           } else {
9409             FirstLoc = FirstSA->getLocStart();
9410             FirstRange = FirstSA->getSourceRange();
9411           }
9412           if (SecondStr) {
9413             SecondLoc = SecondStr->getLocStart();
9414             SecondRange = SecondStr->getSourceRange();
9415           } else {
9416             SecondLoc = SecondSA->getLocStart();
9417             SecondRange = SecondSA->getSourceRange();
9418           }
9419           ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage)
9420               << (FirstStr == nullptr);
9421           ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage)
9422               << (SecondStr == nullptr);
9423           Diagnosed = true;
9424           break;
9425         }
9426
9427         if (FirstStr && SecondStr &&
9428             FirstStr->getString() != SecondStr->getString()) {
9429           ODRDiagError(FirstStr->getLocStart(), FirstStr->getSourceRange(),
9430                        StaticAssertMessage);
9431           ODRDiagNote(SecondStr->getLocStart(), SecondStr->getSourceRange(),
9432                       StaticAssertMessage);
9433           Diagnosed = true;
9434           break;
9435         }
9436         break;
9437       }
9438       case Field: {
9439         FieldDecl *FirstField = cast<FieldDecl>(FirstDecl);
9440         FieldDecl *SecondField = cast<FieldDecl>(SecondDecl);
9441         IdentifierInfo *FirstII = FirstField->getIdentifier();
9442         IdentifierInfo *SecondII = SecondField->getIdentifier();
9443         if (FirstII->getName() != SecondII->getName()) {
9444           ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9445                        FieldName)
9446               << FirstII;
9447           ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9448                       FieldName)
9449               << SecondII;
9450
9451           Diagnosed = true;
9452           break;
9453         }
9454
9455         assert(
9456             Context.hasSameType(FirstField->getType(), SecondField->getType()));
9457
9458         QualType FirstType = FirstField->getType();
9459         QualType SecondType = SecondField->getType();
9460         if (ComputeQualTypeODRHash(FirstType) !=
9461             ComputeQualTypeODRHash(SecondType)) {
9462           ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9463                        FieldTypeName)
9464               << FirstII << FirstType;
9465           ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9466                       FieldTypeName)
9467               << SecondII << SecondType;
9468
9469           Diagnosed = true;
9470           break;
9471         }
9472
9473         const bool IsFirstBitField = FirstField->isBitField();
9474         const bool IsSecondBitField = SecondField->isBitField();
9475         if (IsFirstBitField != IsSecondBitField) {
9476           ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9477                        FieldSingleBitField)
9478               << FirstII << IsFirstBitField;
9479           ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9480                       FieldSingleBitField)
9481               << SecondII << IsSecondBitField;
9482           Diagnosed = true;
9483           break;
9484         }
9485
9486         if (IsFirstBitField && IsSecondBitField) {
9487           ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9488                        FieldDifferentWidthBitField)
9489               << FirstII << FirstField->getBitWidth()->getSourceRange();
9490           ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9491                       FieldDifferentWidthBitField)
9492               << SecondII << SecondField->getBitWidth()->getSourceRange();
9493           Diagnosed = true;
9494           break;
9495         }
9496
9497         const bool IsFirstMutable = FirstField->isMutable();
9498         const bool IsSecondMutable = SecondField->isMutable();
9499         if (IsFirstMutable != IsSecondMutable) {
9500           ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9501                        FieldSingleMutable)
9502               << FirstII << IsFirstMutable;
9503           ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9504                       FieldSingleMutable)
9505               << SecondII << IsSecondMutable;
9506           Diagnosed = true;
9507           break;
9508         }
9509
9510         const Expr *FirstInitializer = FirstField->getInClassInitializer();
9511         const Expr *SecondInitializer = SecondField->getInClassInitializer();
9512         if ((!FirstInitializer && SecondInitializer) ||
9513             (FirstInitializer && !SecondInitializer)) {
9514           ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9515                        FieldSingleInitializer)
9516               << FirstII << (FirstInitializer != nullptr);
9517           ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9518                       FieldSingleInitializer)
9519               << SecondII << (SecondInitializer != nullptr);
9520           Diagnosed = true;
9521           break;
9522         }
9523
9524         if (FirstInitializer && SecondInitializer) {
9525           unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
9526           unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
9527           if (FirstInitHash != SecondInitHash) {
9528             ODRDiagError(FirstField->getLocation(),
9529                          FirstField->getSourceRange(),
9530                          FieldDifferentInitializers)
9531                 << FirstII << FirstInitializer->getSourceRange();
9532             ODRDiagNote(SecondField->getLocation(),
9533                         SecondField->getSourceRange(),
9534                         FieldDifferentInitializers)
9535                 << SecondII << SecondInitializer->getSourceRange();
9536             Diagnosed = true;
9537             break;
9538           }
9539         }
9540
9541         break;
9542       }
9543       case CXXMethod: {
9544         const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
9545         const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
9546         auto FirstName = FirstMethod->getDeclName();
9547         auto SecondName = SecondMethod->getDeclName();
9548         if (FirstName != SecondName) {
9549           ODRDiagError(FirstMethod->getLocation(),
9550                        FirstMethod->getSourceRange(), MethodName)
9551               << FirstName;
9552           ODRDiagNote(SecondMethod->getLocation(),
9553                       SecondMethod->getSourceRange(), MethodName)
9554               << SecondName;
9555
9556           Diagnosed = true;
9557           break;
9558         }
9559
9560         const bool FirstDeleted = FirstMethod->isDeleted();
9561         const bool SecondDeleted = SecondMethod->isDeleted();
9562         if (FirstDeleted != SecondDeleted) {
9563           ODRDiagError(FirstMethod->getLocation(),
9564                        FirstMethod->getSourceRange(), MethodDeleted)
9565               << FirstName << FirstDeleted;
9566
9567           ODRDiagNote(SecondMethod->getLocation(),
9568                       SecondMethod->getSourceRange(), MethodDeleted)
9569               << SecondName << SecondDeleted;
9570           Diagnosed = true;
9571           break;
9572         }
9573
9574         const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
9575         const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
9576         const bool FirstPure = FirstMethod->isPure();
9577         const bool SecondPure = SecondMethod->isPure();
9578         if ((FirstVirtual || SecondVirtual) &&
9579             (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
9580           ODRDiagError(FirstMethod->getLocation(),
9581                        FirstMethod->getSourceRange(), MethodVirtual)
9582               << FirstName << FirstPure << FirstVirtual;
9583           ODRDiagNote(SecondMethod->getLocation(),
9584                       SecondMethod->getSourceRange(), MethodVirtual)
9585               << SecondName << SecondPure << SecondVirtual;
9586           Diagnosed = true;
9587           break;
9588         }
9589
9590         // CXXMethodDecl::isStatic uses the canonical Decl.  With Decl merging,
9591         // FirstDecl is the canonical Decl of SecondDecl, so the storage
9592         // class needs to be checked instead.
9593         const auto FirstStorage = FirstMethod->getStorageClass();
9594         const auto SecondStorage = SecondMethod->getStorageClass();
9595         const bool FirstStatic = FirstStorage == SC_Static;
9596         const bool SecondStatic = SecondStorage == SC_Static;
9597         if (FirstStatic != SecondStatic) {
9598           ODRDiagError(FirstMethod->getLocation(),
9599                        FirstMethod->getSourceRange(), MethodStatic)
9600               << FirstName << FirstStatic;
9601           ODRDiagNote(SecondMethod->getLocation(),
9602                       SecondMethod->getSourceRange(), MethodStatic)
9603               << SecondName << SecondStatic;
9604           Diagnosed = true;
9605           break;
9606         }
9607
9608         const bool FirstVolatile = FirstMethod->isVolatile();
9609         const bool SecondVolatile = SecondMethod->isVolatile();
9610         if (FirstVolatile != SecondVolatile) {
9611           ODRDiagError(FirstMethod->getLocation(),
9612                        FirstMethod->getSourceRange(), MethodVolatile)
9613               << FirstName << FirstVolatile;
9614           ODRDiagNote(SecondMethod->getLocation(),
9615                       SecondMethod->getSourceRange(), MethodVolatile)
9616               << SecondName << SecondVolatile;
9617           Diagnosed = true;
9618           break;
9619         }
9620
9621         const bool FirstConst = FirstMethod->isConst();
9622         const bool SecondConst = SecondMethod->isConst();
9623         if (FirstConst != SecondConst) {
9624           ODRDiagError(FirstMethod->getLocation(),
9625                        FirstMethod->getSourceRange(), MethodConst)
9626               << FirstName << FirstConst;
9627           ODRDiagNote(SecondMethod->getLocation(),
9628                       SecondMethod->getSourceRange(), MethodConst)
9629               << SecondName << SecondConst;
9630           Diagnosed = true;
9631           break;
9632         }
9633
9634         const bool FirstInline = FirstMethod->isInlineSpecified();
9635         const bool SecondInline = SecondMethod->isInlineSpecified();
9636         if (FirstInline != SecondInline) {
9637           ODRDiagError(FirstMethod->getLocation(),
9638                        FirstMethod->getSourceRange(), MethodInline)
9639               << FirstName << FirstInline;
9640           ODRDiagNote(SecondMethod->getLocation(),
9641                       SecondMethod->getSourceRange(), MethodInline)
9642               << SecondName << SecondInline;
9643           Diagnosed = true;
9644           break;
9645         }
9646
9647         const unsigned FirstNumParameters = FirstMethod->param_size();
9648         const unsigned SecondNumParameters = SecondMethod->param_size();
9649         if (FirstNumParameters != SecondNumParameters) {
9650           ODRDiagError(FirstMethod->getLocation(),
9651                        FirstMethod->getSourceRange(), MethodNumberParameters)
9652               << FirstName << FirstNumParameters;
9653           ODRDiagNote(SecondMethod->getLocation(),
9654                       SecondMethod->getSourceRange(), MethodNumberParameters)
9655               << SecondName << SecondNumParameters;
9656           Diagnosed = true;
9657           break;
9658         }
9659
9660         // Need this status boolean to know when break out of the switch.
9661         bool ParameterMismatch = false;
9662         for (unsigned I = 0; I < FirstNumParameters; ++I) {
9663           const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I);
9664           const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I);
9665
9666           QualType FirstParamType = FirstParam->getType();
9667           QualType SecondParamType = SecondParam->getType();
9668           if (FirstParamType != SecondParamType &&
9669               ComputeQualTypeODRHash(FirstParamType) !=
9670                   ComputeQualTypeODRHash(SecondParamType)) {
9671             if (const DecayedType *ParamDecayedType =
9672                     FirstParamType->getAs<DecayedType>()) {
9673               ODRDiagError(FirstMethod->getLocation(),
9674                            FirstMethod->getSourceRange(), MethodParameterType)
9675                   << FirstName << (I + 1) << FirstParamType << true
9676                   << ParamDecayedType->getOriginalType();
9677             } else {
9678               ODRDiagError(FirstMethod->getLocation(),
9679                            FirstMethod->getSourceRange(), MethodParameterType)
9680                   << FirstName << (I + 1) << FirstParamType << false;
9681             }
9682
9683             if (const DecayedType *ParamDecayedType =
9684                     SecondParamType->getAs<DecayedType>()) {
9685               ODRDiagNote(SecondMethod->getLocation(),
9686                           SecondMethod->getSourceRange(), MethodParameterType)
9687                   << SecondName << (I + 1) << SecondParamType << true
9688                   << ParamDecayedType->getOriginalType();
9689             } else {
9690               ODRDiagNote(SecondMethod->getLocation(),
9691                           SecondMethod->getSourceRange(), MethodParameterType)
9692                   << SecondName << (I + 1) << SecondParamType << false;
9693             }
9694             ParameterMismatch = true;
9695             break;
9696           }
9697
9698           DeclarationName FirstParamName = FirstParam->getDeclName();
9699           DeclarationName SecondParamName = SecondParam->getDeclName();
9700           if (FirstParamName != SecondParamName) {
9701             ODRDiagError(FirstMethod->getLocation(),
9702                          FirstMethod->getSourceRange(), MethodParameterName)
9703                 << FirstName << (I + 1) << FirstParamName;
9704             ODRDiagNote(SecondMethod->getLocation(),
9705                         SecondMethod->getSourceRange(), MethodParameterName)
9706                 << SecondName << (I + 1) << SecondParamName;
9707             ParameterMismatch = true;
9708             break;
9709           }
9710         }
9711
9712         if (ParameterMismatch) {
9713           Diagnosed = true;
9714           break;
9715         }
9716
9717         break;
9718       }
9719       }
9720
9721       if (Diagnosed == true)
9722         continue;
9723
9724       Diag(FirstRecord->getLocation(),
9725            diag::err_module_odr_violation_different_definitions)
9726           << FirstRecord << FirstModule.empty() << FirstModule;
9727
9728       Diag(SecondRecord->getLocation(),
9729            diag::note_module_odr_violation_different_definitions)
9730           << SecondModule;
9731       Diagnosed = true;
9732     }
9733
9734     if (!Diagnosed) {
9735       // All definitions are updates to the same declaration. This happens if a
9736       // module instantiates the declaration of a class template specialization
9737       // and two or more other modules instantiate its definition.
9738       //
9739       // FIXME: Indicate which modules had instantiations of this definition.
9740       // FIXME: How can this even happen?
9741       Diag(Merge.first->getLocation(),
9742            diag::err_module_odr_violation_different_instantiations)
9743         << Merge.first;
9744     }
9745   }
9746 }
9747
9748 void ASTReader::StartedDeserializing() {
9749   if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
9750     ReadTimer->startTimer();
9751 }
9752
9753 void ASTReader::FinishedDeserializing() {
9754   assert(NumCurrentElementsDeserializing &&
9755          "FinishedDeserializing not paired with StartedDeserializing");
9756   if (NumCurrentElementsDeserializing == 1) {
9757     // We decrease NumCurrentElementsDeserializing only after pending actions
9758     // are finished, to avoid recursively re-calling finishPendingActions().
9759     finishPendingActions();
9760   }
9761   --NumCurrentElementsDeserializing;
9762
9763   if (NumCurrentElementsDeserializing == 0) {
9764     // Propagate exception specification updates along redeclaration chains.
9765     while (!PendingExceptionSpecUpdates.empty()) {
9766       auto Updates = std::move(PendingExceptionSpecUpdates);
9767       PendingExceptionSpecUpdates.clear();
9768       for (auto Update : Updates) {
9769         ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
9770         auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
9771         auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
9772         if (auto *Listener = Context.getASTMutationListener())
9773           Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
9774         for (auto *Redecl : Update.second->redecls())
9775           Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
9776       }
9777     }
9778
9779     if (ReadTimer)
9780       ReadTimer->stopTimer();
9781
9782     diagnoseOdrViolations();
9783
9784     // We are not in recursive loading, so it's safe to pass the "interesting"
9785     // decls to the consumer.
9786     if (Consumer)
9787       PassInterestingDeclsToConsumer();
9788   }
9789 }
9790
9791 void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
9792   if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
9793     // Remove any fake results before adding any real ones.
9794     auto It = PendingFakeLookupResults.find(II);
9795     if (It != PendingFakeLookupResults.end()) {
9796       for (auto *ND : It->second)
9797         SemaObj->IdResolver.RemoveDecl(ND);
9798       // FIXME: this works around module+PCH performance issue.
9799       // Rather than erase the result from the map, which is O(n), just clear
9800       // the vector of NamedDecls.
9801       It->second.clear();
9802     }
9803   }
9804
9805   if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
9806     SemaObj->TUScope->AddDecl(D);
9807   } else if (SemaObj->TUScope) {
9808     // Adding the decl to IdResolver may have failed because it was already in
9809     // (even though it was not added in scope). If it is already in, make sure
9810     // it gets in the scope as well.
9811     if (std::find(SemaObj->IdResolver.begin(Name),
9812                   SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
9813       SemaObj->TUScope->AddDecl(D);
9814   }
9815 }
9816
9817 ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
9818                      const PCHContainerReader &PCHContainerRdr,
9819                      ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
9820                      StringRef isysroot, bool DisableValidation,
9821                      bool AllowASTWithCompilerErrors,
9822                      bool AllowConfigurationMismatch, bool ValidateSystemInputs,
9823                      bool UseGlobalIndex,
9824                      std::unique_ptr<llvm::Timer> ReadTimer)
9825     : Listener(DisableValidation
9826                    ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
9827                    : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
9828       SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
9829       PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
9830       Context(Context),
9831       ModuleMgr(PP.getFileManager(), PP.getPCMCache(), PCHContainerRdr),
9832       PCMCache(PP.getPCMCache()), DummyIdResolver(PP),
9833       ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
9834       DisableValidation(DisableValidation),
9835       AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
9836       AllowConfigurationMismatch(AllowConfigurationMismatch),
9837       ValidateSystemInputs(ValidateSystemInputs),
9838       UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
9839   SourceMgr.setExternalSLocEntrySource(this);
9840
9841   for (const auto &Ext : Extensions) {
9842     auto BlockName = Ext->getExtensionMetadata().BlockName;
9843     auto Known = ModuleFileExtensions.find(BlockName);
9844     if (Known != ModuleFileExtensions.end()) {
9845       Diags.Report(diag::warn_duplicate_module_file_extension)
9846         << BlockName;
9847       continue;
9848     }
9849
9850     ModuleFileExtensions.insert({BlockName, Ext});
9851   }
9852 }
9853
9854 ASTReader::~ASTReader() {
9855   if (OwnsDeserializationListener)
9856     delete DeserializationListener;
9857 }
9858
9859 IdentifierResolver &ASTReader::getIdResolver() {
9860   return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
9861 }
9862
9863 unsigned ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
9864                                      unsigned AbbrevID) {
9865   Idx = 0;
9866   Record.clear();
9867   return Cursor.readRecord(AbbrevID, Record);
9868 }