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