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