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/DeclTemplate.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/NestedNameSpecifier.h"
23 #include "clang/AST/Type.h"
24 #include "clang/AST/TypeLocVisitor.h"
25 #include "clang/Basic/FileManager.h"
26 #include "clang/Basic/SourceManager.h"
27 #include "clang/Basic/SourceManagerInternals.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Basic/TargetOptions.h"
30 #include "clang/Basic/Version.h"
31 #include "clang/Basic/VersionTuple.h"
32 #include "clang/Lex/HeaderSearch.h"
33 #include "clang/Lex/HeaderSearchOptions.h"
34 #include "clang/Lex/MacroInfo.h"
35 #include "clang/Lex/PreprocessingRecord.h"
36 #include "clang/Lex/Preprocessor.h"
37 #include "clang/Lex/PreprocessorOptions.h"
38 #include "clang/Sema/Scope.h"
39 #include "clang/Sema/Sema.h"
40 #include "clang/Serialization/ASTDeserializationListener.h"
41 #include "clang/Serialization/GlobalModuleIndex.h"
42 #include "clang/Serialization/ModuleManager.h"
43 #include "clang/Serialization/SerializationDiagnostic.h"
44 #include "llvm/ADT/Hashing.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/Bitcode/BitstreamReader.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/FileSystem.h"
49 #include "llvm/Support/MemoryBuffer.h"
50 #include "llvm/Support/Path.h"
51 #include "llvm/Support/SaveAndRestore.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Support/system_error.h"
54 #include <algorithm>
55 #include <cstdio>
56 #include <iterator>
57 
58 using namespace clang;
59 using namespace clang::serialization;
60 using namespace clang::serialization::reader;
61 using llvm::BitstreamCursor;
62 
63 
64 //===----------------------------------------------------------------------===//
65 // ChainedASTReaderListener implementation
66 //===----------------------------------------------------------------------===//
67 
68 bool
69 ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
70   return First->ReadFullVersionInformation(FullVersion) ||
71          Second->ReadFullVersionInformation(FullVersion);
72 }
73 bool ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
74                                                    bool Complain) {
75   return First->ReadLanguageOptions(LangOpts, Complain) ||
76          Second->ReadLanguageOptions(LangOpts, Complain);
77 }
78 bool
79 ChainedASTReaderListener::ReadTargetOptions(const TargetOptions &TargetOpts,
80                                             bool Complain) {
81   return First->ReadTargetOptions(TargetOpts, Complain) ||
82          Second->ReadTargetOptions(TargetOpts, Complain);
83 }
84 bool ChainedASTReaderListener::ReadDiagnosticOptions(
85     const DiagnosticOptions &DiagOpts, bool Complain) {
86   return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
87          Second->ReadDiagnosticOptions(DiagOpts, Complain);
88 }
89 bool
90 ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
91                                                 bool Complain) {
92   return First->ReadFileSystemOptions(FSOpts, Complain) ||
93          Second->ReadFileSystemOptions(FSOpts, Complain);
94 }
95 
96 bool ChainedASTReaderListener::ReadHeaderSearchOptions(
97     const HeaderSearchOptions &HSOpts, bool Complain) {
98   return First->ReadHeaderSearchOptions(HSOpts, Complain) ||
99          Second->ReadHeaderSearchOptions(HSOpts, Complain);
100 }
101 bool ChainedASTReaderListener::ReadPreprocessorOptions(
102     const PreprocessorOptions &PPOpts, bool Complain,
103     std::string &SuggestedPredefines) {
104   return First->ReadPreprocessorOptions(PPOpts, Complain,
105                                         SuggestedPredefines) ||
106          Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
107 }
108 void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
109                                            unsigned Value) {
110   First->ReadCounter(M, Value);
111   Second->ReadCounter(M, Value);
112 }
113 bool ChainedASTReaderListener::needsInputFileVisitation() {
114   return First->needsInputFileVisitation() ||
115          Second->needsInputFileVisitation();
116 }
117 bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
118   return First->needsSystemInputFileVisitation() ||
119   Second->needsSystemInputFileVisitation();
120 }
121 bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
122                                               bool isSystem) {
123   return First->visitInputFile(Filename, isSystem) ||
124          Second->visitInputFile(Filename, isSystem);
125 }
126 
127 //===----------------------------------------------------------------------===//
128 // PCH validator implementation
129 //===----------------------------------------------------------------------===//
130 
131 ASTReaderListener::~ASTReaderListener() {}
132 
133 /// \brief Compare the given set of language options against an existing set of
134 /// language options.
135 ///
136 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
137 ///
138 /// \returns true if the languagae options mis-match, false otherwise.
139 static bool checkLanguageOptions(const LangOptions &LangOpts,
140                                  const LangOptions &ExistingLangOpts,
141                                  DiagnosticsEngine *Diags) {
142 #define LANGOPT(Name, Bits, Default, Description)                 \
143   if (ExistingLangOpts.Name != LangOpts.Name) {                   \
144     if (Diags)                                                    \
145       Diags->Report(diag::err_pch_langopt_mismatch)               \
146         << Description << LangOpts.Name << ExistingLangOpts.Name; \
147     return true;                                                  \
148   }
149 
150 #define VALUE_LANGOPT(Name, Bits, Default, Description)   \
151   if (ExistingLangOpts.Name != LangOpts.Name) {           \
152     if (Diags)                                            \
153       Diags->Report(diag::err_pch_langopt_value_mismatch) \
154         << Description;                                   \
155     return true;                                          \
156   }
157 
158 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description)   \
159   if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) {  \
160     if (Diags)                                                 \
161       Diags->Report(diag::err_pch_langopt_value_mismatch)      \
162         << Description;                                        \
163     return true;                                               \
164   }
165 
166 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
167 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
168 #include "clang/Basic/LangOptions.def"
169 
170   if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
171     if (Diags)
172       Diags->Report(diag::err_pch_langopt_value_mismatch)
173       << "target Objective-C runtime";
174     return true;
175   }
176 
177   if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
178       LangOpts.CommentOpts.BlockCommandNames) {
179     if (Diags)
180       Diags->Report(diag::err_pch_langopt_value_mismatch)
181         << "block command names";
182     return true;
183   }
184 
185   return false;
186 }
187 
188 /// \brief Compare the given set of target options against an existing set of
189 /// target options.
190 ///
191 /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
192 ///
193 /// \returns true if the target options mis-match, false otherwise.
194 static bool checkTargetOptions(const TargetOptions &TargetOpts,
195                                const TargetOptions &ExistingTargetOpts,
196                                DiagnosticsEngine *Diags) {
197 #define CHECK_TARGET_OPT(Field, Name)                             \
198   if (TargetOpts.Field != ExistingTargetOpts.Field) {             \
199     if (Diags)                                                    \
200       Diags->Report(diag::err_pch_targetopt_mismatch)             \
201         << Name << TargetOpts.Field << ExistingTargetOpts.Field;  \
202     return true;                                                  \
203   }
204 
205   CHECK_TARGET_OPT(Triple, "target");
206   CHECK_TARGET_OPT(CPU, "target CPU");
207   CHECK_TARGET_OPT(ABI, "target ABI");
208   CHECK_TARGET_OPT(LinkerVersion, "target linker version");
209 #undef CHECK_TARGET_OPT
210 
211   // Compare feature sets.
212   SmallVector<StringRef, 4> ExistingFeatures(
213                                              ExistingTargetOpts.FeaturesAsWritten.begin(),
214                                              ExistingTargetOpts.FeaturesAsWritten.end());
215   SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
216                                          TargetOpts.FeaturesAsWritten.end());
217   std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
218   std::sort(ReadFeatures.begin(), ReadFeatures.end());
219 
220   unsigned ExistingIdx = 0, ExistingN = ExistingFeatures.size();
221   unsigned ReadIdx = 0, ReadN = ReadFeatures.size();
222   while (ExistingIdx < ExistingN && ReadIdx < ReadN) {
223     if (ExistingFeatures[ExistingIdx] == ReadFeatures[ReadIdx]) {
224       ++ExistingIdx;
225       ++ReadIdx;
226       continue;
227     }
228 
229     if (ReadFeatures[ReadIdx] < ExistingFeatures[ExistingIdx]) {
230       if (Diags)
231         Diags->Report(diag::err_pch_targetopt_feature_mismatch)
232           << false << ReadFeatures[ReadIdx];
233       return true;
234     }
235 
236     if (Diags)
237       Diags->Report(diag::err_pch_targetopt_feature_mismatch)
238         << true << ExistingFeatures[ExistingIdx];
239     return true;
240   }
241 
242   if (ExistingIdx < ExistingN) {
243     if (Diags)
244       Diags->Report(diag::err_pch_targetopt_feature_mismatch)
245         << true << ExistingFeatures[ExistingIdx];
246     return true;
247   }
248 
249   if (ReadIdx < ReadN) {
250     if (Diags)
251       Diags->Report(diag::err_pch_targetopt_feature_mismatch)
252         << false << ReadFeatures[ReadIdx];
253     return true;
254   }
255 
256   return false;
257 }
258 
259 bool
260 PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
261                                   bool Complain) {
262   const LangOptions &ExistingLangOpts = PP.getLangOpts();
263   return checkLanguageOptions(LangOpts, ExistingLangOpts,
264                               Complain? &Reader.Diags : 0);
265 }
266 
267 bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
268                                      bool Complain) {
269   const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
270   return checkTargetOptions(TargetOpts, ExistingTargetOpts,
271                             Complain? &Reader.Diags : 0);
272 }
273 
274 namespace {
275   typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
276     MacroDefinitionsMap;
277   typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
278     DeclsMap;
279 }
280 
281 /// \brief Collect the macro definitions provided by the given preprocessor
282 /// options.
283 static void collectMacroDefinitions(const PreprocessorOptions &PPOpts,
284                                     MacroDefinitionsMap &Macros,
285                                     SmallVectorImpl<StringRef> *MacroNames = 0){
286   for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
287     StringRef Macro = PPOpts.Macros[I].first;
288     bool IsUndef = PPOpts.Macros[I].second;
289 
290     std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
291     StringRef MacroName = MacroPair.first;
292     StringRef MacroBody = MacroPair.second;
293 
294     // For an #undef'd macro, we only care about the name.
295     if (IsUndef) {
296       if (MacroNames && !Macros.count(MacroName))
297         MacroNames->push_back(MacroName);
298 
299       Macros[MacroName] = std::make_pair("", true);
300       continue;
301     }
302 
303     // For a #define'd macro, figure out the actual definition.
304     if (MacroName.size() == Macro.size())
305       MacroBody = "1";
306     else {
307       // Note: GCC drops anything following an end-of-line character.
308       StringRef::size_type End = MacroBody.find_first_of("\n\r");
309       MacroBody = MacroBody.substr(0, End);
310     }
311 
312     if (MacroNames && !Macros.count(MacroName))
313       MacroNames->push_back(MacroName);
314     Macros[MacroName] = std::make_pair(MacroBody, false);
315   }
316 }
317 
318 /// \brief Check the preprocessor options deserialized from the control block
319 /// against the preprocessor options in an existing preprocessor.
320 ///
321 /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
322 static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
323                                      const PreprocessorOptions &ExistingPPOpts,
324                                      DiagnosticsEngine *Diags,
325                                      FileManager &FileMgr,
326                                      std::string &SuggestedPredefines,
327                                      const LangOptions &LangOpts) {
328   // Check macro definitions.
329   MacroDefinitionsMap ASTFileMacros;
330   collectMacroDefinitions(PPOpts, ASTFileMacros);
331   MacroDefinitionsMap ExistingMacros;
332   SmallVector<StringRef, 4> ExistingMacroNames;
333   collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
334 
335   for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
336     // Dig out the macro definition in the existing preprocessor options.
337     StringRef MacroName = ExistingMacroNames[I];
338     std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
339 
340     // Check whether we know anything about this macro name or not.
341     llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
342       = ASTFileMacros.find(MacroName);
343     if (Known == ASTFileMacros.end()) {
344       // FIXME: Check whether this identifier was referenced anywhere in the
345       // AST file. If so, we should reject the AST file. Unfortunately, this
346       // information isn't in the control block. What shall we do about it?
347 
348       if (Existing.second) {
349         SuggestedPredefines += "#undef ";
350         SuggestedPredefines += MacroName.str();
351         SuggestedPredefines += '\n';
352       } else {
353         SuggestedPredefines += "#define ";
354         SuggestedPredefines += MacroName.str();
355         SuggestedPredefines += ' ';
356         SuggestedPredefines += Existing.first.str();
357         SuggestedPredefines += '\n';
358       }
359       continue;
360     }
361 
362     // If the macro was defined in one but undef'd in the other, we have a
363     // conflict.
364     if (Existing.second != Known->second.second) {
365       if (Diags) {
366         Diags->Report(diag::err_pch_macro_def_undef)
367           << MacroName << Known->second.second;
368       }
369       return true;
370     }
371 
372     // If the macro was #undef'd in both, or if the macro bodies are identical,
373     // it's fine.
374     if (Existing.second || Existing.first == Known->second.first)
375       continue;
376 
377     // The macro bodies differ; complain.
378     if (Diags) {
379       Diags->Report(diag::err_pch_macro_def_conflict)
380         << MacroName << Known->second.first << Existing.first;
381     }
382     return true;
383   }
384 
385   // Check whether we're using predefines.
386   if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
387     if (Diags) {
388       Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
389     }
390     return true;
391   }
392 
393   // Detailed record is important since it is used for the module cache hash.
394   if (LangOpts.Modules &&
395       PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
396     if (Diags) {
397       Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
398     }
399     return true;
400   }
401 
402   // Compute the #include and #include_macros lines we need.
403   for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
404     StringRef File = ExistingPPOpts.Includes[I];
405     if (File == ExistingPPOpts.ImplicitPCHInclude)
406       continue;
407 
408     if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
409           != PPOpts.Includes.end())
410       continue;
411 
412     SuggestedPredefines += "#include \"";
413     SuggestedPredefines +=
414       HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
415     SuggestedPredefines += "\"\n";
416   }
417 
418   for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
419     StringRef File = ExistingPPOpts.MacroIncludes[I];
420     if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
421                   File)
422         != PPOpts.MacroIncludes.end())
423       continue;
424 
425     SuggestedPredefines += "#__include_macros \"";
426     SuggestedPredefines +=
427       HeaderSearch::NormalizeDashIncludePath(File, FileMgr);
428     SuggestedPredefines += "\"\n##\n";
429   }
430 
431   return false;
432 }
433 
434 bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
435                                            bool Complain,
436                                            std::string &SuggestedPredefines) {
437   const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
438 
439   return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
440                                   Complain? &Reader.Diags : 0,
441                                   PP.getFileManager(),
442                                   SuggestedPredefines,
443                                   PP.getLangOpts());
444 }
445 
446 void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
447   PP.setCounterValue(Value);
448 }
449 
450 //===----------------------------------------------------------------------===//
451 // AST reader implementation
452 //===----------------------------------------------------------------------===//
453 
454 void
455 ASTReader::setDeserializationListener(ASTDeserializationListener *Listener) {
456   DeserializationListener = Listener;
457 }
458 
459 
460 void NameLookupTableDataDeleter::
461 operator()(ASTDeclContextNameLookupTable *Ptr) const {
462   delete Ptr;
463 }
464 
465 
466 unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
467   return serialization::ComputeHash(Sel);
468 }
469 
470 
471 std::pair<unsigned, unsigned>
472 ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
473   using namespace clang::io;
474   unsigned KeyLen = ReadUnalignedLE16(d);
475   unsigned DataLen = ReadUnalignedLE16(d);
476   return std::make_pair(KeyLen, DataLen);
477 }
478 
479 ASTSelectorLookupTrait::internal_key_type
480 ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
481   using namespace clang::io;
482   SelectorTable &SelTable = Reader.getContext().Selectors;
483   unsigned N = ReadUnalignedLE16(d);
484   IdentifierInfo *FirstII
485     = Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
486   if (N == 0)
487     return SelTable.getNullarySelector(FirstII);
488   else if (N == 1)
489     return SelTable.getUnarySelector(FirstII);
490 
491   SmallVector<IdentifierInfo *, 16> Args;
492   Args.push_back(FirstII);
493   for (unsigned I = 1; I != N; ++I)
494     Args.push_back(Reader.getLocalIdentifier(F, ReadUnalignedLE32(d)));
495 
496   return SelTable.getSelector(N, Args.data());
497 }
498 
499 ASTSelectorLookupTrait::data_type
500 ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
501                                  unsigned DataLen) {
502   using namespace clang::io;
503 
504   data_type Result;
505 
506   Result.ID = Reader.getGlobalSelectorID(F, ReadUnalignedLE32(d));
507   unsigned NumInstanceMethodsAndBits = ReadUnalignedLE16(d);
508   unsigned NumFactoryMethodsAndBits = ReadUnalignedLE16(d);
509   Result.InstanceBits = NumInstanceMethodsAndBits & 0x3;
510   Result.FactoryBits = NumFactoryMethodsAndBits & 0x3;
511   unsigned NumInstanceMethods = NumInstanceMethodsAndBits >> 2;
512   unsigned NumFactoryMethods = NumFactoryMethodsAndBits >> 2;
513 
514   // Load instance methods
515   for (unsigned I = 0; I != NumInstanceMethods; ++I) {
516     if (ObjCMethodDecl *Method
517           = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
518       Result.Instance.push_back(Method);
519   }
520 
521   // Load factory methods
522   for (unsigned I = 0; I != NumFactoryMethods; ++I) {
523     if (ObjCMethodDecl *Method
524           = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
525       Result.Factory.push_back(Method);
526   }
527 
528   return Result;
529 }
530 
531 unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
532   return llvm::HashString(a);
533 }
534 
535 std::pair<unsigned, unsigned>
536 ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
537   using namespace clang::io;
538   unsigned DataLen = ReadUnalignedLE16(d);
539   unsigned KeyLen = ReadUnalignedLE16(d);
540   return std::make_pair(KeyLen, DataLen);
541 }
542 
543 ASTIdentifierLookupTraitBase::internal_key_type
544 ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
545   assert(n >= 2 && d[n-1] == '\0');
546   return StringRef((const char*) d, n-1);
547 }
548 
549 /// \brief Whether the given identifier is "interesting".
550 static bool isInterestingIdentifier(IdentifierInfo &II) {
551   return II.isPoisoned() ||
552          II.isExtensionToken() ||
553          II.getObjCOrBuiltinID() ||
554          II.hasRevertedTokenIDToIdentifier() ||
555          II.hadMacroDefinition() ||
556          II.getFETokenInfo<void>();
557 }
558 
559 IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
560                                                    const unsigned char* d,
561                                                    unsigned DataLen) {
562   using namespace clang::io;
563   unsigned RawID = ReadUnalignedLE32(d);
564   bool IsInteresting = RawID & 0x01;
565 
566   // Wipe out the "is interesting" bit.
567   RawID = RawID >> 1;
568 
569   IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
570   if (!IsInteresting) {
571     // For uninteresting identifiers, just build the IdentifierInfo
572     // and associate it with the persistent ID.
573     IdentifierInfo *II = KnownII;
574     if (!II) {
575       II = &Reader.getIdentifierTable().getOwn(k);
576       KnownII = II;
577     }
578     Reader.SetIdentifierInfo(ID, II);
579     if (!II->isFromAST()) {
580       bool WasInteresting = isInterestingIdentifier(*II);
581       II->setIsFromAST();
582       if (WasInteresting)
583         II->setChangedSinceDeserialization();
584     }
585     Reader.markIdentifierUpToDate(II);
586     return II;
587   }
588 
589   unsigned ObjCOrBuiltinID = ReadUnalignedLE16(d);
590   unsigned Bits = ReadUnalignedLE16(d);
591   bool CPlusPlusOperatorKeyword = Bits & 0x01;
592   Bits >>= 1;
593   bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
594   Bits >>= 1;
595   bool Poisoned = Bits & 0x01;
596   Bits >>= 1;
597   bool ExtensionToken = Bits & 0x01;
598   Bits >>= 1;
599   bool hasSubmoduleMacros = Bits & 0x01;
600   Bits >>= 1;
601   bool hadMacroDefinition = Bits & 0x01;
602   Bits >>= 1;
603 
604   assert(Bits == 0 && "Extra bits in the identifier?");
605   DataLen -= 8;
606 
607   // Build the IdentifierInfo itself and link the identifier ID with
608   // the new IdentifierInfo.
609   IdentifierInfo *II = KnownII;
610   if (!II) {
611     II = &Reader.getIdentifierTable().getOwn(StringRef(k));
612     KnownII = II;
613   }
614   Reader.markIdentifierUpToDate(II);
615   if (!II->isFromAST()) {
616     bool WasInteresting = isInterestingIdentifier(*II);
617     II->setIsFromAST();
618     if (WasInteresting)
619       II->setChangedSinceDeserialization();
620   }
621 
622   // Set or check the various bits in the IdentifierInfo structure.
623   // Token IDs are read-only.
624   if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
625     II->RevertTokenIDToIdentifier();
626   II->setObjCOrBuiltinID(ObjCOrBuiltinID);
627   assert(II->isExtensionToken() == ExtensionToken &&
628          "Incorrect extension token flag");
629   (void)ExtensionToken;
630   if (Poisoned)
631     II->setIsPoisoned(true);
632   assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
633          "Incorrect C++ operator keyword flag");
634   (void)CPlusPlusOperatorKeyword;
635 
636   // If this identifier is a macro, deserialize the macro
637   // definition.
638   if (hadMacroDefinition) {
639     uint32_t MacroDirectivesOffset = ReadUnalignedLE32(d);
640     DataLen -= 4;
641     SmallVector<uint32_t, 8> LocalMacroIDs;
642     if (hasSubmoduleMacros) {
643       while (uint32_t LocalMacroID = ReadUnalignedLE32(d)) {
644         DataLen -= 4;
645         LocalMacroIDs.push_back(LocalMacroID);
646       }
647       DataLen -= 4;
648     }
649 
650     if (F.Kind == MK_Module) {
651       // Macro definitions are stored from newest to oldest, so reverse them
652       // before registering them.
653       llvm::SmallVector<unsigned, 8> MacroSizes;
654       for (SmallVectorImpl<uint32_t>::iterator
655              I = LocalMacroIDs.begin(), E = LocalMacroIDs.end(); I != E; /**/) {
656         unsigned Size = 1;
657 
658         static const uint32_t HasOverridesFlag = 0x80000000U;
659         if (I + 1 != E && (I[1] & HasOverridesFlag))
660           Size += 1 + (I[1] & ~HasOverridesFlag);
661 
662         MacroSizes.push_back(Size);
663         I += Size;
664       }
665 
666       SmallVectorImpl<uint32_t>::iterator I = LocalMacroIDs.end();
667       for (SmallVectorImpl<unsigned>::reverse_iterator SI = MacroSizes.rbegin(),
668                                                        SE = MacroSizes.rend();
669            SI != SE; ++SI) {
670         I -= *SI;
671 
672         uint32_t LocalMacroID = *I;
673         llvm::ArrayRef<uint32_t> Overrides;
674         if (*SI != 1)
675           Overrides = llvm::makeArrayRef(&I[2], *SI - 2);
676         Reader.addPendingMacroFromModule(II, &F, LocalMacroID, Overrides);
677       }
678       assert(I == LocalMacroIDs.begin());
679     } else {
680       Reader.addPendingMacroFromPCH(II, &F, MacroDirectivesOffset);
681     }
682   }
683 
684   Reader.SetIdentifierInfo(ID, II);
685 
686   // Read all of the declarations visible at global scope with this
687   // name.
688   if (DataLen > 0) {
689     SmallVector<uint32_t, 4> DeclIDs;
690     for (; DataLen > 0; DataLen -= 4)
691       DeclIDs.push_back(Reader.getGlobalDeclID(F, ReadUnalignedLE32(d)));
692     Reader.SetGloballyVisibleDecls(II, DeclIDs);
693   }
694 
695   return II;
696 }
697 
698 unsigned
699 ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
700   llvm::FoldingSetNodeID ID;
701   ID.AddInteger(Key.Kind);
702 
703   switch (Key.Kind) {
704   case DeclarationName::Identifier:
705   case DeclarationName::CXXLiteralOperatorName:
706     ID.AddString(((IdentifierInfo*)Key.Data)->getName());
707     break;
708   case DeclarationName::ObjCZeroArgSelector:
709   case DeclarationName::ObjCOneArgSelector:
710   case DeclarationName::ObjCMultiArgSelector:
711     ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
712     break;
713   case DeclarationName::CXXOperatorName:
714     ID.AddInteger((OverloadedOperatorKind)Key.Data);
715     break;
716   case DeclarationName::CXXConstructorName:
717   case DeclarationName::CXXDestructorName:
718   case DeclarationName::CXXConversionFunctionName:
719   case DeclarationName::CXXUsingDirective:
720     break;
721   }
722 
723   return ID.ComputeHash();
724 }
725 
726 ASTDeclContextNameLookupTrait::internal_key_type
727 ASTDeclContextNameLookupTrait::GetInternalKey(
728                                           const external_key_type& Name) const {
729   DeclNameKey Key;
730   Key.Kind = Name.getNameKind();
731   switch (Name.getNameKind()) {
732   case DeclarationName::Identifier:
733     Key.Data = (uint64_t)Name.getAsIdentifierInfo();
734     break;
735   case DeclarationName::ObjCZeroArgSelector:
736   case DeclarationName::ObjCOneArgSelector:
737   case DeclarationName::ObjCMultiArgSelector:
738     Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
739     break;
740   case DeclarationName::CXXOperatorName:
741     Key.Data = Name.getCXXOverloadedOperator();
742     break;
743   case DeclarationName::CXXLiteralOperatorName:
744     Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
745     break;
746   case DeclarationName::CXXConstructorName:
747   case DeclarationName::CXXDestructorName:
748   case DeclarationName::CXXConversionFunctionName:
749   case DeclarationName::CXXUsingDirective:
750     Key.Data = 0;
751     break;
752   }
753 
754   return Key;
755 }
756 
757 std::pair<unsigned, unsigned>
758 ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
759   using namespace clang::io;
760   unsigned KeyLen = ReadUnalignedLE16(d);
761   unsigned DataLen = ReadUnalignedLE16(d);
762   return std::make_pair(KeyLen, DataLen);
763 }
764 
765 ASTDeclContextNameLookupTrait::internal_key_type
766 ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
767   using namespace clang::io;
768 
769   DeclNameKey Key;
770   Key.Kind = (DeclarationName::NameKind)*d++;
771   switch (Key.Kind) {
772   case DeclarationName::Identifier:
773     Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
774     break;
775   case DeclarationName::ObjCZeroArgSelector:
776   case DeclarationName::ObjCOneArgSelector:
777   case DeclarationName::ObjCMultiArgSelector:
778     Key.Data =
779        (uint64_t)Reader.getLocalSelector(F, ReadUnalignedLE32(d))
780                    .getAsOpaquePtr();
781     break;
782   case DeclarationName::CXXOperatorName:
783     Key.Data = *d++; // OverloadedOperatorKind
784     break;
785   case DeclarationName::CXXLiteralOperatorName:
786     Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
787     break;
788   case DeclarationName::CXXConstructorName:
789   case DeclarationName::CXXDestructorName:
790   case DeclarationName::CXXConversionFunctionName:
791   case DeclarationName::CXXUsingDirective:
792     Key.Data = 0;
793     break;
794   }
795 
796   return Key;
797 }
798 
799 ASTDeclContextNameLookupTrait::data_type
800 ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
801                                         const unsigned char* d,
802                                         unsigned DataLen) {
803   using namespace clang::io;
804   unsigned NumDecls = ReadUnalignedLE16(d);
805   LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
806                         const_cast<unsigned char *>(d));
807   return std::make_pair(Start, Start + NumDecls);
808 }
809 
810 bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
811                                        BitstreamCursor &Cursor,
812                                    const std::pair<uint64_t, uint64_t> &Offsets,
813                                        DeclContextInfo &Info) {
814   SavedStreamPosition SavedPosition(Cursor);
815   // First the lexical decls.
816   if (Offsets.first != 0) {
817     Cursor.JumpToBit(Offsets.first);
818 
819     RecordData Record;
820     StringRef Blob;
821     unsigned Code = Cursor.ReadCode();
822     unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
823     if (RecCode != DECL_CONTEXT_LEXICAL) {
824       Error("Expected lexical block");
825       return true;
826     }
827 
828     Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
829     Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
830   }
831 
832   // Now the lookup table.
833   if (Offsets.second != 0) {
834     Cursor.JumpToBit(Offsets.second);
835 
836     RecordData Record;
837     StringRef Blob;
838     unsigned Code = Cursor.ReadCode();
839     unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
840     if (RecCode != DECL_CONTEXT_VISIBLE) {
841       Error("Expected visible lookup table block");
842       return true;
843     }
844     Info.NameLookupTableData.reset(ASTDeclContextNameLookupTable::Create(
845         (const unsigned char *)Blob.data() + Record[0],
846         (const unsigned char *)Blob.data(),
847         ASTDeclContextNameLookupTrait(*this, M)));
848   }
849 
850   return false;
851 }
852 
853 void ASTReader::Error(StringRef Msg) {
854   Error(diag::err_fe_pch_malformed, Msg);
855   if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
856     Diag(diag::note_module_cache_path)
857       << PP.getHeaderSearchInfo().getModuleCachePath();
858   }
859 }
860 
861 void ASTReader::Error(unsigned DiagID,
862                       StringRef Arg1, StringRef Arg2) {
863   if (Diags.isDiagnosticInFlight())
864     Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
865   else
866     Diag(DiagID) << Arg1 << Arg2;
867 }
868 
869 //===----------------------------------------------------------------------===//
870 // Source Manager Deserialization
871 //===----------------------------------------------------------------------===//
872 
873 /// \brief Read the line table in the source manager block.
874 /// \returns true if there was an error.
875 bool ASTReader::ParseLineTable(ModuleFile &F,
876                                SmallVectorImpl<uint64_t> &Record) {
877   unsigned Idx = 0;
878   LineTableInfo &LineTable = SourceMgr.getLineTable();
879 
880   // Parse the file names
881   std::map<int, int> FileIDs;
882   for (int I = 0, N = Record[Idx++]; I != N; ++I) {
883     // Extract the file name
884     unsigned FilenameLen = Record[Idx++];
885     std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
886     Idx += FilenameLen;
887     MaybeAddSystemRootToFilename(F, Filename);
888     FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
889   }
890 
891   // Parse the line entries
892   std::vector<LineEntry> Entries;
893   while (Idx < Record.size()) {
894     int FID = Record[Idx++];
895     assert(FID >= 0 && "Serialized line entries for non-local file.");
896     // Remap FileID from 1-based old view.
897     FID += F.SLocEntryBaseID - 1;
898 
899     // Extract the line entries
900     unsigned NumEntries = Record[Idx++];
901     assert(NumEntries && "Numentries is 00000");
902     Entries.clear();
903     Entries.reserve(NumEntries);
904     for (unsigned I = 0; I != NumEntries; ++I) {
905       unsigned FileOffset = Record[Idx++];
906       unsigned LineNo = Record[Idx++];
907       int FilenameID = FileIDs[Record[Idx++]];
908       SrcMgr::CharacteristicKind FileKind
909         = (SrcMgr::CharacteristicKind)Record[Idx++];
910       unsigned IncludeOffset = Record[Idx++];
911       Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
912                                        FileKind, IncludeOffset));
913     }
914     LineTable.AddEntry(FileID::get(FID), Entries);
915   }
916 
917   return false;
918 }
919 
920 /// \brief Read a source manager block
921 bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
922   using namespace SrcMgr;
923 
924   BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
925 
926   // Set the source-location entry cursor to the current position in
927   // the stream. This cursor will be used to read the contents of the
928   // source manager block initially, and then lazily read
929   // source-location entries as needed.
930   SLocEntryCursor = F.Stream;
931 
932   // The stream itself is going to skip over the source manager block.
933   if (F.Stream.SkipBlock()) {
934     Error("malformed block record in AST file");
935     return true;
936   }
937 
938   // Enter the source manager block.
939   if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
940     Error("malformed source manager block record in AST file");
941     return true;
942   }
943 
944   RecordData Record;
945   while (true) {
946     llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
947 
948     switch (E.Kind) {
949     case llvm::BitstreamEntry::SubBlock: // Handled for us already.
950     case llvm::BitstreamEntry::Error:
951       Error("malformed block record in AST file");
952       return true;
953     case llvm::BitstreamEntry::EndBlock:
954       return false;
955     case llvm::BitstreamEntry::Record:
956       // The interesting case.
957       break;
958     }
959 
960     // Read a record.
961     Record.clear();
962     StringRef Blob;
963     switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
964     default:  // Default behavior: ignore.
965       break;
966 
967     case SM_SLOC_FILE_ENTRY:
968     case SM_SLOC_BUFFER_ENTRY:
969     case SM_SLOC_EXPANSION_ENTRY:
970       // Once we hit one of the source location entries, we're done.
971       return false;
972     }
973   }
974 }
975 
976 /// \brief If a header file is not found at the path that we expect it to be
977 /// and the PCH file was moved from its original location, try to resolve the
978 /// file by assuming that header+PCH were moved together and the header is in
979 /// the same place relative to the PCH.
980 static std::string
981 resolveFileRelativeToOriginalDir(const std::string &Filename,
982                                  const std::string &OriginalDir,
983                                  const std::string &CurrDir) {
984   assert(OriginalDir != CurrDir &&
985          "No point trying to resolve the file if the PCH dir didn't change");
986   using namespace llvm::sys;
987   SmallString<128> filePath(Filename);
988   fs::make_absolute(filePath);
989   assert(path::is_absolute(OriginalDir));
990   SmallString<128> currPCHPath(CurrDir);
991 
992   path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
993                        fileDirE = path::end(path::parent_path(filePath));
994   path::const_iterator origDirI = path::begin(OriginalDir),
995                        origDirE = path::end(OriginalDir);
996   // Skip the common path components from filePath and OriginalDir.
997   while (fileDirI != fileDirE && origDirI != origDirE &&
998          *fileDirI == *origDirI) {
999     ++fileDirI;
1000     ++origDirI;
1001   }
1002   for (; origDirI != origDirE; ++origDirI)
1003     path::append(currPCHPath, "..");
1004   path::append(currPCHPath, fileDirI, fileDirE);
1005   path::append(currPCHPath, path::filename(Filename));
1006   return currPCHPath.str();
1007 }
1008 
1009 bool ASTReader::ReadSLocEntry(int ID) {
1010   if (ID == 0)
1011     return false;
1012 
1013   if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1014     Error("source location entry ID out-of-range for AST file");
1015     return true;
1016   }
1017 
1018   ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1019   F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
1020   BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1021   unsigned BaseOffset = F->SLocEntryBaseOffset;
1022 
1023   ++NumSLocEntriesRead;
1024   llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1025   if (Entry.Kind != llvm::BitstreamEntry::Record) {
1026     Error("incorrectly-formatted source location entry in AST file");
1027     return true;
1028   }
1029 
1030   RecordData Record;
1031   StringRef Blob;
1032   switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
1033   default:
1034     Error("incorrectly-formatted source location entry in AST file");
1035     return true;
1036 
1037   case SM_SLOC_FILE_ENTRY: {
1038     // We will detect whether a file changed and return 'Failure' for it, but
1039     // we will also try to fail gracefully by setting up the SLocEntry.
1040     unsigned InputID = Record[4];
1041     InputFile IF = getInputFile(*F, InputID);
1042     const FileEntry *File = IF.getFile();
1043     bool OverriddenBuffer = IF.isOverridden();
1044 
1045     // Note that we only check if a File was returned. If it was out-of-date
1046     // we have complained but we will continue creating a FileID to recover
1047     // gracefully.
1048     if (!File)
1049       return true;
1050 
1051     SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1052     if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1053       // This is the module's main file.
1054       IncludeLoc = getImportLocation(F);
1055     }
1056     SrcMgr::CharacteristicKind
1057       FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1058     FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1059                                         ID, BaseOffset + Record[0]);
1060     SrcMgr::FileInfo &FileInfo =
1061           const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1062     FileInfo.NumCreatedFIDs = Record[5];
1063     if (Record[3])
1064       FileInfo.setHasLineDirectives();
1065 
1066     const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1067     unsigned NumFileDecls = Record[7];
1068     if (NumFileDecls) {
1069       assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1070       FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1071                                                              NumFileDecls));
1072     }
1073 
1074     const SrcMgr::ContentCache *ContentCache
1075       = SourceMgr.getOrCreateContentCache(File,
1076                               /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1077     if (OverriddenBuffer && !ContentCache->BufferOverridden &&
1078         ContentCache->ContentsEntry == ContentCache->OrigEntry) {
1079       unsigned Code = SLocEntryCursor.ReadCode();
1080       Record.clear();
1081       unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1082 
1083       if (RecCode != SM_SLOC_BUFFER_BLOB) {
1084         Error("AST record has invalid code");
1085         return true;
1086       }
1087 
1088       llvm::MemoryBuffer *Buffer
1089         = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
1090       SourceMgr.overrideFileContents(File, Buffer);
1091     }
1092 
1093     break;
1094   }
1095 
1096   case SM_SLOC_BUFFER_ENTRY: {
1097     const char *Name = Blob.data();
1098     unsigned Offset = Record[0];
1099     SrcMgr::CharacteristicKind
1100       FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1101     SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1102     if (IncludeLoc.isInvalid() && F->Kind == MK_Module) {
1103       IncludeLoc = getImportLocation(F);
1104     }
1105     unsigned Code = SLocEntryCursor.ReadCode();
1106     Record.clear();
1107     unsigned RecCode
1108       = SLocEntryCursor.readRecord(Code, Record, &Blob);
1109 
1110     if (RecCode != SM_SLOC_BUFFER_BLOB) {
1111       Error("AST record has invalid code");
1112       return true;
1113     }
1114 
1115     llvm::MemoryBuffer *Buffer
1116       = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
1117     SourceMgr.createFileIDForMemBuffer(Buffer, FileCharacter, ID,
1118                                        BaseOffset + Offset, IncludeLoc);
1119     break;
1120   }
1121 
1122   case SM_SLOC_EXPANSION_ENTRY: {
1123     SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1124     SourceMgr.createExpansionLoc(SpellingLoc,
1125                                      ReadSourceLocation(*F, Record[2]),
1126                                      ReadSourceLocation(*F, Record[3]),
1127                                      Record[4],
1128                                      ID,
1129                                      BaseOffset + Record[0]);
1130     break;
1131   }
1132   }
1133 
1134   return false;
1135 }
1136 
1137 std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1138   if (ID == 0)
1139     return std::make_pair(SourceLocation(), "");
1140 
1141   if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1142     Error("source location entry ID out-of-range for AST file");
1143     return std::make_pair(SourceLocation(), "");
1144   }
1145 
1146   // Find which module file this entry lands in.
1147   ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
1148   if (M->Kind != MK_Module)
1149     return std::make_pair(SourceLocation(), "");
1150 
1151   // FIXME: Can we map this down to a particular submodule? That would be
1152   // ideal.
1153   return std::make_pair(M->ImportLoc, llvm::sys::path::stem(M->FileName));
1154 }
1155 
1156 /// \brief Find the location where the module F is imported.
1157 SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1158   if (F->ImportLoc.isValid())
1159     return F->ImportLoc;
1160 
1161   // Otherwise we have a PCH. It's considered to be "imported" at the first
1162   // location of its includer.
1163   if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1164     // Main file is the importer. We assume that it is the first entry in the
1165     // entry table. We can't ask the manager, because at the time of PCH loading
1166     // the main file entry doesn't exist yet.
1167     // The very first entry is the invalid instantiation loc, which takes up
1168     // offsets 0 and 1.
1169     return SourceLocation::getFromRawEncoding(2U);
1170   }
1171   //return F->Loaders[0]->FirstLoc;
1172   return F->ImportedBy[0]->FirstLoc;
1173 }
1174 
1175 /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1176 /// specified cursor.  Read the abbreviations that are at the top of the block
1177 /// and then leave the cursor pointing into the block.
1178 bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
1179   if (Cursor.EnterSubBlock(BlockID)) {
1180     Error("malformed block record in AST file");
1181     return Failure;
1182   }
1183 
1184   while (true) {
1185     uint64_t Offset = Cursor.GetCurrentBitNo();
1186     unsigned Code = Cursor.ReadCode();
1187 
1188     // We expect all abbrevs to be at the start of the block.
1189     if (Code != llvm::bitc::DEFINE_ABBREV) {
1190       Cursor.JumpToBit(Offset);
1191       return false;
1192     }
1193     Cursor.ReadAbbrevRecord();
1194   }
1195 }
1196 
1197 Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
1198                            unsigned &Idx) {
1199   Token Tok;
1200   Tok.startToken();
1201   Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1202   Tok.setLength(Record[Idx++]);
1203   if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1204     Tok.setIdentifierInfo(II);
1205   Tok.setKind((tok::TokenKind)Record[Idx++]);
1206   Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1207   return Tok;
1208 }
1209 
1210 MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
1211   BitstreamCursor &Stream = F.MacroCursor;
1212 
1213   // Keep track of where we are in the stream, then jump back there
1214   // after reading this macro.
1215   SavedStreamPosition SavedPosition(Stream);
1216 
1217   Stream.JumpToBit(Offset);
1218   RecordData Record;
1219   SmallVector<IdentifierInfo*, 16> MacroArgs;
1220   MacroInfo *Macro = 0;
1221 
1222   while (true) {
1223     // Advance to the next record, but if we get to the end of the block, don't
1224     // pop it (removing all the abbreviations from the cursor) since we want to
1225     // be able to reseek within the block and read entries.
1226     unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
1227     llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
1228 
1229     switch (Entry.Kind) {
1230     case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1231     case llvm::BitstreamEntry::Error:
1232       Error("malformed block record in AST file");
1233       return Macro;
1234     case llvm::BitstreamEntry::EndBlock:
1235       return Macro;
1236     case llvm::BitstreamEntry::Record:
1237       // The interesting case.
1238       break;
1239     }
1240 
1241     // Read a record.
1242     Record.clear();
1243     PreprocessorRecordTypes RecType =
1244       (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
1245     switch (RecType) {
1246     case PP_MACRO_DIRECTIVE_HISTORY:
1247       return Macro;
1248 
1249     case PP_MACRO_OBJECT_LIKE:
1250     case PP_MACRO_FUNCTION_LIKE: {
1251       // If we already have a macro, that means that we've hit the end
1252       // of the definition of the macro we were looking for. We're
1253       // done.
1254       if (Macro)
1255         return Macro;
1256 
1257       unsigned NextIndex = 1; // Skip identifier ID.
1258       SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
1259       SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
1260       MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
1261       MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
1262       MI->setIsUsed(Record[NextIndex++]);
1263 
1264       if (RecType == PP_MACRO_FUNCTION_LIKE) {
1265         // Decode function-like macro info.
1266         bool isC99VarArgs = Record[NextIndex++];
1267         bool isGNUVarArgs = Record[NextIndex++];
1268         bool hasCommaPasting = Record[NextIndex++];
1269         MacroArgs.clear();
1270         unsigned NumArgs = Record[NextIndex++];
1271         for (unsigned i = 0; i != NumArgs; ++i)
1272           MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1273 
1274         // Install function-like macro info.
1275         MI->setIsFunctionLike();
1276         if (isC99VarArgs) MI->setIsC99Varargs();
1277         if (isGNUVarArgs) MI->setIsGNUVarargs();
1278         if (hasCommaPasting) MI->setHasCommaPasting();
1279         MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1280                             PP.getPreprocessorAllocator());
1281       }
1282 
1283       // Remember that we saw this macro last so that we add the tokens that
1284       // form its body to it.
1285       Macro = MI;
1286 
1287       if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1288           Record[NextIndex]) {
1289         // We have a macro definition. Register the association
1290         PreprocessedEntityID
1291             GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1292         PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
1293         PreprocessingRecord::PPEntityID
1294           PPID = PPRec.getPPEntityID(GlobalID-1, /*isLoaded=*/true);
1295         MacroDefinition *PPDef =
1296           cast_or_null<MacroDefinition>(PPRec.getPreprocessedEntity(PPID));
1297         if (PPDef)
1298           PPRec.RegisterMacroDefinition(Macro, PPDef);
1299       }
1300 
1301       ++NumMacrosRead;
1302       break;
1303     }
1304 
1305     case PP_TOKEN: {
1306       // If we see a TOKEN before a PP_MACRO_*, then the file is
1307       // erroneous, just pretend we didn't see this.
1308       if (Macro == 0) break;
1309 
1310       unsigned Idx = 0;
1311       Token Tok = ReadToken(F, Record, Idx);
1312       Macro->AddTokenToBody(Tok);
1313       break;
1314     }
1315     }
1316   }
1317 }
1318 
1319 PreprocessedEntityID
1320 ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
1321   ContinuousRangeMap<uint32_t, int, 2>::const_iterator
1322     I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1323   assert(I != M.PreprocessedEntityRemap.end()
1324          && "Invalid index into preprocessed entity index remap");
1325 
1326   return LocalID + I->second;
1327 }
1328 
1329 unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1330   return llvm::hash_combine(ikey.Size, ikey.ModTime);
1331 }
1332 
1333 HeaderFileInfoTrait::internal_key_type
1334 HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
1335   internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
1336                              FE->getName() };
1337   return ikey;
1338 }
1339 
1340 bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
1341   if (a.Size != b.Size || a.ModTime != b.ModTime)
1342     return false;
1343 
1344   if (strcmp(a.Filename, b.Filename) == 0)
1345     return true;
1346 
1347   // Determine whether the actual files are equivalent.
1348   FileManager &FileMgr = Reader.getFileManager();
1349   const FileEntry *FEA = FileMgr.getFile(a.Filename);
1350   const FileEntry *FEB = FileMgr.getFile(b.Filename);
1351   return (FEA && FEA == FEB);
1352 }
1353 
1354 std::pair<unsigned, unsigned>
1355 HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1356   unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
1357   unsigned DataLen = (unsigned) *d++;
1358   return std::make_pair(KeyLen, DataLen);
1359 }
1360 
1361 HeaderFileInfoTrait::internal_key_type
1362 HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
1363   internal_key_type ikey;
1364   ikey.Size = off_t(clang::io::ReadUnalignedLE64(d));
1365   ikey.ModTime = time_t(clang::io::ReadUnalignedLE64(d));
1366   ikey.Filename = (const char *)d;
1367   return ikey;
1368 }
1369 
1370 HeaderFileInfoTrait::data_type
1371 HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
1372                               unsigned DataLen) {
1373   const unsigned char *End = d + DataLen;
1374   using namespace clang::io;
1375   HeaderFileInfo HFI;
1376   unsigned Flags = *d++;
1377   HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
1378                    ((Flags >> 6) & 0x03);
1379   HFI.isImport = (Flags >> 5) & 0x01;
1380   HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1381   HFI.DirInfo = (Flags >> 2) & 0x03;
1382   HFI.Resolved = (Flags >> 1) & 0x01;
1383   HFI.IndexHeaderMapHeader = Flags & 0x01;
1384   HFI.NumIncludes = ReadUnalignedLE16(d);
1385   HFI.ControllingMacroID = Reader.getGlobalIdentifierID(M,
1386                                                         ReadUnalignedLE32(d));
1387   if (unsigned FrameworkOffset = ReadUnalignedLE32(d)) {
1388     // The framework offset is 1 greater than the actual offset,
1389     // since 0 is used as an indicator for "no framework name".
1390     StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1391     HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1392   }
1393 
1394   if (d != End) {
1395     uint32_t LocalSMID = ReadUnalignedLE32(d);
1396     if (LocalSMID) {
1397       // This header is part of a module. Associate it with the module to enable
1398       // implicit module import.
1399       SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1400       Module *Mod = Reader.getSubmodule(GlobalSMID);
1401       HFI.isModuleHeader = true;
1402       FileManager &FileMgr = Reader.getFileManager();
1403       ModuleMap &ModMap =
1404           Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1405       ModMap.addHeader(Mod, FileMgr.getFile(key.Filename), HFI.getHeaderRole());
1406     }
1407   }
1408 
1409   assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1410   (void)End;
1411 
1412   // This HeaderFileInfo was externally loaded.
1413   HFI.External = true;
1414   return HFI;
1415 }
1416 
1417 void
1418 ASTReader::addPendingMacroFromModule(IdentifierInfo *II, ModuleFile *M,
1419                                      GlobalMacroID GMacID,
1420                                      llvm::ArrayRef<SubmoduleID> Overrides) {
1421   assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1422   SubmoduleID *OverrideData = 0;
1423   if (!Overrides.empty()) {
1424     OverrideData = new (Context) SubmoduleID[Overrides.size() + 1];
1425     OverrideData[0] = Overrides.size();
1426     for (unsigned I = 0; I != Overrides.size(); ++I)
1427       OverrideData[I + 1] = getGlobalSubmoduleID(*M, Overrides[I]);
1428   }
1429   PendingMacroIDs[II].push_back(PendingMacroInfo(M, GMacID, OverrideData));
1430 }
1431 
1432 void ASTReader::addPendingMacroFromPCH(IdentifierInfo *II,
1433                                        ModuleFile *M,
1434                                        uint64_t MacroDirectivesOffset) {
1435   assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1436   PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
1437 }
1438 
1439 void ASTReader::ReadDefinedMacros() {
1440   // Note that we are loading defined macros.
1441   Deserializing Macros(this);
1442 
1443   for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1444       E = ModuleMgr.rend(); I != E; ++I) {
1445     BitstreamCursor &MacroCursor = (*I)->MacroCursor;
1446 
1447     // If there was no preprocessor block, skip this file.
1448     if (!MacroCursor.getBitStreamReader())
1449       continue;
1450 
1451     BitstreamCursor Cursor = MacroCursor;
1452     Cursor.JumpToBit((*I)->MacroStartOffset);
1453 
1454     RecordData Record;
1455     while (true) {
1456       llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
1457 
1458       switch (E.Kind) {
1459       case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1460       case llvm::BitstreamEntry::Error:
1461         Error("malformed block record in AST file");
1462         return;
1463       case llvm::BitstreamEntry::EndBlock:
1464         goto NextCursor;
1465 
1466       case llvm::BitstreamEntry::Record:
1467         Record.clear();
1468         switch (Cursor.readRecord(E.ID, Record)) {
1469         default:  // Default behavior: ignore.
1470           break;
1471 
1472         case PP_MACRO_OBJECT_LIKE:
1473         case PP_MACRO_FUNCTION_LIKE:
1474           getLocalIdentifier(**I, Record[0]);
1475           break;
1476 
1477         case PP_TOKEN:
1478           // Ignore tokens.
1479           break;
1480         }
1481         break;
1482       }
1483     }
1484     NextCursor:  ;
1485   }
1486 }
1487 
1488 namespace {
1489   /// \brief Visitor class used to look up identifirs in an AST file.
1490   class IdentifierLookupVisitor {
1491     StringRef Name;
1492     unsigned PriorGeneration;
1493     unsigned &NumIdentifierLookups;
1494     unsigned &NumIdentifierLookupHits;
1495     IdentifierInfo *Found;
1496 
1497   public:
1498     IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1499                             unsigned &NumIdentifierLookups,
1500                             unsigned &NumIdentifierLookupHits)
1501       : Name(Name), PriorGeneration(PriorGeneration),
1502         NumIdentifierLookups(NumIdentifierLookups),
1503         NumIdentifierLookupHits(NumIdentifierLookupHits),
1504         Found()
1505     {
1506     }
1507 
1508     static bool visit(ModuleFile &M, void *UserData) {
1509       IdentifierLookupVisitor *This
1510         = static_cast<IdentifierLookupVisitor *>(UserData);
1511 
1512       // If we've already searched this module file, skip it now.
1513       if (M.Generation <= This->PriorGeneration)
1514         return true;
1515 
1516       ASTIdentifierLookupTable *IdTable
1517         = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1518       if (!IdTable)
1519         return false;
1520 
1521       ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
1522                                      M, This->Found);
1523       ++This->NumIdentifierLookups;
1524       ASTIdentifierLookupTable::iterator Pos = IdTable->find(This->Name,&Trait);
1525       if (Pos == IdTable->end())
1526         return false;
1527 
1528       // Dereferencing the iterator has the effect of building the
1529       // IdentifierInfo node and populating it with the various
1530       // declarations it needs.
1531       ++This->NumIdentifierLookupHits;
1532       This->Found = *Pos;
1533       return true;
1534     }
1535 
1536     // \brief Retrieve the identifier info found within the module
1537     // files.
1538     IdentifierInfo *getIdentifierInfo() const { return Found; }
1539   };
1540 }
1541 
1542 void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1543   // Note that we are loading an identifier.
1544   Deserializing AnIdentifier(this);
1545 
1546   unsigned PriorGeneration = 0;
1547   if (getContext().getLangOpts().Modules)
1548     PriorGeneration = IdentifierGeneration[&II];
1549 
1550   // If there is a global index, look there first to determine which modules
1551   // provably do not have any results for this identifier.
1552   GlobalModuleIndex::HitSet Hits;
1553   GlobalModuleIndex::HitSet *HitsPtr = 0;
1554   if (!loadGlobalIndex()) {
1555     if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1556       HitsPtr = &Hits;
1557     }
1558   }
1559 
1560   IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
1561                                   NumIdentifierLookups,
1562                                   NumIdentifierLookupHits);
1563   ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
1564   markIdentifierUpToDate(&II);
1565 }
1566 
1567 void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1568   if (!II)
1569     return;
1570 
1571   II->setOutOfDate(false);
1572 
1573   // Update the generation for this identifier.
1574   if (getContext().getLangOpts().Modules)
1575     IdentifierGeneration[II] = CurrentGeneration;
1576 }
1577 
1578 struct ASTReader::ModuleMacroInfo {
1579   SubmoduleID SubModID;
1580   MacroInfo *MI;
1581   SubmoduleID *Overrides;
1582   // FIXME: Remove this.
1583   ModuleFile *F;
1584 
1585   bool isDefine() const { return MI; }
1586 
1587   SubmoduleID getSubmoduleID() const { return SubModID; }
1588 
1589   llvm::ArrayRef<SubmoduleID> getOverriddenSubmodules() const {
1590     if (!Overrides)
1591       return llvm::ArrayRef<SubmoduleID>();
1592     return llvm::makeArrayRef(Overrides + 1, *Overrides);
1593   }
1594 
1595   DefMacroDirective *import(Preprocessor &PP, SourceLocation ImportLoc) const {
1596     if (!MI)
1597       return 0;
1598     return PP.AllocateDefMacroDirective(MI, ImportLoc, /*isImported=*/true);
1599   }
1600 };
1601 
1602 ASTReader::ModuleMacroInfo *
1603 ASTReader::getModuleMacro(const PendingMacroInfo &PMInfo) {
1604   ModuleMacroInfo Info;
1605 
1606   uint32_t ID = PMInfo.ModuleMacroData.MacID;
1607   if (ID & 1) {
1608     // Macro undefinition.
1609     Info.SubModID = getGlobalSubmoduleID(*PMInfo.M, ID >> 1);
1610     Info.MI = 0;
1611   } else {
1612     // Macro definition.
1613     GlobalMacroID GMacID = getGlobalMacroID(*PMInfo.M, ID >> 1);
1614     assert(GMacID);
1615 
1616     // If this macro has already been loaded, don't do so again.
1617     // FIXME: This is highly dubious. Multiple macro definitions can have the
1618     // same MacroInfo (and hence the same GMacID) due to #pragma push_macro etc.
1619     if (MacrosLoaded[GMacID - NUM_PREDEF_MACRO_IDS])
1620       return 0;
1621 
1622     Info.MI = getMacro(GMacID);
1623     Info.SubModID = Info.MI->getOwningModuleID();
1624   }
1625   Info.Overrides = PMInfo.ModuleMacroData.Overrides;
1626   Info.F = PMInfo.M;
1627 
1628   return new (Context) ModuleMacroInfo(Info);
1629 }
1630 
1631 void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1632                                     const PendingMacroInfo &PMInfo) {
1633   assert(II);
1634 
1635   if (PMInfo.M->Kind != MK_Module) {
1636     installPCHMacroDirectives(II, *PMInfo.M,
1637                               PMInfo.PCHMacroData.MacroDirectivesOffset);
1638     return;
1639   }
1640 
1641   // Module Macro.
1642 
1643   ModuleMacroInfo *MMI = getModuleMacro(PMInfo);
1644   if (!MMI)
1645     return;
1646 
1647   Module *Owner = getSubmodule(MMI->getSubmoduleID());
1648   if (Owner && Owner->NameVisibility == Module::Hidden) {
1649     // Macros in the owning module are hidden. Just remember this macro to
1650     // install if we make this module visible.
1651     HiddenNamesMap[Owner].HiddenMacros.insert(std::make_pair(II, MMI));
1652   } else {
1653     installImportedMacro(II, MMI, Owner);
1654   }
1655 }
1656 
1657 void ASTReader::installPCHMacroDirectives(IdentifierInfo *II,
1658                                           ModuleFile &M, uint64_t Offset) {
1659   assert(M.Kind != MK_Module);
1660 
1661   BitstreamCursor &Cursor = M.MacroCursor;
1662   SavedStreamPosition SavedPosition(Cursor);
1663   Cursor.JumpToBit(Offset);
1664 
1665   llvm::BitstreamEntry Entry =
1666       Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1667   if (Entry.Kind != llvm::BitstreamEntry::Record) {
1668     Error("malformed block record in AST file");
1669     return;
1670   }
1671 
1672   RecordData Record;
1673   PreprocessorRecordTypes RecType =
1674     (PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record);
1675   if (RecType != PP_MACRO_DIRECTIVE_HISTORY) {
1676     Error("malformed block record in AST file");
1677     return;
1678   }
1679 
1680   // Deserialize the macro directives history in reverse source-order.
1681   MacroDirective *Latest = 0, *Earliest = 0;
1682   unsigned Idx = 0, N = Record.size();
1683   while (Idx < N) {
1684     MacroDirective *MD = 0;
1685     SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
1686     MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1687     switch (K) {
1688     case MacroDirective::MD_Define: {
1689       GlobalMacroID GMacID = getGlobalMacroID(M, Record[Idx++]);
1690       MacroInfo *MI = getMacro(GMacID);
1691       bool isImported = Record[Idx++];
1692       bool isAmbiguous = Record[Idx++];
1693       DefMacroDirective *DefMD =
1694           PP.AllocateDefMacroDirective(MI, Loc, isImported);
1695       DefMD->setAmbiguous(isAmbiguous);
1696       MD = DefMD;
1697       break;
1698     }
1699     case MacroDirective::MD_Undefine:
1700       MD = PP.AllocateUndefMacroDirective(Loc);
1701       break;
1702     case MacroDirective::MD_Visibility: {
1703       bool isPublic = Record[Idx++];
1704       MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1705       break;
1706     }
1707     }
1708 
1709     if (!Latest)
1710       Latest = MD;
1711     if (Earliest)
1712       Earliest->setPrevious(MD);
1713     Earliest = MD;
1714   }
1715 
1716   PP.setLoadedMacroDirective(II, Latest);
1717 }
1718 
1719 /// \brief For the given macro definitions, check if they are both in system
1720 /// modules.
1721 static bool areDefinedInSystemModules(MacroInfo *PrevMI, MacroInfo *NewMI,
1722                                       Module *NewOwner, ASTReader &Reader) {
1723   assert(PrevMI && NewMI);
1724   Module *PrevOwner = 0;
1725   if (SubmoduleID PrevModID = PrevMI->getOwningModuleID())
1726     PrevOwner = Reader.getSubmodule(PrevModID);
1727   SourceManager &SrcMgr = Reader.getSourceManager();
1728   bool PrevInSystem
1729     = PrevOwner? PrevOwner->IsSystem
1730                : SrcMgr.isInSystemHeader(PrevMI->getDefinitionLoc());
1731   bool NewInSystem
1732     = NewOwner? NewOwner->IsSystem
1733               : SrcMgr.isInSystemHeader(NewMI->getDefinitionLoc());
1734   if (PrevOwner && PrevOwner == NewOwner)
1735     return false;
1736   return PrevInSystem && NewInSystem;
1737 }
1738 
1739 void ASTReader::removeOverriddenMacros(IdentifierInfo *II,
1740                                        AmbiguousMacros &Ambig,
1741                                        llvm::ArrayRef<SubmoduleID> Overrides) {
1742   for (unsigned OI = 0, ON = Overrides.size(); OI != ON; ++OI) {
1743     SubmoduleID OwnerID = Overrides[OI];
1744 
1745     // If this macro is not yet visible, remove it from the hidden names list.
1746     Module *Owner = getSubmodule(OwnerID);
1747     HiddenNames &Hidden = HiddenNamesMap[Owner];
1748     HiddenMacrosMap::iterator HI = Hidden.HiddenMacros.find(II);
1749     if (HI != Hidden.HiddenMacros.end()) {
1750       auto SubOverrides = HI->second->getOverriddenSubmodules();
1751       Hidden.HiddenMacros.erase(HI);
1752       removeOverriddenMacros(II, Ambig, SubOverrides);
1753     }
1754 
1755     // If this macro is already in our list of conflicts, remove it from there.
1756     Ambig.erase(
1757         std::remove_if(Ambig.begin(), Ambig.end(), [&](DefMacroDirective *MD) {
1758           return MD->getInfo()->getOwningModuleID() == OwnerID;
1759         }),
1760         Ambig.end());
1761   }
1762 }
1763 
1764 ASTReader::AmbiguousMacros *
1765 ASTReader::removeOverriddenMacros(IdentifierInfo *II,
1766                                   llvm::ArrayRef<SubmoduleID> Overrides) {
1767   MacroDirective *Prev = PP.getMacroDirective(II);
1768   if (!Prev && Overrides.empty())
1769     return 0;
1770 
1771   DefMacroDirective *PrevDef = Prev ? Prev->getDefinition().getDirective() : 0;
1772   if (PrevDef && PrevDef->isAmbiguous()) {
1773     // We had a prior ambiguity. Check whether we resolve it (or make it worse).
1774     AmbiguousMacros &Ambig = AmbiguousMacroDefs[II];
1775     Ambig.push_back(PrevDef);
1776 
1777     removeOverriddenMacros(II, Ambig, Overrides);
1778 
1779     if (!Ambig.empty())
1780       return &Ambig;
1781 
1782     AmbiguousMacroDefs.erase(II);
1783   } else {
1784     // There's no ambiguity yet. Maybe we're introducing one.
1785     llvm::SmallVector<DefMacroDirective*, 1> Ambig;
1786     if (PrevDef)
1787       Ambig.push_back(PrevDef);
1788 
1789     removeOverriddenMacros(II, Ambig, Overrides);
1790 
1791     if (!Ambig.empty()) {
1792       AmbiguousMacros &Result = AmbiguousMacroDefs[II];
1793       Result.swap(Ambig);
1794       return &Result;
1795     }
1796   }
1797 
1798   // We ended up with no ambiguity.
1799   return 0;
1800 }
1801 
1802 void ASTReader::installImportedMacro(IdentifierInfo *II, ModuleMacroInfo *MMI,
1803                                      Module *Owner) {
1804   assert(II && Owner);
1805 
1806   SourceLocation ImportLoc = Owner->MacroVisibilityLoc;
1807   if (ImportLoc.isInvalid()) {
1808     // FIXME: If we made macros from this module visible but didn't provide a
1809     // source location for the import, we don't have a location for the macro.
1810     // Use the location at which the containing module file was first imported
1811     // for now.
1812     ImportLoc = MMI->F->DirectImportLoc;
1813   }
1814 
1815   llvm::SmallVectorImpl<DefMacroDirective*> *Prev =
1816       removeOverriddenMacros(II, MMI->getOverriddenSubmodules());
1817 
1818 
1819   // Create a synthetic macro definition corresponding to the import (or null
1820   // if this was an undefinition of the macro).
1821   DefMacroDirective *MD = MMI->import(PP, ImportLoc);
1822 
1823   // If there's no ambiguity, just install the macro.
1824   if (!Prev) {
1825     if (MD)
1826       PP.appendMacroDirective(II, MD);
1827     else
1828       PP.appendMacroDirective(II, PP.AllocateUndefMacroDirective(ImportLoc));
1829     return;
1830   }
1831   assert(!Prev->empty());
1832 
1833   if (!MD) {
1834     // We imported a #undef that didn't remove all prior definitions. The most
1835     // recent prior definition remains, and we install it in the place of the
1836     // imported directive.
1837     MacroInfo *NewMI = Prev->back()->getInfo();
1838     Prev->pop_back();
1839     MD = PP.AllocateDefMacroDirective(NewMI, ImportLoc, /*Imported*/true);
1840   }
1841 
1842   // We're introducing a macro definition that creates or adds to an ambiguity.
1843   // We can resolve that ambiguity if this macro is token-for-token identical to
1844   // all of the existing definitions.
1845   MacroInfo *NewMI = MD->getInfo();
1846   assert(NewMI && "macro definition with no MacroInfo?");
1847   while (!Prev->empty()) {
1848     MacroInfo *PrevMI = Prev->back()->getInfo();
1849     assert(PrevMI && "macro definition with no MacroInfo?");
1850 
1851     // Before marking the macros as ambiguous, check if this is a case where
1852     // both macros are in system headers. If so, we trust that the system
1853     // did not get it wrong. This also handles cases where Clang's own
1854     // headers have a different spelling of certain system macros:
1855     //   #define LONG_MAX __LONG_MAX__ (clang's limits.h)
1856     //   #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
1857     //
1858     // FIXME: Remove the defined-in-system-headers check. clang's limits.h
1859     // overrides the system limits.h's macros, so there's no conflict here.
1860     if (NewMI != PrevMI &&
1861         !PrevMI->isIdenticalTo(*NewMI, PP, /*Syntactically=*/true) &&
1862         !areDefinedInSystemModules(PrevMI, NewMI, Owner, *this))
1863       break;
1864 
1865     // The previous definition is the same as this one (or both are defined in
1866     // system modules so we can assume they're equivalent); we don't need to
1867     // track it any more.
1868     Prev->pop_back();
1869   }
1870 
1871   if (!Prev->empty())
1872     MD->setAmbiguous(true);
1873 
1874   PP.appendMacroDirective(II, MD);
1875 }
1876 
1877 void ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID,
1878                                  std::string &Filename, off_t &StoredSize,
1879                                  time_t &StoredTime, bool &Overridden) {
1880   // Go find this input file.
1881   BitstreamCursor &Cursor = F.InputFilesCursor;
1882   SavedStreamPosition SavedPosition(Cursor);
1883   Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1884 
1885   unsigned Code = Cursor.ReadCode();
1886   RecordData Record;
1887   StringRef Blob;
1888 
1889   unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1890   assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1891          "invalid record type for input file");
1892   (void)Result;
1893 
1894   assert(Record[0] == ID && "Bogus stored ID or offset");
1895   StoredSize = static_cast<off_t>(Record[1]);
1896   StoredTime = static_cast<time_t>(Record[2]);
1897   Overridden = static_cast<bool>(Record[3]);
1898   Filename = Blob;
1899   MaybeAddSystemRootToFilename(F, Filename);
1900 }
1901 
1902 std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
1903   off_t StoredSize;
1904   time_t StoredTime;
1905   bool Overridden;
1906   std::string Filename;
1907   readInputFileInfo(F, ID, Filename, StoredSize, StoredTime, Overridden);
1908   return Filename;
1909 }
1910 
1911 InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
1912   // If this ID is bogus, just return an empty input file.
1913   if (ID == 0 || ID > F.InputFilesLoaded.size())
1914     return InputFile();
1915 
1916   // If we've already loaded this input file, return it.
1917   if (F.InputFilesLoaded[ID-1].getFile())
1918     return F.InputFilesLoaded[ID-1];
1919 
1920   if (F.InputFilesLoaded[ID-1].isNotFound())
1921     return InputFile();
1922 
1923   // Go find this input file.
1924   BitstreamCursor &Cursor = F.InputFilesCursor;
1925   SavedStreamPosition SavedPosition(Cursor);
1926   Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1927 
1928   off_t StoredSize;
1929   time_t StoredTime;
1930   bool Overridden;
1931   std::string Filename;
1932   readInputFileInfo(F, ID, Filename, StoredSize, StoredTime, Overridden);
1933 
1934   const FileEntry *File
1935     = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
1936                 : FileMgr.getFile(Filename, /*OpenFile=*/false);
1937 
1938   // If we didn't find the file, resolve it relative to the
1939   // original directory from which this AST file was created.
1940   if (File == 0 && !F.OriginalDir.empty() && !CurrentDir.empty() &&
1941       F.OriginalDir != CurrentDir) {
1942     std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
1943                                                             F.OriginalDir,
1944                                                             CurrentDir);
1945     if (!Resolved.empty())
1946       File = FileMgr.getFile(Resolved);
1947   }
1948 
1949   // For an overridden file, create a virtual file with the stored
1950   // size/timestamp.
1951   if (Overridden && File == 0) {
1952     File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
1953   }
1954 
1955   if (File == 0) {
1956     if (Complain) {
1957       std::string ErrorStr = "could not find file '";
1958       ErrorStr += Filename;
1959       ErrorStr += "' referenced by AST file";
1960       Error(ErrorStr.c_str());
1961     }
1962     // Record that we didn't find the file.
1963     F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
1964     return InputFile();
1965   }
1966 
1967   // Check if there was a request to override the contents of the file
1968   // that was part of the precompiled header. Overridding such a file
1969   // can lead to problems when lexing using the source locations from the
1970   // PCH.
1971   SourceManager &SM = getSourceManager();
1972   if (!Overridden && SM.isFileOverridden(File)) {
1973     if (Complain)
1974       Error(diag::err_fe_pch_file_overridden, Filename);
1975     // After emitting the diagnostic, recover by disabling the override so
1976     // that the original file will be used.
1977     SM.disableFileContentsOverride(File);
1978     // The FileEntry is a virtual file entry with the size of the contents
1979     // that would override the original contents. Set it to the original's
1980     // size/time.
1981     FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
1982                             StoredSize, StoredTime);
1983   }
1984 
1985   bool IsOutOfDate = false;
1986 
1987   // For an overridden file, there is nothing to validate.
1988   if (!Overridden && (StoredSize != File->getSize()
1989 #if !defined(LLVM_ON_WIN32)
1990        // In our regression testing, the Windows file system seems to
1991        // have inconsistent modification times that sometimes
1992        // erroneously trigger this error-handling path.
1993        || StoredTime != File->getModificationTime()
1994 #endif
1995        )) {
1996     if (Complain) {
1997       // Build a list of the PCH imports that got us here (in reverse).
1998       SmallVector<ModuleFile *, 4> ImportStack(1, &F);
1999       while (ImportStack.back()->ImportedBy.size() > 0)
2000         ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
2001 
2002       // The top-level PCH is stale.
2003       StringRef TopLevelPCHName(ImportStack.back()->FileName);
2004       Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
2005 
2006       // Print the import stack.
2007       if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2008         Diag(diag::note_pch_required_by)
2009           << Filename << ImportStack[0]->FileName;
2010         for (unsigned I = 1; I < ImportStack.size(); ++I)
2011           Diag(diag::note_pch_required_by)
2012             << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
2013       }
2014 
2015       if (!Diags.isDiagnosticInFlight())
2016         Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
2017     }
2018 
2019     IsOutOfDate = true;
2020   }
2021 
2022   InputFile IF = InputFile(File, Overridden, IsOutOfDate);
2023 
2024   // Note that we've loaded this input file.
2025   F.InputFilesLoaded[ID-1] = IF;
2026   return IF;
2027 }
2028 
2029 const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
2030   ModuleFile &M = ModuleMgr.getPrimaryModule();
2031   std::string Filename = filenameStrRef;
2032   MaybeAddSystemRootToFilename(M, Filename);
2033   const FileEntry *File = FileMgr.getFile(Filename);
2034   if (File == 0 && !M.OriginalDir.empty() && !CurrentDir.empty() &&
2035       M.OriginalDir != CurrentDir) {
2036     std::string resolved = resolveFileRelativeToOriginalDir(Filename,
2037                                                             M.OriginalDir,
2038                                                             CurrentDir);
2039     if (!resolved.empty())
2040       File = FileMgr.getFile(resolved);
2041   }
2042 
2043   return File;
2044 }
2045 
2046 /// \brief If we are loading a relocatable PCH file, and the filename is
2047 /// not an absolute path, add the system root to the beginning of the file
2048 /// name.
2049 void ASTReader::MaybeAddSystemRootToFilename(ModuleFile &M,
2050                                              std::string &Filename) {
2051   // If this is not a relocatable PCH file, there's nothing to do.
2052   if (!M.RelocatablePCH)
2053     return;
2054 
2055   if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2056     return;
2057 
2058   if (isysroot.empty()) {
2059     // If no system root was given, default to '/'
2060     Filename.insert(Filename.begin(), '/');
2061     return;
2062   }
2063 
2064   unsigned Length = isysroot.size();
2065   if (isysroot[Length - 1] != '/')
2066     Filename.insert(Filename.begin(), '/');
2067 
2068   Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
2069 }
2070 
2071 ASTReader::ASTReadResult
2072 ASTReader::ReadControlBlock(ModuleFile &F,
2073                             SmallVectorImpl<ImportedModule> &Loaded,
2074                             unsigned ClientLoadCapabilities) {
2075   BitstreamCursor &Stream = F.Stream;
2076 
2077   if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2078     Error("malformed block record in AST file");
2079     return Failure;
2080   }
2081 
2082   // Read all of the records and blocks in the control block.
2083   RecordData Record;
2084   while (1) {
2085     llvm::BitstreamEntry Entry = Stream.advance();
2086 
2087     switch (Entry.Kind) {
2088     case llvm::BitstreamEntry::Error:
2089       Error("malformed block record in AST file");
2090       return Failure;
2091     case llvm::BitstreamEntry::EndBlock: {
2092       // Validate input files.
2093       const HeaderSearchOptions &HSOpts =
2094           PP.getHeaderSearchInfo().getHeaderSearchOpts();
2095 
2096       // All user input files reside at the index range [0, Record[1]), and
2097       // system input files reside at [Record[1], Record[0]).
2098       // Record is the one from INPUT_FILE_OFFSETS.
2099       unsigned NumInputs = Record[0];
2100       unsigned NumUserInputs = Record[1];
2101 
2102       if (!DisableValidation &&
2103           (!HSOpts.ModulesValidateOncePerBuildSession ||
2104            F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp)) {
2105         bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
2106 
2107         // If we are reading a module, we will create a verification timestamp,
2108         // so we verify all input files.  Otherwise, verify only user input
2109         // files.
2110 
2111         unsigned N = NumUserInputs;
2112         if (ValidateSystemInputs ||
2113             (HSOpts.ModulesValidateOncePerBuildSession && F.Kind == MK_Module))
2114           N = NumInputs;
2115 
2116         for (unsigned I = 0; I < N; ++I) {
2117           InputFile IF = getInputFile(F, I+1, Complain);
2118           if (!IF.getFile() || IF.isOutOfDate())
2119             return OutOfDate;
2120         }
2121       }
2122 
2123       if (Listener && Listener->needsInputFileVisitation()) {
2124         unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2125                                                                 : NumUserInputs;
2126         for (unsigned I = 0; I < N; ++I)
2127           Listener->visitInputFile(getInputFileName(F, I+1), I >= NumUserInputs);
2128       }
2129 
2130       return Success;
2131     }
2132 
2133     case llvm::BitstreamEntry::SubBlock:
2134       switch (Entry.ID) {
2135       case INPUT_FILES_BLOCK_ID:
2136         F.InputFilesCursor = Stream;
2137         if (Stream.SkipBlock() || // Skip with the main cursor
2138             // Read the abbreviations
2139             ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2140           Error("malformed block record in AST file");
2141           return Failure;
2142         }
2143         continue;
2144 
2145       default:
2146         if (Stream.SkipBlock()) {
2147           Error("malformed block record in AST file");
2148           return Failure;
2149         }
2150         continue;
2151       }
2152 
2153     case llvm::BitstreamEntry::Record:
2154       // The interesting case.
2155       break;
2156     }
2157 
2158     // Read and process a record.
2159     Record.clear();
2160     StringRef Blob;
2161     switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
2162     case METADATA: {
2163       if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2164         if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2165           Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2166                                         : diag::err_pch_version_too_new);
2167         return VersionMismatch;
2168       }
2169 
2170       bool hasErrors = Record[5];
2171       if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2172         Diag(diag::err_pch_with_compiler_errors);
2173         return HadErrors;
2174       }
2175 
2176       F.RelocatablePCH = Record[4];
2177 
2178       const std::string &CurBranch = getClangFullRepositoryVersion();
2179       StringRef ASTBranch = Blob;
2180       if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2181         if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
2182           Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
2183         return VersionMismatch;
2184       }
2185       break;
2186     }
2187 
2188     case IMPORTS: {
2189       // Load each of the imported PCH files.
2190       unsigned Idx = 0, N = Record.size();
2191       while (Idx < N) {
2192         // Read information about the AST file.
2193         ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2194         // The import location will be the local one for now; we will adjust
2195         // all import locations of module imports after the global source
2196         // location info are setup.
2197         SourceLocation ImportLoc =
2198             SourceLocation::getFromRawEncoding(Record[Idx++]);
2199         off_t StoredSize = (off_t)Record[Idx++];
2200         time_t StoredModTime = (time_t)Record[Idx++];
2201         unsigned Length = Record[Idx++];
2202         SmallString<128> ImportedFile(Record.begin() + Idx,
2203                                       Record.begin() + Idx + Length);
2204         Idx += Length;
2205 
2206         // Load the AST file.
2207         switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
2208                            StoredSize, StoredModTime,
2209                            ClientLoadCapabilities)) {
2210         case Failure: return Failure;
2211           // If we have to ignore the dependency, we'll have to ignore this too.
2212         case Missing:
2213         case OutOfDate: return OutOfDate;
2214         case VersionMismatch: return VersionMismatch;
2215         case ConfigurationMismatch: return ConfigurationMismatch;
2216         case HadErrors: return HadErrors;
2217         case Success: break;
2218         }
2219       }
2220       break;
2221     }
2222 
2223     case LANGUAGE_OPTIONS: {
2224       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2225       if (Listener && &F == *ModuleMgr.begin() &&
2226           ParseLanguageOptions(Record, Complain, *Listener) &&
2227           !DisableValidation && !AllowConfigurationMismatch)
2228         return ConfigurationMismatch;
2229       break;
2230     }
2231 
2232     case TARGET_OPTIONS: {
2233       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2234       if (Listener && &F == *ModuleMgr.begin() &&
2235           ParseTargetOptions(Record, Complain, *Listener) &&
2236           !DisableValidation && !AllowConfigurationMismatch)
2237         return ConfigurationMismatch;
2238       break;
2239     }
2240 
2241     case DIAGNOSTIC_OPTIONS: {
2242       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2243       if (Listener && &F == *ModuleMgr.begin() &&
2244           ParseDiagnosticOptions(Record, Complain, *Listener) &&
2245           !DisableValidation && !AllowConfigurationMismatch)
2246         return ConfigurationMismatch;
2247       break;
2248     }
2249 
2250     case FILE_SYSTEM_OPTIONS: {
2251       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2252       if (Listener && &F == *ModuleMgr.begin() &&
2253           ParseFileSystemOptions(Record, Complain, *Listener) &&
2254           !DisableValidation && !AllowConfigurationMismatch)
2255         return ConfigurationMismatch;
2256       break;
2257     }
2258 
2259     case HEADER_SEARCH_OPTIONS: {
2260       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2261       if (Listener && &F == *ModuleMgr.begin() &&
2262           ParseHeaderSearchOptions(Record, Complain, *Listener) &&
2263           !DisableValidation && !AllowConfigurationMismatch)
2264         return ConfigurationMismatch;
2265       break;
2266     }
2267 
2268     case PREPROCESSOR_OPTIONS: {
2269       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
2270       if (Listener && &F == *ModuleMgr.begin() &&
2271           ParsePreprocessorOptions(Record, Complain, *Listener,
2272                                    SuggestedPredefines) &&
2273           !DisableValidation && !AllowConfigurationMismatch)
2274         return ConfigurationMismatch;
2275       break;
2276     }
2277 
2278     case ORIGINAL_FILE:
2279       F.OriginalSourceFileID = FileID::get(Record[0]);
2280       F.ActualOriginalSourceFileName = Blob;
2281       F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
2282       MaybeAddSystemRootToFilename(F, F.OriginalSourceFileName);
2283       break;
2284 
2285     case ORIGINAL_FILE_ID:
2286       F.OriginalSourceFileID = FileID::get(Record[0]);
2287       break;
2288 
2289     case ORIGINAL_PCH_DIR:
2290       F.OriginalDir = Blob;
2291       break;
2292 
2293     case INPUT_FILE_OFFSETS:
2294       F.InputFileOffsets = (const uint32_t *)Blob.data();
2295       F.InputFilesLoaded.resize(Record[0]);
2296       break;
2297     }
2298   }
2299 }
2300 
2301 bool ASTReader::ReadASTBlock(ModuleFile &F) {
2302   BitstreamCursor &Stream = F.Stream;
2303 
2304   if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2305     Error("malformed block record in AST file");
2306     return true;
2307   }
2308 
2309   // Read all of the records and blocks for the AST file.
2310   RecordData Record;
2311   while (1) {
2312     llvm::BitstreamEntry Entry = Stream.advance();
2313 
2314     switch (Entry.Kind) {
2315     case llvm::BitstreamEntry::Error:
2316       Error("error at end of module block in AST file");
2317       return true;
2318     case llvm::BitstreamEntry::EndBlock: {
2319       // Outside of C++, we do not store a lookup map for the translation unit.
2320       // Instead, mark it as needing a lookup map to be built if this module
2321       // contains any declarations lexically within it (which it always does!).
2322       // This usually has no cost, since we very rarely need the lookup map for
2323       // the translation unit outside C++.
2324       DeclContext *DC = Context.getTranslationUnitDecl();
2325       if (DC->hasExternalLexicalStorage() &&
2326           !getContext().getLangOpts().CPlusPlus)
2327         DC->setMustBuildLookupTable();
2328 
2329       return false;
2330     }
2331     case llvm::BitstreamEntry::SubBlock:
2332       switch (Entry.ID) {
2333       case DECLTYPES_BLOCK_ID:
2334         // We lazily load the decls block, but we want to set up the
2335         // DeclsCursor cursor to point into it.  Clone our current bitcode
2336         // cursor to it, enter the block and read the abbrevs in that block.
2337         // With the main cursor, we just skip over it.
2338         F.DeclsCursor = Stream;
2339         if (Stream.SkipBlock() ||  // Skip with the main cursor.
2340             // Read the abbrevs.
2341             ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2342           Error("malformed block record in AST file");
2343           return true;
2344         }
2345         break;
2346 
2347       case DECL_UPDATES_BLOCK_ID:
2348         if (Stream.SkipBlock()) {
2349           Error("malformed block record in AST file");
2350           return true;
2351         }
2352         break;
2353 
2354       case PREPROCESSOR_BLOCK_ID:
2355         F.MacroCursor = Stream;
2356         if (!PP.getExternalSource())
2357           PP.setExternalSource(this);
2358 
2359         if (Stream.SkipBlock() ||
2360             ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2361           Error("malformed block record in AST file");
2362           return true;
2363         }
2364         F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2365         break;
2366 
2367       case PREPROCESSOR_DETAIL_BLOCK_ID:
2368         F.PreprocessorDetailCursor = Stream;
2369         if (Stream.SkipBlock() ||
2370             ReadBlockAbbrevs(F.PreprocessorDetailCursor,
2371                              PREPROCESSOR_DETAIL_BLOCK_ID)) {
2372               Error("malformed preprocessor detail record in AST file");
2373               return true;
2374             }
2375         F.PreprocessorDetailStartOffset
2376         = F.PreprocessorDetailCursor.GetCurrentBitNo();
2377 
2378         if (!PP.getPreprocessingRecord())
2379           PP.createPreprocessingRecord();
2380         if (!PP.getPreprocessingRecord()->getExternalSource())
2381           PP.getPreprocessingRecord()->SetExternalSource(*this);
2382         break;
2383 
2384       case SOURCE_MANAGER_BLOCK_ID:
2385         if (ReadSourceManagerBlock(F))
2386           return true;
2387         break;
2388 
2389       case SUBMODULE_BLOCK_ID:
2390         if (ReadSubmoduleBlock(F))
2391           return true;
2392         break;
2393 
2394       case COMMENTS_BLOCK_ID: {
2395         BitstreamCursor C = Stream;
2396         if (Stream.SkipBlock() ||
2397             ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2398           Error("malformed comments block in AST file");
2399           return true;
2400         }
2401         CommentsCursors.push_back(std::make_pair(C, &F));
2402         break;
2403       }
2404 
2405       default:
2406         if (Stream.SkipBlock()) {
2407           Error("malformed block record in AST file");
2408           return true;
2409         }
2410         break;
2411       }
2412       continue;
2413 
2414     case llvm::BitstreamEntry::Record:
2415       // The interesting case.
2416       break;
2417     }
2418 
2419     // Read and process a record.
2420     Record.clear();
2421     StringRef Blob;
2422     switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
2423     default:  // Default behavior: ignore.
2424       break;
2425 
2426     case TYPE_OFFSET: {
2427       if (F.LocalNumTypes != 0) {
2428         Error("duplicate TYPE_OFFSET record in AST file");
2429         return true;
2430       }
2431       F.TypeOffsets = (const uint32_t *)Blob.data();
2432       F.LocalNumTypes = Record[0];
2433       unsigned LocalBaseTypeIndex = Record[1];
2434       F.BaseTypeIndex = getTotalNumTypes();
2435 
2436       if (F.LocalNumTypes > 0) {
2437         // Introduce the global -> local mapping for types within this module.
2438         GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
2439 
2440         // Introduce the local -> global mapping for types within this module.
2441         F.TypeRemap.insertOrReplace(
2442           std::make_pair(LocalBaseTypeIndex,
2443                          F.BaseTypeIndex - LocalBaseTypeIndex));
2444 
2445         TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
2446       }
2447       break;
2448     }
2449 
2450     case DECL_OFFSET: {
2451       if (F.LocalNumDecls != 0) {
2452         Error("duplicate DECL_OFFSET record in AST file");
2453         return true;
2454       }
2455       F.DeclOffsets = (const DeclOffset *)Blob.data();
2456       F.LocalNumDecls = Record[0];
2457       unsigned LocalBaseDeclID = Record[1];
2458       F.BaseDeclID = getTotalNumDecls();
2459 
2460       if (F.LocalNumDecls > 0) {
2461         // Introduce the global -> local mapping for declarations within this
2462         // module.
2463         GlobalDeclMap.insert(
2464           std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
2465 
2466         // Introduce the local -> global mapping for declarations within this
2467         // module.
2468         F.DeclRemap.insertOrReplace(
2469           std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
2470 
2471         // Introduce the global -> local mapping for declarations within this
2472         // module.
2473         F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
2474 
2475         DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2476       }
2477       break;
2478     }
2479 
2480     case TU_UPDATE_LEXICAL: {
2481       DeclContext *TU = Context.getTranslationUnitDecl();
2482       DeclContextInfo &Info = F.DeclContextInfos[TU];
2483       Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
2484       Info.NumLexicalDecls
2485         = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
2486       TU->setHasExternalLexicalStorage(true);
2487       break;
2488     }
2489 
2490     case UPDATE_VISIBLE: {
2491       unsigned Idx = 0;
2492       serialization::DeclID ID = ReadDeclID(F, Record, Idx);
2493       ASTDeclContextNameLookupTable *Table =
2494         ASTDeclContextNameLookupTable::Create(
2495                         (const unsigned char *)Blob.data() + Record[Idx++],
2496                         (const unsigned char *)Blob.data(),
2497                         ASTDeclContextNameLookupTrait(*this, F));
2498       if (ID == PREDEF_DECL_TRANSLATION_UNIT_ID) { // Is it the TU?
2499         DeclContext *TU = Context.getTranslationUnitDecl();
2500         F.DeclContextInfos[TU].NameLookupTableData.reset(Table);
2501         TU->setHasExternalVisibleStorage(true);
2502       } else if (Decl *D = DeclsLoaded[ID - NUM_PREDEF_DECL_IDS]) {
2503         auto *DC = cast<DeclContext>(D);
2504         DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
2505         F.DeclContextInfos[DC].NameLookupTableData.reset(Table);
2506       } else
2507         PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
2508       break;
2509     }
2510 
2511     case IDENTIFIER_TABLE:
2512       F.IdentifierTableData = Blob.data();
2513       if (Record[0]) {
2514         F.IdentifierLookupTable
2515           = ASTIdentifierLookupTable::Create(
2516                        (const unsigned char *)F.IdentifierTableData + Record[0],
2517                        (const unsigned char *)F.IdentifierTableData,
2518                        ASTIdentifierLookupTrait(*this, F));
2519 
2520         PP.getIdentifierTable().setExternalIdentifierLookup(this);
2521       }
2522       break;
2523 
2524     case IDENTIFIER_OFFSET: {
2525       if (F.LocalNumIdentifiers != 0) {
2526         Error("duplicate IDENTIFIER_OFFSET record in AST file");
2527         return true;
2528       }
2529       F.IdentifierOffsets = (const uint32_t *)Blob.data();
2530       F.LocalNumIdentifiers = Record[0];
2531       unsigned LocalBaseIdentifierID = Record[1];
2532       F.BaseIdentifierID = getTotalNumIdentifiers();
2533 
2534       if (F.LocalNumIdentifiers > 0) {
2535         // Introduce the global -> local mapping for identifiers within this
2536         // module.
2537         GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2538                                                   &F));
2539 
2540         // Introduce the local -> global mapping for identifiers within this
2541         // module.
2542         F.IdentifierRemap.insertOrReplace(
2543           std::make_pair(LocalBaseIdentifierID,
2544                          F.BaseIdentifierID - LocalBaseIdentifierID));
2545 
2546         IdentifiersLoaded.resize(IdentifiersLoaded.size()
2547                                  + F.LocalNumIdentifiers);
2548       }
2549       break;
2550     }
2551 
2552     case EAGERLY_DESERIALIZED_DECLS:
2553       for (unsigned I = 0, N = Record.size(); I != N; ++I)
2554         EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2555       break;
2556 
2557     case SPECIAL_TYPES:
2558       if (SpecialTypes.empty()) {
2559         for (unsigned I = 0, N = Record.size(); I != N; ++I)
2560           SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2561         break;
2562       }
2563 
2564       if (SpecialTypes.size() != Record.size()) {
2565         Error("invalid special-types record");
2566         return true;
2567       }
2568 
2569       for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2570         serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2571         if (!SpecialTypes[I])
2572           SpecialTypes[I] = ID;
2573         // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2574         // merge step?
2575       }
2576       break;
2577 
2578     case STATISTICS:
2579       TotalNumStatements += Record[0];
2580       TotalNumMacros += Record[1];
2581       TotalLexicalDeclContexts += Record[2];
2582       TotalVisibleDeclContexts += Record[3];
2583       break;
2584 
2585     case UNUSED_FILESCOPED_DECLS:
2586       for (unsigned I = 0, N = Record.size(); I != N; ++I)
2587         UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2588       break;
2589 
2590     case DELEGATING_CTORS:
2591       for (unsigned I = 0, N = Record.size(); I != N; ++I)
2592         DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2593       break;
2594 
2595     case WEAK_UNDECLARED_IDENTIFIERS:
2596       if (Record.size() % 4 != 0) {
2597         Error("invalid weak identifiers record");
2598         return true;
2599       }
2600 
2601       // FIXME: Ignore weak undeclared identifiers from non-original PCH
2602       // files. This isn't the way to do it :)
2603       WeakUndeclaredIdentifiers.clear();
2604 
2605       // Translate the weak, undeclared identifiers into global IDs.
2606       for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2607         WeakUndeclaredIdentifiers.push_back(
2608           getGlobalIdentifierID(F, Record[I++]));
2609         WeakUndeclaredIdentifiers.push_back(
2610           getGlobalIdentifierID(F, Record[I++]));
2611         WeakUndeclaredIdentifiers.push_back(
2612           ReadSourceLocation(F, Record, I).getRawEncoding());
2613         WeakUndeclaredIdentifiers.push_back(Record[I++]);
2614       }
2615       break;
2616 
2617     case LOCALLY_SCOPED_EXTERN_C_DECLS:
2618       for (unsigned I = 0, N = Record.size(); I != N; ++I)
2619         LocallyScopedExternCDecls.push_back(getGlobalDeclID(F, Record[I]));
2620       break;
2621 
2622     case SELECTOR_OFFSETS: {
2623       F.SelectorOffsets = (const uint32_t *)Blob.data();
2624       F.LocalNumSelectors = Record[0];
2625       unsigned LocalBaseSelectorID = Record[1];
2626       F.BaseSelectorID = getTotalNumSelectors();
2627 
2628       if (F.LocalNumSelectors > 0) {
2629         // Introduce the global -> local mapping for selectors within this
2630         // module.
2631         GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2632 
2633         // Introduce the local -> global mapping for selectors within this
2634         // module.
2635         F.SelectorRemap.insertOrReplace(
2636           std::make_pair(LocalBaseSelectorID,
2637                          F.BaseSelectorID - LocalBaseSelectorID));
2638 
2639         SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2640       }
2641       break;
2642     }
2643 
2644     case METHOD_POOL:
2645       F.SelectorLookupTableData = (const unsigned char *)Blob.data();
2646       if (Record[0])
2647         F.SelectorLookupTable
2648           = ASTSelectorLookupTable::Create(
2649                         F.SelectorLookupTableData + Record[0],
2650                         F.SelectorLookupTableData,
2651                         ASTSelectorLookupTrait(*this, F));
2652       TotalNumMethodPoolEntries += Record[1];
2653       break;
2654 
2655     case REFERENCED_SELECTOR_POOL:
2656       if (!Record.empty()) {
2657         for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2658           ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2659                                                                 Record[Idx++]));
2660           ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2661                                               getRawEncoding());
2662         }
2663       }
2664       break;
2665 
2666     case PP_COUNTER_VALUE:
2667       if (!Record.empty() && Listener)
2668         Listener->ReadCounter(F, Record[0]);
2669       break;
2670 
2671     case FILE_SORTED_DECLS:
2672       F.FileSortedDecls = (const DeclID *)Blob.data();
2673       F.NumFileSortedDecls = Record[0];
2674       break;
2675 
2676     case SOURCE_LOCATION_OFFSETS: {
2677       F.SLocEntryOffsets = (const uint32_t *)Blob.data();
2678       F.LocalNumSLocEntries = Record[0];
2679       unsigned SLocSpaceSize = Record[1];
2680       std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
2681           SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
2682                                               SLocSpaceSize);
2683       // Make our entry in the range map. BaseID is negative and growing, so
2684       // we invert it. Because we invert it, though, we need the other end of
2685       // the range.
2686       unsigned RangeStart =
2687           unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2688       GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2689       F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2690 
2691       // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2692       assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2693       GlobalSLocOffsetMap.insert(
2694           std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2695                            - SLocSpaceSize,&F));
2696 
2697       // Initialize the remapping table.
2698       // Invalid stays invalid.
2699       F.SLocRemap.insert(std::make_pair(0U, 0));
2700       // This module. Base was 2 when being compiled.
2701       F.SLocRemap.insert(std::make_pair(2U,
2702                                   static_cast<int>(F.SLocEntryBaseOffset - 2)));
2703 
2704       TotalNumSLocEntries += F.LocalNumSLocEntries;
2705       break;
2706     }
2707 
2708     case MODULE_OFFSET_MAP: {
2709       // Additional remapping information.
2710       const unsigned char *Data = (const unsigned char*)Blob.data();
2711       const unsigned char *DataEnd = Data + Blob.size();
2712 
2713       // Continuous range maps we may be updating in our module.
2714       ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
2715       ContinuousRangeMap<uint32_t, int, 2>::Builder
2716         IdentifierRemap(F.IdentifierRemap);
2717       ContinuousRangeMap<uint32_t, int, 2>::Builder
2718         MacroRemap(F.MacroRemap);
2719       ContinuousRangeMap<uint32_t, int, 2>::Builder
2720         PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2721       ContinuousRangeMap<uint32_t, int, 2>::Builder
2722         SubmoduleRemap(F.SubmoduleRemap);
2723       ContinuousRangeMap<uint32_t, int, 2>::Builder
2724         SelectorRemap(F.SelectorRemap);
2725       ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
2726       ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2727 
2728       while(Data < DataEnd) {
2729         uint16_t Len = io::ReadUnalignedLE16(Data);
2730         StringRef Name = StringRef((const char*)Data, Len);
2731         Data += Len;
2732         ModuleFile *OM = ModuleMgr.lookup(Name);
2733         if (!OM) {
2734           Error("SourceLocation remap refers to unknown module");
2735           return true;
2736         }
2737 
2738         uint32_t SLocOffset = io::ReadUnalignedLE32(Data);
2739         uint32_t IdentifierIDOffset = io::ReadUnalignedLE32(Data);
2740         uint32_t MacroIDOffset = io::ReadUnalignedLE32(Data);
2741         uint32_t PreprocessedEntityIDOffset = io::ReadUnalignedLE32(Data);
2742         uint32_t SubmoduleIDOffset = io::ReadUnalignedLE32(Data);
2743         uint32_t SelectorIDOffset = io::ReadUnalignedLE32(Data);
2744         uint32_t DeclIDOffset = io::ReadUnalignedLE32(Data);
2745         uint32_t TypeIndexOffset = io::ReadUnalignedLE32(Data);
2746 
2747         // Source location offset is mapped to OM->SLocEntryBaseOffset.
2748         SLocRemap.insert(std::make_pair(SLocOffset,
2749           static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
2750         IdentifierRemap.insert(
2751           std::make_pair(IdentifierIDOffset,
2752                          OM->BaseIdentifierID - IdentifierIDOffset));
2753         MacroRemap.insert(std::make_pair(MacroIDOffset,
2754                                          OM->BaseMacroID - MacroIDOffset));
2755         PreprocessedEntityRemap.insert(
2756           std::make_pair(PreprocessedEntityIDOffset,
2757             OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
2758         SubmoduleRemap.insert(std::make_pair(SubmoduleIDOffset,
2759                                       OM->BaseSubmoduleID - SubmoduleIDOffset));
2760         SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2761                                OM->BaseSelectorID - SelectorIDOffset));
2762         DeclRemap.insert(std::make_pair(DeclIDOffset,
2763                                         OM->BaseDeclID - DeclIDOffset));
2764 
2765         TypeRemap.insert(std::make_pair(TypeIndexOffset,
2766                                     OM->BaseTypeIndex - TypeIndexOffset));
2767 
2768         // Global -> local mappings.
2769         F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
2770       }
2771       break;
2772     }
2773 
2774     case SOURCE_MANAGER_LINE_TABLE:
2775       if (ParseLineTable(F, Record))
2776         return true;
2777       break;
2778 
2779     case SOURCE_LOCATION_PRELOADS: {
2780       // Need to transform from the local view (1-based IDs) to the global view,
2781       // which is based off F.SLocEntryBaseID.
2782       if (!F.PreloadSLocEntries.empty()) {
2783         Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
2784         return true;
2785       }
2786 
2787       F.PreloadSLocEntries.swap(Record);
2788       break;
2789     }
2790 
2791     case EXT_VECTOR_DECLS:
2792       for (unsigned I = 0, N = Record.size(); I != N; ++I)
2793         ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2794       break;
2795 
2796     case VTABLE_USES:
2797       if (Record.size() % 3 != 0) {
2798         Error("Invalid VTABLE_USES record");
2799         return true;
2800       }
2801 
2802       // Later tables overwrite earlier ones.
2803       // FIXME: Modules will have some trouble with this. This is clearly not
2804       // the right way to do this.
2805       VTableUses.clear();
2806 
2807       for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2808         VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2809         VTableUses.push_back(
2810           ReadSourceLocation(F, Record, Idx).getRawEncoding());
2811         VTableUses.push_back(Record[Idx++]);
2812       }
2813       break;
2814 
2815     case DYNAMIC_CLASSES:
2816       for (unsigned I = 0, N = Record.size(); I != N; ++I)
2817         DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
2818       break;
2819 
2820     case PENDING_IMPLICIT_INSTANTIATIONS:
2821       if (PendingInstantiations.size() % 2 != 0) {
2822         Error("Invalid existing PendingInstantiations");
2823         return true;
2824       }
2825 
2826       if (Record.size() % 2 != 0) {
2827         Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
2828         return true;
2829       }
2830 
2831       for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2832         PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2833         PendingInstantiations.push_back(
2834           ReadSourceLocation(F, Record, I).getRawEncoding());
2835       }
2836       break;
2837 
2838     case SEMA_DECL_REFS:
2839       if (Record.size() != 2) {
2840         Error("Invalid SEMA_DECL_REFS block");
2841         return true;
2842       }
2843       for (unsigned I = 0, N = Record.size(); I != N; ++I)
2844         SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2845       break;
2846 
2847     case PPD_ENTITIES_OFFSETS: {
2848       F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
2849       assert(Blob.size() % sizeof(PPEntityOffset) == 0);
2850       F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
2851 
2852       unsigned LocalBasePreprocessedEntityID = Record[0];
2853 
2854       unsigned StartingID;
2855       if (!PP.getPreprocessingRecord())
2856         PP.createPreprocessingRecord();
2857       if (!PP.getPreprocessingRecord()->getExternalSource())
2858         PP.getPreprocessingRecord()->SetExternalSource(*this);
2859       StartingID
2860         = PP.getPreprocessingRecord()
2861             ->allocateLoadedEntities(F.NumPreprocessedEntities);
2862       F.BasePreprocessedEntityID = StartingID;
2863 
2864       if (F.NumPreprocessedEntities > 0) {
2865         // Introduce the global -> local mapping for preprocessed entities in
2866         // this module.
2867         GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2868 
2869         // Introduce the local -> global mapping for preprocessed entities in
2870         // this module.
2871         F.PreprocessedEntityRemap.insertOrReplace(
2872           std::make_pair(LocalBasePreprocessedEntityID,
2873             F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2874       }
2875 
2876       break;
2877     }
2878 
2879     case DECL_UPDATE_OFFSETS: {
2880       if (Record.size() % 2 != 0) {
2881         Error("invalid DECL_UPDATE_OFFSETS block in AST file");
2882         return true;
2883       }
2884       for (unsigned I = 0, N = Record.size(); I != N; I += 2)
2885         DeclUpdateOffsets[getGlobalDeclID(F, Record[I])]
2886           .push_back(std::make_pair(&F, Record[I+1]));
2887       break;
2888     }
2889 
2890     case DECL_REPLACEMENTS: {
2891       if (Record.size() % 3 != 0) {
2892         Error("invalid DECL_REPLACEMENTS block in AST file");
2893         return true;
2894       }
2895       for (unsigned I = 0, N = Record.size(); I != N; I += 3)
2896         ReplacedDecls[getGlobalDeclID(F, Record[I])]
2897           = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
2898       break;
2899     }
2900 
2901     case OBJC_CATEGORIES_MAP: {
2902       if (F.LocalNumObjCCategoriesInMap != 0) {
2903         Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
2904         return true;
2905       }
2906 
2907       F.LocalNumObjCCategoriesInMap = Record[0];
2908       F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
2909       break;
2910     }
2911 
2912     case OBJC_CATEGORIES:
2913       F.ObjCCategories.swap(Record);
2914       break;
2915 
2916     case CXX_BASE_SPECIFIER_OFFSETS: {
2917       if (F.LocalNumCXXBaseSpecifiers != 0) {
2918         Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
2919         return true;
2920       }
2921 
2922       F.LocalNumCXXBaseSpecifiers = Record[0];
2923       F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
2924       NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
2925       break;
2926     }
2927 
2928     case DIAG_PRAGMA_MAPPINGS:
2929       if (F.PragmaDiagMappings.empty())
2930         F.PragmaDiagMappings.swap(Record);
2931       else
2932         F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2933                                     Record.begin(), Record.end());
2934       break;
2935 
2936     case CUDA_SPECIAL_DECL_REFS:
2937       // Later tables overwrite earlier ones.
2938       // FIXME: Modules will have trouble with this.
2939       CUDASpecialDeclRefs.clear();
2940       for (unsigned I = 0, N = Record.size(); I != N; ++I)
2941         CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2942       break;
2943 
2944     case HEADER_SEARCH_TABLE: {
2945       F.HeaderFileInfoTableData = Blob.data();
2946       F.LocalNumHeaderFileInfos = Record[1];
2947       if (Record[0]) {
2948         F.HeaderFileInfoTable
2949           = HeaderFileInfoLookupTable::Create(
2950                    (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2951                    (const unsigned char *)F.HeaderFileInfoTableData,
2952                    HeaderFileInfoTrait(*this, F,
2953                                        &PP.getHeaderSearchInfo(),
2954                                        Blob.data() + Record[2]));
2955 
2956         PP.getHeaderSearchInfo().SetExternalSource(this);
2957         if (!PP.getHeaderSearchInfo().getExternalLookup())
2958           PP.getHeaderSearchInfo().SetExternalLookup(this);
2959       }
2960       break;
2961     }
2962 
2963     case FP_PRAGMA_OPTIONS:
2964       // Later tables overwrite earlier ones.
2965       FPPragmaOptions.swap(Record);
2966       break;
2967 
2968     case OPENCL_EXTENSIONS:
2969       // Later tables overwrite earlier ones.
2970       OpenCLExtensions.swap(Record);
2971       break;
2972 
2973     case TENTATIVE_DEFINITIONS:
2974       for (unsigned I = 0, N = Record.size(); I != N; ++I)
2975         TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
2976       break;
2977 
2978     case KNOWN_NAMESPACES:
2979       for (unsigned I = 0, N = Record.size(); I != N; ++I)
2980         KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
2981       break;
2982 
2983     case UNDEFINED_BUT_USED:
2984       if (UndefinedButUsed.size() % 2 != 0) {
2985         Error("Invalid existing UndefinedButUsed");
2986         return true;
2987       }
2988 
2989       if (Record.size() % 2 != 0) {
2990         Error("invalid undefined-but-used record");
2991         return true;
2992       }
2993       for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2994         UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
2995         UndefinedButUsed.push_back(
2996             ReadSourceLocation(F, Record, I).getRawEncoding());
2997       }
2998       break;
2999 
3000     case IMPORTED_MODULES: {
3001       if (F.Kind != MK_Module) {
3002         // If we aren't loading a module (which has its own exports), make
3003         // all of the imported modules visible.
3004         // FIXME: Deal with macros-only imports.
3005         for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3006           if (unsigned GlobalID = getGlobalSubmoduleID(F, Record[I]))
3007             ImportedModules.push_back(GlobalID);
3008         }
3009       }
3010       break;
3011     }
3012 
3013     case LOCAL_REDECLARATIONS: {
3014       F.RedeclarationChains.swap(Record);
3015       break;
3016     }
3017 
3018     case LOCAL_REDECLARATIONS_MAP: {
3019       if (F.LocalNumRedeclarationsInMap != 0) {
3020         Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
3021         return true;
3022       }
3023 
3024       F.LocalNumRedeclarationsInMap = Record[0];
3025       F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
3026       break;
3027     }
3028 
3029     case MERGED_DECLARATIONS: {
3030       for (unsigned Idx = 0; Idx < Record.size(); /* increment in loop */) {
3031         GlobalDeclID CanonID = getGlobalDeclID(F, Record[Idx++]);
3032         SmallVectorImpl<GlobalDeclID> &Decls = StoredMergedDecls[CanonID];
3033         for (unsigned N = Record[Idx++]; N > 0; --N)
3034           Decls.push_back(getGlobalDeclID(F, Record[Idx++]));
3035       }
3036       break;
3037     }
3038 
3039     case MACRO_OFFSET: {
3040       if (F.LocalNumMacros != 0) {
3041         Error("duplicate MACRO_OFFSET record in AST file");
3042         return true;
3043       }
3044       F.MacroOffsets = (const uint32_t *)Blob.data();
3045       F.LocalNumMacros = Record[0];
3046       unsigned LocalBaseMacroID = Record[1];
3047       F.BaseMacroID = getTotalNumMacros();
3048 
3049       if (F.LocalNumMacros > 0) {
3050         // Introduce the global -> local mapping for macros within this module.
3051         GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3052 
3053         // Introduce the local -> global mapping for macros within this module.
3054         F.MacroRemap.insertOrReplace(
3055           std::make_pair(LocalBaseMacroID,
3056                          F.BaseMacroID - LocalBaseMacroID));
3057 
3058         MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
3059       }
3060       break;
3061     }
3062 
3063     case MACRO_TABLE: {
3064       // FIXME: Not used yet.
3065       break;
3066     }
3067 
3068     case LATE_PARSED_TEMPLATE: {
3069       LateParsedTemplates.append(Record.begin(), Record.end());
3070       break;
3071     }
3072     }
3073   }
3074 }
3075 
3076 /// \brief Move the given method to the back of the global list of methods.
3077 static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3078   // Find the entry for this selector in the method pool.
3079   Sema::GlobalMethodPool::iterator Known
3080     = S.MethodPool.find(Method->getSelector());
3081   if (Known == S.MethodPool.end())
3082     return;
3083 
3084   // Retrieve the appropriate method list.
3085   ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3086                                                     : Known->second.second;
3087   bool Found = false;
3088   for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
3089     if (!Found) {
3090       if (List->Method == Method) {
3091         Found = true;
3092       } else {
3093         // Keep searching.
3094         continue;
3095       }
3096     }
3097 
3098     if (List->getNext())
3099       List->Method = List->getNext()->Method;
3100     else
3101       List->Method = Method;
3102   }
3103 }
3104 
3105 void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
3106   for (unsigned I = 0, N = Names.HiddenDecls.size(); I != N; ++I) {
3107     Decl *D = Names.HiddenDecls[I];
3108     bool wasHidden = D->Hidden;
3109     D->Hidden = false;
3110 
3111     if (wasHidden && SemaObj) {
3112       if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3113         moveMethodToBackOfGlobalList(*SemaObj, Method);
3114       }
3115     }
3116   }
3117 
3118   for (HiddenMacrosMap::const_iterator I = Names.HiddenMacros.begin(),
3119                                        E = Names.HiddenMacros.end();
3120        I != E; ++I)
3121     installImportedMacro(I->first, I->second, Owner);
3122 }
3123 
3124 void ASTReader::makeModuleVisible(Module *Mod,
3125                                   Module::NameVisibilityKind NameVisibility,
3126                                   SourceLocation ImportLoc,
3127                                   bool Complain) {
3128   llvm::SmallPtrSet<Module *, 4> Visited;
3129   SmallVector<Module *, 4> Stack;
3130   Stack.push_back(Mod);
3131   while (!Stack.empty()) {
3132     Mod = Stack.pop_back_val();
3133 
3134     if (NameVisibility <= Mod->NameVisibility) {
3135       // This module already has this level of visibility (or greater), so
3136       // there is nothing more to do.
3137       continue;
3138     }
3139 
3140     if (!Mod->isAvailable()) {
3141       // Modules that aren't available cannot be made visible.
3142       continue;
3143     }
3144 
3145     // Update the module's name visibility.
3146     if (NameVisibility >= Module::MacrosVisible &&
3147         Mod->NameVisibility < Module::MacrosVisible)
3148       Mod->MacroVisibilityLoc = ImportLoc;
3149     Mod->NameVisibility = NameVisibility;
3150 
3151     // If we've already deserialized any names from this module,
3152     // mark them as visible.
3153     HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3154     if (Hidden != HiddenNamesMap.end()) {
3155       makeNamesVisible(Hidden->second, Hidden->first);
3156       HiddenNamesMap.erase(Hidden);
3157     }
3158 
3159     // Push any exported modules onto the stack to be marked as visible.
3160     SmallVector<Module *, 16> Exports;
3161     Mod->getExportedModules(Exports);
3162     for (SmallVectorImpl<Module *>::iterator
3163            I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3164       Module *Exported = *I;
3165       if (Visited.insert(Exported))
3166         Stack.push_back(Exported);
3167     }
3168 
3169     // Detect any conflicts.
3170     if (Complain) {
3171       assert(ImportLoc.isValid() && "Missing import location");
3172       for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
3173         if (Mod->Conflicts[I].Other->NameVisibility >= NameVisibility) {
3174           Diag(ImportLoc, diag::warn_module_conflict)
3175             << Mod->getFullModuleName()
3176             << Mod->Conflicts[I].Other->getFullModuleName()
3177             << Mod->Conflicts[I].Message;
3178           // FIXME: Need note where the other module was imported.
3179         }
3180       }
3181     }
3182   }
3183 }
3184 
3185 bool ASTReader::loadGlobalIndex() {
3186   if (GlobalIndex)
3187     return false;
3188 
3189   if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3190       !Context.getLangOpts().Modules)
3191     return true;
3192 
3193   // Try to load the global index.
3194   TriedLoadingGlobalIndex = true;
3195   StringRef ModuleCachePath
3196     = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3197   std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
3198     = GlobalModuleIndex::readIndex(ModuleCachePath);
3199   if (!Result.first)
3200     return true;
3201 
3202   GlobalIndex.reset(Result.first);
3203   ModuleMgr.setGlobalIndex(GlobalIndex.get());
3204   return false;
3205 }
3206 
3207 bool ASTReader::isGlobalIndexUnavailable() const {
3208   return Context.getLangOpts().Modules && UseGlobalIndex &&
3209          !hasGlobalIndex() && TriedLoadingGlobalIndex;
3210 }
3211 
3212 static void updateModuleTimestamp(ModuleFile &MF) {
3213   // Overwrite the timestamp file contents so that file's mtime changes.
3214   std::string TimestampFilename = MF.getTimestampFilename();
3215   std::string ErrorInfo;
3216   llvm::raw_fd_ostream OS(TimestampFilename.c_str(), ErrorInfo,
3217                           llvm::sys::fs::F_Text);
3218   if (!ErrorInfo.empty())
3219     return;
3220   OS << "Timestamp file\n";
3221 }
3222 
3223 ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
3224                                             ModuleKind Type,
3225                                             SourceLocation ImportLoc,
3226                                             unsigned ClientLoadCapabilities) {
3227   llvm::SaveAndRestore<SourceLocation>
3228     SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3229 
3230   // Bump the generation number.
3231   unsigned PreviousGeneration = CurrentGeneration++;
3232 
3233   unsigned NumModules = ModuleMgr.size();
3234   SmallVector<ImportedModule, 4> Loaded;
3235   switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
3236                                                 /*ImportedBy=*/0, Loaded,
3237                                                 0, 0,
3238                                                 ClientLoadCapabilities)) {
3239   case Failure:
3240   case Missing:
3241   case OutOfDate:
3242   case VersionMismatch:
3243   case ConfigurationMismatch:
3244   case HadErrors:
3245     ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
3246                             Context.getLangOpts().Modules
3247                               ? &PP.getHeaderSearchInfo().getModuleMap()
3248                               : 0);
3249 
3250     // If we find that any modules are unusable, the global index is going
3251     // to be out-of-date. Just remove it.
3252     GlobalIndex.reset();
3253     ModuleMgr.setGlobalIndex(0);
3254     return ReadResult;
3255 
3256   case Success:
3257     break;
3258   }
3259 
3260   // Here comes stuff that we only do once the entire chain is loaded.
3261 
3262   // Load the AST blocks of all of the modules that we loaded.
3263   for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3264                                               MEnd = Loaded.end();
3265        M != MEnd; ++M) {
3266     ModuleFile &F = *M->Mod;
3267 
3268     // Read the AST block.
3269     if (ReadASTBlock(F))
3270       return Failure;
3271 
3272     // Once read, set the ModuleFile bit base offset and update the size in
3273     // bits of all files we've seen.
3274     F.GlobalBitOffset = TotalModulesSizeInBits;
3275     TotalModulesSizeInBits += F.SizeInBits;
3276     GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
3277 
3278     // Preload SLocEntries.
3279     for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3280       int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3281       // Load it through the SourceManager and don't call ReadSLocEntry()
3282       // directly because the entry may have already been loaded in which case
3283       // calling ReadSLocEntry() directly would trigger an assertion in
3284       // SourceManager.
3285       SourceMgr.getLoadedSLocEntryByID(Index);
3286     }
3287   }
3288 
3289   // Setup the import locations and notify the module manager that we've
3290   // committed to these module files.
3291   for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3292                                               MEnd = Loaded.end();
3293        M != MEnd; ++M) {
3294     ModuleFile &F = *M->Mod;
3295 
3296     ModuleMgr.moduleFileAccepted(&F);
3297 
3298     // Set the import location.
3299     F.DirectImportLoc = ImportLoc;
3300     if (!M->ImportedBy)
3301       F.ImportLoc = M->ImportLoc;
3302     else
3303       F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
3304                                        M->ImportLoc.getRawEncoding());
3305   }
3306 
3307   // Mark all of the identifiers in the identifier table as being out of date,
3308   // so that various accessors know to check the loaded modules when the
3309   // identifier is used.
3310   for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3311                               IdEnd = PP.getIdentifierTable().end();
3312        Id != IdEnd; ++Id)
3313     Id->second->setOutOfDate(true);
3314 
3315   // Resolve any unresolved module exports.
3316   for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3317     UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
3318     SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3319     Module *ResolvedMod = getSubmodule(GlobalID);
3320 
3321     switch (Unresolved.Kind) {
3322     case UnresolvedModuleRef::Conflict:
3323       if (ResolvedMod) {
3324         Module::Conflict Conflict;
3325         Conflict.Other = ResolvedMod;
3326         Conflict.Message = Unresolved.String.str();
3327         Unresolved.Mod->Conflicts.push_back(Conflict);
3328       }
3329       continue;
3330 
3331     case UnresolvedModuleRef::Import:
3332       if (ResolvedMod)
3333         Unresolved.Mod->Imports.push_back(ResolvedMod);
3334       continue;
3335 
3336     case UnresolvedModuleRef::Export:
3337       if (ResolvedMod || Unresolved.IsWildcard)
3338         Unresolved.Mod->Exports.push_back(
3339           Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3340       continue;
3341     }
3342   }
3343   UnresolvedModuleRefs.clear();
3344 
3345   // FIXME: How do we load the 'use'd modules? They may not be submodules.
3346   // Might be unnecessary as use declarations are only used to build the
3347   // module itself.
3348 
3349   InitializeContext();
3350 
3351   if (SemaObj)
3352     UpdateSema();
3353 
3354   if (DeserializationListener)
3355     DeserializationListener->ReaderInitialized(this);
3356 
3357   ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
3358   if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
3359     PrimaryModule.OriginalSourceFileID
3360       = FileID::get(PrimaryModule.SLocEntryBaseID
3361                     + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3362 
3363     // If this AST file is a precompiled preamble, then set the
3364     // preamble file ID of the source manager to the file source file
3365     // from which the preamble was built.
3366     if (Type == MK_Preamble) {
3367       SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3368     } else if (Type == MK_MainFile) {
3369       SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3370     }
3371   }
3372 
3373   // For any Objective-C class definitions we have already loaded, make sure
3374   // that we load any additional categories.
3375   for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3376     loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3377                        ObjCClassesLoaded[I],
3378                        PreviousGeneration);
3379   }
3380 
3381   if (PP.getHeaderSearchInfo()
3382           .getHeaderSearchOpts()
3383           .ModulesValidateOncePerBuildSession) {
3384     // Now we are certain that the module and all modules it depends on are
3385     // up to date.  Create or update timestamp files for modules that are
3386     // located in the module cache (not for PCH files that could be anywhere
3387     // in the filesystem).
3388     for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3389       ImportedModule &M = Loaded[I];
3390       if (M.Mod->Kind == MK_Module) {
3391         updateModuleTimestamp(*M.Mod);
3392       }
3393     }
3394   }
3395 
3396   return Success;
3397 }
3398 
3399 ASTReader::ASTReadResult
3400 ASTReader::ReadASTCore(StringRef FileName,
3401                        ModuleKind Type,
3402                        SourceLocation ImportLoc,
3403                        ModuleFile *ImportedBy,
3404                        SmallVectorImpl<ImportedModule> &Loaded,
3405                        off_t ExpectedSize, time_t ExpectedModTime,
3406                        unsigned ClientLoadCapabilities) {
3407   ModuleFile *M;
3408   std::string ErrorStr;
3409   ModuleManager::AddModuleResult AddResult
3410     = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
3411                           CurrentGeneration, ExpectedSize, ExpectedModTime,
3412                           M, ErrorStr);
3413 
3414   switch (AddResult) {
3415   case ModuleManager::AlreadyLoaded:
3416     return Success;
3417 
3418   case ModuleManager::NewlyLoaded:
3419     // Load module file below.
3420     break;
3421 
3422   case ModuleManager::Missing:
3423     // The module file was missing; if the client handle handle, that, return
3424     // it.
3425     if (ClientLoadCapabilities & ARR_Missing)
3426       return Missing;
3427 
3428     // Otherwise, return an error.
3429     {
3430       std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3431                       + ErrorStr;
3432       Error(Msg);
3433     }
3434     return Failure;
3435 
3436   case ModuleManager::OutOfDate:
3437     // We couldn't load the module file because it is out-of-date. If the
3438     // client can handle out-of-date, return it.
3439     if (ClientLoadCapabilities & ARR_OutOfDate)
3440       return OutOfDate;
3441 
3442     // Otherwise, return an error.
3443     {
3444       std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
3445                       + ErrorStr;
3446       Error(Msg);
3447     }
3448     return Failure;
3449   }
3450 
3451   assert(M && "Missing module file");
3452 
3453   // FIXME: This seems rather a hack. Should CurrentDir be part of the
3454   // module?
3455   if (FileName != "-") {
3456     CurrentDir = llvm::sys::path::parent_path(FileName);
3457     if (CurrentDir.empty()) CurrentDir = ".";
3458   }
3459 
3460   ModuleFile &F = *M;
3461   BitstreamCursor &Stream = F.Stream;
3462   Stream.init(F.StreamFile);
3463   F.SizeInBits = F.Buffer->getBufferSize() * 8;
3464 
3465   // Sniff for the signature.
3466   if (Stream.Read(8) != 'C' ||
3467       Stream.Read(8) != 'P' ||
3468       Stream.Read(8) != 'C' ||
3469       Stream.Read(8) != 'H') {
3470     Diag(diag::err_not_a_pch_file) << FileName;
3471     return Failure;
3472   }
3473 
3474   // This is used for compatibility with older PCH formats.
3475   bool HaveReadControlBlock = false;
3476 
3477   while (1) {
3478     llvm::BitstreamEntry Entry = Stream.advance();
3479 
3480     switch (Entry.Kind) {
3481     case llvm::BitstreamEntry::Error:
3482     case llvm::BitstreamEntry::EndBlock:
3483     case llvm::BitstreamEntry::Record:
3484       Error("invalid record at top-level of AST file");
3485       return Failure;
3486 
3487     case llvm::BitstreamEntry::SubBlock:
3488       break;
3489     }
3490 
3491     // We only know the control subblock ID.
3492     switch (Entry.ID) {
3493     case llvm::bitc::BLOCKINFO_BLOCK_ID:
3494       if (Stream.ReadBlockInfoBlock()) {
3495         Error("malformed BlockInfoBlock in AST file");
3496         return Failure;
3497       }
3498       break;
3499     case CONTROL_BLOCK_ID:
3500       HaveReadControlBlock = true;
3501       switch (ReadControlBlock(F, Loaded, ClientLoadCapabilities)) {
3502       case Success:
3503         break;
3504 
3505       case Failure: return Failure;
3506       case Missing: return Missing;
3507       case OutOfDate: return OutOfDate;
3508       case VersionMismatch: return VersionMismatch;
3509       case ConfigurationMismatch: return ConfigurationMismatch;
3510       case HadErrors: return HadErrors;
3511       }
3512       break;
3513     case AST_BLOCK_ID:
3514       if (!HaveReadControlBlock) {
3515         if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
3516           Diag(diag::err_pch_version_too_old);
3517         return VersionMismatch;
3518       }
3519 
3520       // Record that we've loaded this module.
3521       Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
3522       return Success;
3523 
3524     default:
3525       if (Stream.SkipBlock()) {
3526         Error("malformed block record in AST file");
3527         return Failure;
3528       }
3529       break;
3530     }
3531   }
3532 
3533   return Success;
3534 }
3535 
3536 void ASTReader::InitializeContext() {
3537   // If there's a listener, notify them that we "read" the translation unit.
3538   if (DeserializationListener)
3539     DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
3540                                       Context.getTranslationUnitDecl());
3541 
3542   // Make sure we load the declaration update records for the translation unit,
3543   // if there are any.
3544   loadDeclUpdateRecords(PREDEF_DECL_TRANSLATION_UNIT_ID,
3545                         Context.getTranslationUnitDecl());
3546 
3547   // FIXME: Find a better way to deal with collisions between these
3548   // built-in types. Right now, we just ignore the problem.
3549 
3550   // Load the special types.
3551   if (SpecialTypes.size() >= NumSpecialTypeIDs) {
3552     if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
3553       if (!Context.CFConstantStringTypeDecl)
3554         Context.setCFConstantStringType(GetType(String));
3555     }
3556 
3557     if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
3558       QualType FileType = GetType(File);
3559       if (FileType.isNull()) {
3560         Error("FILE type is NULL");
3561         return;
3562       }
3563 
3564       if (!Context.FILEDecl) {
3565         if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
3566           Context.setFILEDecl(Typedef->getDecl());
3567         else {
3568           const TagType *Tag = FileType->getAs<TagType>();
3569           if (!Tag) {
3570             Error("Invalid FILE type in AST file");
3571             return;
3572           }
3573           Context.setFILEDecl(Tag->getDecl());
3574         }
3575       }
3576     }
3577 
3578     if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
3579       QualType Jmp_bufType = GetType(Jmp_buf);
3580       if (Jmp_bufType.isNull()) {
3581         Error("jmp_buf type is NULL");
3582         return;
3583       }
3584 
3585       if (!Context.jmp_bufDecl) {
3586         if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
3587           Context.setjmp_bufDecl(Typedef->getDecl());
3588         else {
3589           const TagType *Tag = Jmp_bufType->getAs<TagType>();
3590           if (!Tag) {
3591             Error("Invalid jmp_buf type in AST file");
3592             return;
3593           }
3594           Context.setjmp_bufDecl(Tag->getDecl());
3595         }
3596       }
3597     }
3598 
3599     if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
3600       QualType Sigjmp_bufType = GetType(Sigjmp_buf);
3601       if (Sigjmp_bufType.isNull()) {
3602         Error("sigjmp_buf type is NULL");
3603         return;
3604       }
3605 
3606       if (!Context.sigjmp_bufDecl) {
3607         if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
3608           Context.setsigjmp_bufDecl(Typedef->getDecl());
3609         else {
3610           const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
3611           assert(Tag && "Invalid sigjmp_buf type in AST file");
3612           Context.setsigjmp_bufDecl(Tag->getDecl());
3613         }
3614       }
3615     }
3616 
3617     if (unsigned ObjCIdRedef
3618           = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
3619       if (Context.ObjCIdRedefinitionType.isNull())
3620         Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
3621     }
3622 
3623     if (unsigned ObjCClassRedef
3624           = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
3625       if (Context.ObjCClassRedefinitionType.isNull())
3626         Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
3627     }
3628 
3629     if (unsigned ObjCSelRedef
3630           = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
3631       if (Context.ObjCSelRedefinitionType.isNull())
3632         Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
3633     }
3634 
3635     if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
3636       QualType Ucontext_tType = GetType(Ucontext_t);
3637       if (Ucontext_tType.isNull()) {
3638         Error("ucontext_t type is NULL");
3639         return;
3640       }
3641 
3642       if (!Context.ucontext_tDecl) {
3643         if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
3644           Context.setucontext_tDecl(Typedef->getDecl());
3645         else {
3646           const TagType *Tag = Ucontext_tType->getAs<TagType>();
3647           assert(Tag && "Invalid ucontext_t type in AST file");
3648           Context.setucontext_tDecl(Tag->getDecl());
3649         }
3650       }
3651     }
3652   }
3653 
3654   ReadPragmaDiagnosticMappings(Context.getDiagnostics());
3655 
3656   // If there were any CUDA special declarations, deserialize them.
3657   if (!CUDASpecialDeclRefs.empty()) {
3658     assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
3659     Context.setcudaConfigureCallDecl(
3660                            cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
3661   }
3662 
3663   // Re-export any modules that were imported by a non-module AST file.
3664   for (unsigned I = 0, N = ImportedModules.size(); I != N; ++I) {
3665     if (Module *Imported = getSubmodule(ImportedModules[I]))
3666       makeModuleVisible(Imported, Module::AllVisible,
3667                         /*ImportLoc=*/SourceLocation(),
3668                         /*Complain=*/false);
3669   }
3670   ImportedModules.clear();
3671 }
3672 
3673 void ASTReader::finalizeForWriting() {
3674   for (HiddenNamesMapType::iterator Hidden = HiddenNamesMap.begin(),
3675                                  HiddenEnd = HiddenNamesMap.end();
3676        Hidden != HiddenEnd; ++Hidden) {
3677     makeNamesVisible(Hidden->second, Hidden->first);
3678   }
3679   HiddenNamesMap.clear();
3680 }
3681 
3682 /// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3683 /// cursor into the start of the given block ID, returning false on success and
3684 /// true on failure.
3685 static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
3686   while (1) {
3687     llvm::BitstreamEntry Entry = Cursor.advance();
3688     switch (Entry.Kind) {
3689     case llvm::BitstreamEntry::Error:
3690     case llvm::BitstreamEntry::EndBlock:
3691       return true;
3692 
3693     case llvm::BitstreamEntry::Record:
3694       // Ignore top-level records.
3695       Cursor.skipRecord(Entry.ID);
3696       break;
3697 
3698     case llvm::BitstreamEntry::SubBlock:
3699       if (Entry.ID == BlockID) {
3700         if (Cursor.EnterSubBlock(BlockID))
3701           return true;
3702         // Found it!
3703         return false;
3704       }
3705 
3706       if (Cursor.SkipBlock())
3707         return true;
3708     }
3709   }
3710 }
3711 
3712 /// \brief Retrieve the name of the original source file name
3713 /// directly from the AST file, without actually loading the AST
3714 /// file.
3715 std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
3716                                              FileManager &FileMgr,
3717                                              DiagnosticsEngine &Diags) {
3718   // Open the AST file.
3719   std::string ErrStr;
3720   std::unique_ptr<llvm::MemoryBuffer> Buffer;
3721   Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
3722   if (!Buffer) {
3723     Diags.Report(diag::err_fe_unable_to_read_pch_file) << ASTFileName << ErrStr;
3724     return std::string();
3725   }
3726 
3727   // Initialize the stream
3728   llvm::BitstreamReader StreamFile;
3729   BitstreamCursor Stream;
3730   StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3731                   (const unsigned char *)Buffer->getBufferEnd());
3732   Stream.init(StreamFile);
3733 
3734   // Sniff for the signature.
3735   if (Stream.Read(8) != 'C' ||
3736       Stream.Read(8) != 'P' ||
3737       Stream.Read(8) != 'C' ||
3738       Stream.Read(8) != 'H') {
3739     Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
3740     return std::string();
3741   }
3742 
3743   // Scan for the CONTROL_BLOCK_ID block.
3744   if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
3745     Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3746     return std::string();
3747   }
3748 
3749   // Scan for ORIGINAL_FILE inside the control block.
3750   RecordData Record;
3751   while (1) {
3752     llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3753     if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3754       return std::string();
3755 
3756     if (Entry.Kind != llvm::BitstreamEntry::Record) {
3757       Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
3758       return std::string();
3759     }
3760 
3761     Record.clear();
3762     StringRef Blob;
3763     if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
3764       return Blob.str();
3765   }
3766 }
3767 
3768 namespace {
3769   class SimplePCHValidator : public ASTReaderListener {
3770     const LangOptions &ExistingLangOpts;
3771     const TargetOptions &ExistingTargetOpts;
3772     const PreprocessorOptions &ExistingPPOpts;
3773     FileManager &FileMgr;
3774 
3775   public:
3776     SimplePCHValidator(const LangOptions &ExistingLangOpts,
3777                        const TargetOptions &ExistingTargetOpts,
3778                        const PreprocessorOptions &ExistingPPOpts,
3779                        FileManager &FileMgr)
3780       : ExistingLangOpts(ExistingLangOpts),
3781         ExistingTargetOpts(ExistingTargetOpts),
3782         ExistingPPOpts(ExistingPPOpts),
3783         FileMgr(FileMgr)
3784     {
3785     }
3786 
3787     virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
3788                                      bool Complain) {
3789       return checkLanguageOptions(ExistingLangOpts, LangOpts, 0);
3790     }
3791     virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
3792                                    bool Complain) {
3793       return checkTargetOptions(ExistingTargetOpts, TargetOpts, 0);
3794     }
3795     virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
3796                                          bool Complain,
3797                                          std::string &SuggestedPredefines) {
3798       return checkPreprocessorOptions(ExistingPPOpts, PPOpts, 0, FileMgr,
3799                                       SuggestedPredefines, ExistingLangOpts);
3800     }
3801   };
3802 }
3803 
3804 bool ASTReader::readASTFileControlBlock(StringRef Filename,
3805                                         FileManager &FileMgr,
3806                                         ASTReaderListener &Listener) {
3807   // Open the AST file.
3808   std::string ErrStr;
3809   std::unique_ptr<llvm::MemoryBuffer> Buffer;
3810   Buffer.reset(FileMgr.getBufferForFile(Filename, &ErrStr));
3811   if (!Buffer) {
3812     return true;
3813   }
3814 
3815   // Initialize the stream
3816   llvm::BitstreamReader StreamFile;
3817   BitstreamCursor Stream;
3818   StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
3819                   (const unsigned char *)Buffer->getBufferEnd());
3820   Stream.init(StreamFile);
3821 
3822   // Sniff for the signature.
3823   if (Stream.Read(8) != 'C' ||
3824       Stream.Read(8) != 'P' ||
3825       Stream.Read(8) != 'C' ||
3826       Stream.Read(8) != 'H') {
3827     return true;
3828   }
3829 
3830   // Scan for the CONTROL_BLOCK_ID block.
3831   if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
3832     return true;
3833 
3834   bool NeedsInputFiles = Listener.needsInputFileVisitation();
3835   bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
3836   BitstreamCursor InputFilesCursor;
3837   if (NeedsInputFiles) {
3838     InputFilesCursor = Stream;
3839     if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
3840       return true;
3841 
3842     // Read the abbreviations
3843     while (true) {
3844       uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
3845       unsigned Code = InputFilesCursor.ReadCode();
3846 
3847       // We expect all abbrevs to be at the start of the block.
3848       if (Code != llvm::bitc::DEFINE_ABBREV) {
3849         InputFilesCursor.JumpToBit(Offset);
3850         break;
3851       }
3852       InputFilesCursor.ReadAbbrevRecord();
3853     }
3854   }
3855 
3856   // Scan for ORIGINAL_FILE inside the control block.
3857   RecordData Record;
3858   while (1) {
3859     llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3860     if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
3861       return false;
3862 
3863     if (Entry.Kind != llvm::BitstreamEntry::Record)
3864       return true;
3865 
3866     Record.clear();
3867     StringRef Blob;
3868     unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
3869     switch ((ControlRecordTypes)RecCode) {
3870     case METADATA: {
3871       if (Record[0] != VERSION_MAJOR)
3872         return true;
3873 
3874       if (Listener.ReadFullVersionInformation(Blob))
3875         return true;
3876 
3877       break;
3878     }
3879     case LANGUAGE_OPTIONS:
3880       if (ParseLanguageOptions(Record, false, Listener))
3881         return true;
3882       break;
3883 
3884     case TARGET_OPTIONS:
3885       if (ParseTargetOptions(Record, false, Listener))
3886         return true;
3887       break;
3888 
3889     case DIAGNOSTIC_OPTIONS:
3890       if (ParseDiagnosticOptions(Record, false, Listener))
3891         return true;
3892       break;
3893 
3894     case FILE_SYSTEM_OPTIONS:
3895       if (ParseFileSystemOptions(Record, false, Listener))
3896         return true;
3897       break;
3898 
3899     case HEADER_SEARCH_OPTIONS:
3900       if (ParseHeaderSearchOptions(Record, false, Listener))
3901         return true;
3902       break;
3903 
3904     case PREPROCESSOR_OPTIONS: {
3905       std::string IgnoredSuggestedPredefines;
3906       if (ParsePreprocessorOptions(Record, false, Listener,
3907                                    IgnoredSuggestedPredefines))
3908         return true;
3909       break;
3910     }
3911 
3912     case INPUT_FILE_OFFSETS: {
3913       if (!NeedsInputFiles)
3914         break;
3915 
3916       unsigned NumInputFiles = Record[0];
3917       unsigned NumUserFiles = Record[1];
3918       const uint32_t *InputFileOffs = (const uint32_t *)Blob.data();
3919       for (unsigned I = 0; I != NumInputFiles; ++I) {
3920         // Go find this input file.
3921         bool isSystemFile = I >= NumUserFiles;
3922 
3923         if (isSystemFile && !NeedsSystemInputFiles)
3924           break; // the rest are system input files
3925 
3926         BitstreamCursor &Cursor = InputFilesCursor;
3927         SavedStreamPosition SavedPosition(Cursor);
3928         Cursor.JumpToBit(InputFileOffs[I]);
3929 
3930         unsigned Code = Cursor.ReadCode();
3931         RecordData Record;
3932         StringRef Blob;
3933         bool shouldContinue = false;
3934         switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
3935         case INPUT_FILE:
3936           shouldContinue = Listener.visitInputFile(Blob, isSystemFile);
3937           break;
3938         }
3939         if (!shouldContinue)
3940           break;
3941       }
3942       break;
3943     }
3944 
3945     default:
3946       // No other validation to perform.
3947       break;
3948     }
3949   }
3950 }
3951 
3952 
3953 bool ASTReader::isAcceptableASTFile(StringRef Filename,
3954                                     FileManager &FileMgr,
3955                                     const LangOptions &LangOpts,
3956                                     const TargetOptions &TargetOpts,
3957                                     const PreprocessorOptions &PPOpts) {
3958   SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts, FileMgr);
3959   return !readASTFileControlBlock(Filename, FileMgr, validator);
3960 }
3961 
3962 bool ASTReader::ReadSubmoduleBlock(ModuleFile &F) {
3963   // Enter the submodule block.
3964   if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
3965     Error("malformed submodule block record in AST file");
3966     return true;
3967   }
3968 
3969   ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
3970   bool First = true;
3971   Module *CurrentModule = 0;
3972   RecordData Record;
3973   while (true) {
3974     llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
3975 
3976     switch (Entry.Kind) {
3977     case llvm::BitstreamEntry::SubBlock: // Handled for us already.
3978     case llvm::BitstreamEntry::Error:
3979       Error("malformed block record in AST file");
3980       return true;
3981     case llvm::BitstreamEntry::EndBlock:
3982       return false;
3983     case llvm::BitstreamEntry::Record:
3984       // The interesting case.
3985       break;
3986     }
3987 
3988     // Read a record.
3989     StringRef Blob;
3990     Record.clear();
3991     switch (F.Stream.readRecord(Entry.ID, Record, &Blob)) {
3992     default:  // Default behavior: ignore.
3993       break;
3994 
3995     case SUBMODULE_DEFINITION: {
3996       if (First) {
3997         Error("missing submodule metadata record at beginning of block");
3998         return true;
3999       }
4000 
4001       if (Record.size() < 8) {
4002         Error("malformed module definition");
4003         return true;
4004       }
4005 
4006       StringRef Name = Blob;
4007       unsigned Idx = 0;
4008       SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4009       SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4010       bool IsFramework = Record[Idx++];
4011       bool IsExplicit = Record[Idx++];
4012       bool IsSystem = Record[Idx++];
4013       bool IsExternC = Record[Idx++];
4014       bool InferSubmodules = Record[Idx++];
4015       bool InferExplicitSubmodules = Record[Idx++];
4016       bool InferExportWildcard = Record[Idx++];
4017       bool ConfigMacrosExhaustive = Record[Idx++];
4018 
4019       Module *ParentModule = 0;
4020       if (Parent)
4021         ParentModule = getSubmodule(Parent);
4022 
4023       // Retrieve this (sub)module from the module map, creating it if
4024       // necessary.
4025       CurrentModule = ModMap.findOrCreateModule(Name, ParentModule,
4026                                                 IsFramework,
4027                                                 IsExplicit).first;
4028       SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4029       if (GlobalIndex >= SubmodulesLoaded.size() ||
4030           SubmodulesLoaded[GlobalIndex]) {
4031         Error("too many submodules");
4032         return true;
4033       }
4034 
4035       if (!ParentModule) {
4036         if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4037           if (CurFile != F.File) {
4038             if (!Diags.isDiagnosticInFlight()) {
4039               Diag(diag::err_module_file_conflict)
4040                 << CurrentModule->getTopLevelModuleName()
4041                 << CurFile->getName()
4042                 << F.File->getName();
4043             }
4044             return true;
4045           }
4046         }
4047 
4048         CurrentModule->setASTFile(F.File);
4049       }
4050 
4051       CurrentModule->IsFromModuleFile = true;
4052       CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
4053       CurrentModule->IsExternC = IsExternC;
4054       CurrentModule->InferSubmodules = InferSubmodules;
4055       CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4056       CurrentModule->InferExportWildcard = InferExportWildcard;
4057       CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
4058       if (DeserializationListener)
4059         DeserializationListener->ModuleRead(GlobalID, CurrentModule);
4060 
4061       SubmodulesLoaded[GlobalIndex] = CurrentModule;
4062 
4063       // Clear out data that will be replaced by what is the module file.
4064       CurrentModule->LinkLibraries.clear();
4065       CurrentModule->ConfigMacros.clear();
4066       CurrentModule->UnresolvedConflicts.clear();
4067       CurrentModule->Conflicts.clear();
4068       break;
4069     }
4070 
4071     case SUBMODULE_UMBRELLA_HEADER: {
4072       if (First) {
4073         Error("missing submodule metadata record at beginning of block");
4074         return true;
4075       }
4076 
4077       if (!CurrentModule)
4078         break;
4079 
4080       if (const FileEntry *Umbrella = PP.getFileManager().getFile(Blob)) {
4081         if (!CurrentModule->getUmbrellaHeader())
4082           ModMap.setUmbrellaHeader(CurrentModule, Umbrella);
4083         else if (CurrentModule->getUmbrellaHeader() != Umbrella) {
4084           Error("mismatched umbrella headers in submodule");
4085           return true;
4086         }
4087       }
4088       break;
4089     }
4090 
4091     case SUBMODULE_HEADER: {
4092       if (First) {
4093         Error("missing submodule metadata record at beginning of block");
4094         return true;
4095       }
4096 
4097       if (!CurrentModule)
4098         break;
4099 
4100       // We lazily associate headers with their modules via the HeaderInfoTable.
4101       // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4102       // of complete filenames or remove it entirely.
4103       break;
4104     }
4105 
4106     case SUBMODULE_EXCLUDED_HEADER: {
4107       if (First) {
4108         Error("missing submodule metadata record at beginning of block");
4109         return true;
4110       }
4111 
4112       if (!CurrentModule)
4113         break;
4114 
4115       // We lazily associate headers with their modules via the HeaderInfoTable.
4116       // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4117       // of complete filenames or remove it entirely.
4118       break;
4119     }
4120 
4121     case SUBMODULE_PRIVATE_HEADER: {
4122       if (First) {
4123         Error("missing submodule metadata record at beginning of block");
4124         return true;
4125       }
4126 
4127       if (!CurrentModule)
4128         break;
4129 
4130       // We lazily associate headers with their modules via the HeaderInfoTable.
4131       // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4132       // of complete filenames or remove it entirely.
4133       break;
4134     }
4135 
4136     case SUBMODULE_TOPHEADER: {
4137       if (First) {
4138         Error("missing submodule metadata record at beginning of block");
4139         return true;
4140       }
4141 
4142       if (!CurrentModule)
4143         break;
4144 
4145       CurrentModule->addTopHeaderFilename(Blob);
4146       break;
4147     }
4148 
4149     case SUBMODULE_UMBRELLA_DIR: {
4150       if (First) {
4151         Error("missing submodule metadata record at beginning of block");
4152         return true;
4153       }
4154 
4155       if (!CurrentModule)
4156         break;
4157 
4158       if (const DirectoryEntry *Umbrella
4159                                   = PP.getFileManager().getDirectory(Blob)) {
4160         if (!CurrentModule->getUmbrellaDir())
4161           ModMap.setUmbrellaDir(CurrentModule, Umbrella);
4162         else if (CurrentModule->getUmbrellaDir() != Umbrella) {
4163           Error("mismatched umbrella directories in submodule");
4164           return true;
4165         }
4166       }
4167       break;
4168     }
4169 
4170     case SUBMODULE_METADATA: {
4171       if (!First) {
4172         Error("submodule metadata record not at beginning of block");
4173         return true;
4174       }
4175       First = false;
4176 
4177       F.BaseSubmoduleID = getTotalNumSubmodules();
4178       F.LocalNumSubmodules = Record[0];
4179       unsigned LocalBaseSubmoduleID = Record[1];
4180       if (F.LocalNumSubmodules > 0) {
4181         // Introduce the global -> local mapping for submodules within this
4182         // module.
4183         GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
4184 
4185         // Introduce the local -> global mapping for submodules within this
4186         // module.
4187         F.SubmoduleRemap.insertOrReplace(
4188           std::make_pair(LocalBaseSubmoduleID,
4189                          F.BaseSubmoduleID - LocalBaseSubmoduleID));
4190 
4191         SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4192       }
4193       break;
4194     }
4195 
4196     case SUBMODULE_IMPORTS: {
4197       if (First) {
4198         Error("missing submodule metadata record at beginning of block");
4199         return true;
4200       }
4201 
4202       if (!CurrentModule)
4203         break;
4204 
4205       for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
4206         UnresolvedModuleRef Unresolved;
4207         Unresolved.File = &F;
4208         Unresolved.Mod = CurrentModule;
4209         Unresolved.ID = Record[Idx];
4210         Unresolved.Kind = UnresolvedModuleRef::Import;
4211         Unresolved.IsWildcard = false;
4212         UnresolvedModuleRefs.push_back(Unresolved);
4213       }
4214       break;
4215     }
4216 
4217     case SUBMODULE_EXPORTS: {
4218       if (First) {
4219         Error("missing submodule metadata record at beginning of block");
4220         return true;
4221       }
4222 
4223       if (!CurrentModule)
4224         break;
4225 
4226       for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
4227         UnresolvedModuleRef Unresolved;
4228         Unresolved.File = &F;
4229         Unresolved.Mod = CurrentModule;
4230         Unresolved.ID = Record[Idx];
4231         Unresolved.Kind = UnresolvedModuleRef::Export;
4232         Unresolved.IsWildcard = Record[Idx + 1];
4233         UnresolvedModuleRefs.push_back(Unresolved);
4234       }
4235 
4236       // Once we've loaded the set of exports, there's no reason to keep
4237       // the parsed, unresolved exports around.
4238       CurrentModule->UnresolvedExports.clear();
4239       break;
4240     }
4241     case SUBMODULE_REQUIRES: {
4242       if (First) {
4243         Error("missing submodule metadata record at beginning of block");
4244         return true;
4245       }
4246 
4247       if (!CurrentModule)
4248         break;
4249 
4250       CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
4251                                     Context.getTargetInfo());
4252       break;
4253     }
4254 
4255     case SUBMODULE_LINK_LIBRARY:
4256       if (First) {
4257         Error("missing submodule metadata record at beginning of block");
4258         return true;
4259       }
4260 
4261       if (!CurrentModule)
4262         break;
4263 
4264       CurrentModule->LinkLibraries.push_back(
4265                                          Module::LinkLibrary(Blob, Record[0]));
4266       break;
4267 
4268     case SUBMODULE_CONFIG_MACRO:
4269       if (First) {
4270         Error("missing submodule metadata record at beginning of block");
4271         return true;
4272       }
4273 
4274       if (!CurrentModule)
4275         break;
4276 
4277       CurrentModule->ConfigMacros.push_back(Blob.str());
4278       break;
4279 
4280     case SUBMODULE_CONFLICT: {
4281       if (First) {
4282         Error("missing submodule metadata record at beginning of block");
4283         return true;
4284       }
4285 
4286       if (!CurrentModule)
4287         break;
4288 
4289       UnresolvedModuleRef Unresolved;
4290       Unresolved.File = &F;
4291       Unresolved.Mod = CurrentModule;
4292       Unresolved.ID = Record[0];
4293       Unresolved.Kind = UnresolvedModuleRef::Conflict;
4294       Unresolved.IsWildcard = false;
4295       Unresolved.String = Blob;
4296       UnresolvedModuleRefs.push_back(Unresolved);
4297       break;
4298     }
4299     }
4300   }
4301 }
4302 
4303 /// \brief Parse the record that corresponds to a LangOptions data
4304 /// structure.
4305 ///
4306 /// This routine parses the language options from the AST file and then gives
4307 /// them to the AST listener if one is set.
4308 ///
4309 /// \returns true if the listener deems the file unacceptable, false otherwise.
4310 bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4311                                      bool Complain,
4312                                      ASTReaderListener &Listener) {
4313   LangOptions LangOpts;
4314   unsigned Idx = 0;
4315 #define LANGOPT(Name, Bits, Default, Description) \
4316   LangOpts.Name = Record[Idx++];
4317 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4318   LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4319 #include "clang/Basic/LangOptions.def"
4320 #define SANITIZER(NAME, ID) LangOpts.Sanitize.ID = Record[Idx++];
4321 #include "clang/Basic/Sanitizers.def"
4322 
4323   ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4324   VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4325   LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
4326 
4327   unsigned Length = Record[Idx++];
4328   LangOpts.CurrentModule.assign(Record.begin() + Idx,
4329                                 Record.begin() + Idx + Length);
4330 
4331   Idx += Length;
4332 
4333   // Comment options.
4334   for (unsigned N = Record[Idx++]; N; --N) {
4335     LangOpts.CommentOpts.BlockCommandNames.push_back(
4336       ReadString(Record, Idx));
4337   }
4338   LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
4339 
4340   return Listener.ReadLanguageOptions(LangOpts, Complain);
4341 }
4342 
4343 bool ASTReader::ParseTargetOptions(const RecordData &Record,
4344                                    bool Complain,
4345                                    ASTReaderListener &Listener) {
4346   unsigned Idx = 0;
4347   TargetOptions TargetOpts;
4348   TargetOpts.Triple = ReadString(Record, Idx);
4349   TargetOpts.CPU = ReadString(Record, Idx);
4350   TargetOpts.ABI = ReadString(Record, Idx);
4351   TargetOpts.LinkerVersion = ReadString(Record, Idx);
4352   for (unsigned N = Record[Idx++]; N; --N) {
4353     TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4354   }
4355   for (unsigned N = Record[Idx++]; N; --N) {
4356     TargetOpts.Features.push_back(ReadString(Record, Idx));
4357   }
4358 
4359   return Listener.ReadTargetOptions(TargetOpts, Complain);
4360 }
4361 
4362 bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4363                                        ASTReaderListener &Listener) {
4364   DiagnosticOptions DiagOpts;
4365   unsigned Idx = 0;
4366 #define DIAGOPT(Name, Bits, Default) DiagOpts.Name = Record[Idx++];
4367 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
4368   DiagOpts.set##Name(static_cast<Type>(Record[Idx++]));
4369 #include "clang/Basic/DiagnosticOptions.def"
4370 
4371   for (unsigned N = Record[Idx++]; N; --N) {
4372     DiagOpts.Warnings.push_back(ReadString(Record, Idx));
4373   }
4374 
4375   return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4376 }
4377 
4378 bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4379                                        ASTReaderListener &Listener) {
4380   FileSystemOptions FSOpts;
4381   unsigned Idx = 0;
4382   FSOpts.WorkingDir = ReadString(Record, Idx);
4383   return Listener.ReadFileSystemOptions(FSOpts, Complain);
4384 }
4385 
4386 bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4387                                          bool Complain,
4388                                          ASTReaderListener &Listener) {
4389   HeaderSearchOptions HSOpts;
4390   unsigned Idx = 0;
4391   HSOpts.Sysroot = ReadString(Record, Idx);
4392 
4393   // Include entries.
4394   for (unsigned N = Record[Idx++]; N; --N) {
4395     std::string Path = ReadString(Record, Idx);
4396     frontend::IncludeDirGroup Group
4397       = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
4398     bool IsFramework = Record[Idx++];
4399     bool IgnoreSysRoot = Record[Idx++];
4400     HSOpts.UserEntries.push_back(
4401       HeaderSearchOptions::Entry(Path, Group, IsFramework, IgnoreSysRoot));
4402   }
4403 
4404   // System header prefixes.
4405   for (unsigned N = Record[Idx++]; N; --N) {
4406     std::string Prefix = ReadString(Record, Idx);
4407     bool IsSystemHeader = Record[Idx++];
4408     HSOpts.SystemHeaderPrefixes.push_back(
4409       HeaderSearchOptions::SystemHeaderPrefix(Prefix, IsSystemHeader));
4410   }
4411 
4412   HSOpts.ResourceDir = ReadString(Record, Idx);
4413   HSOpts.ModuleCachePath = ReadString(Record, Idx);
4414   HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
4415   HSOpts.DisableModuleHash = Record[Idx++];
4416   HSOpts.UseBuiltinIncludes = Record[Idx++];
4417   HSOpts.UseStandardSystemIncludes = Record[Idx++];
4418   HSOpts.UseStandardCXXIncludes = Record[Idx++];
4419   HSOpts.UseLibcxx = Record[Idx++];
4420 
4421   return Listener.ReadHeaderSearchOptions(HSOpts, Complain);
4422 }
4423 
4424 bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4425                                          bool Complain,
4426                                          ASTReaderListener &Listener,
4427                                          std::string &SuggestedPredefines) {
4428   PreprocessorOptions PPOpts;
4429   unsigned Idx = 0;
4430 
4431   // Macro definitions/undefs
4432   for (unsigned N = Record[Idx++]; N; --N) {
4433     std::string Macro = ReadString(Record, Idx);
4434     bool IsUndef = Record[Idx++];
4435     PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4436   }
4437 
4438   // Includes
4439   for (unsigned N = Record[Idx++]; N; --N) {
4440     PPOpts.Includes.push_back(ReadString(Record, Idx));
4441   }
4442 
4443   // Macro Includes
4444   for (unsigned N = Record[Idx++]; N; --N) {
4445     PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
4446   }
4447 
4448   PPOpts.UsePredefines = Record[Idx++];
4449   PPOpts.DetailedRecord = Record[Idx++];
4450   PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
4451   PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
4452   PPOpts.ObjCXXARCStandardLibrary =
4453     static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
4454   SuggestedPredefines.clear();
4455   return Listener.ReadPreprocessorOptions(PPOpts, Complain,
4456                                           SuggestedPredefines);
4457 }
4458 
4459 std::pair<ModuleFile *, unsigned>
4460 ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
4461   GlobalPreprocessedEntityMapType::iterator
4462   I = GlobalPreprocessedEntityMap.find(GlobalIndex);
4463   assert(I != GlobalPreprocessedEntityMap.end() &&
4464          "Corrupted global preprocessed entity map");
4465   ModuleFile *M = I->second;
4466   unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
4467   return std::make_pair(M, LocalIndex);
4468 }
4469 
4470 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
4471 ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
4472   if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
4473     return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
4474                                              Mod.NumPreprocessedEntities);
4475 
4476   return std::make_pair(PreprocessingRecord::iterator(),
4477                         PreprocessingRecord::iterator());
4478 }
4479 
4480 std::pair<ASTReader::ModuleDeclIterator, ASTReader::ModuleDeclIterator>
4481 ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
4482   return std::make_pair(ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
4483                         ModuleDeclIterator(this, &Mod,
4484                                  Mod.FileSortedDecls + Mod.NumFileSortedDecls));
4485 }
4486 
4487 PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
4488   PreprocessedEntityID PPID = Index+1;
4489   std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4490   ModuleFile &M = *PPInfo.first;
4491   unsigned LocalIndex = PPInfo.second;
4492   const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4493 
4494   if (!PP.getPreprocessingRecord()) {
4495     Error("no preprocessing record");
4496     return 0;
4497   }
4498 
4499   SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
4500   M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
4501 
4502   llvm::BitstreamEntry Entry =
4503     M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
4504   if (Entry.Kind != llvm::BitstreamEntry::Record)
4505     return 0;
4506 
4507   // Read the record.
4508   SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
4509                     ReadSourceLocation(M, PPOffs.End));
4510   PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
4511   StringRef Blob;
4512   RecordData Record;
4513   PreprocessorDetailRecordTypes RecType =
4514     (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
4515                                           Entry.ID, Record, &Blob);
4516   switch (RecType) {
4517   case PPD_MACRO_EXPANSION: {
4518     bool isBuiltin = Record[0];
4519     IdentifierInfo *Name = 0;
4520     MacroDefinition *Def = 0;
4521     if (isBuiltin)
4522       Name = getLocalIdentifier(M, Record[1]);
4523     else {
4524       PreprocessedEntityID
4525           GlobalID = getGlobalPreprocessedEntityID(M, Record[1]);
4526       Def =cast<MacroDefinition>(PPRec.getLoadedPreprocessedEntity(GlobalID-1));
4527     }
4528 
4529     MacroExpansion *ME;
4530     if (isBuiltin)
4531       ME = new (PPRec) MacroExpansion(Name, Range);
4532     else
4533       ME = new (PPRec) MacroExpansion(Def, Range);
4534 
4535     return ME;
4536   }
4537 
4538   case PPD_MACRO_DEFINITION: {
4539     // Decode the identifier info and then check again; if the macro is
4540     // still defined and associated with the identifier,
4541     IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
4542     MacroDefinition *MD
4543       = new (PPRec) MacroDefinition(II, Range);
4544 
4545     if (DeserializationListener)
4546       DeserializationListener->MacroDefinitionRead(PPID, MD);
4547 
4548     return MD;
4549   }
4550 
4551   case PPD_INCLUSION_DIRECTIVE: {
4552     const char *FullFileNameStart = Blob.data() + Record[0];
4553     StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
4554     const FileEntry *File = 0;
4555     if (!FullFileName.empty())
4556       File = PP.getFileManager().getFile(FullFileName);
4557 
4558     // FIXME: Stable encoding
4559     InclusionDirective::InclusionKind Kind
4560       = static_cast<InclusionDirective::InclusionKind>(Record[2]);
4561     InclusionDirective *ID
4562       = new (PPRec) InclusionDirective(PPRec, Kind,
4563                                        StringRef(Blob.data(), Record[0]),
4564                                        Record[1], Record[3],
4565                                        File,
4566                                        Range);
4567     return ID;
4568   }
4569   }
4570 
4571   llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
4572 }
4573 
4574 /// \brief \arg SLocMapI points at a chunk of a module that contains no
4575 /// preprocessed entities or the entities it contains are not the ones we are
4576 /// looking for. Find the next module that contains entities and return the ID
4577 /// of the first entry.
4578 PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
4579                        GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
4580   ++SLocMapI;
4581   for (GlobalSLocOffsetMapType::const_iterator
4582          EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
4583     ModuleFile &M = *SLocMapI->second;
4584     if (M.NumPreprocessedEntities)
4585       return M.BasePreprocessedEntityID;
4586   }
4587 
4588   return getTotalNumPreprocessedEntities();
4589 }
4590 
4591 namespace {
4592 
4593 template <unsigned PPEntityOffset::*PPLoc>
4594 struct PPEntityComp {
4595   const ASTReader &Reader;
4596   ModuleFile &M;
4597 
4598   PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
4599 
4600   bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
4601     SourceLocation LHS = getLoc(L);
4602     SourceLocation RHS = getLoc(R);
4603     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4604   }
4605 
4606   bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
4607     SourceLocation LHS = getLoc(L);
4608     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4609   }
4610 
4611   bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
4612     SourceLocation RHS = getLoc(R);
4613     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
4614   }
4615 
4616   SourceLocation getLoc(const PPEntityOffset &PPE) const {
4617     return Reader.ReadSourceLocation(M, PPE.*PPLoc);
4618   }
4619 };
4620 
4621 }
4622 
4623 /// \brief Returns the first preprocessed entity ID that ends after \arg BLoc.
4624 PreprocessedEntityID
4625 ASTReader::findBeginPreprocessedEntity(SourceLocation BLoc) const {
4626   if (SourceMgr.isLocalSourceLocation(BLoc))
4627     return getTotalNumPreprocessedEntities();
4628 
4629   GlobalSLocOffsetMapType::const_iterator
4630     SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
4631                                         BLoc.getOffset() - 1);
4632   assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4633          "Corrupted global sloc offset map");
4634 
4635   if (SLocMapI->second->NumPreprocessedEntities == 0)
4636     return findNextPreprocessedEntity(SLocMapI);
4637 
4638   ModuleFile &M = *SLocMapI->second;
4639   typedef const PPEntityOffset *pp_iterator;
4640   pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4641   pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4642 
4643   size_t Count = M.NumPreprocessedEntities;
4644   size_t Half;
4645   pp_iterator First = pp_begin;
4646   pp_iterator PPI;
4647 
4648   // Do a binary search manually instead of using std::lower_bound because
4649   // The end locations of entities may be unordered (when a macro expansion
4650   // is inside another macro argument), but for this case it is not important
4651   // whether we get the first macro expansion or its containing macro.
4652   while (Count > 0) {
4653     Half = Count/2;
4654     PPI = First;
4655     std::advance(PPI, Half);
4656     if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
4657                                             BLoc)){
4658       First = PPI;
4659       ++First;
4660       Count = Count - Half - 1;
4661     } else
4662       Count = Half;
4663   }
4664 
4665   if (PPI == pp_end)
4666     return findNextPreprocessedEntity(SLocMapI);
4667 
4668   return M.BasePreprocessedEntityID + (PPI - pp_begin);
4669 }
4670 
4671 /// \brief Returns the first preprocessed entity ID that begins after \arg ELoc.
4672 PreprocessedEntityID
4673 ASTReader::findEndPreprocessedEntity(SourceLocation ELoc) const {
4674   if (SourceMgr.isLocalSourceLocation(ELoc))
4675     return getTotalNumPreprocessedEntities();
4676 
4677   GlobalSLocOffsetMapType::const_iterator
4678     SLocMapI = GlobalSLocOffsetMap.find(SourceManager::MaxLoadedOffset -
4679                                         ELoc.getOffset() - 1);
4680   assert(SLocMapI != GlobalSLocOffsetMap.end() &&
4681          "Corrupted global sloc offset map");
4682 
4683   if (SLocMapI->second->NumPreprocessedEntities == 0)
4684     return findNextPreprocessedEntity(SLocMapI);
4685 
4686   ModuleFile &M = *SLocMapI->second;
4687   typedef const PPEntityOffset *pp_iterator;
4688   pp_iterator pp_begin = M.PreprocessedEntityOffsets;
4689   pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
4690   pp_iterator PPI =
4691       std::upper_bound(pp_begin, pp_end, ELoc,
4692                        PPEntityComp<&PPEntityOffset::Begin>(*this, M));
4693 
4694   if (PPI == pp_end)
4695     return findNextPreprocessedEntity(SLocMapI);
4696 
4697   return M.BasePreprocessedEntityID + (PPI - pp_begin);
4698 }
4699 
4700 /// \brief Returns a pair of [Begin, End) indices of preallocated
4701 /// preprocessed entities that \arg Range encompasses.
4702 std::pair<unsigned, unsigned>
4703     ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
4704   if (Range.isInvalid())
4705     return std::make_pair(0,0);
4706   assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
4707 
4708   PreprocessedEntityID BeginID = findBeginPreprocessedEntity(Range.getBegin());
4709   PreprocessedEntityID EndID = findEndPreprocessedEntity(Range.getEnd());
4710   return std::make_pair(BeginID, EndID);
4711 }
4712 
4713 /// \brief Optionally returns true or false if the preallocated preprocessed
4714 /// entity with index \arg Index came from file \arg FID.
4715 Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
4716                                                              FileID FID) {
4717   if (FID.isInvalid())
4718     return false;
4719 
4720   std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
4721   ModuleFile &M = *PPInfo.first;
4722   unsigned LocalIndex = PPInfo.second;
4723   const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
4724 
4725   SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
4726   if (Loc.isInvalid())
4727     return false;
4728 
4729   if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
4730     return true;
4731   else
4732     return false;
4733 }
4734 
4735 namespace {
4736   /// \brief Visitor used to search for information about a header file.
4737   class HeaderFileInfoVisitor {
4738     const FileEntry *FE;
4739 
4740     Optional<HeaderFileInfo> HFI;
4741 
4742   public:
4743     explicit HeaderFileInfoVisitor(const FileEntry *FE)
4744       : FE(FE) { }
4745 
4746     static bool visit(ModuleFile &M, void *UserData) {
4747       HeaderFileInfoVisitor *This
4748         = static_cast<HeaderFileInfoVisitor *>(UserData);
4749 
4750       HeaderFileInfoLookupTable *Table
4751         = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
4752       if (!Table)
4753         return false;
4754 
4755       // Look in the on-disk hash table for an entry for this file name.
4756       HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
4757       if (Pos == Table->end())
4758         return false;
4759 
4760       This->HFI = *Pos;
4761       return true;
4762     }
4763 
4764     Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
4765   };
4766 }
4767 
4768 HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
4769   HeaderFileInfoVisitor Visitor(FE);
4770   ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
4771   if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
4772     return *HFI;
4773 
4774   return HeaderFileInfo();
4775 }
4776 
4777 void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
4778   // FIXME: Make it work properly with modules.
4779   SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
4780   for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
4781     ModuleFile &F = *(*I);
4782     unsigned Idx = 0;
4783     DiagStates.clear();
4784     assert(!Diag.DiagStates.empty());
4785     DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
4786     while (Idx < F.PragmaDiagMappings.size()) {
4787       SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
4788       unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
4789       if (DiagStateID != 0) {
4790         Diag.DiagStatePoints.push_back(
4791                     DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
4792                     FullSourceLoc(Loc, SourceMgr)));
4793         continue;
4794       }
4795 
4796       assert(DiagStateID == 0);
4797       // A new DiagState was created here.
4798       Diag.DiagStates.push_back(*Diag.GetCurDiagState());
4799       DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
4800       DiagStates.push_back(NewState);
4801       Diag.DiagStatePoints.push_back(
4802           DiagnosticsEngine::DiagStatePoint(NewState,
4803                                             FullSourceLoc(Loc, SourceMgr)));
4804       while (1) {
4805         assert(Idx < F.PragmaDiagMappings.size() &&
4806                "Invalid data, didn't find '-1' marking end of diag/map pairs");
4807         if (Idx >= F.PragmaDiagMappings.size()) {
4808           break; // Something is messed up but at least avoid infinite loop in
4809                  // release build.
4810         }
4811         unsigned DiagID = F.PragmaDiagMappings[Idx++];
4812         if (DiagID == (unsigned)-1) {
4813           break; // no more diag/map pairs for this location.
4814         }
4815         diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
4816         DiagnosticMappingInfo MappingInfo = Diag.makeMappingInfo(Map, Loc);
4817         Diag.GetCurDiagState()->setMappingInfo(DiagID, MappingInfo);
4818       }
4819     }
4820   }
4821 }
4822 
4823 /// \brief Get the correct cursor and offset for loading a type.
4824 ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
4825   GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
4826   assert(I != GlobalTypeMap.end() && "Corrupted global type map");
4827   ModuleFile *M = I->second;
4828   return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
4829 }
4830 
4831 /// \brief Read and return the type with the given index..
4832 ///
4833 /// The index is the type ID, shifted and minus the number of predefs. This
4834 /// routine actually reads the record corresponding to the type at the given
4835 /// location. It is a helper routine for GetType, which deals with reading type
4836 /// IDs.
4837 QualType ASTReader::readTypeRecord(unsigned Index) {
4838   RecordLocation Loc = TypeCursorForIndex(Index);
4839   BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
4840 
4841   // Keep track of where we are in the stream, then jump back there
4842   // after reading this type.
4843   SavedStreamPosition SavedPosition(DeclsCursor);
4844 
4845   ReadingKindTracker ReadingKind(Read_Type, *this);
4846 
4847   // Note that we are loading a type record.
4848   Deserializing AType(this);
4849 
4850   unsigned Idx = 0;
4851   DeclsCursor.JumpToBit(Loc.Offset);
4852   RecordData Record;
4853   unsigned Code = DeclsCursor.ReadCode();
4854   switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
4855   case TYPE_EXT_QUAL: {
4856     if (Record.size() != 2) {
4857       Error("Incorrect encoding of extended qualifier type");
4858       return QualType();
4859     }
4860     QualType Base = readType(*Loc.F, Record, Idx);
4861     Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
4862     return Context.getQualifiedType(Base, Quals);
4863   }
4864 
4865   case TYPE_COMPLEX: {
4866     if (Record.size() != 1) {
4867       Error("Incorrect encoding of complex type");
4868       return QualType();
4869     }
4870     QualType ElemType = readType(*Loc.F, Record, Idx);
4871     return Context.getComplexType(ElemType);
4872   }
4873 
4874   case TYPE_POINTER: {
4875     if (Record.size() != 1) {
4876       Error("Incorrect encoding of pointer type");
4877       return QualType();
4878     }
4879     QualType PointeeType = readType(*Loc.F, Record, Idx);
4880     return Context.getPointerType(PointeeType);
4881   }
4882 
4883   case TYPE_DECAYED: {
4884     if (Record.size() != 1) {
4885       Error("Incorrect encoding of decayed type");
4886       return QualType();
4887     }
4888     QualType OriginalType = readType(*Loc.F, Record, Idx);
4889     QualType DT = Context.getAdjustedParameterType(OriginalType);
4890     if (!isa<DecayedType>(DT))
4891       Error("Decayed type does not decay");
4892     return DT;
4893   }
4894 
4895   case TYPE_ADJUSTED: {
4896     if (Record.size() != 2) {
4897       Error("Incorrect encoding of adjusted type");
4898       return QualType();
4899     }
4900     QualType OriginalTy = readType(*Loc.F, Record, Idx);
4901     QualType AdjustedTy = readType(*Loc.F, Record, Idx);
4902     return Context.getAdjustedType(OriginalTy, AdjustedTy);
4903   }
4904 
4905   case TYPE_BLOCK_POINTER: {
4906     if (Record.size() != 1) {
4907       Error("Incorrect encoding of block pointer type");
4908       return QualType();
4909     }
4910     QualType PointeeType = readType(*Loc.F, Record, Idx);
4911     return Context.getBlockPointerType(PointeeType);
4912   }
4913 
4914   case TYPE_LVALUE_REFERENCE: {
4915     if (Record.size() != 2) {
4916       Error("Incorrect encoding of lvalue reference type");
4917       return QualType();
4918     }
4919     QualType PointeeType = readType(*Loc.F, Record, Idx);
4920     return Context.getLValueReferenceType(PointeeType, Record[1]);
4921   }
4922 
4923   case TYPE_RVALUE_REFERENCE: {
4924     if (Record.size() != 1) {
4925       Error("Incorrect encoding of rvalue reference type");
4926       return QualType();
4927     }
4928     QualType PointeeType = readType(*Loc.F, Record, Idx);
4929     return Context.getRValueReferenceType(PointeeType);
4930   }
4931 
4932   case TYPE_MEMBER_POINTER: {
4933     if (Record.size() != 2) {
4934       Error("Incorrect encoding of member pointer type");
4935       return QualType();
4936     }
4937     QualType PointeeType = readType(*Loc.F, Record, Idx);
4938     QualType ClassType = readType(*Loc.F, Record, Idx);
4939     if (PointeeType.isNull() || ClassType.isNull())
4940       return QualType();
4941 
4942     return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
4943   }
4944 
4945   case TYPE_CONSTANT_ARRAY: {
4946     QualType ElementType = readType(*Loc.F, Record, Idx);
4947     ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4948     unsigned IndexTypeQuals = Record[2];
4949     unsigned Idx = 3;
4950     llvm::APInt Size = ReadAPInt(Record, Idx);
4951     return Context.getConstantArrayType(ElementType, Size,
4952                                          ASM, IndexTypeQuals);
4953   }
4954 
4955   case TYPE_INCOMPLETE_ARRAY: {
4956     QualType ElementType = readType(*Loc.F, Record, Idx);
4957     ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4958     unsigned IndexTypeQuals = Record[2];
4959     return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
4960   }
4961 
4962   case TYPE_VARIABLE_ARRAY: {
4963     QualType ElementType = readType(*Loc.F, Record, Idx);
4964     ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
4965     unsigned IndexTypeQuals = Record[2];
4966     SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
4967     SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
4968     return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
4969                                          ASM, IndexTypeQuals,
4970                                          SourceRange(LBLoc, RBLoc));
4971   }
4972 
4973   case TYPE_VECTOR: {
4974     if (Record.size() != 3) {
4975       Error("incorrect encoding of vector type in AST file");
4976       return QualType();
4977     }
4978 
4979     QualType ElementType = readType(*Loc.F, Record, Idx);
4980     unsigned NumElements = Record[1];
4981     unsigned VecKind = Record[2];
4982     return Context.getVectorType(ElementType, NumElements,
4983                                   (VectorType::VectorKind)VecKind);
4984   }
4985 
4986   case TYPE_EXT_VECTOR: {
4987     if (Record.size() != 3) {
4988       Error("incorrect encoding of extended vector type in AST file");
4989       return QualType();
4990     }
4991 
4992     QualType ElementType = readType(*Loc.F, Record, Idx);
4993     unsigned NumElements = Record[1];
4994     return Context.getExtVectorType(ElementType, NumElements);
4995   }
4996 
4997   case TYPE_FUNCTION_NO_PROTO: {
4998     if (Record.size() != 6) {
4999       Error("incorrect encoding of no-proto function type");
5000       return QualType();
5001     }
5002     QualType ResultType = readType(*Loc.F, Record, Idx);
5003     FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5004                                (CallingConv)Record[4], Record[5]);
5005     return Context.getFunctionNoProtoType(ResultType, Info);
5006   }
5007 
5008   case TYPE_FUNCTION_PROTO: {
5009     QualType ResultType = readType(*Loc.F, Record, Idx);
5010 
5011     FunctionProtoType::ExtProtoInfo EPI;
5012     EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5013                                         /*hasregparm*/ Record[2],
5014                                         /*regparm*/ Record[3],
5015                                         static_cast<CallingConv>(Record[4]),
5016                                         /*produces*/ Record[5]);
5017 
5018     unsigned Idx = 6;
5019     unsigned NumParams = Record[Idx++];
5020     SmallVector<QualType, 16> ParamTypes;
5021     for (unsigned I = 0; I != NumParams; ++I)
5022       ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5023 
5024     EPI.Variadic = Record[Idx++];
5025     EPI.HasTrailingReturn = Record[Idx++];
5026     EPI.TypeQuals = Record[Idx++];
5027     EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
5028     ExceptionSpecificationType EST =
5029         static_cast<ExceptionSpecificationType>(Record[Idx++]);
5030     EPI.ExceptionSpecType = EST;
5031     SmallVector<QualType, 2> Exceptions;
5032     if (EST == EST_Dynamic) {
5033       EPI.NumExceptions = Record[Idx++];
5034       for (unsigned I = 0; I != EPI.NumExceptions; ++I)
5035         Exceptions.push_back(readType(*Loc.F, Record, Idx));
5036       EPI.Exceptions = Exceptions.data();
5037     } else if (EST == EST_ComputedNoexcept) {
5038       EPI.NoexceptExpr = ReadExpr(*Loc.F);
5039     } else if (EST == EST_Uninstantiated) {
5040       EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
5041       EPI.ExceptionSpecTemplate = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
5042     } else if (EST == EST_Unevaluated) {
5043       EPI.ExceptionSpecDecl = ReadDeclAs<FunctionDecl>(*Loc.F, Record, Idx);
5044     }
5045     return Context.getFunctionType(ResultType, ParamTypes, EPI);
5046   }
5047 
5048   case TYPE_UNRESOLVED_USING: {
5049     unsigned Idx = 0;
5050     return Context.getTypeDeclType(
5051                   ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5052   }
5053 
5054   case TYPE_TYPEDEF: {
5055     if (Record.size() != 2) {
5056       Error("incorrect encoding of typedef type");
5057       return QualType();
5058     }
5059     unsigned Idx = 0;
5060     TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5061     QualType Canonical = readType(*Loc.F, Record, Idx);
5062     if (!Canonical.isNull())
5063       Canonical = Context.getCanonicalType(Canonical);
5064     return Context.getTypedefType(Decl, Canonical);
5065   }
5066 
5067   case TYPE_TYPEOF_EXPR:
5068     return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5069 
5070   case TYPE_TYPEOF: {
5071     if (Record.size() != 1) {
5072       Error("incorrect encoding of typeof(type) in AST file");
5073       return QualType();
5074     }
5075     QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5076     return Context.getTypeOfType(UnderlyingType);
5077   }
5078 
5079   case TYPE_DECLTYPE: {
5080     QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5081     return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5082   }
5083 
5084   case TYPE_UNARY_TRANSFORM: {
5085     QualType BaseType = readType(*Loc.F, Record, Idx);
5086     QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5087     UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5088     return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5089   }
5090 
5091   case TYPE_AUTO: {
5092     QualType Deduced = readType(*Loc.F, Record, Idx);
5093     bool IsDecltypeAuto = Record[Idx++];
5094     bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
5095     return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
5096   }
5097 
5098   case TYPE_RECORD: {
5099     if (Record.size() != 2) {
5100       Error("incorrect encoding of record type");
5101       return QualType();
5102     }
5103     unsigned Idx = 0;
5104     bool IsDependent = Record[Idx++];
5105     RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5106     RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5107     QualType T = Context.getRecordType(RD);
5108     const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5109     return T;
5110   }
5111 
5112   case TYPE_ENUM: {
5113     if (Record.size() != 2) {
5114       Error("incorrect encoding of enum type");
5115       return QualType();
5116     }
5117     unsigned Idx = 0;
5118     bool IsDependent = Record[Idx++];
5119     QualType T
5120       = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5121     const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5122     return T;
5123   }
5124 
5125   case TYPE_ATTRIBUTED: {
5126     if (Record.size() != 3) {
5127       Error("incorrect encoding of attributed type");
5128       return QualType();
5129     }
5130     QualType modifiedType = readType(*Loc.F, Record, Idx);
5131     QualType equivalentType = readType(*Loc.F, Record, Idx);
5132     AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5133     return Context.getAttributedType(kind, modifiedType, equivalentType);
5134   }
5135 
5136   case TYPE_PAREN: {
5137     if (Record.size() != 1) {
5138       Error("incorrect encoding of paren type");
5139       return QualType();
5140     }
5141     QualType InnerType = readType(*Loc.F, Record, Idx);
5142     return Context.getParenType(InnerType);
5143   }
5144 
5145   case TYPE_PACK_EXPANSION: {
5146     if (Record.size() != 2) {
5147       Error("incorrect encoding of pack expansion type");
5148       return QualType();
5149     }
5150     QualType Pattern = readType(*Loc.F, Record, Idx);
5151     if (Pattern.isNull())
5152       return QualType();
5153     Optional<unsigned> NumExpansions;
5154     if (Record[1])
5155       NumExpansions = Record[1] - 1;
5156     return Context.getPackExpansionType(Pattern, NumExpansions);
5157   }
5158 
5159   case TYPE_ELABORATED: {
5160     unsigned Idx = 0;
5161     ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5162     NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5163     QualType NamedType = readType(*Loc.F, Record, Idx);
5164     return Context.getElaboratedType(Keyword, NNS, NamedType);
5165   }
5166 
5167   case TYPE_OBJC_INTERFACE: {
5168     unsigned Idx = 0;
5169     ObjCInterfaceDecl *ItfD
5170       = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5171     return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5172   }
5173 
5174   case TYPE_OBJC_OBJECT: {
5175     unsigned Idx = 0;
5176     QualType Base = readType(*Loc.F, Record, Idx);
5177     unsigned NumProtos = Record[Idx++];
5178     SmallVector<ObjCProtocolDecl*, 4> Protos;
5179     for (unsigned I = 0; I != NumProtos; ++I)
5180       Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5181     return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
5182   }
5183 
5184   case TYPE_OBJC_OBJECT_POINTER: {
5185     unsigned Idx = 0;
5186     QualType Pointee = readType(*Loc.F, Record, Idx);
5187     return Context.getObjCObjectPointerType(Pointee);
5188   }
5189 
5190   case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5191     unsigned Idx = 0;
5192     QualType Parm = readType(*Loc.F, Record, Idx);
5193     QualType Replacement = readType(*Loc.F, Record, Idx);
5194     return
5195       Context.getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
5196                                             Replacement);
5197   }
5198 
5199   case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5200     unsigned Idx = 0;
5201     QualType Parm = readType(*Loc.F, Record, Idx);
5202     TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5203     return Context.getSubstTemplateTypeParmPackType(
5204                                                cast<TemplateTypeParmType>(Parm),
5205                                                      ArgPack);
5206   }
5207 
5208   case TYPE_INJECTED_CLASS_NAME: {
5209     CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5210     QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5211     // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5212     // for AST reading, too much interdependencies.
5213     return
5214       QualType(new (Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
5215   }
5216 
5217   case TYPE_TEMPLATE_TYPE_PARM: {
5218     unsigned Idx = 0;
5219     unsigned Depth = Record[Idx++];
5220     unsigned Index = Record[Idx++];
5221     bool Pack = Record[Idx++];
5222     TemplateTypeParmDecl *D
5223       = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5224     return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5225   }
5226 
5227   case TYPE_DEPENDENT_NAME: {
5228     unsigned Idx = 0;
5229     ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5230     NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5231     const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5232     QualType Canon = readType(*Loc.F, Record, Idx);
5233     if (!Canon.isNull())
5234       Canon = Context.getCanonicalType(Canon);
5235     return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5236   }
5237 
5238   case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5239     unsigned Idx = 0;
5240     ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5241     NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5242     const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
5243     unsigned NumArgs = Record[Idx++];
5244     SmallVector<TemplateArgument, 8> Args;
5245     Args.reserve(NumArgs);
5246     while (NumArgs--)
5247       Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5248     return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
5249                                                       Args.size(), Args.data());
5250   }
5251 
5252   case TYPE_DEPENDENT_SIZED_ARRAY: {
5253     unsigned Idx = 0;
5254 
5255     // ArrayType
5256     QualType ElementType = readType(*Loc.F, Record, Idx);
5257     ArrayType::ArraySizeModifier ASM
5258       = (ArrayType::ArraySizeModifier)Record[Idx++];
5259     unsigned IndexTypeQuals = Record[Idx++];
5260 
5261     // DependentSizedArrayType
5262     Expr *NumElts = ReadExpr(*Loc.F);
5263     SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5264 
5265     return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5266                                                IndexTypeQuals, Brackets);
5267   }
5268 
5269   case TYPE_TEMPLATE_SPECIALIZATION: {
5270     unsigned Idx = 0;
5271     bool IsDependent = Record[Idx++];
5272     TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5273     SmallVector<TemplateArgument, 8> Args;
5274     ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5275     QualType Underlying = readType(*Loc.F, Record, Idx);
5276     QualType T;
5277     if (Underlying.isNull())
5278       T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
5279                                                           Args.size());
5280     else
5281       T = Context.getTemplateSpecializationType(Name, Args.data(),
5282                                                  Args.size(), Underlying);
5283     const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5284     return T;
5285   }
5286 
5287   case TYPE_ATOMIC: {
5288     if (Record.size() != 1) {
5289       Error("Incorrect encoding of atomic type");
5290       return QualType();
5291     }
5292     QualType ValueType = readType(*Loc.F, Record, Idx);
5293     return Context.getAtomicType(ValueType);
5294   }
5295   }
5296   llvm_unreachable("Invalid TypeCode!");
5297 }
5298 
5299 class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
5300   ASTReader &Reader;
5301   ModuleFile &F;
5302   const ASTReader::RecordData &Record;
5303   unsigned &Idx;
5304 
5305   SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
5306                                     unsigned &I) {
5307     return Reader.ReadSourceLocation(F, R, I);
5308   }
5309 
5310   template<typename T>
5311   T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
5312     return Reader.ReadDeclAs<T>(F, Record, Idx);
5313   }
5314 
5315 public:
5316   TypeLocReader(ASTReader &Reader, ModuleFile &F,
5317                 const ASTReader::RecordData &Record, unsigned &Idx)
5318     : Reader(Reader), F(F), Record(Record), Idx(Idx)
5319   { }
5320 
5321   // We want compile-time assurance that we've enumerated all of
5322   // these, so unfortunately we have to declare them first, then
5323   // define them out-of-line.
5324 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5325 #define TYPELOC(CLASS, PARENT) \
5326   void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5327 #include "clang/AST/TypeLocNodes.def"
5328 
5329   void VisitFunctionTypeLoc(FunctionTypeLoc);
5330   void VisitArrayTypeLoc(ArrayTypeLoc);
5331 };
5332 
5333 void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5334   // nothing to do
5335 }
5336 void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5337   TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
5338   if (TL.needsExtraLocalData()) {
5339     TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5340     TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5341     TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5342     TL.setModeAttr(Record[Idx++]);
5343   }
5344 }
5345 void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
5346   TL.setNameLoc(ReadSourceLocation(Record, Idx));
5347 }
5348 void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
5349   TL.setStarLoc(ReadSourceLocation(Record, Idx));
5350 }
5351 void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5352   // nothing to do
5353 }
5354 void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5355   // nothing to do
5356 }
5357 void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5358   TL.setCaretLoc(ReadSourceLocation(Record, Idx));
5359 }
5360 void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5361   TL.setAmpLoc(ReadSourceLocation(Record, Idx));
5362 }
5363 void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5364   TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
5365 }
5366 void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5367   TL.setStarLoc(ReadSourceLocation(Record, Idx));
5368   TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5369 }
5370 void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
5371   TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
5372   TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
5373   if (Record[Idx++])
5374     TL.setSizeExpr(Reader.ReadExpr(F));
5375   else
5376     TL.setSizeExpr(0);
5377 }
5378 void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
5379   VisitArrayTypeLoc(TL);
5380 }
5381 void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
5382   VisitArrayTypeLoc(TL);
5383 }
5384 void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
5385   VisitArrayTypeLoc(TL);
5386 }
5387 void TypeLocReader::VisitDependentSizedArrayTypeLoc(
5388                                             DependentSizedArrayTypeLoc TL) {
5389   VisitArrayTypeLoc(TL);
5390 }
5391 void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
5392                                         DependentSizedExtVectorTypeLoc TL) {
5393   TL.setNameLoc(ReadSourceLocation(Record, Idx));
5394 }
5395 void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
5396   TL.setNameLoc(ReadSourceLocation(Record, Idx));
5397 }
5398 void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
5399   TL.setNameLoc(ReadSourceLocation(Record, Idx));
5400 }
5401 void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5402   TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
5403   TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5404   TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5405   TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
5406   for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
5407     TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
5408   }
5409 }
5410 void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
5411   VisitFunctionTypeLoc(TL);
5412 }
5413 void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
5414   VisitFunctionTypeLoc(TL);
5415 }
5416 void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5417   TL.setNameLoc(ReadSourceLocation(Record, Idx));
5418 }
5419 void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5420   TL.setNameLoc(ReadSourceLocation(Record, Idx));
5421 }
5422 void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5423   TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5424   TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5425   TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5426 }
5427 void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5428   TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
5429   TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5430   TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5431   TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5432 }
5433 void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
5434   TL.setNameLoc(ReadSourceLocation(Record, Idx));
5435 }
5436 void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5437   TL.setKWLoc(ReadSourceLocation(Record, Idx));
5438   TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5439   TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5440   TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
5441 }
5442 void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
5443   TL.setNameLoc(ReadSourceLocation(Record, Idx));
5444 }
5445 void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
5446   TL.setNameLoc(ReadSourceLocation(Record, Idx));
5447 }
5448 void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
5449   TL.setNameLoc(ReadSourceLocation(Record, Idx));
5450 }
5451 void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5452   TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
5453   if (TL.hasAttrOperand()) {
5454     SourceRange range;
5455     range.setBegin(ReadSourceLocation(Record, Idx));
5456     range.setEnd(ReadSourceLocation(Record, Idx));
5457     TL.setAttrOperandParensRange(range);
5458   }
5459   if (TL.hasAttrExprOperand()) {
5460     if (Record[Idx++])
5461       TL.setAttrExprOperand(Reader.ReadExpr(F));
5462     else
5463       TL.setAttrExprOperand(0);
5464   } else if (TL.hasAttrEnumOperand())
5465     TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
5466 }
5467 void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
5468   TL.setNameLoc(ReadSourceLocation(Record, Idx));
5469 }
5470 void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
5471                                             SubstTemplateTypeParmTypeLoc TL) {
5472   TL.setNameLoc(ReadSourceLocation(Record, Idx));
5473 }
5474 void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
5475                                           SubstTemplateTypeParmPackTypeLoc TL) {
5476   TL.setNameLoc(ReadSourceLocation(Record, Idx));
5477 }
5478 void TypeLocReader::VisitTemplateSpecializationTypeLoc(
5479                                            TemplateSpecializationTypeLoc TL) {
5480   TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5481   TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5482   TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5483   TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5484   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
5485     TL.setArgLocInfo(i,
5486         Reader.GetTemplateArgumentLocInfo(F,
5487                                           TL.getTypePtr()->getArg(i).getKind(),
5488                                           Record, Idx));
5489 }
5490 void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
5491   TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5492   TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5493 }
5494 void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5495   TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5496   TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5497 }
5498 void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
5499   TL.setNameLoc(ReadSourceLocation(Record, Idx));
5500 }
5501 void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5502   TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5503   TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5504   TL.setNameLoc(ReadSourceLocation(Record, Idx));
5505 }
5506 void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
5507        DependentTemplateSpecializationTypeLoc TL) {
5508   TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
5509   TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
5510   TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
5511   TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
5512   TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5513   TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5514   for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
5515     TL.setArgLocInfo(I,
5516         Reader.GetTemplateArgumentLocInfo(F,
5517                                           TL.getTypePtr()->getArg(I).getKind(),
5518                                           Record, Idx));
5519 }
5520 void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
5521   TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
5522 }
5523 void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5524   TL.setNameLoc(ReadSourceLocation(Record, Idx));
5525 }
5526 void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5527   TL.setHasBaseTypeAsWritten(Record[Idx++]);
5528   TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
5529   TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
5530   for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
5531     TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
5532 }
5533 void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5534   TL.setStarLoc(ReadSourceLocation(Record, Idx));
5535 }
5536 void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5537   TL.setKWLoc(ReadSourceLocation(Record, Idx));
5538   TL.setLParenLoc(ReadSourceLocation(Record, Idx));
5539   TL.setRParenLoc(ReadSourceLocation(Record, Idx));
5540 }
5541 
5542 TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
5543                                              const RecordData &Record,
5544                                              unsigned &Idx) {
5545   QualType InfoTy = readType(F, Record, Idx);
5546   if (InfoTy.isNull())
5547     return 0;
5548 
5549   TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
5550   TypeLocReader TLR(*this, F, Record, Idx);
5551   for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
5552     TLR.Visit(TL);
5553   return TInfo;
5554 }
5555 
5556 QualType ASTReader::GetType(TypeID ID) {
5557   unsigned FastQuals = ID & Qualifiers::FastMask;
5558   unsigned Index = ID >> Qualifiers::FastWidth;
5559 
5560   if (Index < NUM_PREDEF_TYPE_IDS) {
5561     QualType T;
5562     switch ((PredefinedTypeIDs)Index) {
5563     case PREDEF_TYPE_NULL_ID: return QualType();
5564     case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
5565     case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
5566 
5567     case PREDEF_TYPE_CHAR_U_ID:
5568     case PREDEF_TYPE_CHAR_S_ID:
5569       // FIXME: Check that the signedness of CharTy is correct!
5570       T = Context.CharTy;
5571       break;
5572 
5573     case PREDEF_TYPE_UCHAR_ID:      T = Context.UnsignedCharTy;     break;
5574     case PREDEF_TYPE_USHORT_ID:     T = Context.UnsignedShortTy;    break;
5575     case PREDEF_TYPE_UINT_ID:       T = Context.UnsignedIntTy;      break;
5576     case PREDEF_TYPE_ULONG_ID:      T = Context.UnsignedLongTy;     break;
5577     case PREDEF_TYPE_ULONGLONG_ID:  T = Context.UnsignedLongLongTy; break;
5578     case PREDEF_TYPE_UINT128_ID:    T = Context.UnsignedInt128Ty;   break;
5579     case PREDEF_TYPE_SCHAR_ID:      T = Context.SignedCharTy;       break;
5580     case PREDEF_TYPE_WCHAR_ID:      T = Context.WCharTy;            break;
5581     case PREDEF_TYPE_SHORT_ID:      T = Context.ShortTy;            break;
5582     case PREDEF_TYPE_INT_ID:        T = Context.IntTy;              break;
5583     case PREDEF_TYPE_LONG_ID:       T = Context.LongTy;             break;
5584     case PREDEF_TYPE_LONGLONG_ID:   T = Context.LongLongTy;         break;
5585     case PREDEF_TYPE_INT128_ID:     T = Context.Int128Ty;           break;
5586     case PREDEF_TYPE_HALF_ID:       T = Context.HalfTy;             break;
5587     case PREDEF_TYPE_FLOAT_ID:      T = Context.FloatTy;            break;
5588     case PREDEF_TYPE_DOUBLE_ID:     T = Context.DoubleTy;           break;
5589     case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy;       break;
5590     case PREDEF_TYPE_OVERLOAD_ID:   T = Context.OverloadTy;         break;
5591     case PREDEF_TYPE_BOUND_MEMBER:  T = Context.BoundMemberTy;      break;
5592     case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy;     break;
5593     case PREDEF_TYPE_DEPENDENT_ID:  T = Context.DependentTy;        break;
5594     case PREDEF_TYPE_UNKNOWN_ANY:   T = Context.UnknownAnyTy;       break;
5595     case PREDEF_TYPE_NULLPTR_ID:    T = Context.NullPtrTy;          break;
5596     case PREDEF_TYPE_CHAR16_ID:     T = Context.Char16Ty;           break;
5597     case PREDEF_TYPE_CHAR32_ID:     T = Context.Char32Ty;           break;
5598     case PREDEF_TYPE_OBJC_ID:       T = Context.ObjCBuiltinIdTy;    break;
5599     case PREDEF_TYPE_OBJC_CLASS:    T = Context.ObjCBuiltinClassTy; break;
5600     case PREDEF_TYPE_OBJC_SEL:      T = Context.ObjCBuiltinSelTy;   break;
5601     case PREDEF_TYPE_IMAGE1D_ID:    T = Context.OCLImage1dTy;       break;
5602     case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
5603     case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
5604     case PREDEF_TYPE_IMAGE2D_ID:    T = Context.OCLImage2dTy;       break;
5605     case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
5606     case PREDEF_TYPE_IMAGE3D_ID:    T = Context.OCLImage3dTy;       break;
5607     case PREDEF_TYPE_SAMPLER_ID:    T = Context.OCLSamplerTy;       break;
5608     case PREDEF_TYPE_EVENT_ID:      T = Context.OCLEventTy;         break;
5609     case PREDEF_TYPE_AUTO_DEDUCT:   T = Context.getAutoDeductType(); break;
5610 
5611     case PREDEF_TYPE_AUTO_RREF_DEDUCT:
5612       T = Context.getAutoRRefDeductType();
5613       break;
5614 
5615     case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
5616       T = Context.ARCUnbridgedCastTy;
5617       break;
5618 
5619     case PREDEF_TYPE_VA_LIST_TAG:
5620       T = Context.getVaListTagType();
5621       break;
5622 
5623     case PREDEF_TYPE_BUILTIN_FN:
5624       T = Context.BuiltinFnTy;
5625       break;
5626     }
5627 
5628     assert(!T.isNull() && "Unknown predefined type");
5629     return T.withFastQualifiers(FastQuals);
5630   }
5631 
5632   Index -= NUM_PREDEF_TYPE_IDS;
5633   assert(Index < TypesLoaded.size() && "Type index out-of-range");
5634   if (TypesLoaded[Index].isNull()) {
5635     TypesLoaded[Index] = readTypeRecord(Index);
5636     if (TypesLoaded[Index].isNull())
5637       return QualType();
5638 
5639     TypesLoaded[Index]->setFromAST();
5640     if (DeserializationListener)
5641       DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
5642                                         TypesLoaded[Index]);
5643   }
5644 
5645   return TypesLoaded[Index].withFastQualifiers(FastQuals);
5646 }
5647 
5648 QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
5649   return GetType(getGlobalTypeID(F, LocalID));
5650 }
5651 
5652 serialization::TypeID
5653 ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
5654   unsigned FastQuals = LocalID & Qualifiers::FastMask;
5655   unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
5656 
5657   if (LocalIndex < NUM_PREDEF_TYPE_IDS)
5658     return LocalID;
5659 
5660   ContinuousRangeMap<uint32_t, int, 2>::iterator I
5661     = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
5662   assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
5663 
5664   unsigned GlobalIndex = LocalIndex + I->second;
5665   return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
5666 }
5667 
5668 TemplateArgumentLocInfo
5669 ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
5670                                       TemplateArgument::ArgKind Kind,
5671                                       const RecordData &Record,
5672                                       unsigned &Index) {
5673   switch (Kind) {
5674   case TemplateArgument::Expression:
5675     return ReadExpr(F);
5676   case TemplateArgument::Type:
5677     return GetTypeSourceInfo(F, Record, Index);
5678   case TemplateArgument::Template: {
5679     NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5680                                                                      Index);
5681     SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5682     return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5683                                    SourceLocation());
5684   }
5685   case TemplateArgument::TemplateExpansion: {
5686     NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
5687                                                                      Index);
5688     SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
5689     SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
5690     return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
5691                                    EllipsisLoc);
5692   }
5693   case TemplateArgument::Null:
5694   case TemplateArgument::Integral:
5695   case TemplateArgument::Declaration:
5696   case TemplateArgument::NullPtr:
5697   case TemplateArgument::Pack:
5698     // FIXME: Is this right?
5699     return TemplateArgumentLocInfo();
5700   }
5701   llvm_unreachable("unexpected template argument loc");
5702 }
5703 
5704 TemplateArgumentLoc
5705 ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
5706                                    const RecordData &Record, unsigned &Index) {
5707   TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
5708 
5709   if (Arg.getKind() == TemplateArgument::Expression) {
5710     if (Record[Index++]) // bool InfoHasSameExpr.
5711       return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
5712   }
5713   return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
5714                                                              Record, Index));
5715 }
5716 
5717 const ASTTemplateArgumentListInfo*
5718 ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
5719                                            const RecordData &Record,
5720                                            unsigned &Index) {
5721   SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
5722   SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
5723   unsigned NumArgsAsWritten = Record[Index++];
5724   TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
5725   for (unsigned i = 0; i != NumArgsAsWritten; ++i)
5726     TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
5727   return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
5728 }
5729 
5730 Decl *ASTReader::GetExternalDecl(uint32_t ID) {
5731   return GetDecl(ID);
5732 }
5733 
5734 uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M, const RecordData &Record,
5735                                           unsigned &Idx){
5736   if (Idx >= Record.size())
5737     return 0;
5738 
5739   unsigned LocalID = Record[Idx++];
5740   return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
5741 }
5742 
5743 CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
5744   RecordLocation Loc = getLocalBitOffset(Offset);
5745   BitstreamCursor &Cursor = Loc.F->DeclsCursor;
5746   SavedStreamPosition SavedPosition(Cursor);
5747   Cursor.JumpToBit(Loc.Offset);
5748   ReadingKindTracker ReadingKind(Read_Decl, *this);
5749   RecordData Record;
5750   unsigned Code = Cursor.ReadCode();
5751   unsigned RecCode = Cursor.readRecord(Code, Record);
5752   if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
5753     Error("Malformed AST file: missing C++ base specifiers");
5754     return 0;
5755   }
5756 
5757   unsigned Idx = 0;
5758   unsigned NumBases = Record[Idx++];
5759   void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
5760   CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
5761   for (unsigned I = 0; I != NumBases; ++I)
5762     Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
5763   return Bases;
5764 }
5765 
5766 serialization::DeclID
5767 ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
5768   if (LocalID < NUM_PREDEF_DECL_IDS)
5769     return LocalID;
5770 
5771   ContinuousRangeMap<uint32_t, int, 2>::iterator I
5772     = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
5773   assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
5774 
5775   return LocalID + I->second;
5776 }
5777 
5778 bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
5779                                    ModuleFile &M) const {
5780   GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
5781   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5782   return &M == I->second;
5783 }
5784 
5785 ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
5786   if (!D->isFromASTFile())
5787     return 0;
5788   GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
5789   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5790   return I->second;
5791 }
5792 
5793 SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
5794   if (ID < NUM_PREDEF_DECL_IDS)
5795     return SourceLocation();
5796 
5797   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5798 
5799   if (Index > DeclsLoaded.size()) {
5800     Error("declaration ID out-of-range for AST file");
5801     return SourceLocation();
5802   }
5803 
5804   if (Decl *D = DeclsLoaded[Index])
5805     return D->getLocation();
5806 
5807   unsigned RawLocation = 0;
5808   RecordLocation Rec = DeclCursorForID(ID, RawLocation);
5809   return ReadSourceLocation(*Rec.F, RawLocation);
5810 }
5811 
5812 Decl *ASTReader::GetDecl(DeclID ID) {
5813   if (ID < NUM_PREDEF_DECL_IDS) {
5814     switch ((PredefinedDeclIDs)ID) {
5815     case PREDEF_DECL_NULL_ID:
5816       return 0;
5817 
5818     case PREDEF_DECL_TRANSLATION_UNIT_ID:
5819       return Context.getTranslationUnitDecl();
5820 
5821     case PREDEF_DECL_OBJC_ID_ID:
5822       return Context.getObjCIdDecl();
5823 
5824     case PREDEF_DECL_OBJC_SEL_ID:
5825       return Context.getObjCSelDecl();
5826 
5827     case PREDEF_DECL_OBJC_CLASS_ID:
5828       return Context.getObjCClassDecl();
5829 
5830     case PREDEF_DECL_OBJC_PROTOCOL_ID:
5831       return Context.getObjCProtocolDecl();
5832 
5833     case PREDEF_DECL_INT_128_ID:
5834       return Context.getInt128Decl();
5835 
5836     case PREDEF_DECL_UNSIGNED_INT_128_ID:
5837       return Context.getUInt128Decl();
5838 
5839     case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
5840       return Context.getObjCInstanceTypeDecl();
5841 
5842     case PREDEF_DECL_BUILTIN_VA_LIST_ID:
5843       return Context.getBuiltinVaListDecl();
5844     }
5845   }
5846 
5847   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
5848 
5849   if (Index >= DeclsLoaded.size()) {
5850     assert(0 && "declaration ID out-of-range for AST file");
5851     Error("declaration ID out-of-range for AST file");
5852     return 0;
5853   }
5854 
5855   if (!DeclsLoaded[Index]) {
5856     ReadDeclRecord(ID);
5857     if (DeserializationListener)
5858       DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
5859   }
5860 
5861   return DeclsLoaded[Index];
5862 }
5863 
5864 DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
5865                                                   DeclID GlobalID) {
5866   if (GlobalID < NUM_PREDEF_DECL_IDS)
5867     return GlobalID;
5868 
5869   GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
5870   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
5871   ModuleFile *Owner = I->second;
5872 
5873   llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
5874     = M.GlobalToLocalDeclIDs.find(Owner);
5875   if (Pos == M.GlobalToLocalDeclIDs.end())
5876     return 0;
5877 
5878   return GlobalID - Owner->BaseDeclID + Pos->second;
5879 }
5880 
5881 serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
5882                                             const RecordData &Record,
5883                                             unsigned &Idx) {
5884   if (Idx >= Record.size()) {
5885     Error("Corrupted AST file");
5886     return 0;
5887   }
5888 
5889   return getGlobalDeclID(F, Record[Idx++]);
5890 }
5891 
5892 /// \brief Resolve the offset of a statement into a statement.
5893 ///
5894 /// This operation will read a new statement from the external
5895 /// source each time it is called, and is meant to be used via a
5896 /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
5897 Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
5898   // Switch case IDs are per Decl.
5899   ClearSwitchCaseIDs();
5900 
5901   // Offset here is a global offset across the entire chain.
5902   RecordLocation Loc = getLocalBitOffset(Offset);
5903   Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
5904   return ReadStmtFromStream(*Loc.F);
5905 }
5906 
5907 namespace {
5908   class FindExternalLexicalDeclsVisitor {
5909     ASTReader &Reader;
5910     const DeclContext *DC;
5911     bool (*isKindWeWant)(Decl::Kind);
5912 
5913     SmallVectorImpl<Decl*> &Decls;
5914     bool PredefsVisited[NUM_PREDEF_DECL_IDS];
5915 
5916   public:
5917     FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
5918                                     bool (*isKindWeWant)(Decl::Kind),
5919                                     SmallVectorImpl<Decl*> &Decls)
5920       : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
5921     {
5922       for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
5923         PredefsVisited[I] = false;
5924     }
5925 
5926     static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
5927       if (Preorder)
5928         return false;
5929 
5930       FindExternalLexicalDeclsVisitor *This
5931         = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
5932 
5933       ModuleFile::DeclContextInfosMap::iterator Info
5934         = M.DeclContextInfos.find(This->DC);
5935       if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
5936         return false;
5937 
5938       // Load all of the declaration IDs
5939       for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
5940                                *IDE = ID + Info->second.NumLexicalDecls;
5941            ID != IDE; ++ID) {
5942         if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
5943           continue;
5944 
5945         // Don't add predefined declarations to the lexical context more
5946         // than once.
5947         if (ID->second < NUM_PREDEF_DECL_IDS) {
5948           if (This->PredefsVisited[ID->second])
5949             continue;
5950 
5951           This->PredefsVisited[ID->second] = true;
5952         }
5953 
5954         if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
5955           if (!This->DC->isDeclInLexicalTraversal(D))
5956             This->Decls.push_back(D);
5957         }
5958       }
5959 
5960       return false;
5961     }
5962   };
5963 }
5964 
5965 ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
5966                                          bool (*isKindWeWant)(Decl::Kind),
5967                                          SmallVectorImpl<Decl*> &Decls) {
5968   // There might be lexical decls in multiple modules, for the TU at
5969   // least. Walk all of the modules in the order they were loaded.
5970   FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
5971   ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
5972   ++NumLexicalDeclContextsRead;
5973   return ELR_Success;
5974 }
5975 
5976 namespace {
5977 
5978 class DeclIDComp {
5979   ASTReader &Reader;
5980   ModuleFile &Mod;
5981 
5982 public:
5983   DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
5984 
5985   bool operator()(LocalDeclID L, LocalDeclID R) const {
5986     SourceLocation LHS = getLocation(L);
5987     SourceLocation RHS = getLocation(R);
5988     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5989   }
5990 
5991   bool operator()(SourceLocation LHS, LocalDeclID R) const {
5992     SourceLocation RHS = getLocation(R);
5993     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5994   }
5995 
5996   bool operator()(LocalDeclID L, SourceLocation RHS) const {
5997     SourceLocation LHS = getLocation(L);
5998     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5999   }
6000 
6001   SourceLocation getLocation(LocalDeclID ID) const {
6002     return Reader.getSourceManager().getFileLoc(
6003             Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6004   }
6005 };
6006 
6007 }
6008 
6009 void ASTReader::FindFileRegionDecls(FileID File,
6010                                     unsigned Offset, unsigned Length,
6011                                     SmallVectorImpl<Decl *> &Decls) {
6012   SourceManager &SM = getSourceManager();
6013 
6014   llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6015   if (I == FileDeclIDs.end())
6016     return;
6017 
6018   FileDeclsInfo &DInfo = I->second;
6019   if (DInfo.Decls.empty())
6020     return;
6021 
6022   SourceLocation
6023     BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6024   SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6025 
6026   DeclIDComp DIDComp(*this, *DInfo.Mod);
6027   ArrayRef<serialization::LocalDeclID>::iterator
6028     BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6029                                BeginLoc, DIDComp);
6030   if (BeginIt != DInfo.Decls.begin())
6031     --BeginIt;
6032 
6033   // If we are pointing at a top-level decl inside an objc container, we need
6034   // to backtrack until we find it otherwise we will fail to report that the
6035   // region overlaps with an objc container.
6036   while (BeginIt != DInfo.Decls.begin() &&
6037          GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6038              ->isTopLevelDeclInObjCContainer())
6039     --BeginIt;
6040 
6041   ArrayRef<serialization::LocalDeclID>::iterator
6042     EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6043                              EndLoc, DIDComp);
6044   if (EndIt != DInfo.Decls.end())
6045     ++EndIt;
6046 
6047   for (ArrayRef<serialization::LocalDeclID>::iterator
6048          DIt = BeginIt; DIt != EndIt; ++DIt)
6049     Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6050 }
6051 
6052 namespace {
6053   /// \brief ModuleFile visitor used to perform name lookup into a
6054   /// declaration context.
6055   class DeclContextNameLookupVisitor {
6056     ASTReader &Reader;
6057     SmallVectorImpl<const DeclContext *> &Contexts;
6058     DeclarationName Name;
6059     SmallVectorImpl<NamedDecl *> &Decls;
6060 
6061   public:
6062     DeclContextNameLookupVisitor(ASTReader &Reader,
6063                                  SmallVectorImpl<const DeclContext *> &Contexts,
6064                                  DeclarationName Name,
6065                                  SmallVectorImpl<NamedDecl *> &Decls)
6066       : Reader(Reader), Contexts(Contexts), Name(Name), Decls(Decls) { }
6067 
6068     static bool visit(ModuleFile &M, void *UserData) {
6069       DeclContextNameLookupVisitor *This
6070         = static_cast<DeclContextNameLookupVisitor *>(UserData);
6071 
6072       // Check whether we have any visible declaration information for
6073       // this context in this module.
6074       ModuleFile::DeclContextInfosMap::iterator Info;
6075       bool FoundInfo = false;
6076       for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6077         Info = M.DeclContextInfos.find(This->Contexts[I]);
6078         if (Info != M.DeclContextInfos.end() &&
6079             Info->second.NameLookupTableData) {
6080           FoundInfo = true;
6081           break;
6082         }
6083       }
6084 
6085       if (!FoundInfo)
6086         return false;
6087 
6088       // Look for this name within this module.
6089       const auto &LookupTable =
6090         Info->second.NameLookupTableData;
6091       ASTDeclContextNameLookupTable::iterator Pos
6092         = LookupTable->find(This->Name);
6093       if (Pos == LookupTable->end())
6094         return false;
6095 
6096       bool FoundAnything = false;
6097       ASTDeclContextNameLookupTrait::data_type Data = *Pos;
6098       for (; Data.first != Data.second; ++Data.first) {
6099         NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
6100         if (!ND)
6101           continue;
6102 
6103         if (ND->getDeclName() != This->Name) {
6104           // A name might be null because the decl's redeclarable part is
6105           // currently read before reading its name. The lookup is triggered by
6106           // building that decl (likely indirectly), and so it is later in the
6107           // sense of "already existing" and can be ignored here.
6108           continue;
6109         }
6110 
6111         // Record this declaration.
6112         FoundAnything = true;
6113         This->Decls.push_back(ND);
6114       }
6115 
6116       return FoundAnything;
6117     }
6118   };
6119 }
6120 
6121 /// \brief Retrieve the "definitive" module file for the definition of the
6122 /// given declaration context, if there is one.
6123 ///
6124 /// The "definitive" module file is the only place where we need to look to
6125 /// find information about the declarations within the given declaration
6126 /// context. For example, C++ and Objective-C classes, C structs/unions, and
6127 /// Objective-C protocols, categories, and extensions are all defined in a
6128 /// single place in the source code, so they have definitive module files
6129 /// associated with them. C++ namespaces, on the other hand, can have
6130 /// definitions in multiple different module files.
6131 ///
6132 /// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
6133 /// NDEBUG checking.
6134 static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
6135                                               ASTReader &Reader) {
6136   if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
6137     return Reader.getOwningModuleFile(cast<Decl>(DefDC));
6138 
6139   return 0;
6140 }
6141 
6142 bool
6143 ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6144                                           DeclarationName Name) {
6145   assert(DC->hasExternalVisibleStorage() &&
6146          "DeclContext has no visible decls in storage");
6147   if (!Name)
6148     return false;
6149 
6150   SmallVector<NamedDecl *, 64> Decls;
6151 
6152   // Compute the declaration contexts we need to look into. Multiple such
6153   // declaration contexts occur when two declaration contexts from disjoint
6154   // modules get merged, e.g., when two namespaces with the same name are
6155   // independently defined in separate modules.
6156   SmallVector<const DeclContext *, 2> Contexts;
6157   Contexts.push_back(DC);
6158 
6159   if (DC->isNamespace()) {
6160     MergedDeclsMap::iterator Merged
6161       = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6162     if (Merged != MergedDecls.end()) {
6163       for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6164         Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6165     }
6166   }
6167 
6168   DeclContextNameLookupVisitor Visitor(*this, Contexts, Name, Decls);
6169 
6170   // If we can definitively determine which module file to look into,
6171   // only look there. Otherwise, look in all module files.
6172   ModuleFile *Definitive;
6173   if (Contexts.size() == 1 &&
6174       (Definitive = getDefinitiveModuleFileFor(DC, *this))) {
6175     DeclContextNameLookupVisitor::visit(*Definitive, &Visitor);
6176   } else {
6177     ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
6178   }
6179   ++NumVisibleDeclContextsRead;
6180   SetExternalVisibleDeclsForName(DC, Name, Decls);
6181   return !Decls.empty();
6182 }
6183 
6184 namespace {
6185   /// \brief ModuleFile visitor used to retrieve all visible names in a
6186   /// declaration context.
6187   class DeclContextAllNamesVisitor {
6188     ASTReader &Reader;
6189     SmallVectorImpl<const DeclContext *> &Contexts;
6190     DeclsMap &Decls;
6191     bool VisitAll;
6192 
6193   public:
6194     DeclContextAllNamesVisitor(ASTReader &Reader,
6195                                SmallVectorImpl<const DeclContext *> &Contexts,
6196                                DeclsMap &Decls, bool VisitAll)
6197       : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
6198 
6199     static bool visit(ModuleFile &M, void *UserData) {
6200       DeclContextAllNamesVisitor *This
6201         = static_cast<DeclContextAllNamesVisitor *>(UserData);
6202 
6203       // Check whether we have any visible declaration information for
6204       // this context in this module.
6205       ModuleFile::DeclContextInfosMap::iterator Info;
6206       bool FoundInfo = false;
6207       for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
6208         Info = M.DeclContextInfos.find(This->Contexts[I]);
6209         if (Info != M.DeclContextInfos.end() &&
6210             Info->second.NameLookupTableData) {
6211           FoundInfo = true;
6212           break;
6213         }
6214       }
6215 
6216       if (!FoundInfo)
6217         return false;
6218 
6219       const auto &LookupTable =
6220         Info->second.NameLookupTableData;
6221       bool FoundAnything = false;
6222       for (ASTDeclContextNameLookupTable::data_iterator
6223              I = LookupTable->data_begin(), E = LookupTable->data_end();
6224            I != E;
6225            ++I) {
6226         ASTDeclContextNameLookupTrait::data_type Data = *I;
6227         for (; Data.first != Data.second; ++Data.first) {
6228           NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
6229                                                                  *Data.first);
6230           if (!ND)
6231             continue;
6232 
6233           // Record this declaration.
6234           FoundAnything = true;
6235           This->Decls[ND->getDeclName()].push_back(ND);
6236         }
6237       }
6238 
6239       return FoundAnything && !This->VisitAll;
6240     }
6241   };
6242 }
6243 
6244 void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6245   if (!DC->hasExternalVisibleStorage())
6246     return;
6247   DeclsMap Decls;
6248 
6249   // Compute the declaration contexts we need to look into. Multiple such
6250   // declaration contexts occur when two declaration contexts from disjoint
6251   // modules get merged, e.g., when two namespaces with the same name are
6252   // independently defined in separate modules.
6253   SmallVector<const DeclContext *, 2> Contexts;
6254   Contexts.push_back(DC);
6255 
6256   if (DC->isNamespace()) {
6257     MergedDeclsMap::iterator Merged
6258       = MergedDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
6259     if (Merged != MergedDecls.end()) {
6260       for (unsigned I = 0, N = Merged->second.size(); I != N; ++I)
6261         Contexts.push_back(cast<DeclContext>(GetDecl(Merged->second[I])));
6262     }
6263   }
6264 
6265   DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
6266                                      /*VisitAll=*/DC->isFileContext());
6267   ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
6268   ++NumVisibleDeclContextsRead;
6269 
6270   for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
6271     SetExternalVisibleDeclsForName(DC, I->first, I->second);
6272   }
6273   const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6274 }
6275 
6276 /// \brief Under non-PCH compilation the consumer receives the objc methods
6277 /// before receiving the implementation, and codegen depends on this.
6278 /// We simulate this by deserializing and passing to consumer the methods of the
6279 /// implementation before passing the deserialized implementation decl.
6280 static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6281                                        ASTConsumer *Consumer) {
6282   assert(ImplD && Consumer);
6283 
6284   for (ObjCImplDecl::method_iterator
6285          I = ImplD->meth_begin(), E = ImplD->meth_end(); I != E; ++I)
6286     Consumer->HandleInterestingDecl(DeclGroupRef(*I));
6287 
6288   Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6289 }
6290 
6291 void ASTReader::PassInterestingDeclsToConsumer() {
6292   assert(Consumer);
6293   while (!InterestingDecls.empty()) {
6294     Decl *D = InterestingDecls.front();
6295     InterestingDecls.pop_front();
6296 
6297     PassInterestingDeclToConsumer(D);
6298   }
6299 }
6300 
6301 void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
6302   if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
6303     PassObjCImplDeclToConsumer(ImplD, Consumer);
6304   else
6305     Consumer->HandleInterestingDecl(DeclGroupRef(D));
6306 }
6307 
6308 void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
6309   this->Consumer = Consumer;
6310 
6311   if (!Consumer)
6312     return;
6313 
6314   for (unsigned I = 0, N = EagerlyDeserializedDecls.size(); I != N; ++I) {
6315     // Force deserialization of this decl, which will cause it to be queued for
6316     // passing to the consumer.
6317     GetDecl(EagerlyDeserializedDecls[I]);
6318   }
6319   EagerlyDeserializedDecls.clear();
6320 
6321   PassInterestingDeclsToConsumer();
6322 }
6323 
6324 void ASTReader::PrintStats() {
6325   std::fprintf(stderr, "*** AST File Statistics:\n");
6326 
6327   unsigned NumTypesLoaded
6328     = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
6329                                       QualType());
6330   unsigned NumDeclsLoaded
6331     = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
6332                                       (Decl *)0);
6333   unsigned NumIdentifiersLoaded
6334     = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
6335                                             IdentifiersLoaded.end(),
6336                                             (IdentifierInfo *)0);
6337   unsigned NumMacrosLoaded
6338     = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
6339                                        MacrosLoaded.end(),
6340                                        (MacroInfo *)0);
6341   unsigned NumSelectorsLoaded
6342     = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
6343                                           SelectorsLoaded.end(),
6344                                           Selector());
6345 
6346   if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
6347     std::fprintf(stderr, "  %u/%u source location entries read (%f%%)\n",
6348                  NumSLocEntriesRead, TotalNumSLocEntries,
6349                  ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
6350   if (!TypesLoaded.empty())
6351     std::fprintf(stderr, "  %u/%u types read (%f%%)\n",
6352                  NumTypesLoaded, (unsigned)TypesLoaded.size(),
6353                  ((float)NumTypesLoaded/TypesLoaded.size() * 100));
6354   if (!DeclsLoaded.empty())
6355     std::fprintf(stderr, "  %u/%u declarations read (%f%%)\n",
6356                  NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
6357                  ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
6358   if (!IdentifiersLoaded.empty())
6359     std::fprintf(stderr, "  %u/%u identifiers read (%f%%)\n",
6360                  NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
6361                  ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
6362   if (!MacrosLoaded.empty())
6363     std::fprintf(stderr, "  %u/%u macros read (%f%%)\n",
6364                  NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
6365                  ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
6366   if (!SelectorsLoaded.empty())
6367     std::fprintf(stderr, "  %u/%u selectors read (%f%%)\n",
6368                  NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
6369                  ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
6370   if (TotalNumStatements)
6371     std::fprintf(stderr, "  %u/%u statements read (%f%%)\n",
6372                  NumStatementsRead, TotalNumStatements,
6373                  ((float)NumStatementsRead/TotalNumStatements * 100));
6374   if (TotalNumMacros)
6375     std::fprintf(stderr, "  %u/%u macros read (%f%%)\n",
6376                  NumMacrosRead, TotalNumMacros,
6377                  ((float)NumMacrosRead/TotalNumMacros * 100));
6378   if (TotalLexicalDeclContexts)
6379     std::fprintf(stderr, "  %u/%u lexical declcontexts read (%f%%)\n",
6380                  NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
6381                  ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
6382                   * 100));
6383   if (TotalVisibleDeclContexts)
6384     std::fprintf(stderr, "  %u/%u visible declcontexts read (%f%%)\n",
6385                  NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
6386                  ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
6387                   * 100));
6388   if (TotalNumMethodPoolEntries) {
6389     std::fprintf(stderr, "  %u/%u method pool entries read (%f%%)\n",
6390                  NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
6391                  ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
6392                   * 100));
6393   }
6394   if (NumMethodPoolLookups) {
6395     std::fprintf(stderr, "  %u/%u method pool lookups succeeded (%f%%)\n",
6396                  NumMethodPoolHits, NumMethodPoolLookups,
6397                  ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
6398   }
6399   if (NumMethodPoolTableLookups) {
6400     std::fprintf(stderr, "  %u/%u method pool table lookups succeeded (%f%%)\n",
6401                  NumMethodPoolTableHits, NumMethodPoolTableLookups,
6402                  ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
6403                   * 100.0));
6404   }
6405 
6406   if (NumIdentifierLookupHits) {
6407     std::fprintf(stderr,
6408                  "  %u / %u identifier table lookups succeeded (%f%%)\n",
6409                  NumIdentifierLookupHits, NumIdentifierLookups,
6410                  (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
6411   }
6412 
6413   if (GlobalIndex) {
6414     std::fprintf(stderr, "\n");
6415     GlobalIndex->printStats();
6416   }
6417 
6418   std::fprintf(stderr, "\n");
6419   dump();
6420   std::fprintf(stderr, "\n");
6421 }
6422 
6423 template<typename Key, typename ModuleFile, unsigned InitialCapacity>
6424 static void
6425 dumpModuleIDMap(StringRef Name,
6426                 const ContinuousRangeMap<Key, ModuleFile *,
6427                                          InitialCapacity> &Map) {
6428   if (Map.begin() == Map.end())
6429     return;
6430 
6431   typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
6432   llvm::errs() << Name << ":\n";
6433   for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
6434        I != IEnd; ++I) {
6435     llvm::errs() << "  " << I->first << " -> " << I->second->FileName
6436       << "\n";
6437   }
6438 }
6439 
6440 void ASTReader::dump() {
6441   llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
6442   dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
6443   dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
6444   dumpModuleIDMap("Global type map", GlobalTypeMap);
6445   dumpModuleIDMap("Global declaration map", GlobalDeclMap);
6446   dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
6447   dumpModuleIDMap("Global macro map", GlobalMacroMap);
6448   dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
6449   dumpModuleIDMap("Global selector map", GlobalSelectorMap);
6450   dumpModuleIDMap("Global preprocessed entity map",
6451                   GlobalPreprocessedEntityMap);
6452 
6453   llvm::errs() << "\n*** PCH/Modules Loaded:";
6454   for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
6455                                        MEnd = ModuleMgr.end();
6456        M != MEnd; ++M)
6457     (*M)->dump();
6458 }
6459 
6460 /// Return the amount of memory used by memory buffers, breaking down
6461 /// by heap-backed versus mmap'ed memory.
6462 void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
6463   for (ModuleConstIterator I = ModuleMgr.begin(),
6464       E = ModuleMgr.end(); I != E; ++I) {
6465     if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
6466       size_t bytes = buf->getBufferSize();
6467       switch (buf->getBufferKind()) {
6468         case llvm::MemoryBuffer::MemoryBuffer_Malloc:
6469           sizes.malloc_bytes += bytes;
6470           break;
6471         case llvm::MemoryBuffer::MemoryBuffer_MMap:
6472           sizes.mmap_bytes += bytes;
6473           break;
6474       }
6475     }
6476   }
6477 }
6478 
6479 void ASTReader::InitializeSema(Sema &S) {
6480   SemaObj = &S;
6481   S.addExternalSource(this);
6482 
6483   // Makes sure any declarations that were deserialized "too early"
6484   // still get added to the identifier's declaration chains.
6485   for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
6486     pushExternalDeclIntoScope(PreloadedDecls[I],
6487                               PreloadedDecls[I]->getDeclName());
6488   }
6489   PreloadedDecls.clear();
6490 
6491   // FIXME: What happens if these are changed by a module import?
6492   if (!FPPragmaOptions.empty()) {
6493     assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
6494     SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
6495   }
6496 
6497   // FIXME: What happens if these are changed by a module import?
6498   if (!OpenCLExtensions.empty()) {
6499     unsigned I = 0;
6500 #define OPENCLEXT(nm)  SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
6501 #include "clang/Basic/OpenCLExtensions.def"
6502 
6503     assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
6504   }
6505 
6506   UpdateSema();
6507 }
6508 
6509 void ASTReader::UpdateSema() {
6510   assert(SemaObj && "no Sema to update");
6511 
6512   // Load the offsets of the declarations that Sema references.
6513   // They will be lazily deserialized when needed.
6514   if (!SemaDeclRefs.empty()) {
6515     assert(SemaDeclRefs.size() % 2 == 0);
6516     for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
6517       if (!SemaObj->StdNamespace)
6518         SemaObj->StdNamespace = SemaDeclRefs[I];
6519       if (!SemaObj->StdBadAlloc)
6520         SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
6521     }
6522     SemaDeclRefs.clear();
6523   }
6524 }
6525 
6526 IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
6527   // Note that we are loading an identifier.
6528   Deserializing AnIdentifier(this);
6529   StringRef Name(NameStart, NameEnd - NameStart);
6530 
6531   // If there is a global index, look there first to determine which modules
6532   // provably do not have any results for this identifier.
6533   GlobalModuleIndex::HitSet Hits;
6534   GlobalModuleIndex::HitSet *HitsPtr = 0;
6535   if (!loadGlobalIndex()) {
6536     if (GlobalIndex->lookupIdentifier(Name, Hits)) {
6537       HitsPtr = &Hits;
6538     }
6539   }
6540   IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
6541                                   NumIdentifierLookups,
6542                                   NumIdentifierLookupHits);
6543   ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
6544   IdentifierInfo *II = Visitor.getIdentifierInfo();
6545   markIdentifierUpToDate(II);
6546   return II;
6547 }
6548 
6549 namespace clang {
6550   /// \brief An identifier-lookup iterator that enumerates all of the
6551   /// identifiers stored within a set of AST files.
6552   class ASTIdentifierIterator : public IdentifierIterator {
6553     /// \brief The AST reader whose identifiers are being enumerated.
6554     const ASTReader &Reader;
6555 
6556     /// \brief The current index into the chain of AST files stored in
6557     /// the AST reader.
6558     unsigned Index;
6559 
6560     /// \brief The current position within the identifier lookup table
6561     /// of the current AST file.
6562     ASTIdentifierLookupTable::key_iterator Current;
6563 
6564     /// \brief The end position within the identifier lookup table of
6565     /// the current AST file.
6566     ASTIdentifierLookupTable::key_iterator End;
6567 
6568   public:
6569     explicit ASTIdentifierIterator(const ASTReader &Reader);
6570 
6571     virtual StringRef Next();
6572   };
6573 }
6574 
6575 ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
6576   : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
6577   ASTIdentifierLookupTable *IdTable
6578     = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
6579   Current = IdTable->key_begin();
6580   End = IdTable->key_end();
6581 }
6582 
6583 StringRef ASTIdentifierIterator::Next() {
6584   while (Current == End) {
6585     // If we have exhausted all of our AST files, we're done.
6586     if (Index == 0)
6587       return StringRef();
6588 
6589     --Index;
6590     ASTIdentifierLookupTable *IdTable
6591       = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
6592         IdentifierLookupTable;
6593     Current = IdTable->key_begin();
6594     End = IdTable->key_end();
6595   }
6596 
6597   // We have any identifiers remaining in the current AST file; return
6598   // the next one.
6599   StringRef Result = *Current;
6600   ++Current;
6601   return Result;
6602 }
6603 
6604 IdentifierIterator *ASTReader::getIdentifiers() {
6605   if (!loadGlobalIndex())
6606     return GlobalIndex->createIdentifierIterator();
6607 
6608   return new ASTIdentifierIterator(*this);
6609 }
6610 
6611 namespace clang { namespace serialization {
6612   class ReadMethodPoolVisitor {
6613     ASTReader &Reader;
6614     Selector Sel;
6615     unsigned PriorGeneration;
6616     unsigned InstanceBits;
6617     unsigned FactoryBits;
6618     SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
6619     SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
6620 
6621   public:
6622     ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
6623                           unsigned PriorGeneration)
6624       : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
6625         InstanceBits(0), FactoryBits(0) { }
6626 
6627     static bool visit(ModuleFile &M, void *UserData) {
6628       ReadMethodPoolVisitor *This
6629         = static_cast<ReadMethodPoolVisitor *>(UserData);
6630 
6631       if (!M.SelectorLookupTable)
6632         return false;
6633 
6634       // If we've already searched this module file, skip it now.
6635       if (M.Generation <= This->PriorGeneration)
6636         return true;
6637 
6638       ++This->Reader.NumMethodPoolTableLookups;
6639       ASTSelectorLookupTable *PoolTable
6640         = (ASTSelectorLookupTable*)M.SelectorLookupTable;
6641       ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
6642       if (Pos == PoolTable->end())
6643         return false;
6644 
6645       ++This->Reader.NumMethodPoolTableHits;
6646       ++This->Reader.NumSelectorsRead;
6647       // FIXME: Not quite happy with the statistics here. We probably should
6648       // disable this tracking when called via LoadSelector.
6649       // Also, should entries without methods count as misses?
6650       ++This->Reader.NumMethodPoolEntriesRead;
6651       ASTSelectorLookupTrait::data_type Data = *Pos;
6652       if (This->Reader.DeserializationListener)
6653         This->Reader.DeserializationListener->SelectorRead(Data.ID,
6654                                                            This->Sel);
6655 
6656       This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
6657       This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
6658       This->InstanceBits = Data.InstanceBits;
6659       This->FactoryBits = Data.FactoryBits;
6660       return true;
6661     }
6662 
6663     /// \brief Retrieve the instance methods found by this visitor.
6664     ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
6665       return InstanceMethods;
6666     }
6667 
6668     /// \brief Retrieve the instance methods found by this visitor.
6669     ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
6670       return FactoryMethods;
6671     }
6672 
6673     unsigned getInstanceBits() const { return InstanceBits; }
6674     unsigned getFactoryBits() const { return FactoryBits; }
6675   };
6676 } } // end namespace clang::serialization
6677 
6678 /// \brief Add the given set of methods to the method list.
6679 static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
6680                              ObjCMethodList &List) {
6681   for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
6682     S.addMethodToGlobalList(&List, Methods[I]);
6683   }
6684 }
6685 
6686 void ASTReader::ReadMethodPool(Selector Sel) {
6687   // Get the selector generation and update it to the current generation.
6688   unsigned &Generation = SelectorGeneration[Sel];
6689   unsigned PriorGeneration = Generation;
6690   Generation = CurrentGeneration;
6691 
6692   // Search for methods defined with this selector.
6693   ++NumMethodPoolLookups;
6694   ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
6695   ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
6696 
6697   if (Visitor.getInstanceMethods().empty() &&
6698       Visitor.getFactoryMethods().empty())
6699     return;
6700 
6701   ++NumMethodPoolHits;
6702 
6703   if (!getSema())
6704     return;
6705 
6706   Sema &S = *getSema();
6707   Sema::GlobalMethodPool::iterator Pos
6708     = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
6709 
6710   addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
6711   addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
6712   Pos->second.first.setBits(Visitor.getInstanceBits());
6713   Pos->second.second.setBits(Visitor.getFactoryBits());
6714 }
6715 
6716 void ASTReader::ReadKnownNamespaces(
6717                           SmallVectorImpl<NamespaceDecl *> &Namespaces) {
6718   Namespaces.clear();
6719 
6720   for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
6721     if (NamespaceDecl *Namespace
6722                 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
6723       Namespaces.push_back(Namespace);
6724   }
6725 }
6726 
6727 void ASTReader::ReadUndefinedButUsed(
6728                         llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
6729   for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
6730     NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
6731     SourceLocation Loc =
6732         SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
6733     Undefined.insert(std::make_pair(D, Loc));
6734   }
6735 }
6736 
6737 void ASTReader::ReadTentativeDefinitions(
6738                   SmallVectorImpl<VarDecl *> &TentativeDefs) {
6739   for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
6740     VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
6741     if (Var)
6742       TentativeDefs.push_back(Var);
6743   }
6744   TentativeDefinitions.clear();
6745 }
6746 
6747 void ASTReader::ReadUnusedFileScopedDecls(
6748                                SmallVectorImpl<const DeclaratorDecl *> &Decls) {
6749   for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
6750     DeclaratorDecl *D
6751       = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
6752     if (D)
6753       Decls.push_back(D);
6754   }
6755   UnusedFileScopedDecls.clear();
6756 }
6757 
6758 void ASTReader::ReadDelegatingConstructors(
6759                                  SmallVectorImpl<CXXConstructorDecl *> &Decls) {
6760   for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
6761     CXXConstructorDecl *D
6762       = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
6763     if (D)
6764       Decls.push_back(D);
6765   }
6766   DelegatingCtorDecls.clear();
6767 }
6768 
6769 void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
6770   for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
6771     TypedefNameDecl *D
6772       = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
6773     if (D)
6774       Decls.push_back(D);
6775   }
6776   ExtVectorDecls.clear();
6777 }
6778 
6779 void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
6780   for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6781     CXXRecordDecl *D
6782       = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
6783     if (D)
6784       Decls.push_back(D);
6785   }
6786   DynamicClasses.clear();
6787 }
6788 
6789 void
6790 ASTReader::ReadLocallyScopedExternCDecls(SmallVectorImpl<NamedDecl *> &Decls) {
6791   for (unsigned I = 0, N = LocallyScopedExternCDecls.size(); I != N; ++I) {
6792     NamedDecl *D
6793       = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternCDecls[I]));
6794     if (D)
6795       Decls.push_back(D);
6796   }
6797   LocallyScopedExternCDecls.clear();
6798 }
6799 
6800 void ASTReader::ReadReferencedSelectors(
6801        SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
6802   if (ReferencedSelectorsData.empty())
6803     return;
6804 
6805   // If there are @selector references added them to its pool. This is for
6806   // implementation of -Wselector.
6807   unsigned int DataSize = ReferencedSelectorsData.size()-1;
6808   unsigned I = 0;
6809   while (I < DataSize) {
6810     Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
6811     SourceLocation SelLoc
6812       = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
6813     Sels.push_back(std::make_pair(Sel, SelLoc));
6814   }
6815   ReferencedSelectorsData.clear();
6816 }
6817 
6818 void ASTReader::ReadWeakUndeclaredIdentifiers(
6819        SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
6820   if (WeakUndeclaredIdentifiers.empty())
6821     return;
6822 
6823   for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
6824     IdentifierInfo *WeakId
6825       = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6826     IdentifierInfo *AliasId
6827       = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
6828     SourceLocation Loc
6829       = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
6830     bool Used = WeakUndeclaredIdentifiers[I++];
6831     WeakInfo WI(AliasId, Loc);
6832     WI.setUsed(Used);
6833     WeakIDs.push_back(std::make_pair(WeakId, WI));
6834   }
6835   WeakUndeclaredIdentifiers.clear();
6836 }
6837 
6838 void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
6839   for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
6840     ExternalVTableUse VT;
6841     VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
6842     VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
6843     VT.DefinitionRequired = VTableUses[Idx++];
6844     VTables.push_back(VT);
6845   }
6846 
6847   VTableUses.clear();
6848 }
6849 
6850 void ASTReader::ReadPendingInstantiations(
6851        SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
6852   for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
6853     ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
6854     SourceLocation Loc
6855       = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
6856 
6857     Pending.push_back(std::make_pair(D, Loc));
6858   }
6859   PendingInstantiations.clear();
6860 }
6861 
6862 void ASTReader::ReadLateParsedTemplates(
6863     llvm::DenseMap<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
6864   for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
6865        /* In loop */) {
6866     FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
6867 
6868     LateParsedTemplate *LT = new LateParsedTemplate;
6869     LT->D = GetDecl(LateParsedTemplates[Idx++]);
6870 
6871     ModuleFile *F = getOwningModuleFile(LT->D);
6872     assert(F && "No module");
6873 
6874     unsigned TokN = LateParsedTemplates[Idx++];
6875     LT->Toks.reserve(TokN);
6876     for (unsigned T = 0; T < TokN; ++T)
6877       LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
6878 
6879     LPTMap[FD] = LT;
6880   }
6881 
6882   LateParsedTemplates.clear();
6883 }
6884 
6885 void ASTReader::LoadSelector(Selector Sel) {
6886   // It would be complicated to avoid reading the methods anyway. So don't.
6887   ReadMethodPool(Sel);
6888 }
6889 
6890 void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
6891   assert(ID && "Non-zero identifier ID required");
6892   assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
6893   IdentifiersLoaded[ID - 1] = II;
6894   if (DeserializationListener)
6895     DeserializationListener->IdentifierRead(ID, II);
6896 }
6897 
6898 /// \brief Set the globally-visible declarations associated with the given
6899 /// identifier.
6900 ///
6901 /// If the AST reader is currently in a state where the given declaration IDs
6902 /// cannot safely be resolved, they are queued until it is safe to resolve
6903 /// them.
6904 ///
6905 /// \param II an IdentifierInfo that refers to one or more globally-visible
6906 /// declarations.
6907 ///
6908 /// \param DeclIDs the set of declaration IDs with the name @p II that are
6909 /// visible at global scope.
6910 ///
6911 /// \param Decls if non-null, this vector will be populated with the set of
6912 /// deserialized declarations. These declarations will not be pushed into
6913 /// scope.
6914 void
6915 ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
6916                               const SmallVectorImpl<uint32_t> &DeclIDs,
6917                                    SmallVectorImpl<Decl *> *Decls) {
6918   if (NumCurrentElementsDeserializing && !Decls) {
6919     PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
6920     return;
6921   }
6922 
6923   for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
6924     NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
6925     if (SemaObj) {
6926       // If we're simply supposed to record the declarations, do so now.
6927       if (Decls) {
6928         Decls->push_back(D);
6929         continue;
6930       }
6931 
6932       // Introduce this declaration into the translation-unit scope
6933       // and add it to the declaration chain for this identifier, so
6934       // that (unqualified) name lookup will find it.
6935       pushExternalDeclIntoScope(D, II);
6936     } else {
6937       // Queue this declaration so that it will be added to the
6938       // translation unit scope and identifier's declaration chain
6939       // once a Sema object is known.
6940       PreloadedDecls.push_back(D);
6941     }
6942   }
6943 }
6944 
6945 IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
6946   if (ID == 0)
6947     return 0;
6948 
6949   if (IdentifiersLoaded.empty()) {
6950     Error("no identifier table in AST file");
6951     return 0;
6952   }
6953 
6954   ID -= 1;
6955   if (!IdentifiersLoaded[ID]) {
6956     GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
6957     assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
6958     ModuleFile *M = I->second;
6959     unsigned Index = ID - M->BaseIdentifierID;
6960     const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
6961 
6962     // All of the strings in the AST file are preceded by a 16-bit length.
6963     // Extract that 16-bit length to avoid having to execute strlen().
6964     // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
6965     //  unsigned integers.  This is important to avoid integer overflow when
6966     //  we cast them to 'unsigned'.
6967     const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
6968     unsigned StrLen = (((unsigned) StrLenPtr[0])
6969                        | (((unsigned) StrLenPtr[1]) << 8)) - 1;
6970     IdentifiersLoaded[ID]
6971       = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
6972     if (DeserializationListener)
6973       DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
6974   }
6975 
6976   return IdentifiersLoaded[ID];
6977 }
6978 
6979 IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
6980   return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
6981 }
6982 
6983 IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
6984   if (LocalID < NUM_PREDEF_IDENT_IDS)
6985     return LocalID;
6986 
6987   ContinuousRangeMap<uint32_t, int, 2>::iterator I
6988     = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
6989   assert(I != M.IdentifierRemap.end()
6990          && "Invalid index into identifier index remap");
6991 
6992   return LocalID + I->second;
6993 }
6994 
6995 MacroInfo *ASTReader::getMacro(MacroID ID) {
6996   if (ID == 0)
6997     return 0;
6998 
6999   if (MacrosLoaded.empty()) {
7000     Error("no macro table in AST file");
7001     return 0;
7002   }
7003 
7004   ID -= NUM_PREDEF_MACRO_IDS;
7005   if (!MacrosLoaded[ID]) {
7006     GlobalMacroMapType::iterator I
7007       = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7008     assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7009     ModuleFile *M = I->second;
7010     unsigned Index = ID - M->BaseMacroID;
7011     MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
7012 
7013     if (DeserializationListener)
7014       DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7015                                          MacrosLoaded[ID]);
7016   }
7017 
7018   return MacrosLoaded[ID];
7019 }
7020 
7021 MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7022   if (LocalID < NUM_PREDEF_MACRO_IDS)
7023     return LocalID;
7024 
7025   ContinuousRangeMap<uint32_t, int, 2>::iterator I
7026     = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7027   assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7028 
7029   return LocalID + I->second;
7030 }
7031 
7032 serialization::SubmoduleID
7033 ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7034   if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7035     return LocalID;
7036 
7037   ContinuousRangeMap<uint32_t, int, 2>::iterator I
7038     = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
7039   assert(I != M.SubmoduleRemap.end()
7040          && "Invalid index into submodule index remap");
7041 
7042   return LocalID + I->second;
7043 }
7044 
7045 Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7046   if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7047     assert(GlobalID == 0 && "Unhandled global submodule ID");
7048     return 0;
7049   }
7050 
7051   if (GlobalID > SubmodulesLoaded.size()) {
7052     Error("submodule ID out of range in AST file");
7053     return 0;
7054   }
7055 
7056   return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7057 }
7058 
7059 Module *ASTReader::getModule(unsigned ID) {
7060   return getSubmodule(ID);
7061 }
7062 
7063 Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7064   return DecodeSelector(getGlobalSelectorID(M, LocalID));
7065 }
7066 
7067 Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7068   if (ID == 0)
7069     return Selector();
7070 
7071   if (ID > SelectorsLoaded.size()) {
7072     Error("selector ID out of range in AST file");
7073     return Selector();
7074   }
7075 
7076   if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
7077     // Load this selector from the selector table.
7078     GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7079     assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7080     ModuleFile &M = *I->second;
7081     ASTSelectorLookupTrait Trait(*this, M);
7082     unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7083     SelectorsLoaded[ID - 1] =
7084       Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7085     if (DeserializationListener)
7086       DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7087   }
7088 
7089   return SelectorsLoaded[ID - 1];
7090 }
7091 
7092 Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7093   return DecodeSelector(ID);
7094 }
7095 
7096 uint32_t ASTReader::GetNumExternalSelectors() {
7097   // ID 0 (the null selector) is considered an external selector.
7098   return getTotalNumSelectors() + 1;
7099 }
7100 
7101 serialization::SelectorID
7102 ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7103   if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7104     return LocalID;
7105 
7106   ContinuousRangeMap<uint32_t, int, 2>::iterator I
7107     = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
7108   assert(I != M.SelectorRemap.end()
7109          && "Invalid index into selector index remap");
7110 
7111   return LocalID + I->second;
7112 }
7113 
7114 DeclarationName
7115 ASTReader::ReadDeclarationName(ModuleFile &F,
7116                                const RecordData &Record, unsigned &Idx) {
7117   DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7118   switch (Kind) {
7119   case DeclarationName::Identifier:
7120     return DeclarationName(GetIdentifierInfo(F, Record, Idx));
7121 
7122   case DeclarationName::ObjCZeroArgSelector:
7123   case DeclarationName::ObjCOneArgSelector:
7124   case DeclarationName::ObjCMultiArgSelector:
7125     return DeclarationName(ReadSelector(F, Record, Idx));
7126 
7127   case DeclarationName::CXXConstructorName:
7128     return Context.DeclarationNames.getCXXConstructorName(
7129                           Context.getCanonicalType(readType(F, Record, Idx)));
7130 
7131   case DeclarationName::CXXDestructorName:
7132     return Context.DeclarationNames.getCXXDestructorName(
7133                           Context.getCanonicalType(readType(F, Record, Idx)));
7134 
7135   case DeclarationName::CXXConversionFunctionName:
7136     return Context.DeclarationNames.getCXXConversionFunctionName(
7137                           Context.getCanonicalType(readType(F, Record, Idx)));
7138 
7139   case DeclarationName::CXXOperatorName:
7140     return Context.DeclarationNames.getCXXOperatorName(
7141                                        (OverloadedOperatorKind)Record[Idx++]);
7142 
7143   case DeclarationName::CXXLiteralOperatorName:
7144     return Context.DeclarationNames.getCXXLiteralOperatorName(
7145                                        GetIdentifierInfo(F, Record, Idx));
7146 
7147   case DeclarationName::CXXUsingDirective:
7148     return DeclarationName::getUsingDirectiveName();
7149   }
7150 
7151   llvm_unreachable("Invalid NameKind!");
7152 }
7153 
7154 void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
7155                                        DeclarationNameLoc &DNLoc,
7156                                        DeclarationName Name,
7157                                       const RecordData &Record, unsigned &Idx) {
7158   switch (Name.getNameKind()) {
7159   case DeclarationName::CXXConstructorName:
7160   case DeclarationName::CXXDestructorName:
7161   case DeclarationName::CXXConversionFunctionName:
7162     DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
7163     break;
7164 
7165   case DeclarationName::CXXOperatorName:
7166     DNLoc.CXXOperatorName.BeginOpNameLoc
7167         = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7168     DNLoc.CXXOperatorName.EndOpNameLoc
7169         = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7170     break;
7171 
7172   case DeclarationName::CXXLiteralOperatorName:
7173     DNLoc.CXXLiteralOperatorName.OpNameLoc
7174         = ReadSourceLocation(F, Record, Idx).getRawEncoding();
7175     break;
7176 
7177   case DeclarationName::Identifier:
7178   case DeclarationName::ObjCZeroArgSelector:
7179   case DeclarationName::ObjCOneArgSelector:
7180   case DeclarationName::ObjCMultiArgSelector:
7181   case DeclarationName::CXXUsingDirective:
7182     break;
7183   }
7184 }
7185 
7186 void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
7187                                         DeclarationNameInfo &NameInfo,
7188                                       const RecordData &Record, unsigned &Idx) {
7189   NameInfo.setName(ReadDeclarationName(F, Record, Idx));
7190   NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
7191   DeclarationNameLoc DNLoc;
7192   ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
7193   NameInfo.setInfo(DNLoc);
7194 }
7195 
7196 void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
7197                                   const RecordData &Record, unsigned &Idx) {
7198   Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
7199   unsigned NumTPLists = Record[Idx++];
7200   Info.NumTemplParamLists = NumTPLists;
7201   if (NumTPLists) {
7202     Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
7203     for (unsigned i=0; i != NumTPLists; ++i)
7204       Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
7205   }
7206 }
7207 
7208 TemplateName
7209 ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
7210                             unsigned &Idx) {
7211   TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
7212   switch (Kind) {
7213   case TemplateName::Template:
7214       return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
7215 
7216   case TemplateName::OverloadedTemplate: {
7217     unsigned size = Record[Idx++];
7218     UnresolvedSet<8> Decls;
7219     while (size--)
7220       Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
7221 
7222     return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
7223   }
7224 
7225   case TemplateName::QualifiedTemplate: {
7226     NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7227     bool hasTemplKeyword = Record[Idx++];
7228     TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
7229     return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
7230   }
7231 
7232   case TemplateName::DependentTemplate: {
7233     NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
7234     if (Record[Idx++])  // isIdentifier
7235       return Context.getDependentTemplateName(NNS,
7236                                                GetIdentifierInfo(F, Record,
7237                                                                  Idx));
7238     return Context.getDependentTemplateName(NNS,
7239                                          (OverloadedOperatorKind)Record[Idx++]);
7240   }
7241 
7242   case TemplateName::SubstTemplateTemplateParm: {
7243     TemplateTemplateParmDecl *param
7244       = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7245     if (!param) return TemplateName();
7246     TemplateName replacement = ReadTemplateName(F, Record, Idx);
7247     return Context.getSubstTemplateTemplateParm(param, replacement);
7248   }
7249 
7250   case TemplateName::SubstTemplateTemplateParmPack: {
7251     TemplateTemplateParmDecl *Param
7252       = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
7253     if (!Param)
7254       return TemplateName();
7255 
7256     TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
7257     if (ArgPack.getKind() != TemplateArgument::Pack)
7258       return TemplateName();
7259 
7260     return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
7261   }
7262   }
7263 
7264   llvm_unreachable("Unhandled template name kind!");
7265 }
7266 
7267 TemplateArgument
7268 ASTReader::ReadTemplateArgument(ModuleFile &F,
7269                                 const RecordData &Record, unsigned &Idx) {
7270   TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
7271   switch (Kind) {
7272   case TemplateArgument::Null:
7273     return TemplateArgument();
7274   case TemplateArgument::Type:
7275     return TemplateArgument(readType(F, Record, Idx));
7276   case TemplateArgument::Declaration: {
7277     ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
7278     bool ForReferenceParam = Record[Idx++];
7279     return TemplateArgument(D, ForReferenceParam);
7280   }
7281   case TemplateArgument::NullPtr:
7282     return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
7283   case TemplateArgument::Integral: {
7284     llvm::APSInt Value = ReadAPSInt(Record, Idx);
7285     QualType T = readType(F, Record, Idx);
7286     return TemplateArgument(Context, Value, T);
7287   }
7288   case TemplateArgument::Template:
7289     return TemplateArgument(ReadTemplateName(F, Record, Idx));
7290   case TemplateArgument::TemplateExpansion: {
7291     TemplateName Name = ReadTemplateName(F, Record, Idx);
7292     Optional<unsigned> NumTemplateExpansions;
7293     if (unsigned NumExpansions = Record[Idx++])
7294       NumTemplateExpansions = NumExpansions - 1;
7295     return TemplateArgument(Name, NumTemplateExpansions);
7296   }
7297   case TemplateArgument::Expression:
7298     return TemplateArgument(ReadExpr(F));
7299   case TemplateArgument::Pack: {
7300     unsigned NumArgs = Record[Idx++];
7301     TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
7302     for (unsigned I = 0; I != NumArgs; ++I)
7303       Args[I] = ReadTemplateArgument(F, Record, Idx);
7304     return TemplateArgument(Args, NumArgs);
7305   }
7306   }
7307 
7308   llvm_unreachable("Unhandled template argument kind!");
7309 }
7310 
7311 TemplateParameterList *
7312 ASTReader::ReadTemplateParameterList(ModuleFile &F,
7313                                      const RecordData &Record, unsigned &Idx) {
7314   SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
7315   SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
7316   SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
7317 
7318   unsigned NumParams = Record[Idx++];
7319   SmallVector<NamedDecl *, 16> Params;
7320   Params.reserve(NumParams);
7321   while (NumParams--)
7322     Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
7323 
7324   TemplateParameterList* TemplateParams =
7325     TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
7326                                   Params.data(), Params.size(), RAngleLoc);
7327   return TemplateParams;
7328 }
7329 
7330 void
7331 ASTReader::
7332 ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
7333                          ModuleFile &F, const RecordData &Record,
7334                          unsigned &Idx) {
7335   unsigned NumTemplateArgs = Record[Idx++];
7336   TemplArgs.reserve(NumTemplateArgs);
7337   while (NumTemplateArgs--)
7338     TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
7339 }
7340 
7341 /// \brief Read a UnresolvedSet structure.
7342 void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
7343                                   const RecordData &Record, unsigned &Idx) {
7344   unsigned NumDecls = Record[Idx++];
7345   Set.reserve(Context, NumDecls);
7346   while (NumDecls--) {
7347     DeclID ID = ReadDeclID(F, Record, Idx);
7348     AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
7349     Set.addLazyDecl(Context, ID, AS);
7350   }
7351 }
7352 
7353 CXXBaseSpecifier
7354 ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
7355                                 const RecordData &Record, unsigned &Idx) {
7356   bool isVirtual = static_cast<bool>(Record[Idx++]);
7357   bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
7358   AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
7359   bool inheritConstructors = static_cast<bool>(Record[Idx++]);
7360   TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
7361   SourceRange Range = ReadSourceRange(F, Record, Idx);
7362   SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
7363   CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
7364                           EllipsisLoc);
7365   Result.setInheritConstructors(inheritConstructors);
7366   return Result;
7367 }
7368 
7369 std::pair<CXXCtorInitializer **, unsigned>
7370 ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
7371                                    unsigned &Idx) {
7372   CXXCtorInitializer **CtorInitializers = 0;
7373   unsigned NumInitializers = Record[Idx++];
7374   if (NumInitializers) {
7375     CtorInitializers
7376         = new (Context) CXXCtorInitializer*[NumInitializers];
7377     for (unsigned i=0; i != NumInitializers; ++i) {
7378       TypeSourceInfo *TInfo = 0;
7379       bool IsBaseVirtual = false;
7380       FieldDecl *Member = 0;
7381       IndirectFieldDecl *IndirectMember = 0;
7382 
7383       CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
7384       switch (Type) {
7385       case CTOR_INITIALIZER_BASE:
7386         TInfo = GetTypeSourceInfo(F, Record, Idx);
7387         IsBaseVirtual = Record[Idx++];
7388         break;
7389 
7390       case CTOR_INITIALIZER_DELEGATING:
7391         TInfo = GetTypeSourceInfo(F, Record, Idx);
7392         break;
7393 
7394        case CTOR_INITIALIZER_MEMBER:
7395         Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
7396         break;
7397 
7398        case CTOR_INITIALIZER_INDIRECT_MEMBER:
7399         IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
7400         break;
7401       }
7402 
7403       SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
7404       Expr *Init = ReadExpr(F);
7405       SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
7406       SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
7407       bool IsWritten = Record[Idx++];
7408       unsigned SourceOrderOrNumArrayIndices;
7409       SmallVector<VarDecl *, 8> Indices;
7410       if (IsWritten) {
7411         SourceOrderOrNumArrayIndices = Record[Idx++];
7412       } else {
7413         SourceOrderOrNumArrayIndices = Record[Idx++];
7414         Indices.reserve(SourceOrderOrNumArrayIndices);
7415         for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
7416           Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
7417       }
7418 
7419       CXXCtorInitializer *BOMInit;
7420       if (Type == CTOR_INITIALIZER_BASE) {
7421         BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, IsBaseVirtual,
7422                                              LParenLoc, Init, RParenLoc,
7423                                              MemberOrEllipsisLoc);
7424       } else if (Type == CTOR_INITIALIZER_DELEGATING) {
7425         BOMInit = new (Context) CXXCtorInitializer(Context, TInfo, LParenLoc,
7426                                                    Init, RParenLoc);
7427       } else if (IsWritten) {
7428         if (Member)
7429           BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
7430                                                LParenLoc, Init, RParenLoc);
7431         else
7432           BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7433                                                MemberOrEllipsisLoc, LParenLoc,
7434                                                Init, RParenLoc);
7435       } else {
7436         if (IndirectMember) {
7437           assert(Indices.empty() && "Indirect field improperly initialized");
7438           BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
7439                                                      MemberOrEllipsisLoc, LParenLoc,
7440                                                      Init, RParenLoc);
7441         } else {
7442           BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
7443                                                LParenLoc, Init, RParenLoc,
7444                                                Indices.data(), Indices.size());
7445         }
7446       }
7447 
7448       if (IsWritten)
7449         BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
7450       CtorInitializers[i] = BOMInit;
7451     }
7452   }
7453 
7454   return std::make_pair(CtorInitializers, NumInitializers);
7455 }
7456 
7457 NestedNameSpecifier *
7458 ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
7459                                    const RecordData &Record, unsigned &Idx) {
7460   unsigned N = Record[Idx++];
7461   NestedNameSpecifier *NNS = 0, *Prev = 0;
7462   for (unsigned I = 0; I != N; ++I) {
7463     NestedNameSpecifier::SpecifierKind Kind
7464       = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7465     switch (Kind) {
7466     case NestedNameSpecifier::Identifier: {
7467       IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7468       NNS = NestedNameSpecifier::Create(Context, Prev, II);
7469       break;
7470     }
7471 
7472     case NestedNameSpecifier::Namespace: {
7473       NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7474       NNS = NestedNameSpecifier::Create(Context, Prev, NS);
7475       break;
7476     }
7477 
7478     case NestedNameSpecifier::NamespaceAlias: {
7479       NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7480       NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
7481       break;
7482     }
7483 
7484     case NestedNameSpecifier::TypeSpec:
7485     case NestedNameSpecifier::TypeSpecWithTemplate: {
7486       const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
7487       if (!T)
7488         return 0;
7489 
7490       bool Template = Record[Idx++];
7491       NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
7492       break;
7493     }
7494 
7495     case NestedNameSpecifier::Global: {
7496       NNS = NestedNameSpecifier::GlobalSpecifier(Context);
7497       // No associated value, and there can't be a prefix.
7498       break;
7499     }
7500     }
7501     Prev = NNS;
7502   }
7503   return NNS;
7504 }
7505 
7506 NestedNameSpecifierLoc
7507 ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
7508                                       unsigned &Idx) {
7509   unsigned N = Record[Idx++];
7510   NestedNameSpecifierLocBuilder Builder;
7511   for (unsigned I = 0; I != N; ++I) {
7512     NestedNameSpecifier::SpecifierKind Kind
7513       = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
7514     switch (Kind) {
7515     case NestedNameSpecifier::Identifier: {
7516       IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
7517       SourceRange Range = ReadSourceRange(F, Record, Idx);
7518       Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
7519       break;
7520     }
7521 
7522     case NestedNameSpecifier::Namespace: {
7523       NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
7524       SourceRange Range = ReadSourceRange(F, Record, Idx);
7525       Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
7526       break;
7527     }
7528 
7529     case NestedNameSpecifier::NamespaceAlias: {
7530       NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
7531       SourceRange Range = ReadSourceRange(F, Record, Idx);
7532       Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
7533       break;
7534     }
7535 
7536     case NestedNameSpecifier::TypeSpec:
7537     case NestedNameSpecifier::TypeSpecWithTemplate: {
7538       bool Template = Record[Idx++];
7539       TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
7540       if (!T)
7541         return NestedNameSpecifierLoc();
7542       SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7543 
7544       // FIXME: 'template' keyword location not saved anywhere, so we fake it.
7545       Builder.Extend(Context,
7546                      Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
7547                      T->getTypeLoc(), ColonColonLoc);
7548       break;
7549     }
7550 
7551     case NestedNameSpecifier::Global: {
7552       SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
7553       Builder.MakeGlobal(Context, ColonColonLoc);
7554       break;
7555     }
7556     }
7557   }
7558 
7559   return Builder.getWithLocInContext(Context);
7560 }
7561 
7562 SourceRange
7563 ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
7564                            unsigned &Idx) {
7565   SourceLocation beg = ReadSourceLocation(F, Record, Idx);
7566   SourceLocation end = ReadSourceLocation(F, Record, Idx);
7567   return SourceRange(beg, end);
7568 }
7569 
7570 /// \brief Read an integral value
7571 llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
7572   unsigned BitWidth = Record[Idx++];
7573   unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
7574   llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
7575   Idx += NumWords;
7576   return Result;
7577 }
7578 
7579 /// \brief Read a signed integral value
7580 llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
7581   bool isUnsigned = Record[Idx++];
7582   return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
7583 }
7584 
7585 /// \brief Read a floating-point value
7586 llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
7587                                      const llvm::fltSemantics &Sem,
7588                                      unsigned &Idx) {
7589   return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
7590 }
7591 
7592 // \brief Read a string
7593 std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
7594   unsigned Len = Record[Idx++];
7595   std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
7596   Idx += Len;
7597   return Result;
7598 }
7599 
7600 VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
7601                                          unsigned &Idx) {
7602   unsigned Major = Record[Idx++];
7603   unsigned Minor = Record[Idx++];
7604   unsigned Subminor = Record[Idx++];
7605   if (Minor == 0)
7606     return VersionTuple(Major);
7607   if (Subminor == 0)
7608     return VersionTuple(Major, Minor - 1);
7609   return VersionTuple(Major, Minor - 1, Subminor - 1);
7610 }
7611 
7612 CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
7613                                           const RecordData &Record,
7614                                           unsigned &Idx) {
7615   CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
7616   return CXXTemporary::Create(Context, Decl);
7617 }
7618 
7619 DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
7620   return Diag(CurrentImportLoc, DiagID);
7621 }
7622 
7623 DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
7624   return Diags.Report(Loc, DiagID);
7625 }
7626 
7627 /// \brief Retrieve the identifier table associated with the
7628 /// preprocessor.
7629 IdentifierTable &ASTReader::getIdentifierTable() {
7630   return PP.getIdentifierTable();
7631 }
7632 
7633 /// \brief Record that the given ID maps to the given switch-case
7634 /// statement.
7635 void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
7636   assert((*CurrSwitchCaseStmts)[ID] == 0 &&
7637          "Already have a SwitchCase with this ID");
7638   (*CurrSwitchCaseStmts)[ID] = SC;
7639 }
7640 
7641 /// \brief Retrieve the switch-case statement with the given ID.
7642 SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
7643   assert((*CurrSwitchCaseStmts)[ID] != 0 && "No SwitchCase with this ID");
7644   return (*CurrSwitchCaseStmts)[ID];
7645 }
7646 
7647 void ASTReader::ClearSwitchCaseIDs() {
7648   CurrSwitchCaseStmts->clear();
7649 }
7650 
7651 void ASTReader::ReadComments() {
7652   std::vector<RawComment *> Comments;
7653   for (SmallVectorImpl<std::pair<BitstreamCursor,
7654                                  serialization::ModuleFile *> >::iterator
7655        I = CommentsCursors.begin(),
7656        E = CommentsCursors.end();
7657        I != E; ++I) {
7658     BitstreamCursor &Cursor = I->first;
7659     serialization::ModuleFile &F = *I->second;
7660     SavedStreamPosition SavedPosition(Cursor);
7661 
7662     RecordData Record;
7663     while (true) {
7664       llvm::BitstreamEntry Entry =
7665         Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
7666 
7667       switch (Entry.Kind) {
7668       case llvm::BitstreamEntry::SubBlock: // Handled for us already.
7669       case llvm::BitstreamEntry::Error:
7670         Error("malformed block record in AST file");
7671         return;
7672       case llvm::BitstreamEntry::EndBlock:
7673         goto NextCursor;
7674       case llvm::BitstreamEntry::Record:
7675         // The interesting case.
7676         break;
7677       }
7678 
7679       // Read a record.
7680       Record.clear();
7681       switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
7682       case COMMENTS_RAW_COMMENT: {
7683         unsigned Idx = 0;
7684         SourceRange SR = ReadSourceRange(F, Record, Idx);
7685         RawComment::CommentKind Kind =
7686             (RawComment::CommentKind) Record[Idx++];
7687         bool IsTrailingComment = Record[Idx++];
7688         bool IsAlmostTrailingComment = Record[Idx++];
7689         Comments.push_back(new (Context) RawComment(
7690             SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
7691             Context.getLangOpts().CommentOpts.ParseAllComments));
7692         break;
7693       }
7694       }
7695     }
7696   NextCursor:;
7697   }
7698   Context.Comments.addCommentsToFront(Comments);
7699 }
7700 
7701 void ASTReader::finishPendingActions() {
7702   while (!PendingIdentifierInfos.empty() || !PendingDeclChains.empty() ||
7703          !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
7704          !PendingOdrMergeChecks.empty()) {
7705     // If any identifiers with corresponding top-level declarations have
7706     // been loaded, load those declarations now.
7707     typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
7708       TopLevelDeclsMap;
7709     TopLevelDeclsMap TopLevelDecls;
7710 
7711     while (!PendingIdentifierInfos.empty()) {
7712       // FIXME: std::move
7713       IdentifierInfo *II = PendingIdentifierInfos.back().first;
7714       SmallVector<uint32_t, 4> DeclIDs = PendingIdentifierInfos.back().second;
7715       PendingIdentifierInfos.pop_back();
7716 
7717       SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
7718     }
7719 
7720     // Load pending declaration chains.
7721     for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
7722       loadPendingDeclChain(PendingDeclChains[I]);
7723       PendingDeclChainsKnown.erase(PendingDeclChains[I]);
7724     }
7725     PendingDeclChains.clear();
7726 
7727     // Make the most recent of the top-level declarations visible.
7728     for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
7729            TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
7730       IdentifierInfo *II = TLD->first;
7731       for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
7732         pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
7733       }
7734     }
7735 
7736     // Load any pending macro definitions.
7737     for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
7738       IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
7739       SmallVector<PendingMacroInfo, 2> GlobalIDs;
7740       GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
7741       // Initialize the macro history from chained-PCHs ahead of module imports.
7742       for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
7743            ++IDIdx) {
7744         const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7745         if (Info.M->Kind != MK_Module)
7746           resolvePendingMacro(II, Info);
7747       }
7748       // Handle module imports.
7749       for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
7750            ++IDIdx) {
7751         const PendingMacroInfo &Info = GlobalIDs[IDIdx];
7752         if (Info.M->Kind == MK_Module)
7753           resolvePendingMacro(II, Info);
7754       }
7755     }
7756     PendingMacroIDs.clear();
7757 
7758     // Wire up the DeclContexts for Decls that we delayed setting until
7759     // recursive loading is completed.
7760     while (!PendingDeclContextInfos.empty()) {
7761       PendingDeclContextInfo Info = PendingDeclContextInfos.front();
7762       PendingDeclContextInfos.pop_front();
7763       DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
7764       DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
7765       Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
7766     }
7767 
7768     // For each declaration from a merged context, check that the canonical
7769     // definition of that context also contains a declaration of the same
7770     // entity.
7771     while (!PendingOdrMergeChecks.empty()) {
7772       NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
7773 
7774       // FIXME: Skip over implicit declarations for now. This matters for things
7775       // like implicitly-declared special member functions. This isn't entirely
7776       // correct; we can end up with multiple unmerged declarations of the same
7777       // implicit entity.
7778       if (D->isImplicit())
7779         continue;
7780 
7781       DeclContext *CanonDef = D->getDeclContext();
7782       DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
7783 
7784       bool Found = false;
7785       const Decl *DCanon = D->getCanonicalDecl();
7786 
7787       llvm::SmallVector<const NamedDecl*, 4> Candidates;
7788       for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
7789            !Found && I != E; ++I) {
7790         for (auto RI : (*I)->redecls()) {
7791           if (RI->getLexicalDeclContext() == CanonDef) {
7792             // This declaration is present in the canonical definition. If it's
7793             // in the same redecl chain, it's the one we're looking for.
7794             if (RI->getCanonicalDecl() == DCanon)
7795               Found = true;
7796             else
7797               Candidates.push_back(cast<NamedDecl>(RI));
7798             break;
7799           }
7800         }
7801       }
7802 
7803       if (!Found) {
7804         D->setInvalidDecl();
7805 
7806         Module *CanonDefModule = cast<Decl>(CanonDef)->getOwningModule();
7807         Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
7808           << D << D->getOwningModule()->getFullModuleName()
7809           << CanonDef << !CanonDefModule
7810           << (CanonDefModule ? CanonDefModule->getFullModuleName() : "");
7811 
7812         if (Candidates.empty())
7813           Diag(cast<Decl>(CanonDef)->getLocation(),
7814                diag::note_module_odr_violation_no_possible_decls) << D;
7815         else {
7816           for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
7817             Diag(Candidates[I]->getLocation(),
7818                  diag::note_module_odr_violation_possible_decl)
7819               << Candidates[I];
7820         }
7821       }
7822     }
7823   }
7824 
7825   // If we deserialized any C++ or Objective-C class definitions, any
7826   // Objective-C protocol definitions, or any redeclarable templates, make sure
7827   // that all redeclarations point to the definitions. Note that this can only
7828   // happen now, after the redeclaration chains have been fully wired.
7829   for (llvm::SmallPtrSet<Decl *, 4>::iterator D = PendingDefinitions.begin(),
7830                                            DEnd = PendingDefinitions.end();
7831        D != DEnd; ++D) {
7832     if (TagDecl *TD = dyn_cast<TagDecl>(*D)) {
7833       if (const TagType *TagT = dyn_cast<TagType>(TD->TypeForDecl)) {
7834         // Make sure that the TagType points at the definition.
7835         const_cast<TagType*>(TagT)->decl = TD;
7836       }
7837 
7838       if (auto RD = dyn_cast<CXXRecordDecl>(*D)) {
7839         for (auto R : RD->redecls())
7840           cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
7841 
7842       }
7843 
7844       continue;
7845     }
7846 
7847     if (auto ID = dyn_cast<ObjCInterfaceDecl>(*D)) {
7848       // Make sure that the ObjCInterfaceType points at the definition.
7849       const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
7850         ->Decl = ID;
7851 
7852       for (auto R : ID->redecls())
7853         R->Data = ID->Data;
7854 
7855       continue;
7856     }
7857 
7858     if (auto PD = dyn_cast<ObjCProtocolDecl>(*D)) {
7859       for (auto R : PD->redecls())
7860         R->Data = PD->Data;
7861 
7862       continue;
7863     }
7864 
7865     auto RTD = cast<RedeclarableTemplateDecl>(*D)->getCanonicalDecl();
7866     for (auto R : RTD->redecls())
7867       R->Common = RTD->Common;
7868   }
7869   PendingDefinitions.clear();
7870 
7871   // Load the bodies of any functions or methods we've encountered. We do
7872   // this now (delayed) so that we can be sure that the declaration chains
7873   // have been fully wired up.
7874   for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
7875                                PBEnd = PendingBodies.end();
7876        PB != PBEnd; ++PB) {
7877     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
7878       // FIXME: Check for =delete/=default?
7879       // FIXME: Complain about ODR violations here?
7880       if (!getContext().getLangOpts().Modules || !FD->hasBody())
7881         FD->setLazyBody(PB->second);
7882       continue;
7883     }
7884 
7885     ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
7886     if (!getContext().getLangOpts().Modules || !MD->hasBody())
7887       MD->setLazyBody(PB->second);
7888   }
7889   PendingBodies.clear();
7890 }
7891 
7892 void ASTReader::FinishedDeserializing() {
7893   assert(NumCurrentElementsDeserializing &&
7894          "FinishedDeserializing not paired with StartedDeserializing");
7895   if (NumCurrentElementsDeserializing == 1) {
7896     // We decrease NumCurrentElementsDeserializing only after pending actions
7897     // are finished, to avoid recursively re-calling finishPendingActions().
7898     finishPendingActions();
7899   }
7900   --NumCurrentElementsDeserializing;
7901 
7902   if (NumCurrentElementsDeserializing == 0 &&
7903       Consumer && !PassingDeclsToConsumer) {
7904     // Guard variable to avoid recursively redoing the process of passing
7905     // decls to consumer.
7906     SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
7907                                                      true);
7908 
7909     while (!InterestingDecls.empty()) {
7910       // We are not in recursive loading, so it's safe to pass the "interesting"
7911       // decls to the consumer.
7912       Decl *D = InterestingDecls.front();
7913       InterestingDecls.pop_front();
7914       PassInterestingDeclToConsumer(D);
7915     }
7916   }
7917 }
7918 
7919 void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
7920   D = D->getMostRecentDecl();
7921 
7922   if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
7923     SemaObj->TUScope->AddDecl(D);
7924   } else if (SemaObj->TUScope) {
7925     // Adding the decl to IdResolver may have failed because it was already in
7926     // (even though it was not added in scope). If it is already in, make sure
7927     // it gets in the scope as well.
7928     if (std::find(SemaObj->IdResolver.begin(Name),
7929                   SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
7930       SemaObj->TUScope->AddDecl(D);
7931   }
7932 }
7933 
7934 ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
7935                      StringRef isysroot, bool DisableValidation,
7936                      bool AllowASTWithCompilerErrors,
7937                      bool AllowConfigurationMismatch,
7938                      bool ValidateSystemInputs,
7939                      bool UseGlobalIndex)
7940   : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
7941     SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
7942     Diags(PP.getDiagnostics()), SemaObj(0), PP(PP), Context(Context),
7943     Consumer(0), ModuleMgr(PP.getFileManager()),
7944     isysroot(isysroot), DisableValidation(DisableValidation),
7945     AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
7946     AllowConfigurationMismatch(AllowConfigurationMismatch),
7947     ValidateSystemInputs(ValidateSystemInputs),
7948     UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
7949     CurrentGeneration(0), CurrSwitchCaseStmts(&SwitchCaseStmts),
7950     NumSLocEntriesRead(0), TotalNumSLocEntries(0),
7951     NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
7952     TotalNumMacros(0), NumIdentifierLookups(0), NumIdentifierLookupHits(0),
7953     NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
7954     NumMethodPoolLookups(0), NumMethodPoolHits(0),
7955     NumMethodPoolTableLookups(0), NumMethodPoolTableHits(0),
7956     TotalNumMethodPoolEntries(0),
7957     NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
7958     NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
7959     TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
7960     PassingDeclsToConsumer(false),
7961     NumCXXBaseSpecifiersLoaded(0), ReadingKind(Read_None)
7962 {
7963   SourceMgr.setExternalSLocEntrySource(this);
7964 }
7965 
7966 ASTReader::~ASTReader() {
7967   for (DeclContextVisibleUpdatesPending::iterator
7968            I = PendingVisibleUpdates.begin(),
7969            E = PendingVisibleUpdates.end();
7970        I != E; ++I) {
7971     for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
7972                                              F = I->second.end();
7973          J != F; ++J)
7974       delete J->first;
7975   }
7976 }
7977