ASTReader.cpp revision 26d43cd3a088d4f1f1645328db3b73afbc7eaa61
15d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)//===--- ASTReader.cpp - AST File Reader ------------------------*- C++ -*-===//
25d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)//
35d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)//                     The LLVM Compiler Infrastructure
45d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)//
55d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)// This file is distributed under the University of Illinois Open Source
65d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)// License. See LICENSE.TXT for details.
7010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)//
85d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)//===----------------------------------------------------------------------===//
9010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)//
10010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)//  This file defines the ASTReader class, which reads AST files.
11010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)//
12cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)//===----------------------------------------------------------------------===//
13a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
145d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "clang/Serialization/ASTReader.h"
15010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include "clang/Serialization/ASTDeserializationListener.h"
165d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "clang/Serialization/ModuleManager.h"
17a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "ASTCommon.h"
18a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "ASTReaderInternals.h"
19a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/Frontend/FrontendDiagnostic.h"
205d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "clang/Frontend/Utils.h"
21010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include "clang/Sema/Sema.h"
22010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include "clang/Sema/Scope.h"
235f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)#include "clang/AST/ASTConsumer.h"
24010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include "clang/AST/ASTContext.h"
25010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include "clang/AST/DeclTemplate.h"
26a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/AST/Expr.h"
275d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "clang/AST/ExprCXX.h"
285d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "clang/AST/NestedNameSpecifier.h"
29a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/AST/Type.h"
30a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/AST/TypeLocVisitor.h"
315d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "clang/Lex/MacroInfo.h"
325d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "clang/Lex/PreprocessingRecord.h"
335d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "clang/Lex/Preprocessor.h"
34a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/Lex/HeaderSearch.h"
35a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/Basic/OnDiskHashTable.h"
36a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/Basic/SourceManager.h"
37a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/Basic/SourceManagerInternals.h"
385d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "clang/Basic/FileManager.h"
39010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include "clang/Basic/FileSystemStatCache.h"
40010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include "clang/Basic/TargetInfo.h"
41010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include "clang/Basic/Version.h"
42010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include "clang/Basic/VersionTuple.h"
43010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include "llvm/ADT/StringExtras.h"
44010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include "llvm/Bitcode/BitstreamReader.h"
45010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include "llvm/Support/MemoryBuffer.h"
46010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include "llvm/Support/ErrorHandling.h"
47010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include "llvm/Support/FileSystem.h"
48010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include "llvm/Support/Path.h"
49010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include "llvm/Support/system_error.h"
50010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include <algorithm>
51010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include <iterator>
52010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include <cstdio>
53010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include <sys/stat.h>
54010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)
55010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)using namespace clang;
565d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)using namespace clang::serialization;
575d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)using namespace clang::serialization::reader;
585d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
595d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)//===----------------------------------------------------------------------===//
605d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)// PCH validator implementation
615d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)//===----------------------------------------------------------------------===//
625d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
635d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)ASTReaderListener::~ASTReaderListener() {}
645d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
655d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)bool
665d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
675d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  const LangOptions &PPLangOpts = PP.getLangOptions();
68a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#define PARSE_LANGOPT_BENIGN(Option)
69a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#define PARSE_LANGOPT_IMPORTANT(Option, DiagID)                    \
70a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  if (PPLangOpts.Option != LangOpts.Option) {                      \
71a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option;   \
72a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    return true;                                                   \
73a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  }
74a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
75a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_BENIGN(Trigraphs);
76a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_BENIGN(BCPLComment);
77a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_BENIGN(DollarIdents);
78a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_BENIGN(AsmPreprocessor);
79a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
80a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(GNUKeywords, diag::warn_pch_gnu_keywords);
81a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_BENIGN(ImplicitInt);
82a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch  PARSE_LANGOPT_BENIGN(Digraphs);
83a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_BENIGN(HexFloats);
84a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
85a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(C1X, diag::warn_pch_c1x);
86a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
87a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_BENIGN(MSCVersion);
88a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
89a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
90a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_BENIGN(CXXOperatorName);
91a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
92a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
93a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
94a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI2, diag::warn_pch_nonfragile_abi2);
95a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(AppleKext, diag::warn_pch_apple_kext);
96a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(ObjCDefaultSynthProperties,
97a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)                          diag::warn_pch_objc_auto_properties);
98a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch  PARSE_LANGOPT_BENIGN(ObjCInferRelatedResultType)
99a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(NoConstantCFStrings,
100a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)                          diag::warn_pch_no_constant_cfstrings);
101a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_BENIGN(PascalStrings);
102a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_BENIGN(WritableStrings);
103a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
104a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)                          diag::warn_pch_lax_vector_conversions);
105a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
106a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
107a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(ObjCExceptions, diag::warn_pch_objc_exceptions);
108a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(CXXExceptions, diag::warn_pch_cxx_exceptions);
109a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(SjLjExceptions, diag::warn_pch_sjlj_exceptions);
110a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(MSBitfields, diag::warn_pch_ms_bitfields);
111a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
112a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
113a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
114a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
115a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)                          diag::warn_pch_thread_safe_statics);
116a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
117a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
118a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_BENIGN(EmitAllDecls);
119a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
120a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_BENIGN(getSignedOverflowBehavior());
121a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
122a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)                          diag::warn_pch_heinous_extensions);
123a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  // FIXME: Most of the options below are benign if the macro wasn't
124a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  // used. Unfortunately, this means that a PCH compiled without
125a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  // optimization can't be used with optimization turned on, even
126a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  // though the only thing that changes is whether __OPTIMIZE__ was
127a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  // defined... but if __OPTIMIZE__ never showed up in the header, it
128a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  // doesn't matter. We could consider making this some special kind
129a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  // of check.
130a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch  PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
131a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch  PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
132a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch  PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
133a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch  PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
134a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
135a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
136a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(Deprecated, diag::warn_pch_deprecated);
137a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
138a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
139a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(ShortWChar, diag::warn_pch_short_wchar);
140a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(ShortEnums, diag::warn_pch_short_enums);
141a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
142a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch    Reader.Diag(diag::warn_pch_gc_mode)
143a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch      << LangOpts.getGCMode() << PPLangOpts.getGCMode();
144a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch    return true;
145a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch  }
146a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_BENIGN(getVisibilityMode());
147a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
148a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)                          diag::warn_pch_stack_protector);
149a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_BENIGN(InstantiationDepth);
150a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
151a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_IMPORTANT(CUDA, diag::warn_pch_cuda);
152a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_BENIGN(CatchUndefined);
153a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PARSE_LANGOPT_BENIGN(DefaultFPContract);
154a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch  PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
155a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch  PARSE_LANGOPT_BENIGN(SpellChecking);
156a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch  PARSE_LANGOPT_IMPORTANT(ObjCAutoRefCount, diag::warn_pch_auto_ref_count);
157a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch#undef PARSE_LANGOPT_IMPORTANT
158a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch#undef PARSE_LANGOPT_BENIGN
159a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch
160a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  return false;
161a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)}
162a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
163a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)bool PCHValidator::ReadTargetTriple(StringRef Triple) {
164a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch  if (Triple == PP.getTargetInfo().getTriple().str())
165a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch    return false;
166a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch
167a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch  Reader.Diag(diag::warn_pch_target_triple)
168a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch    << Triple << PP.getTargetInfo().getTriple().str();
169a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch  return true;
170a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)}
171a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
172a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)namespace {
173a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  struct EmptyStringRef {
174a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    bool operator ()(StringRef r) const { return r.empty(); }
175a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  };
1765d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  struct EmptyBlock {
1775d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    bool operator ()(const PCHPredefinesBlock &r) const {return r.Data.empty();}
1785d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  };
1795d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)}
180010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)
181010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)static bool EqualConcatenations(SmallVector<StringRef, 2> L,
182010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)                                PCHPredefinesBlocks R) {
183010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  // First, sum up the lengths.
184010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  unsigned LL = 0, RL = 0;
185010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  for (unsigned I = 0, N = L.size(); I != N; ++I) {
186010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    LL += L[I].size();
187010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  }
188010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  for (unsigned I = 0, N = R.size(); I != N; ++I) {
189010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    RL += R[I].Data.size();
190010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  }
191010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  if (LL != RL)
192010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    return false;
193010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  if (LL == 0 && RL == 0)
194010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    return true;
195010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)
196010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  // Kick out empty parts, they confuse the algorithm below.
197010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  L.erase(std::remove_if(L.begin(), L.end(), EmptyStringRef()), L.end());
198010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  R.erase(std::remove_if(R.begin(), R.end(), EmptyBlock()), R.end());
199010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)
200010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  // Do it the hard way. At this point, both vectors must be non-empty.
201010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  StringRef LR = L[0], RR = R[0].Data;
202010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  unsigned LI = 0, RI = 0, LN = L.size(), RN = R.size();
203010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  (void) RN;
204010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  for (;;) {
205010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    // Compare the current pieces.
206010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    if (LR.size() == RR.size()) {
207010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      // If they're the same length, it's pretty easy.
208010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      if (LR != RR)
209010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)        return false;
210010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      // Both pieces are done, advance.
211010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      ++LI;
212010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      ++RI;
213010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      // If either string is done, they're both done, since they're the same
214010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      // length.
215010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      if (LI == LN) {
216010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)        assert(RI == RN && "Strings not the same length after all?");
217010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)        return true;
218010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      }
219010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      LR = L[LI];
220010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      RR = R[RI].Data;
221010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    } else if (LR.size() < RR.size()) {
222010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      // Right piece is longer.
223010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      if (!RR.startswith(LR))
224010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)        return false;
225010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      ++LI;
226010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      assert(LI != LN && "Strings not the same length after all?");
227010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      RR = RR.substr(LR.size());
22846d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)      LR = L[LI];
22946d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)    } else {
23046d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)      // Left piece is longer.
231010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      if (!LR.startswith(RR))
232010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)        return false;
2335d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)      ++RI;
2345d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)      assert(RI != RN && "Strings not the same length after all?");
2355d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)      LR = LR.substr(RR.size());
2365d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)      RR = R[RI].Data;
2375d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    }
2385d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  }
2395d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)}
2405d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
241a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)static std::pair<FileID, StringRef::size_type>
242a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)FindMacro(const PCHPredefinesBlocks &Buffers, StringRef MacroDef) {
243a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  std::pair<FileID, StringRef::size_type> Res;
244010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  for (unsigned I = 0, N = Buffers.size(); I != N; ++I) {
245010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    Res.second = Buffers[I].Data.find(MacroDef);
246cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)    if (Res.second != StringRef::npos) {
247cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)      Res.first = Buffers[I].BufferID;
248010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      break;
249010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    }
250010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  }
251010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  return Res;
252010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)}
253010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)
254010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)bool PCHValidator::ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
255010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)                                        StringRef OriginalFileName,
256010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)                                        std::string &SuggestedPredefines,
257010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)                                        FileManager &FileMgr) {
258010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  // We are in the context of an implicit include, so the predefines buffer will
259010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  // have a #include entry for the PCH file itself (as normalized by the
260010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  // preprocessor initialization). Find it and skip over it in the checking
261010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  // below.
262cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)  llvm::SmallString<256> PCHInclude;
263cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)  PCHInclude += "#include \"";
264010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  PCHInclude += NormalizeDashIncludePath(OriginalFileName, FileMgr);
2655d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  PCHInclude += "\"\n";
2665d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  std::pair<StringRef,StringRef> Split =
2675d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    StringRef(PP.getPredefines()).split(PCHInclude.str());
268010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  StringRef Left =  Split.first, Right = Split.second;
269010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  if (Left == PP.getPredefines()) {
270010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    Error("Missing PCH include entry!");
271010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    return true;
2725d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  }
2735d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
2745d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  // If the concatenation of all the PCH buffers is equal to the adjusted
2755d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  // command line, we're done.
276a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  SmallVector<StringRef, 2> CommandLine;
277a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  CommandLine.push_back(Left);
278a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  CommandLine.push_back(Right);
279a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  if (EqualConcatenations(CommandLine, Buffers))
280a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    return false;
281a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch
282a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  SourceManager &SourceMgr = PP.getSourceManager();
283a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
284a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  // The predefines buffers are different. Determine what the differences are,
285a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  // and whether they require us to reject the PCH file.
286a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  SmallVector<StringRef, 8> PCHLines;
287a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch  for (unsigned I = 0, N = Buffers.size(); I != N; ++I)
288a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch    Buffers[I].Data.split(PCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
289a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
290a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  SmallVector<StringRef, 8> CmdLineLines;
291a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Left.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
292a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
293a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  // Pick out implicit #includes after the PCH and don't consider them for
294a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  // validation; we will insert them into SuggestedPredefines so that the
295010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  // preprocessor includes them.
296010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  std::string IncludesAfterPCH;
297a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  SmallVector<StringRef, 8> AfterPCHLines;
298010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  Right.split(AfterPCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
299010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  for (unsigned i = 0, e = AfterPCHLines.size(); i != e; ++i) {
300010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    if (AfterPCHLines[i].startswith("#include ")) {
301010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      IncludesAfterPCH += AfterPCHLines[i];
302010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      IncludesAfterPCH += '\n';
303010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    } else {
304010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      CmdLineLines.push_back(AfterPCHLines[i]);
305010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    }
306010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  }
307010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)
308010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  // Make sure we add the includes last into SuggestedPredefines before we
309010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  // exit this function.
310010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  struct AddIncludesRAII {
311010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    std::string &SuggestedPredefines;
312010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    std::string &IncludesAfterPCH;
313010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)
314010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    AddIncludesRAII(std::string &SuggestedPredefines,
315a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)                    std::string &IncludesAfterPCH)
316a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)      : SuggestedPredefines(SuggestedPredefines),
3175d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)        IncludesAfterPCH(IncludesAfterPCH) { }
3185d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    ~AddIncludesRAII() {
3195d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)      SuggestedPredefines += IncludesAfterPCH;
320cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)    }
3215d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  } AddIncludes(SuggestedPredefines, IncludesAfterPCH);
3225d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
3235d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  // Sort both sets of predefined buffer lines, since we allow some extra
3245d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  // definitions and they may appear at any point in the output.
325010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  std::sort(CmdLineLines.begin(), CmdLineLines.end());
326010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  std::sort(PCHLines.begin(), PCHLines.end());
327010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)
328010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  // Determine which predefines that were used to build the PCH file are missing
329010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  // from the command line.
330010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  std::vector<StringRef> MissingPredefines;
331010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  std::set_difference(PCHLines.begin(), PCHLines.end(),
332010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)                      CmdLineLines.begin(), CmdLineLines.end(),
333010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)                      std::back_inserter(MissingPredefines));
334010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)
335010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  bool MissingDefines = false;
336010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  bool ConflictingDefines = false;
337010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
338010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    StringRef Missing = MissingPredefines[I];
339010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    if (Missing.startswith("#include ")) {
340010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      // An -include was specified when generating the PCH; it is included in
341010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      // the PCH, just ignore it.
342010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      continue;
343010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    }
344010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    if (!Missing.startswith("#define ")) {
345010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      Reader.Diag(diag::warn_pch_compiler_options_mismatch);
346010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      return true;
347010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    }
348010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)
349010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    // This is a macro definition. Determine the name of the macro we're
350010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    // defining.
351010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    std::string::size_type StartOfMacroName = strlen("#define ");
352010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    std::string::size_type EndOfMacroName
353010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      = Missing.find_first_of("( \n\r", StartOfMacroName);
354010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    assert(EndOfMacroName != std::string::npos &&
355010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)           "Couldn't find the end of the macro name");
356010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
357010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)
358010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    // Determine whether this macro was given a different definition on the
359010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    // command line.
360010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    std::string MacroDefStart = "#define " + MacroName.str();
361010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    std::string::size_type MacroDefLen = MacroDefStart.size();
362010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    SmallVector<StringRef, 8>::iterator ConflictPos
363010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
364010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)                         MacroDefStart);
365010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
366010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      if (!ConflictPos->startswith(MacroDefStart)) {
367010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)        // Different macro; we're done.
368010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)        ConflictPos = CmdLineLines.end();
369010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)        break;
370010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      }
371010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)
372010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      assert(ConflictPos->size() > MacroDefLen &&
373010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)             "Invalid #define in predefines buffer?");
374010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      if ((*ConflictPos)[MacroDefLen] != ' ' &&
375010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)          (*ConflictPos)[MacroDefLen] != '(')
376010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)        continue; // Longer macro name; keep trying.
377010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)
378010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      // We found a conflicting macro definition.
379010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      break;
380010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    }
381010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)
382010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    if (ConflictPos != CmdLineLines.end()) {
383010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
3845d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)          << MacroName;
385cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)
38646d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)      // Show the definition of this macro within the PCH file.
38746d4c2bc3267f3f028f39e7e311b0f89aba2e4fdTorne (Richard Coles)      std::pair<FileID, StringRef::size_type> MacroLoc =
3881320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci          FindMacro(Buffers, Missing);
3895d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)      assert(MacroLoc.second!=StringRef::npos && "Unable to find macro!");
3905d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)      SourceLocation PCHMissingLoc =
3915d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)          SourceMgr.getLocForStartOfFile(MacroLoc.first)
3925d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)            .getFileLocWithOffset(MacroLoc.second);
3935d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)      Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
394a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
395a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)      ConflictingDefines = true;
396a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)      continue;
397a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    }
3985d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
3995d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    // If the macro doesn't conflict, then we'll just pick up the macro
4005d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    // definition from the PCH file. Warn the user that they made a mistake.
4015d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    if (ConflictingDefines)
402a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)      continue; // Don't complain if there are already conflicting defs
403a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
4045d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    if (!MissingDefines) {
405a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)      Reader.Diag(diag::warn_cmdline_missing_macro_defs);
406a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)      MissingDefines = true;
407a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    }
4085d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)
409a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    // Show the definition of this macro within the PCH file.
410cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)    std::pair<FileID, StringRef::size_type> MacroLoc =
411a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch        FindMacro(Buffers, Missing);
4125d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    assert(MacroLoc.second!=StringRef::npos && "Unable to find macro!");
4135d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    SourceLocation PCHMissingLoc =
4145d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)        SourceMgr.getLocForStartOfFile(MacroLoc.first)
4155d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)          .getFileLocWithOffset(MacroLoc.second);
416c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch    Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
417cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)  }
418a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
419a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  if (ConflictingDefines)
4205d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    return true;
421cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)
422010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  // Determine what predefines were introduced based on command-line
4235d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  // parameters that were not present when building the PCH
4245d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  // file. Extra #defines are okay, so long as the identifiers being
4255d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  // defined were not used within the precompiled header.
426010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  std::vector<StringRef> ExtraPredefines;
427010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
4285f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)                      PCHLines.begin(), PCHLines.end(),
429010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)                      std::back_inserter(ExtraPredefines));
430010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
431010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    StringRef &Extra = ExtraPredefines[I];
432010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    if (!Extra.startswith("#define ")) {
433010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      Reader.Diag(diag::warn_pch_compiler_options_mismatch);
434010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      return true;
435010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    }
436010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)
437010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    // This is an extra macro definition. Determine the name of the
438010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    // macro we're defining.
439010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    std::string::size_type StartOfMacroName = strlen("#define ");
440010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    std::string::size_type EndOfMacroName
441010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      = Extra.find_first_of("( \n\r", StartOfMacroName);
442010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    assert(EndOfMacroName != std::string::npos &&
443010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)           "Couldn't find the end of the macro name");
444010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
4451320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci
446010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    // Check whether this name was used somewhere in the PCH file. If
447010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    // so, defining it as a macro could change behavior, so we reject
448010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    // the PCH file.
449010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    if (IdentifierInfo *II = Reader.get(MacroName)) {
450010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
451010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      return true;
452010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    }
453010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)
454010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    // Add this definition to the suggested predefines buffer.
455010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    SuggestedPredefines += Extra;
4565d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)    SuggestedPredefines += '\n';
4575d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  }
458cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)
459cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)  // If we get here, it's because the predefines buffer had compatible
460cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)  // contents. Accept the PCH file.
461cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)  return false;
462cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)}
463cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)
464cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI,
4655d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)                                      unsigned ID) {
4665d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, ID);
4675d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  ++NumHeaderInfos;
4685d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)}
469a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
470a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)void PCHValidator::ReadCounter(unsigned Value) {
471a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  PP.setCounterValue(Value);
472cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)}
473cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)
474cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)//===----------------------------------------------------------------------===//
475cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)// AST reader implementation
476a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)//===----------------------------------------------------------------------===//
477a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
478a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)void
479a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)ASTReader::setDeserializationListener(ASTDeserializationListener *Listener) {
480a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  DeserializationListener = Listener;
481a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)}
482a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
483a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
484a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
485a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
486a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  return serialization::ComputeHash(Sel);
487a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)}
488a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
489a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch
490a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)std::pair<unsigned, unsigned>
491a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
492a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  using namespace clang::io;
493a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch  unsigned KeyLen = ReadUnalignedLE16(d);
494a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch  unsigned DataLen = ReadUnalignedLE16(d);
495a02191e04bc25c4935f804f2c080ae28663d096dBen Murdoch  return std::make_pair(KeyLen, DataLen);
496a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)}
497a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
498a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)ASTSelectorLookupTrait::internal_key_type
499a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
500a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  using namespace clang::io;
501a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  SelectorTable &SelTable = Reader.getContext().Selectors;
502a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  unsigned N = ReadUnalignedLE16(d);
503a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  IdentifierInfo *FirstII
504a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    = Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
505a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  if (N == 0)
506a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    return SelTable.getNullarySelector(FirstII);
507a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  else if (N == 1)
508a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    return SelTable.getUnarySelector(FirstII);
509a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
510010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  SmallVector<IdentifierInfo *, 16> Args;
511a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  Args.push_back(FirstII);
512a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  for (unsigned I = 1; I != N; ++I)
513010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    Args.push_back(Reader.getLocalIdentifier(F, ReadUnalignedLE32(d)));
514010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)
515010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  return SelTable.getSelector(N, Args.data());
516010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)}
517a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
518a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)ASTSelectorLookupTrait::data_type
519a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
520010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)                                 unsigned DataLen) {
521010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  using namespace clang::io;
522010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)
523010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  data_type Result;
524010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)
525010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  Result.ID = Reader.getGlobalSelectorID(F, ReadUnalignedLE32(d));
526010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  unsigned NumInstanceMethods = ReadUnalignedLE16(d);
527010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  unsigned NumFactoryMethods = ReadUnalignedLE16(d);
528010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)
529010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  // Load instance methods
530010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  for (unsigned I = 0; I != NumInstanceMethods; ++I) {
531010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    if (ObjCMethodDecl *Method
532010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)          = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
533010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      Result.Instance.push_back(Method);
534010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  }
535010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)
536010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  // Load factory methods
537010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)  for (unsigned I = 0; I != NumFactoryMethods; ++I) {
538010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)    if (ObjCMethodDecl *Method
539010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)          = Reader.GetLocalDeclAs<ObjCMethodDecl>(F, ReadUnalignedLE32(d)))
540010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)      Result.Factory.push_back(Method);
5416e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)  }
5426e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)
5436e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)  return Result;
5446e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)}
545010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)
546010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)unsigned ASTIdentifierLookupTrait::ComputeHash(const internal_key_type& a) {
5475d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)  return llvm::HashString(StringRef(a.first, a.second));
548}
549
550std::pair<unsigned, unsigned>
551ASTIdentifierLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
552  using namespace clang::io;
553  unsigned DataLen = ReadUnalignedLE16(d);
554  unsigned KeyLen = ReadUnalignedLE16(d);
555  return std::make_pair(KeyLen, DataLen);
556}
557
558std::pair<const char*, unsigned>
559ASTIdentifierLookupTrait::ReadKey(const unsigned char* d, unsigned n) {
560  assert(n >= 2 && d[n-1] == '\0');
561  return std::make_pair((const char*) d, n-1);
562}
563
564IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
565                                                   const unsigned char* d,
566                                                   unsigned DataLen) {
567  using namespace clang::io;
568  unsigned RawID = ReadUnalignedLE32(d);
569  bool IsInteresting = RawID & 0x01;
570
571  // Wipe out the "is interesting" bit.
572  RawID = RawID >> 1;
573
574  IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
575  if (!IsInteresting) {
576    // For uninteresting identifiers, just build the IdentifierInfo
577    // and associate it with the persistent ID.
578    IdentifierInfo *II = KnownII;
579    if (!II)
580      II = &Reader.getIdentifierTable().getOwn(StringRef(k.first, k.second));
581    Reader.SetIdentifierInfo(ID, II);
582    II->setIsFromAST();
583    return II;
584  }
585
586  unsigned Bits = ReadUnalignedLE16(d);
587  bool CPlusPlusOperatorKeyword = Bits & 0x01;
588  Bits >>= 1;
589  bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
590  Bits >>= 1;
591  bool Poisoned = Bits & 0x01;
592  Bits >>= 1;
593  bool ExtensionToken = Bits & 0x01;
594  Bits >>= 1;
595  bool hasMacroDefinition = Bits & 0x01;
596  Bits >>= 1;
597  unsigned ObjCOrBuiltinID = Bits & 0x3FF;
598  Bits >>= 10;
599
600  assert(Bits == 0 && "Extra bits in the identifier?");
601  DataLen -= 6;
602
603  // Build the IdentifierInfo itself and link the identifier ID with
604  // the new IdentifierInfo.
605  IdentifierInfo *II = KnownII;
606  if (!II)
607    II = &Reader.getIdentifierTable().getOwn(StringRef(k.first, k.second));
608  Reader.SetIdentifierInfo(ID, II);
609
610  // Set or check the various bits in the IdentifierInfo structure.
611  // Token IDs are read-only.
612  if (HasRevertedTokenIDToIdentifier)
613    II->RevertTokenIDToIdentifier();
614  II->setObjCOrBuiltinID(ObjCOrBuiltinID);
615  assert(II->isExtensionToken() == ExtensionToken &&
616         "Incorrect extension token flag");
617  (void)ExtensionToken;
618  if (Poisoned)
619    II->setIsPoisoned(true);
620  assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
621         "Incorrect C++ operator keyword flag");
622  (void)CPlusPlusOperatorKeyword;
623
624  // If this identifier is a macro, deserialize the macro
625  // definition.
626  if (hasMacroDefinition) {
627    // FIXME: Check for conflicts?
628    uint32_t Offset = ReadUnalignedLE32(d);
629    Reader.SetIdentifierIsMacro(II, F, Offset);
630    DataLen -= 4;
631  }
632
633  // Read all of the declarations visible at global scope with this
634  // name.
635  if (DataLen > 0) {
636    SmallVector<uint32_t, 4> DeclIDs;
637    for (; DataLen > 0; DataLen -= 4)
638      DeclIDs.push_back(Reader.getGlobalDeclID(F, ReadUnalignedLE32(d)));
639    Reader.SetGloballyVisibleDecls(II, DeclIDs);
640  }
641
642  II->setIsFromAST();
643  return II;
644}
645
646unsigned
647ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) const {
648  llvm::FoldingSetNodeID ID;
649  ID.AddInteger(Key.Kind);
650
651  switch (Key.Kind) {
652  case DeclarationName::Identifier:
653  case DeclarationName::CXXLiteralOperatorName:
654    ID.AddString(((IdentifierInfo*)Key.Data)->getName());
655    break;
656  case DeclarationName::ObjCZeroArgSelector:
657  case DeclarationName::ObjCOneArgSelector:
658  case DeclarationName::ObjCMultiArgSelector:
659    ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
660    break;
661  case DeclarationName::CXXOperatorName:
662    ID.AddInteger((OverloadedOperatorKind)Key.Data);
663    break;
664  case DeclarationName::CXXConstructorName:
665  case DeclarationName::CXXDestructorName:
666  case DeclarationName::CXXConversionFunctionName:
667  case DeclarationName::CXXUsingDirective:
668    break;
669  }
670
671  return ID.ComputeHash();
672}
673
674ASTDeclContextNameLookupTrait::internal_key_type
675ASTDeclContextNameLookupTrait::GetInternalKey(
676                                          const external_key_type& Name) const {
677  DeclNameKey Key;
678  Key.Kind = Name.getNameKind();
679  switch (Name.getNameKind()) {
680  case DeclarationName::Identifier:
681    Key.Data = (uint64_t)Name.getAsIdentifierInfo();
682    break;
683  case DeclarationName::ObjCZeroArgSelector:
684  case DeclarationName::ObjCOneArgSelector:
685  case DeclarationName::ObjCMultiArgSelector:
686    Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
687    break;
688  case DeclarationName::CXXOperatorName:
689    Key.Data = Name.getCXXOverloadedOperator();
690    break;
691  case DeclarationName::CXXLiteralOperatorName:
692    Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
693    break;
694  case DeclarationName::CXXConstructorName:
695  case DeclarationName::CXXDestructorName:
696  case DeclarationName::CXXConversionFunctionName:
697  case DeclarationName::CXXUsingDirective:
698    Key.Data = 0;
699    break;
700  }
701
702  return Key;
703}
704
705ASTDeclContextNameLookupTrait::external_key_type
706ASTDeclContextNameLookupTrait::GetExternalKey(
707                                          const internal_key_type& Key) const {
708  ASTContext &Context = Reader.getContext();
709  switch (Key.Kind) {
710  case DeclarationName::Identifier:
711    return DeclarationName((IdentifierInfo*)Key.Data);
712
713  case DeclarationName::ObjCZeroArgSelector:
714  case DeclarationName::ObjCOneArgSelector:
715  case DeclarationName::ObjCMultiArgSelector:
716    return DeclarationName(Selector(Key.Data));
717
718  case DeclarationName::CXXConstructorName:
719    return Context.DeclarationNames.getCXXConstructorName(
720             Context.getCanonicalType(Reader.getLocalType(F, Key.Data)));
721
722  case DeclarationName::CXXDestructorName:
723    return Context.DeclarationNames.getCXXDestructorName(
724             Context.getCanonicalType(Reader.getLocalType(F, Key.Data)));
725
726  case DeclarationName::CXXConversionFunctionName:
727    return Context.DeclarationNames.getCXXConversionFunctionName(
728             Context.getCanonicalType(Reader.getLocalType(F, Key.Data)));
729
730  case DeclarationName::CXXOperatorName:
731    return Context.DeclarationNames.getCXXOperatorName(
732                                       (OverloadedOperatorKind)Key.Data);
733
734  case DeclarationName::CXXLiteralOperatorName:
735    return Context.DeclarationNames.getCXXLiteralOperatorName(
736                                                   (IdentifierInfo*)Key.Data);
737
738  case DeclarationName::CXXUsingDirective:
739    return DeclarationName::getUsingDirectiveName();
740  }
741
742  llvm_unreachable("Invalid Name Kind ?");
743}
744
745std::pair<unsigned, unsigned>
746ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
747  using namespace clang::io;
748  unsigned KeyLen = ReadUnalignedLE16(d);
749  unsigned DataLen = ReadUnalignedLE16(d);
750  return std::make_pair(KeyLen, DataLen);
751}
752
753ASTDeclContextNameLookupTrait::internal_key_type
754ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
755  using namespace clang::io;
756
757  DeclNameKey Key;
758  Key.Kind = (DeclarationName::NameKind)*d++;
759  switch (Key.Kind) {
760  case DeclarationName::Identifier:
761    Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
762    break;
763  case DeclarationName::ObjCZeroArgSelector:
764  case DeclarationName::ObjCOneArgSelector:
765  case DeclarationName::ObjCMultiArgSelector:
766    Key.Data =
767       (uint64_t)Reader.getLocalSelector(F, ReadUnalignedLE32(d))
768                   .getAsOpaquePtr();
769    break;
770  case DeclarationName::CXXOperatorName:
771    Key.Data = *d++; // OverloadedOperatorKind
772    break;
773  case DeclarationName::CXXLiteralOperatorName:
774    Key.Data = (uint64_t)Reader.getLocalIdentifier(F, ReadUnalignedLE32(d));
775    break;
776  case DeclarationName::CXXConstructorName:
777  case DeclarationName::CXXDestructorName:
778  case DeclarationName::CXXConversionFunctionName:
779  case DeclarationName::CXXUsingDirective:
780    Key.Data = 0;
781    break;
782  }
783
784  return Key;
785}
786
787ASTDeclContextNameLookupTrait::data_type
788ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
789                                        const unsigned char* d,
790                                      unsigned DataLen) {
791  using namespace clang::io;
792  unsigned NumDecls = ReadUnalignedLE16(d);
793  DeclID *Start = (DeclID *)d;
794  return std::make_pair(Start, Start + NumDecls);
795}
796
797bool ASTReader::ReadDeclContextStorage(Module &M,
798                                       llvm::BitstreamCursor &Cursor,
799                                   const std::pair<uint64_t, uint64_t> &Offsets,
800                                       DeclContextInfo &Info) {
801  SavedStreamPosition SavedPosition(Cursor);
802  // First the lexical decls.
803  if (Offsets.first != 0) {
804    Cursor.JumpToBit(Offsets.first);
805
806    RecordData Record;
807    const char *Blob;
808    unsigned BlobLen;
809    unsigned Code = Cursor.ReadCode();
810    unsigned RecCode = Cursor.ReadRecord(Code, Record, &Blob, &BlobLen);
811    if (RecCode != DECL_CONTEXT_LEXICAL) {
812      Error("Expected lexical block");
813      return true;
814    }
815
816    Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob);
817    Info.NumLexicalDecls = BlobLen / sizeof(KindDeclIDPair);
818  }
819
820  // Now the lookup table.
821  if (Offsets.second != 0) {
822    Cursor.JumpToBit(Offsets.second);
823
824    RecordData Record;
825    const char *Blob;
826    unsigned BlobLen;
827    unsigned Code = Cursor.ReadCode();
828    unsigned RecCode = Cursor.ReadRecord(Code, Record, &Blob, &BlobLen);
829    if (RecCode != DECL_CONTEXT_VISIBLE) {
830      Error("Expected visible lookup table block");
831      return true;
832    }
833    Info.NameLookupTableData
834      = ASTDeclContextNameLookupTable::Create(
835                    (const unsigned char *)Blob + Record[0],
836                    (const unsigned char *)Blob,
837                    ASTDeclContextNameLookupTrait(*this, M));
838  }
839
840  return false;
841}
842
843void ASTReader::Error(StringRef Msg) {
844  Error(diag::err_fe_pch_malformed, Msg);
845}
846
847void ASTReader::Error(unsigned DiagID,
848                      StringRef Arg1, StringRef Arg2) {
849  if (Diags.isDiagnosticInFlight())
850    Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
851  else
852    Diag(DiagID) << Arg1 << Arg2;
853}
854
855/// \brief Tell the AST listener about the predefines buffers in the chain.
856bool ASTReader::CheckPredefinesBuffers() {
857  if (Listener)
858    return Listener->ReadPredefinesBuffer(PCHPredefinesBuffers,
859                                          ActualOriginalFileName,
860                                          SuggestedPredefines,
861                                          FileMgr);
862  return false;
863}
864
865//===----------------------------------------------------------------------===//
866// Source Manager Deserialization
867//===----------------------------------------------------------------------===//
868
869/// \brief Read the line table in the source manager block.
870/// \returns true if there was an error.
871bool ASTReader::ParseLineTable(Module &F,
872                               SmallVectorImpl<uint64_t> &Record) {
873  unsigned Idx = 0;
874  LineTableInfo &LineTable = SourceMgr.getLineTable();
875
876  // Parse the file names
877  std::map<int, int> FileIDs;
878  for (int I = 0, N = Record[Idx++]; I != N; ++I) {
879    // Extract the file name
880    unsigned FilenameLen = Record[Idx++];
881    std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
882    Idx += FilenameLen;
883    MaybeAddSystemRootToFilename(Filename);
884    FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
885  }
886
887  // Parse the line entries
888  std::vector<LineEntry> Entries;
889  while (Idx < Record.size()) {
890    int FID = Record[Idx++];
891    assert(FID >= 0 && "Serialized line entries for non-local file.");
892    // Remap FileID from 1-based old view.
893    FID += F.SLocEntryBaseID - 1;
894
895    // Extract the line entries
896    unsigned NumEntries = Record[Idx++];
897    assert(NumEntries && "Numentries is 00000");
898    Entries.clear();
899    Entries.reserve(NumEntries);
900    for (unsigned I = 0; I != NumEntries; ++I) {
901      unsigned FileOffset = Record[Idx++];
902      unsigned LineNo = Record[Idx++];
903      int FilenameID = FileIDs[Record[Idx++]];
904      SrcMgr::CharacteristicKind FileKind
905        = (SrcMgr::CharacteristicKind)Record[Idx++];
906      unsigned IncludeOffset = Record[Idx++];
907      Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
908                                       FileKind, IncludeOffset));
909    }
910    LineTable.AddEntry(FID, Entries);
911  }
912
913  return false;
914}
915
916namespace {
917
918class ASTStatData {
919public:
920  const ino_t ino;
921  const dev_t dev;
922  const mode_t mode;
923  const time_t mtime;
924  const off_t size;
925
926  ASTStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
927    : ino(i), dev(d), mode(mo), mtime(m), size(s) {}
928};
929
930class ASTStatLookupTrait {
931 public:
932  typedef const char *external_key_type;
933  typedef const char *internal_key_type;
934
935  typedef ASTStatData data_type;
936
937  static unsigned ComputeHash(const char *path) {
938    return llvm::HashString(path);
939  }
940
941  static internal_key_type GetInternalKey(const char *path) { return path; }
942
943  static bool EqualKey(internal_key_type a, internal_key_type b) {
944    return strcmp(a, b) == 0;
945  }
946
947  static std::pair<unsigned, unsigned>
948  ReadKeyDataLength(const unsigned char*& d) {
949    unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
950    unsigned DataLen = (unsigned) *d++;
951    return std::make_pair(KeyLen + 1, DataLen);
952  }
953
954  static internal_key_type ReadKey(const unsigned char *d, unsigned) {
955    return (const char *)d;
956  }
957
958  static data_type ReadData(const internal_key_type, const unsigned char *d,
959                            unsigned /*DataLen*/) {
960    using namespace clang::io;
961
962    ino_t ino = (ino_t) ReadUnalignedLE32(d);
963    dev_t dev = (dev_t) ReadUnalignedLE32(d);
964    mode_t mode = (mode_t) ReadUnalignedLE16(d);
965    time_t mtime = (time_t) ReadUnalignedLE64(d);
966    off_t size = (off_t) ReadUnalignedLE64(d);
967    return data_type(ino, dev, mode, mtime, size);
968  }
969};
970
971/// \brief stat() cache for precompiled headers.
972///
973/// This cache is very similar to the stat cache used by pretokenized
974/// headers.
975class ASTStatCache : public FileSystemStatCache {
976  typedef OnDiskChainedHashTable<ASTStatLookupTrait> CacheTy;
977  CacheTy *Cache;
978
979  unsigned &NumStatHits, &NumStatMisses;
980public:
981  ASTStatCache(const unsigned char *Buckets, const unsigned char *Base,
982               unsigned &NumStatHits, unsigned &NumStatMisses)
983    : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
984    Cache = CacheTy::Create(Buckets, Base);
985  }
986
987  ~ASTStatCache() { delete Cache; }
988
989  LookupResult getStat(const char *Path, struct stat &StatBuf,
990                       int *FileDescriptor) {
991    // Do the lookup for the file's data in the AST file.
992    CacheTy::iterator I = Cache->find(Path);
993
994    // If we don't get a hit in the AST file just forward to 'stat'.
995    if (I == Cache->end()) {
996      ++NumStatMisses;
997      return statChained(Path, StatBuf, FileDescriptor);
998    }
999
1000    ++NumStatHits;
1001    ASTStatData Data = *I;
1002
1003    StatBuf.st_ino = Data.ino;
1004    StatBuf.st_dev = Data.dev;
1005    StatBuf.st_mtime = Data.mtime;
1006    StatBuf.st_mode = Data.mode;
1007    StatBuf.st_size = Data.size;
1008    return CacheExists;
1009  }
1010};
1011} // end anonymous namespace
1012
1013
1014/// \brief Read a source manager block
1015ASTReader::ASTReadResult ASTReader::ReadSourceManagerBlock(Module &F) {
1016  using namespace SrcMgr;
1017
1018  llvm::BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1019
1020  // Set the source-location entry cursor to the current position in
1021  // the stream. This cursor will be used to read the contents of the
1022  // source manager block initially, and then lazily read
1023  // source-location entries as needed.
1024  SLocEntryCursor = F.Stream;
1025
1026  // The stream itself is going to skip over the source manager block.
1027  if (F.Stream.SkipBlock()) {
1028    Error("malformed block record in AST file");
1029    return Failure;
1030  }
1031
1032  // Enter the source manager block.
1033  if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1034    Error("malformed source manager block record in AST file");
1035    return Failure;
1036  }
1037
1038  RecordData Record;
1039  while (true) {
1040    unsigned Code = SLocEntryCursor.ReadCode();
1041    if (Code == llvm::bitc::END_BLOCK) {
1042      if (SLocEntryCursor.ReadBlockEnd()) {
1043        Error("error at end of Source Manager block in AST file");
1044        return Failure;
1045      }
1046      return Success;
1047    }
1048
1049    if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1050      // No known subblocks, always skip them.
1051      SLocEntryCursor.ReadSubBlockID();
1052      if (SLocEntryCursor.SkipBlock()) {
1053        Error("malformed block record in AST file");
1054        return Failure;
1055      }
1056      continue;
1057    }
1058
1059    if (Code == llvm::bitc::DEFINE_ABBREV) {
1060      SLocEntryCursor.ReadAbbrevRecord();
1061      continue;
1062    }
1063
1064    // Read a record.
1065    const char *BlobStart;
1066    unsigned BlobLen;
1067    Record.clear();
1068    switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1069    default:  // Default behavior: ignore.
1070      break;
1071
1072    case SM_SLOC_FILE_ENTRY:
1073    case SM_SLOC_BUFFER_ENTRY:
1074    case SM_SLOC_EXPANSION_ENTRY:
1075      // Once we hit one of the source location entries, we're done.
1076      return Success;
1077    }
1078  }
1079}
1080
1081/// \brief If a header file is not found at the path that we expect it to be
1082/// and the PCH file was moved from its original location, try to resolve the
1083/// file by assuming that header+PCH were moved together and the header is in
1084/// the same place relative to the PCH.
1085static std::string
1086resolveFileRelativeToOriginalDir(const std::string &Filename,
1087                                 const std::string &OriginalDir,
1088                                 const std::string &CurrDir) {
1089  assert(OriginalDir != CurrDir &&
1090         "No point trying to resolve the file if the PCH dir didn't change");
1091  using namespace llvm::sys;
1092  llvm::SmallString<128> filePath(Filename);
1093  fs::make_absolute(filePath);
1094  assert(path::is_absolute(OriginalDir));
1095  llvm::SmallString<128> currPCHPath(CurrDir);
1096
1097  path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1098                       fileDirE = path::end(path::parent_path(filePath));
1099  path::const_iterator origDirI = path::begin(OriginalDir),
1100                       origDirE = path::end(OriginalDir);
1101  // Skip the common path components from filePath and OriginalDir.
1102  while (fileDirI != fileDirE && origDirI != origDirE &&
1103         *fileDirI == *origDirI) {
1104    ++fileDirI;
1105    ++origDirI;
1106  }
1107  for (; origDirI != origDirE; ++origDirI)
1108    path::append(currPCHPath, "..");
1109  path::append(currPCHPath, fileDirI, fileDirE);
1110  path::append(currPCHPath, path::filename(Filename));
1111  return currPCHPath.str();
1112}
1113
1114/// \brief Read in the source location entry with the given ID.
1115ASTReader::ASTReadResult ASTReader::ReadSLocEntryRecord(int ID) {
1116  if (ID == 0)
1117    return Success;
1118
1119  if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1120    Error("source location entry ID out-of-range for AST file");
1121    return Failure;
1122  }
1123
1124  Module *F = GlobalSLocEntryMap.find(-ID)->second;
1125  F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
1126  llvm::BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1127  unsigned BaseOffset = F->SLocEntryBaseOffset;
1128
1129  ++NumSLocEntriesRead;
1130  unsigned Code = SLocEntryCursor.ReadCode();
1131  if (Code == llvm::bitc::END_BLOCK ||
1132      Code == llvm::bitc::ENTER_SUBBLOCK ||
1133      Code == llvm::bitc::DEFINE_ABBREV) {
1134    Error("incorrectly-formatted source location entry in AST file");
1135    return Failure;
1136  }
1137
1138  RecordData Record;
1139  const char *BlobStart;
1140  unsigned BlobLen;
1141  switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1142  default:
1143    Error("incorrectly-formatted source location entry in AST file");
1144    return Failure;
1145
1146  case SM_SLOC_FILE_ENTRY: {
1147    std::string Filename(BlobStart, BlobStart + BlobLen);
1148    MaybeAddSystemRootToFilename(Filename);
1149    const FileEntry *File = FileMgr.getFile(Filename);
1150    if (File == 0 && !OriginalDir.empty() && !CurrentDir.empty() &&
1151        OriginalDir != CurrentDir) {
1152      std::string resolved = resolveFileRelativeToOriginalDir(Filename,
1153                                                              OriginalDir,
1154                                                              CurrentDir);
1155      if (!resolved.empty())
1156        File = FileMgr.getFile(resolved);
1157    }
1158    if (File == 0)
1159      File = FileMgr.getVirtualFile(Filename, (off_t)Record[4],
1160                                    (time_t)Record[5]);
1161    if (File == 0) {
1162      std::string ErrorStr = "could not find file '";
1163      ErrorStr += Filename;
1164      ErrorStr += "' referenced by AST file";
1165      Error(ErrorStr.c_str());
1166      return Failure;
1167    }
1168
1169    if (Record.size() < 6) {
1170      Error("source location entry is incorrect");
1171      return Failure;
1172    }
1173
1174    if (!DisableValidation &&
1175        ((off_t)Record[4] != File->getSize()
1176#if !defined(LLVM_ON_WIN32)
1177        // In our regression testing, the Windows file system seems to
1178        // have inconsistent modification times that sometimes
1179        // erroneously trigger this error-handling path.
1180         || (time_t)Record[5] != File->getModificationTime()
1181#endif
1182        )) {
1183      Error(diag::err_fe_pch_file_modified, Filename);
1184      return Failure;
1185    }
1186
1187    SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1188    if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1189      // This is the module's main file.
1190      IncludeLoc = getImportLocation(F);
1191    }
1192    FileID FID = SourceMgr.createFileID(File, IncludeLoc,
1193                                        (SrcMgr::CharacteristicKind)Record[2],
1194                                        ID, BaseOffset + Record[0]);
1195    SrcMgr::FileInfo &FileInfo =
1196          const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1197    FileInfo.NumCreatedFIDs = Record[6];
1198    if (Record[3])
1199      FileInfo.setHasLineDirectives();
1200
1201    break;
1202  }
1203
1204  case SM_SLOC_BUFFER_ENTRY: {
1205    const char *Name = BlobStart;
1206    unsigned Offset = Record[0];
1207    unsigned Code = SLocEntryCursor.ReadCode();
1208    Record.clear();
1209    unsigned RecCode
1210      = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
1211
1212    if (RecCode != SM_SLOC_BUFFER_BLOB) {
1213      Error("AST record has invalid code");
1214      return Failure;
1215    }
1216
1217    llvm::MemoryBuffer *Buffer
1218    = llvm::MemoryBuffer::getMemBuffer(StringRef(BlobStart, BlobLen - 1),
1219                                       Name);
1220    FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID,
1221                                                         BaseOffset + Offset);
1222
1223    if (strcmp(Name, "<built-in>") == 0) {
1224      PCHPredefinesBlock Block = {
1225        BufferID,
1226        StringRef(BlobStart, BlobLen - 1)
1227      };
1228      PCHPredefinesBuffers.push_back(Block);
1229    }
1230
1231    break;
1232  }
1233
1234  case SM_SLOC_EXPANSION_ENTRY: {
1235    SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1236    SourceMgr.createExpansionLoc(SpellingLoc,
1237                                     ReadSourceLocation(*F, Record[2]),
1238                                     ReadSourceLocation(*F, Record[3]),
1239                                     Record[4],
1240                                     ID,
1241                                     BaseOffset + Record[0]);
1242    break;
1243  }
1244  }
1245
1246  return Success;
1247}
1248
1249/// \brief Find the location where the module F is imported.
1250SourceLocation ASTReader::getImportLocation(Module *F) {
1251  if (F->ImportLoc.isValid())
1252    return F->ImportLoc;
1253
1254  // Otherwise we have a PCH. It's considered to be "imported" at the first
1255  // location of its includer.
1256  if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
1257    // Main file is the importer. We assume that it is the first entry in the
1258    // entry table. We can't ask the manager, because at the time of PCH loading
1259    // the main file entry doesn't exist yet.
1260    // The very first entry is the invalid instantiation loc, which takes up
1261    // offsets 0 and 1.
1262    return SourceLocation::getFromRawEncoding(2U);
1263  }
1264  //return F->Loaders[0]->FirstLoc;
1265  return F->ImportedBy[0]->FirstLoc;
1266}
1267
1268/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1269/// specified cursor.  Read the abbreviations that are at the top of the block
1270/// and then leave the cursor pointing into the block.
1271bool ASTReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
1272                                 unsigned BlockID) {
1273  if (Cursor.EnterSubBlock(BlockID)) {
1274    Error("malformed block record in AST file");
1275    return Failure;
1276  }
1277
1278  while (true) {
1279    uint64_t Offset = Cursor.GetCurrentBitNo();
1280    unsigned Code = Cursor.ReadCode();
1281
1282    // We expect all abbrevs to be at the start of the block.
1283    if (Code != llvm::bitc::DEFINE_ABBREV) {
1284      Cursor.JumpToBit(Offset);
1285      return false;
1286    }
1287    Cursor.ReadAbbrevRecord();
1288  }
1289}
1290
1291void ASTReader::ReadMacroRecord(Module &F, uint64_t Offset) {
1292  llvm::BitstreamCursor &Stream = F.MacroCursor;
1293
1294  // Keep track of where we are in the stream, then jump back there
1295  // after reading this macro.
1296  SavedStreamPosition SavedPosition(Stream);
1297
1298  Stream.JumpToBit(Offset);
1299  RecordData Record;
1300  SmallVector<IdentifierInfo*, 16> MacroArgs;
1301  MacroInfo *Macro = 0;
1302
1303  while (true) {
1304    unsigned Code = Stream.ReadCode();
1305    switch (Code) {
1306    case llvm::bitc::END_BLOCK:
1307      return;
1308
1309    case llvm::bitc::ENTER_SUBBLOCK:
1310      // No known subblocks, always skip them.
1311      Stream.ReadSubBlockID();
1312      if (Stream.SkipBlock()) {
1313        Error("malformed block record in AST file");
1314        return;
1315      }
1316      continue;
1317
1318    case llvm::bitc::DEFINE_ABBREV:
1319      Stream.ReadAbbrevRecord();
1320      continue;
1321    default: break;
1322    }
1323
1324    // Read a record.
1325    const char *BlobStart = 0;
1326    unsigned BlobLen = 0;
1327    Record.clear();
1328    PreprocessorRecordTypes RecType =
1329      (PreprocessorRecordTypes)Stream.ReadRecord(Code, Record, BlobStart,
1330                                                 BlobLen);
1331    switch (RecType) {
1332    case PP_MACRO_OBJECT_LIKE:
1333    case PP_MACRO_FUNCTION_LIKE: {
1334      // If we already have a macro, that means that we've hit the end
1335      // of the definition of the macro we were looking for. We're
1336      // done.
1337      if (Macro)
1338        return;
1339
1340      IdentifierInfo *II = getLocalIdentifier(F, Record[0]);
1341      if (II == 0) {
1342        Error("macro must have a name in AST file");
1343        return;
1344      }
1345      SourceLocation Loc = ReadSourceLocation(F, Record[1]);
1346      bool isUsed = Record[2];
1347
1348      MacroInfo *MI = PP.AllocateMacroInfo(Loc);
1349      MI->setIsUsed(isUsed);
1350      MI->setIsFromAST();
1351
1352      unsigned NextIndex = 3;
1353      MI->setExportLocation(ReadSourceLocation(F, Record, NextIndex));
1354
1355      if (RecType == PP_MACRO_FUNCTION_LIKE) {
1356        // Decode function-like macro info.
1357        bool isC99VarArgs = Record[NextIndex++];
1358        bool isGNUVarArgs = Record[NextIndex++];
1359        MacroArgs.clear();
1360        unsigned NumArgs = Record[NextIndex++];
1361        for (unsigned i = 0; i != NumArgs; ++i)
1362          MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1363
1364        // Install function-like macro info.
1365        MI->setIsFunctionLike();
1366        if (isC99VarArgs) MI->setIsC99Varargs();
1367        if (isGNUVarArgs) MI->setIsGNUVarargs();
1368        MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1369                            PP.getPreprocessorAllocator());
1370      }
1371
1372      // Finally, install the macro.
1373      PP.setMacroInfo(II, MI);
1374
1375      // Remember that we saw this macro last so that we add the tokens that
1376      // form its body to it.
1377      Macro = MI;
1378
1379      if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord()) {
1380        // We have a macro definition. Load it now.
1381        PP.getPreprocessingRecord()->RegisterMacroDefinition(Macro,
1382              getLocalMacroDefinition(F, Record[NextIndex]));
1383      }
1384
1385      ++NumMacrosRead;
1386      break;
1387    }
1388
1389    case PP_TOKEN: {
1390      // If we see a TOKEN before a PP_MACRO_*, then the file is
1391      // erroneous, just pretend we didn't see this.
1392      if (Macro == 0) break;
1393
1394      Token Tok;
1395      Tok.startToken();
1396      Tok.setLocation(ReadSourceLocation(F, Record[0]));
1397      Tok.setLength(Record[1]);
1398      if (IdentifierInfo *II = getLocalIdentifier(F, Record[2]))
1399        Tok.setIdentifierInfo(II);
1400      Tok.setKind((tok::TokenKind)Record[3]);
1401      Tok.setFlag((Token::TokenFlags)Record[4]);
1402      Macro->AddTokenToBody(Tok);
1403      break;
1404    }
1405  }
1406  }
1407
1408  return;
1409}
1410
1411PreprocessedEntity *ASTReader::LoadPreprocessedEntity(Module &F) {
1412  unsigned Code = F.PreprocessorDetailCursor.ReadCode();
1413  switch (Code) {
1414  case llvm::bitc::END_BLOCK:
1415    return 0;
1416
1417  case llvm::bitc::ENTER_SUBBLOCK:
1418    Error("unexpected subblock record in preprocessor detail block");
1419    return 0;
1420
1421  case llvm::bitc::DEFINE_ABBREV:
1422    Error("unexpected abbrevation record in preprocessor detail block");
1423    return 0;
1424
1425  default:
1426    break;
1427  }
1428
1429  if (!PP.getPreprocessingRecord()) {
1430    Error("no preprocessing record");
1431    return 0;
1432  }
1433
1434  // Read the record.
1435  PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
1436  const char *BlobStart = 0;
1437  unsigned BlobLen = 0;
1438  RecordData Record;
1439  PreprocessorDetailRecordTypes RecType =
1440    (PreprocessorDetailRecordTypes)F.PreprocessorDetailCursor.ReadRecord(
1441                                             Code, Record, BlobStart, BlobLen);
1442  switch (RecType) {
1443  case PPD_MACRO_EXPANSION: {
1444    PreprocessedEntityID GlobalID = getGlobalPreprocessedEntityID(F, Record[0]);
1445    if (PreprocessedEntity *PE = PPRec.getLoadedPreprocessedEntity(GlobalID-1))
1446      return PE;
1447
1448    bool isBuiltin = Record[3];
1449    MacroExpansion *ME;
1450    if (isBuiltin)
1451      ME = new (PPRec) MacroExpansion(getLocalIdentifier(F, Record[4]),
1452                                 SourceRange(ReadSourceLocation(F, Record[1]),
1453                                             ReadSourceLocation(F, Record[2])));
1454    else
1455      ME = new (PPRec) MacroExpansion(getLocalMacroDefinition(F, Record[4]),
1456                                 SourceRange(ReadSourceLocation(F, Record[1]),
1457                                             ReadSourceLocation(F, Record[2])));
1458    PPRec.setLoadedPreallocatedEntity(GlobalID - 1, ME);
1459    return ME;
1460  }
1461
1462  case PPD_MACRO_DEFINITION: {
1463    PreprocessedEntityID GlobalID = getGlobalPreprocessedEntityID(F, Record[0]);
1464    if (PreprocessedEntity *PE = PPRec.getLoadedPreprocessedEntity(GlobalID-1))
1465      return PE;
1466
1467    unsigned MacroDefID = getGlobalMacroDefinitionID(F, Record[1]);
1468    if (MacroDefID > MacroDefinitionsLoaded.size()) {
1469      Error("out-of-bounds macro definition record");
1470      return 0;
1471    }
1472
1473    // Decode the identifier info and then check again; if the macro is
1474    // still defined and associated with the identifier,
1475    IdentifierInfo *II = getLocalIdentifier(F, Record[4]);
1476    if (!MacroDefinitionsLoaded[MacroDefID - 1]) {
1477      MacroDefinition *MD
1478        = new (PPRec) MacroDefinition(II,
1479                                      ReadSourceLocation(F, Record[5]),
1480                                      SourceRange(
1481                                            ReadSourceLocation(F, Record[2]),
1482                                            ReadSourceLocation(F, Record[3])));
1483
1484      PPRec.setLoadedPreallocatedEntity(GlobalID - 1, MD);
1485      MacroDefinitionsLoaded[MacroDefID - 1] = MD;
1486
1487      if (DeserializationListener)
1488        DeserializationListener->MacroDefinitionRead(MacroDefID, MD);
1489    }
1490
1491    return MacroDefinitionsLoaded[MacroDefID - 1];
1492  }
1493
1494  case PPD_INCLUSION_DIRECTIVE: {
1495    PreprocessedEntityID GlobalID = getGlobalPreprocessedEntityID(F, Record[0]);
1496    if (PreprocessedEntity *PE = PPRec.getLoadedPreprocessedEntity(GlobalID-1))
1497      return PE;
1498
1499    const char *FullFileNameStart = BlobStart + Record[3];
1500    const FileEntry *File
1501      = PP.getFileManager().getFile(StringRef(FullFileNameStart,
1502                                               BlobLen - Record[3]));
1503
1504    // FIXME: Stable encoding
1505    InclusionDirective::InclusionKind Kind
1506      = static_cast<InclusionDirective::InclusionKind>(Record[5]);
1507    InclusionDirective *ID
1508      = new (PPRec) InclusionDirective(PPRec, Kind,
1509                                       StringRef(BlobStart, Record[3]),
1510                                       Record[4],
1511                                       File,
1512                                 SourceRange(ReadSourceLocation(F, Record[1]),
1513                                             ReadSourceLocation(F, Record[2])));
1514    PPRec.setLoadedPreallocatedEntity(GlobalID - 1, ID);
1515    return ID;
1516  }
1517  }
1518
1519  Error("invalid offset in preprocessor detail block");
1520  return 0;
1521}
1522
1523PreprocessedEntityID
1524ASTReader::getGlobalPreprocessedEntityID(Module &M, unsigned LocalID) {
1525  ContinuousRangeMap<uint32_t, int, 2>::iterator
1526    I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
1527  assert(I != M.PreprocessedEntityRemap.end()
1528         && "Invalid index into preprocessed entity index remap");
1529
1530  return LocalID + I->second;
1531}
1532
1533unsigned HeaderFileInfoTrait::ComputeHash(const char *path) {
1534  return llvm::HashString(llvm::sys::path::filename(path));
1535}
1536
1537HeaderFileInfoTrait::internal_key_type
1538HeaderFileInfoTrait::GetInternalKey(const char *path) { return path; }
1539
1540bool HeaderFileInfoTrait::EqualKey(internal_key_type a, internal_key_type b) {
1541  if (strcmp(a, b) == 0)
1542    return true;
1543
1544  if (llvm::sys::path::filename(a) != llvm::sys::path::filename(b))
1545    return false;
1546
1547  // The file names match, but the path names don't. stat() the files to
1548  // see if they are the same.
1549  struct stat StatBufA, StatBufB;
1550  if (StatSimpleCache(a, &StatBufA) || StatSimpleCache(b, &StatBufB))
1551    return false;
1552
1553  return StatBufA.st_ino == StatBufB.st_ino;
1554}
1555
1556std::pair<unsigned, unsigned>
1557HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1558  unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
1559  unsigned DataLen = (unsigned) *d++;
1560  return std::make_pair(KeyLen + 1, DataLen);
1561}
1562
1563HeaderFileInfoTrait::data_type
1564HeaderFileInfoTrait::ReadData(const internal_key_type, const unsigned char *d,
1565                              unsigned DataLen) {
1566  const unsigned char *End = d + DataLen;
1567  using namespace clang::io;
1568  HeaderFileInfo HFI;
1569  unsigned Flags = *d++;
1570  HFI.isImport = (Flags >> 5) & 0x01;
1571  HFI.isPragmaOnce = (Flags >> 4) & 0x01;
1572  HFI.DirInfo = (Flags >> 2) & 0x03;
1573  HFI.Resolved = (Flags >> 1) & 0x01;
1574  HFI.IndexHeaderMapHeader = Flags & 0x01;
1575  HFI.NumIncludes = ReadUnalignedLE16(d);
1576  HFI.ControllingMacroID = Reader.getGlobalDeclID(M, ReadUnalignedLE32(d));
1577  if (unsigned FrameworkOffset = ReadUnalignedLE32(d)) {
1578    // The framework offset is 1 greater than the actual offset,
1579    // since 0 is used as an indicator for "no framework name".
1580    StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1581    HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1582  }
1583
1584  assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
1585  (void)End;
1586
1587  // This HeaderFileInfo was externally loaded.
1588  HFI.External = true;
1589  return HFI;
1590}
1591
1592void ASTReader::SetIdentifierIsMacro(IdentifierInfo *II, Module &F,
1593                                     uint64_t LocalOffset) {
1594  // Note that this identifier has a macro definition.
1595  II->setHasMacroDefinition(true);
1596
1597  // Adjust the offset to a global offset.
1598  UnreadMacroRecordOffsets[II] = F.GlobalBitOffset + LocalOffset;
1599}
1600
1601void ASTReader::ReadDefinedMacros() {
1602  for (ModuleReverseIterator I = ModuleMgr.rbegin(),
1603      E = ModuleMgr.rend(); I != E; ++I) {
1604    llvm::BitstreamCursor &MacroCursor = (*I)->MacroCursor;
1605
1606    // If there was no preprocessor block, skip this file.
1607    if (!MacroCursor.getBitStreamReader())
1608      continue;
1609
1610    llvm::BitstreamCursor Cursor = MacroCursor;
1611    Cursor.JumpToBit((*I)->MacroStartOffset);
1612
1613    RecordData Record;
1614    while (true) {
1615      unsigned Code = Cursor.ReadCode();
1616      if (Code == llvm::bitc::END_BLOCK)
1617        break;
1618
1619      if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1620        // No known subblocks, always skip them.
1621        Cursor.ReadSubBlockID();
1622        if (Cursor.SkipBlock()) {
1623          Error("malformed block record in AST file");
1624          return;
1625        }
1626        continue;
1627      }
1628
1629      if (Code == llvm::bitc::DEFINE_ABBREV) {
1630        Cursor.ReadAbbrevRecord();
1631        continue;
1632      }
1633
1634      // Read a record.
1635      const char *BlobStart;
1636      unsigned BlobLen;
1637      Record.clear();
1638      switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1639      default:  // Default behavior: ignore.
1640        break;
1641
1642      case PP_MACRO_OBJECT_LIKE:
1643      case PP_MACRO_FUNCTION_LIKE:
1644        getLocalIdentifier(**I, Record[0]);
1645        break;
1646
1647      case PP_TOKEN:
1648        // Ignore tokens.
1649        break;
1650      }
1651    }
1652  }
1653
1654  // Drain the unread macro-record offsets map.
1655  while (!UnreadMacroRecordOffsets.empty())
1656    LoadMacroDefinition(UnreadMacroRecordOffsets.begin());
1657}
1658
1659void ASTReader::LoadMacroDefinition(
1660                     llvm::DenseMap<IdentifierInfo *, uint64_t>::iterator Pos) {
1661  assert(Pos != UnreadMacroRecordOffsets.end() && "Unknown macro definition");
1662  uint64_t Offset = Pos->second;
1663  UnreadMacroRecordOffsets.erase(Pos);
1664
1665  RecordLocation Loc = getLocalBitOffset(Offset);
1666  ReadMacroRecord(*Loc.F, Loc.Offset);
1667}
1668
1669void ASTReader::LoadMacroDefinition(IdentifierInfo *II) {
1670  llvm::DenseMap<IdentifierInfo *, uint64_t>::iterator Pos
1671    = UnreadMacroRecordOffsets.find(II);
1672  LoadMacroDefinition(Pos);
1673}
1674
1675MacroDefinition *ASTReader::getMacroDefinition(MacroID ID) {
1676  if (ID == 0 || ID > MacroDefinitionsLoaded.size())
1677    return 0;
1678
1679  if (!MacroDefinitionsLoaded[ID - 1]) {
1680    GlobalMacroDefinitionMapType::iterator I =GlobalMacroDefinitionMap.find(ID);
1681    assert(I != GlobalMacroDefinitionMap.end() &&
1682           "Corrupted global macro definition map");
1683    Module &M = *I->second;
1684    unsigned Index = ID - 1 - M.BaseMacroDefinitionID;
1685    SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
1686    M.PreprocessorDetailCursor.JumpToBit(M.MacroDefinitionOffsets[Index]);
1687    LoadPreprocessedEntity(M);
1688  }
1689
1690  return MacroDefinitionsLoaded[ID - 1];
1691}
1692
1693const FileEntry *ASTReader::getFileEntry(StringRef filenameStrRef) {
1694  std::string Filename = filenameStrRef;
1695  MaybeAddSystemRootToFilename(Filename);
1696  const FileEntry *File = FileMgr.getFile(Filename);
1697  if (File == 0 && !OriginalDir.empty() && !CurrentDir.empty() &&
1698      OriginalDir != CurrentDir) {
1699    std::string resolved = resolveFileRelativeToOriginalDir(Filename,
1700                                                            OriginalDir,
1701                                                            CurrentDir);
1702    if (!resolved.empty())
1703      File = FileMgr.getFile(resolved);
1704  }
1705
1706  return File;
1707}
1708
1709MacroID ASTReader::getGlobalMacroDefinitionID(Module &M, unsigned LocalID) {
1710  if (LocalID < NUM_PREDEF_MACRO_IDS)
1711    return LocalID;
1712
1713  ContinuousRangeMap<uint32_t, int, 2>::iterator I
1714    = M.MacroDefinitionRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
1715  assert(I != M.MacroDefinitionRemap.end() &&
1716         "Invalid index into macro definition ID remap");
1717
1718  return LocalID + I->second;
1719}
1720
1721/// \brief If we are loading a relocatable PCH file, and the filename is
1722/// not an absolute path, add the system root to the beginning of the file
1723/// name.
1724void ASTReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1725  // If this is not a relocatable PCH file, there's nothing to do.
1726  if (!RelocatablePCH)
1727    return;
1728
1729  if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
1730    return;
1731
1732  if (isysroot.empty()) {
1733    // If no system root was given, default to '/'
1734    Filename.insert(Filename.begin(), '/');
1735    return;
1736  }
1737
1738  unsigned Length = isysroot.size();
1739  if (isysroot[Length - 1] != '/')
1740    Filename.insert(Filename.begin(), '/');
1741
1742  Filename.insert(Filename.begin(), isysroot.begin(), isysroot.end());
1743}
1744
1745ASTReader::ASTReadResult
1746ASTReader::ReadASTBlock(Module &F) {
1747  llvm::BitstreamCursor &Stream = F.Stream;
1748
1749  if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
1750    Error("malformed block record in AST file");
1751    return Failure;
1752  }
1753
1754  // Read all of the records and blocks for the ASt file.
1755  RecordData Record;
1756  while (!Stream.AtEndOfStream()) {
1757    unsigned Code = Stream.ReadCode();
1758    if (Code == llvm::bitc::END_BLOCK) {
1759      if (Stream.ReadBlockEnd()) {
1760        Error("error at end of module block in AST file");
1761        return Failure;
1762      }
1763
1764      return Success;
1765    }
1766
1767    if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1768      switch (Stream.ReadSubBlockID()) {
1769      case DECLTYPES_BLOCK_ID:
1770        // We lazily load the decls block, but we want to set up the
1771        // DeclsCursor cursor to point into it.  Clone our current bitcode
1772        // cursor to it, enter the block and read the abbrevs in that block.
1773        // With the main cursor, we just skip over it.
1774        F.DeclsCursor = Stream;
1775        if (Stream.SkipBlock() ||  // Skip with the main cursor.
1776            // Read the abbrevs.
1777            ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
1778          Error("malformed block record in AST file");
1779          return Failure;
1780        }
1781        break;
1782
1783      case DECL_UPDATES_BLOCK_ID:
1784        if (Stream.SkipBlock()) {
1785          Error("malformed block record in AST file");
1786          return Failure;
1787        }
1788        break;
1789
1790      case PREPROCESSOR_BLOCK_ID:
1791        F.MacroCursor = Stream;
1792        if (!PP.getExternalSource())
1793          PP.setExternalSource(this);
1794
1795        if (Stream.SkipBlock() ||
1796            ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
1797          Error("malformed block record in AST file");
1798          return Failure;
1799        }
1800        F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
1801        break;
1802
1803      case PREPROCESSOR_DETAIL_BLOCK_ID:
1804        F.PreprocessorDetailCursor = Stream;
1805        if (Stream.SkipBlock() ||
1806            ReadBlockAbbrevs(F.PreprocessorDetailCursor,
1807                             PREPROCESSOR_DETAIL_BLOCK_ID)) {
1808          Error("malformed preprocessor detail record in AST file");
1809          return Failure;
1810        }
1811        F.PreprocessorDetailStartOffset
1812          = F.PreprocessorDetailCursor.GetCurrentBitNo();
1813
1814        if (!PP.getPreprocessingRecord())
1815          PP.createPreprocessingRecord(true);
1816        if (!PP.getPreprocessingRecord()->getExternalSource())
1817          PP.getPreprocessingRecord()->SetExternalSource(*this);
1818        break;
1819
1820      case SOURCE_MANAGER_BLOCK_ID:
1821        switch (ReadSourceManagerBlock(F)) {
1822        case Success:
1823          break;
1824
1825        case Failure:
1826          Error("malformed source manager block in AST file");
1827          return Failure;
1828
1829        case IgnorePCH:
1830          return IgnorePCH;
1831        }
1832        break;
1833      }
1834      continue;
1835    }
1836
1837    if (Code == llvm::bitc::DEFINE_ABBREV) {
1838      Stream.ReadAbbrevRecord();
1839      continue;
1840    }
1841
1842    // Read and process a record.
1843    Record.clear();
1844    const char *BlobStart = 0;
1845    unsigned BlobLen = 0;
1846    switch ((ASTRecordTypes)Stream.ReadRecord(Code, Record,
1847                                              &BlobStart, &BlobLen)) {
1848    default:  // Default behavior: ignore.
1849      break;
1850
1851    case METADATA: {
1852      if (Record[0] != VERSION_MAJOR && !DisableValidation) {
1853        Diag(Record[0] < VERSION_MAJOR? diag::warn_pch_version_too_old
1854                                           : diag::warn_pch_version_too_new);
1855        return IgnorePCH;
1856      }
1857
1858      RelocatablePCH = Record[4];
1859      if (Listener) {
1860        std::string TargetTriple(BlobStart, BlobLen);
1861        if (Listener->ReadTargetTriple(TargetTriple))
1862          return IgnorePCH;
1863      }
1864      break;
1865    }
1866
1867    case IMPORTS: {
1868      // Load each of the imported PCH files.
1869      unsigned Idx = 0, N = Record.size();
1870      while (Idx < N) {
1871        // Read information about the AST file.
1872        ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
1873        unsigned Length = Record[Idx++];
1874        llvm::SmallString<128> ImportedFile(Record.begin() + Idx,
1875                                            Record.begin() + Idx + Length);
1876        Idx += Length;
1877
1878        // Load the AST file.
1879        switch(ReadASTCore(ImportedFile, ImportedKind, &F)) {
1880        case Failure: return Failure;
1881          // If we have to ignore the dependency, we'll have to ignore this too.
1882        case IgnorePCH: return IgnorePCH;
1883        case Success: break;
1884        }
1885      }
1886      break;
1887    }
1888
1889    case TYPE_OFFSET: {
1890      if (F.LocalNumTypes != 0) {
1891        Error("duplicate TYPE_OFFSET record in AST file");
1892        return Failure;
1893      }
1894      F.TypeOffsets = (const uint32_t *)BlobStart;
1895      F.LocalNumTypes = Record[0];
1896      unsigned LocalBaseTypeIndex = Record[1];
1897      F.BaseTypeIndex = getTotalNumTypes();
1898
1899      if (F.LocalNumTypes > 0) {
1900        // Introduce the global -> local mapping for types within this module.
1901        GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
1902
1903        // Introduce the local -> global mapping for types within this module.
1904        F.TypeRemap.insert(std::make_pair(LocalBaseTypeIndex,
1905                             F.BaseTypeIndex - LocalBaseTypeIndex));
1906
1907        TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
1908      }
1909      break;
1910    }
1911
1912    case DECL_OFFSET: {
1913      if (F.LocalNumDecls != 0) {
1914        Error("duplicate DECL_OFFSET record in AST file");
1915        return Failure;
1916      }
1917      F.DeclOffsets = (const uint32_t *)BlobStart;
1918      F.LocalNumDecls = Record[0];
1919      unsigned LocalBaseDeclID = Record[1];
1920      F.BaseDeclID = getTotalNumDecls();
1921
1922      if (F.LocalNumDecls > 0) {
1923        // Introduce the global -> local mapping for declarations within this
1924        // module.
1925        GlobalDeclMap.insert(
1926          std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
1927
1928        // Introduce the local -> global mapping for declarations within this
1929        // module.
1930        F.DeclRemap.insert(std::make_pair(LocalBaseDeclID,
1931                                          F.BaseDeclID - LocalBaseDeclID));
1932
1933        DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
1934      }
1935      break;
1936    }
1937
1938    case TU_UPDATE_LEXICAL: {
1939      DeclContext *TU = Context.getTranslationUnitDecl();
1940      DeclContextInfo &Info = F.DeclContextInfos[TU];
1941      Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(BlobStart);
1942      Info.NumLexicalDecls
1943        = static_cast<unsigned int>(BlobLen / sizeof(KindDeclIDPair));
1944      TU->setHasExternalLexicalStorage(true);
1945      break;
1946    }
1947
1948    case UPDATE_VISIBLE: {
1949      unsigned Idx = 0;
1950      serialization::DeclID ID = ReadDeclID(F, Record, Idx);
1951      void *Table = ASTDeclContextNameLookupTable::Create(
1952                        (const unsigned char *)BlobStart + Record[Idx++],
1953                        (const unsigned char *)BlobStart,
1954                        ASTDeclContextNameLookupTrait(*this, F));
1955      if (ID == PREDEF_DECL_TRANSLATION_UNIT_ID) { // Is it the TU?
1956        DeclContext *TU = Context.getTranslationUnitDecl();
1957        F.DeclContextInfos[TU].NameLookupTableData = Table;
1958        TU->setHasExternalVisibleStorage(true);
1959      } else
1960        PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
1961      break;
1962    }
1963
1964    case REDECLS_UPDATE_LATEST: {
1965      assert(Record.size() % 2 == 0 && "Expected pairs of DeclIDs");
1966      for (unsigned i = 0, e = Record.size(); i < e; /* in loop */) {
1967        DeclID First = ReadDeclID(F, Record, i);
1968        DeclID Latest = ReadDeclID(F, Record, i);
1969        FirstLatestDeclIDs[First] = Latest;
1970      }
1971      break;
1972    }
1973
1974    case LANGUAGE_OPTIONS:
1975      if (ParseLanguageOptions(Record) && !DisableValidation)
1976        return IgnorePCH;
1977      break;
1978
1979    case IDENTIFIER_TABLE:
1980      F.IdentifierTableData = BlobStart;
1981      if (Record[0]) {
1982        F.IdentifierLookupTable
1983          = ASTIdentifierLookupTable::Create(
1984                       (const unsigned char *)F.IdentifierTableData + Record[0],
1985                       (const unsigned char *)F.IdentifierTableData,
1986                       ASTIdentifierLookupTrait(*this, F));
1987
1988        PP.getIdentifierTable().setExternalIdentifierLookup(this);
1989      }
1990      break;
1991
1992    case IDENTIFIER_OFFSET: {
1993      if (F.LocalNumIdentifiers != 0) {
1994        Error("duplicate IDENTIFIER_OFFSET record in AST file");
1995        return Failure;
1996      }
1997      F.IdentifierOffsets = (const uint32_t *)BlobStart;
1998      F.LocalNumIdentifiers = Record[0];
1999      unsigned LocalBaseIdentifierID = Record[1];
2000      F.BaseIdentifierID = getTotalNumIdentifiers();
2001
2002      if (F.LocalNumIdentifiers > 0) {
2003        // Introduce the global -> local mapping for identifiers within this
2004        // module.
2005        GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
2006                                                  &F));
2007
2008        // Introduce the local -> global mapping for identifiers within this
2009        // module.
2010        F.IdentifierRemap.insert(
2011                            std::make_pair(LocalBaseIdentifierID,
2012                              F.BaseIdentifierID - LocalBaseIdentifierID));
2013
2014        IdentifiersLoaded.resize(IdentifiersLoaded.size()
2015                                 + F.LocalNumIdentifiers);
2016      }
2017      break;
2018    }
2019
2020    case EXTERNAL_DEFINITIONS:
2021      for (unsigned I = 0, N = Record.size(); I != N; ++I)
2022        ExternalDefinitions.push_back(getGlobalDeclID(F, Record[I]));
2023      break;
2024
2025    case SPECIAL_TYPES:
2026      for (unsigned I = 0, N = Record.size(); I != N; ++I)
2027        SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2028      break;
2029
2030    case STATISTICS:
2031      TotalNumStatements += Record[0];
2032      TotalNumMacros += Record[1];
2033      TotalLexicalDeclContexts += Record[2];
2034      TotalVisibleDeclContexts += Record[3];
2035      break;
2036
2037    case UNUSED_FILESCOPED_DECLS:
2038      for (unsigned I = 0, N = Record.size(); I != N; ++I)
2039        UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2040      break;
2041
2042    case DELEGATING_CTORS:
2043      for (unsigned I = 0, N = Record.size(); I != N; ++I)
2044        DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2045      break;
2046
2047    case WEAK_UNDECLARED_IDENTIFIERS:
2048      if (Record.size() % 4 != 0) {
2049        Error("invalid weak identifiers record");
2050        return Failure;
2051      }
2052
2053      // FIXME: Ignore weak undeclared identifiers from non-original PCH
2054      // files. This isn't the way to do it :)
2055      WeakUndeclaredIdentifiers.clear();
2056
2057      // Translate the weak, undeclared identifiers into global IDs.
2058      for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2059        WeakUndeclaredIdentifiers.push_back(
2060          getGlobalIdentifierID(F, Record[I++]));
2061        WeakUndeclaredIdentifiers.push_back(
2062          getGlobalIdentifierID(F, Record[I++]));
2063        WeakUndeclaredIdentifiers.push_back(
2064          ReadSourceLocation(F, Record, I).getRawEncoding());
2065        WeakUndeclaredIdentifiers.push_back(Record[I++]);
2066      }
2067      break;
2068
2069    case LOCALLY_SCOPED_EXTERNAL_DECLS:
2070      for (unsigned I = 0, N = Record.size(); I != N; ++I)
2071        LocallyScopedExternalDecls.push_back(getGlobalDeclID(F, Record[I]));
2072      break;
2073
2074    case SELECTOR_OFFSETS: {
2075      F.SelectorOffsets = (const uint32_t *)BlobStart;
2076      F.LocalNumSelectors = Record[0];
2077      unsigned LocalBaseSelectorID = Record[1];
2078      F.BaseSelectorID = getTotalNumSelectors();
2079
2080      if (F.LocalNumSelectors > 0) {
2081        // Introduce the global -> local mapping for selectors within this
2082        // module.
2083        GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
2084
2085        // Introduce the local -> global mapping for selectors within this
2086        // module.
2087        F.SelectorRemap.insert(std::make_pair(LocalBaseSelectorID,
2088                                 F.BaseSelectorID - LocalBaseSelectorID));
2089
2090        SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
2091      }
2092      break;
2093    }
2094
2095    case METHOD_POOL:
2096      F.SelectorLookupTableData = (const unsigned char *)BlobStart;
2097      if (Record[0])
2098        F.SelectorLookupTable
2099          = ASTSelectorLookupTable::Create(
2100                        F.SelectorLookupTableData + Record[0],
2101                        F.SelectorLookupTableData,
2102                        ASTSelectorLookupTrait(*this, F));
2103      TotalNumMethodPoolEntries += Record[1];
2104      break;
2105
2106    case REFERENCED_SELECTOR_POOL:
2107      if (!Record.empty()) {
2108        for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2109          ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
2110                                                                Record[Idx++]));
2111          ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2112                                              getRawEncoding());
2113        }
2114      }
2115      break;
2116
2117    case PP_COUNTER_VALUE:
2118      if (!Record.empty() && Listener)
2119        Listener->ReadCounter(Record[0]);
2120      break;
2121
2122    case SOURCE_LOCATION_OFFSETS: {
2123      F.SLocEntryOffsets = (const uint32_t *)BlobStart;
2124      F.LocalNumSLocEntries = Record[0];
2125      llvm::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
2126          SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries, Record[1]);
2127      // Make our entry in the range map. BaseID is negative and growing, so
2128      // we invert it. Because we invert it, though, we need the other end of
2129      // the range.
2130      unsigned RangeStart =
2131          unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2132      GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2133      F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2134
2135      // Initialize the remapping table.
2136      // Invalid stays invalid.
2137      F.SLocRemap.insert(std::make_pair(0U, 0));
2138      // This module. Base was 2 when being compiled.
2139      F.SLocRemap.insert(std::make_pair(2U,
2140                                  static_cast<int>(F.SLocEntryBaseOffset - 2)));
2141
2142      TotalNumSLocEntries += F.LocalNumSLocEntries;
2143      break;
2144    }
2145
2146    case MODULE_OFFSET_MAP: {
2147      // Additional remapping information.
2148      const unsigned char *Data = (const unsigned char*)BlobStart;
2149      const unsigned char *DataEnd = Data + BlobLen;
2150
2151      // Continuous range maps we may be updating in our module.
2152      ContinuousRangeMap<uint32_t, int, 2>::Builder SLocRemap(F.SLocRemap);
2153      ContinuousRangeMap<uint32_t, int, 2>::Builder
2154        IdentifierRemap(F.IdentifierRemap);
2155      ContinuousRangeMap<uint32_t, int, 2>::Builder
2156        PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2157      ContinuousRangeMap<uint32_t, int, 2>::Builder
2158        MacroDefinitionRemap(F.MacroDefinitionRemap);
2159      ContinuousRangeMap<uint32_t, int, 2>::Builder
2160        SelectorRemap(F.SelectorRemap);
2161      ContinuousRangeMap<uint32_t, int, 2>::Builder DeclRemap(F.DeclRemap);
2162      ContinuousRangeMap<uint32_t, int, 2>::Builder TypeRemap(F.TypeRemap);
2163
2164      while(Data < DataEnd) {
2165        uint16_t Len = io::ReadUnalignedLE16(Data);
2166        StringRef Name = StringRef((const char*)Data, Len);
2167        Data += Len;
2168        Module *OM = ModuleMgr.lookup(Name);
2169        if (!OM) {
2170          Error("SourceLocation remap refers to unknown module");
2171          return Failure;
2172        }
2173
2174        uint32_t SLocOffset = io::ReadUnalignedLE32(Data);
2175        uint32_t IdentifierIDOffset = io::ReadUnalignedLE32(Data);
2176        uint32_t PreprocessedEntityIDOffset = io::ReadUnalignedLE32(Data);
2177        uint32_t MacroDefinitionIDOffset = io::ReadUnalignedLE32(Data);
2178        uint32_t SelectorIDOffset = io::ReadUnalignedLE32(Data);
2179        uint32_t DeclIDOffset = io::ReadUnalignedLE32(Data);
2180        uint32_t TypeIndexOffset = io::ReadUnalignedLE32(Data);
2181
2182        // Source location offset is mapped to OM->SLocEntryBaseOffset.
2183        SLocRemap.insert(std::make_pair(SLocOffset,
2184          static_cast<int>(OM->SLocEntryBaseOffset - SLocOffset)));
2185        IdentifierRemap.insert(
2186          std::make_pair(IdentifierIDOffset,
2187                         OM->BaseIdentifierID - IdentifierIDOffset));
2188        PreprocessedEntityRemap.insert(
2189          std::make_pair(PreprocessedEntityIDOffset,
2190            OM->BasePreprocessedEntityID - PreprocessedEntityIDOffset));
2191        MacroDefinitionRemap.insert(
2192          std::make_pair(MacroDefinitionIDOffset,
2193                         OM->BaseMacroDefinitionID - MacroDefinitionIDOffset));
2194        SelectorRemap.insert(std::make_pair(SelectorIDOffset,
2195                               OM->BaseSelectorID - SelectorIDOffset));
2196        DeclRemap.insert(std::make_pair(DeclIDOffset,
2197                                        OM->BaseDeclID - DeclIDOffset));
2198
2199        TypeRemap.insert(std::make_pair(TypeIndexOffset,
2200                                    OM->BaseTypeIndex - TypeIndexOffset));
2201      }
2202      break;
2203    }
2204
2205    case SOURCE_MANAGER_LINE_TABLE:
2206      if (ParseLineTable(F, Record))
2207        return Failure;
2208      break;
2209
2210    case FILE_SOURCE_LOCATION_OFFSETS:
2211      F.SLocFileOffsets = (const uint32_t *)BlobStart;
2212      F.LocalNumSLocFileEntries = Record[0];
2213      break;
2214
2215    case SOURCE_LOCATION_PRELOADS: {
2216      // Need to transform from the local view (1-based IDs) to the global view,
2217      // which is based off F.SLocEntryBaseID.
2218      if (!F.PreloadSLocEntries.empty()) {
2219        Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
2220        return Failure;
2221      }
2222
2223      F.PreloadSLocEntries.swap(Record);
2224      break;
2225    }
2226
2227    case STAT_CACHE: {
2228      if (!DisableStatCache) {
2229        ASTStatCache *MyStatCache =
2230          new ASTStatCache((const unsigned char *)BlobStart + Record[0],
2231                           (const unsigned char *)BlobStart,
2232                           NumStatHits, NumStatMisses);
2233        FileMgr.addStatCache(MyStatCache);
2234        F.StatCache = MyStatCache;
2235      }
2236      break;
2237    }
2238
2239    case EXT_VECTOR_DECLS:
2240      for (unsigned I = 0, N = Record.size(); I != N; ++I)
2241        ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
2242      break;
2243
2244    case VTABLE_USES:
2245      if (Record.size() % 3 != 0) {
2246        Error("Invalid VTABLE_USES record");
2247        return Failure;
2248      }
2249
2250      // Later tables overwrite earlier ones.
2251      // FIXME: Modules will have some trouble with this. This is clearly not
2252      // the right way to do this.
2253      VTableUses.clear();
2254
2255      for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
2256        VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
2257        VTableUses.push_back(
2258          ReadSourceLocation(F, Record, Idx).getRawEncoding());
2259        VTableUses.push_back(Record[Idx++]);
2260      }
2261      break;
2262
2263    case DYNAMIC_CLASSES:
2264      for (unsigned I = 0, N = Record.size(); I != N; ++I)
2265        DynamicClasses.push_back(getGlobalDeclID(F, Record[I]));
2266      break;
2267
2268    case PENDING_IMPLICIT_INSTANTIATIONS:
2269      if (PendingInstantiations.size() % 2 != 0) {
2270        Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
2271        return Failure;
2272      }
2273
2274      // Later lists of pending instantiations overwrite earlier ones.
2275      // FIXME: This is most certainly wrong for modules.
2276      PendingInstantiations.clear();
2277      for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
2278        PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
2279        PendingInstantiations.push_back(
2280          ReadSourceLocation(F, Record, I).getRawEncoding());
2281      }
2282      break;
2283
2284    case SEMA_DECL_REFS:
2285      // Later tables overwrite earlier ones.
2286      // FIXME: Modules will have some trouble with this.
2287      SemaDeclRefs.clear();
2288      for (unsigned I = 0, N = Record.size(); I != N; ++I)
2289        SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2290      break;
2291
2292    case ORIGINAL_FILE_NAME:
2293      // The primary AST will be the last to get here, so it will be the one
2294      // that's used.
2295      ActualOriginalFileName.assign(BlobStart, BlobLen);
2296      OriginalFileName = ActualOriginalFileName;
2297      MaybeAddSystemRootToFilename(OriginalFileName);
2298      break;
2299
2300    case ORIGINAL_FILE_ID:
2301      OriginalFileID = FileID::get(Record[0]);
2302      break;
2303
2304    case ORIGINAL_PCH_DIR:
2305      // The primary AST will be the last to get here, so it will be the one
2306      // that's used.
2307      OriginalDir.assign(BlobStart, BlobLen);
2308      break;
2309
2310    case VERSION_CONTROL_BRANCH_REVISION: {
2311      const std::string &CurBranch = getClangFullRepositoryVersion();
2312      StringRef ASTBranch(BlobStart, BlobLen);
2313      if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2314        Diag(diag::warn_pch_different_branch) << ASTBranch << CurBranch;
2315        return IgnorePCH;
2316      }
2317      break;
2318    }
2319
2320    case MACRO_DEFINITION_OFFSETS: {
2321      F.MacroDefinitionOffsets = (const uint32_t *)BlobStart;
2322      F.NumPreallocatedPreprocessingEntities = Record[0];
2323      unsigned LocalBasePreprocessedEntityID = Record[1];
2324      F.LocalNumMacroDefinitions = Record[2];
2325      unsigned LocalBaseMacroID = Record[3];
2326
2327      unsigned StartingID;
2328      if (!PP.getPreprocessingRecord())
2329        PP.createPreprocessingRecord(true);
2330      if (!PP.getPreprocessingRecord()->getExternalSource())
2331        PP.getPreprocessingRecord()->SetExternalSource(*this);
2332      StartingID
2333        = PP.getPreprocessingRecord()
2334            ->allocateLoadedEntities(F.NumPreallocatedPreprocessingEntities);
2335      F.BaseMacroDefinitionID = getTotalNumMacroDefinitions();
2336      F.BasePreprocessedEntityID = StartingID;
2337
2338      if (F.NumPreallocatedPreprocessingEntities > 0) {
2339        // Introduce the global -> local mapping for preprocessed entities in
2340        // this module.
2341        GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
2342
2343        // Introduce the local -> global mapping for preprocessed entities in
2344        // this module.
2345        F.PreprocessedEntityRemap.insert(
2346          std::make_pair(LocalBasePreprocessedEntityID,
2347            F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
2348      }
2349
2350
2351      if (F.LocalNumMacroDefinitions > 0) {
2352        // Introduce the global -> local mapping for macro definitions within
2353        // this module.
2354        GlobalMacroDefinitionMap.insert(
2355          std::make_pair(getTotalNumMacroDefinitions() + 1, &F));
2356
2357        // Introduce the local -> global mapping for macro definitions within
2358        // this module.
2359        F.MacroDefinitionRemap.insert(
2360          std::make_pair(LocalBaseMacroID,
2361                         F.BaseMacroDefinitionID - LocalBaseMacroID));
2362
2363        MacroDefinitionsLoaded.resize(
2364                    MacroDefinitionsLoaded.size() + F.LocalNumMacroDefinitions);
2365      }
2366
2367      break;
2368    }
2369
2370    case DECL_UPDATE_OFFSETS: {
2371      if (Record.size() % 2 != 0) {
2372        Error("invalid DECL_UPDATE_OFFSETS block in AST file");
2373        return Failure;
2374      }
2375      for (unsigned I = 0, N = Record.size(); I != N; I += 2)
2376        DeclUpdateOffsets[getGlobalDeclID(F, Record[I])]
2377          .push_back(std::make_pair(&F, Record[I+1]));
2378      break;
2379    }
2380
2381    case DECL_REPLACEMENTS: {
2382      if (Record.size() % 2 != 0) {
2383        Error("invalid DECL_REPLACEMENTS block in AST file");
2384        return Failure;
2385      }
2386      for (unsigned I = 0, N = Record.size(); I != N; I += 2)
2387        ReplacedDecls[getGlobalDeclID(F, Record[I])]
2388          = std::make_pair(&F, Record[I+1]);
2389      break;
2390    }
2391
2392    case OBJC_CHAINED_CATEGORIES: {
2393      if (Record.size() % 3 != 0) {
2394        Error("invalid OBJC_CHAINED_CATEGORIES block in AST file");
2395        return Failure;
2396      }
2397      for (unsigned I = 0, N = Record.size(); I != N; I += 3) {
2398        serialization::GlobalDeclID GlobID = getGlobalDeclID(F, Record[I]);
2399        F.ChainedObjCCategories[GlobID] = std::make_pair(Record[I+1],
2400                                                         Record[I+2]);
2401        ObjCChainedCategoriesInterfaces.insert(GlobID);
2402      }
2403      break;
2404    }
2405
2406    case CXX_BASE_SPECIFIER_OFFSETS: {
2407      if (F.LocalNumCXXBaseSpecifiers != 0) {
2408        Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
2409        return Failure;
2410      }
2411
2412      F.LocalNumCXXBaseSpecifiers = Record[0];
2413      F.CXXBaseSpecifiersOffsets = (const uint32_t *)BlobStart;
2414      NumCXXBaseSpecifiersLoaded += F.LocalNumCXXBaseSpecifiers;
2415      break;
2416    }
2417
2418    case DIAG_PRAGMA_MAPPINGS:
2419      if (Record.size() % 2 != 0) {
2420        Error("invalid DIAG_USER_MAPPINGS block in AST file");
2421        return Failure;
2422      }
2423
2424      if (F.PragmaDiagMappings.empty())
2425        F.PragmaDiagMappings.swap(Record);
2426      else
2427        F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
2428                                    Record.begin(), Record.end());
2429      break;
2430
2431    case CUDA_SPECIAL_DECL_REFS:
2432      // Later tables overwrite earlier ones.
2433      // FIXME: Modules will have trouble with this.
2434      CUDASpecialDeclRefs.clear();
2435      for (unsigned I = 0, N = Record.size(); I != N; ++I)
2436        CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
2437      break;
2438
2439    case HEADER_SEARCH_TABLE: {
2440      F.HeaderFileInfoTableData = BlobStart;
2441      F.LocalNumHeaderFileInfos = Record[1];
2442      F.HeaderFileFrameworkStrings = BlobStart + Record[2];
2443      if (Record[0]) {
2444        F.HeaderFileInfoTable
2445          = HeaderFileInfoLookupTable::Create(
2446                   (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
2447                   (const unsigned char *)F.HeaderFileInfoTableData,
2448                   HeaderFileInfoTrait(*this, F,
2449                                       &PP.getHeaderSearchInfo(),
2450                                       BlobStart + Record[2]));
2451
2452        PP.getHeaderSearchInfo().SetExternalSource(this);
2453        if (!PP.getHeaderSearchInfo().getExternalLookup())
2454          PP.getHeaderSearchInfo().SetExternalLookup(this);
2455      }
2456      break;
2457    }
2458
2459    case FP_PRAGMA_OPTIONS:
2460      // Later tables overwrite earlier ones.
2461      FPPragmaOptions.swap(Record);
2462      break;
2463
2464    case OPENCL_EXTENSIONS:
2465      // Later tables overwrite earlier ones.
2466      OpenCLExtensions.swap(Record);
2467      break;
2468
2469    case TENTATIVE_DEFINITIONS:
2470      for (unsigned I = 0, N = Record.size(); I != N; ++I)
2471        TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
2472      break;
2473
2474    case KNOWN_NAMESPACES:
2475      for (unsigned I = 0, N = Record.size(); I != N; ++I)
2476        KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
2477      break;
2478    }
2479  }
2480  Error("premature end of bitstream in AST file");
2481  return Failure;
2482}
2483
2484ASTReader::ASTReadResult ASTReader::validateFileEntries(Module &M) {
2485  llvm::BitstreamCursor &SLocEntryCursor = M.SLocEntryCursor;
2486
2487  for (unsigned i = 0, e = M.LocalNumSLocFileEntries; i != e; ++i) {
2488    SLocEntryCursor.JumpToBit(M.SLocFileOffsets[i]);
2489    unsigned Code = SLocEntryCursor.ReadCode();
2490    if (Code == llvm::bitc::END_BLOCK ||
2491        Code == llvm::bitc::ENTER_SUBBLOCK ||
2492        Code == llvm::bitc::DEFINE_ABBREV) {
2493      Error("incorrectly-formatted source location entry in AST file");
2494      return Failure;
2495    }
2496
2497    RecordData Record;
2498    const char *BlobStart;
2499    unsigned BlobLen;
2500    switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
2501    default:
2502      Error("incorrectly-formatted source location entry in AST file");
2503      return Failure;
2504
2505    case SM_SLOC_FILE_ENTRY: {
2506      StringRef Filename(BlobStart, BlobLen);
2507      const FileEntry *File = getFileEntry(Filename);
2508
2509      if (File == 0) {
2510        std::string ErrorStr = "could not find file '";
2511        ErrorStr += Filename;
2512        ErrorStr += "' referenced by AST file";
2513        Error(ErrorStr.c_str());
2514        return IgnorePCH;
2515      }
2516
2517      if (Record.size() < 6) {
2518        Error("source location entry is incorrect");
2519        return Failure;
2520      }
2521
2522      // The stat info from the FileEntry came from the cached stat
2523      // info of the PCH, so we cannot trust it.
2524      struct stat StatBuf;
2525      if (::stat(File->getName(), &StatBuf) != 0) {
2526        StatBuf.st_size = File->getSize();
2527        StatBuf.st_mtime = File->getModificationTime();
2528      }
2529
2530      if (((off_t)Record[4] != StatBuf.st_size
2531#if !defined(LLVM_ON_WIN32)
2532          // In our regression testing, the Windows file system seems to
2533          // have inconsistent modification times that sometimes
2534          // erroneously trigger this error-handling path.
2535           || (time_t)Record[5] != StatBuf.st_mtime
2536#endif
2537          )) {
2538        Error(diag::err_fe_pch_file_modified, Filename);
2539        return IgnorePCH;
2540      }
2541
2542      break;
2543    }
2544    }
2545  }
2546
2547  return Success;
2548}
2549
2550namespace {
2551  /// \brief Visitor class used to look up identifirs in an AST file.
2552  class IdentifierLookupVisitor {
2553    StringRef Name;
2554    IdentifierInfo *Found;
2555  public:
2556    explicit IdentifierLookupVisitor(StringRef Name) : Name(Name), Found() { }
2557
2558    static bool visit(Module &M, void *UserData) {
2559      IdentifierLookupVisitor *This
2560      = static_cast<IdentifierLookupVisitor *>(UserData);
2561
2562      ASTIdentifierLookupTable *IdTable
2563        = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
2564      if (!IdTable)
2565        return false;
2566
2567      std::pair<const char*, unsigned> Key(This->Name.begin(),
2568                                           This->Name.size());
2569      ASTIdentifierLookupTable::iterator Pos = IdTable->find(Key);
2570      if (Pos == IdTable->end())
2571        return false;
2572
2573      // Dereferencing the iterator has the effect of building the
2574      // IdentifierInfo node and populating it with the various
2575      // declarations it needs.
2576      This->Found = *Pos;
2577      return true;
2578    }
2579
2580    // \brief Retrieve the identifier info found within the module
2581    // files.
2582    IdentifierInfo *getIdentifierInfo() const { return Found; }
2583  };
2584}
2585
2586
2587ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
2588                                            ModuleKind Type) {
2589  switch(ReadASTCore(FileName, Type, /*ImportedBy=*/0)) {
2590  case Failure: return Failure;
2591  case IgnorePCH: return IgnorePCH;
2592  case Success: break;
2593  }
2594
2595  // Here comes stuff that we only do once the entire chain is loaded.
2596
2597  // Check the predefines buffers.
2598  if (!DisableValidation && Type != MK_Module && Type != MK_Preamble &&
2599      // FIXME: CheckPredefinesBuffers also sets the SuggestedPredefines;
2600      // if DisableValidation is true, defines that were set on command-line
2601      // but not in the PCH file will not be added to SuggestedPredefines.
2602      CheckPredefinesBuffers())
2603    return IgnorePCH;
2604
2605  // Initialization of keywords and pragmas occurs before the
2606  // AST file is read, so there may be some identifiers that were
2607  // loaded into the IdentifierTable before we intercepted the
2608  // creation of identifiers. Iterate through the list of known
2609  // identifiers and determine whether we have to establish
2610  // preprocessor definitions or top-level identifier declaration
2611  // chains for those identifiers.
2612  //
2613  // We copy the IdentifierInfo pointers to a small vector first,
2614  // since de-serializing declarations or macro definitions can add
2615  // new entries into the identifier table, invalidating the
2616  // iterators.
2617  //
2618  // FIXME: We need a lazier way to load this information, e.g., by marking
2619  // the identifier data as 'dirty', so that it will be looked up in the
2620  // AST file(s) if it is uttered in the source. This could save us some
2621  // module load time.
2622  SmallVector<IdentifierInfo *, 128> Identifiers;
2623  for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
2624                              IdEnd = PP.getIdentifierTable().end();
2625       Id != IdEnd; ++Id)
2626    Identifiers.push_back(Id->second);
2627
2628  for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
2629    IdentifierLookupVisitor Visitor(Identifiers[I]->getName());
2630    ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor);
2631  }
2632
2633  InitializeContext();
2634
2635  if (DeserializationListener)
2636    DeserializationListener->ReaderInitialized(this);
2637
2638  // If this AST file is a precompiled preamble, then set the main file ID of
2639  // the source manager to the file source file from which the preamble was
2640  // built. This is the only valid way to use a precompiled preamble.
2641  if (Type == MK_Preamble) {
2642    if (OriginalFileID.isInvalid()) {
2643      SourceLocation Loc
2644        = SourceMgr.getLocation(FileMgr.getFile(getOriginalSourceFile()), 1, 1);
2645      if (Loc.isValid())
2646        OriginalFileID = SourceMgr.getDecomposedLoc(Loc).first;
2647    }
2648    else {
2649      OriginalFileID = FileID::get(ModuleMgr.getPrimaryModule().SLocEntryBaseID
2650                                        + OriginalFileID.getOpaqueValue() - 1);
2651    }
2652
2653    if (!OriginalFileID.isInvalid())
2654      SourceMgr.SetPreambleFileID(OriginalFileID);
2655  }
2656
2657  return Success;
2658}
2659
2660ASTReader::ASTReadResult ASTReader::ReadASTCore(StringRef FileName,
2661                                                ModuleKind Type,
2662                                                Module *ImportedBy) {
2663  Module *M;
2664  bool NewModule;
2665  std::string ErrorStr;
2666  llvm::tie(M, NewModule) = ModuleMgr.addModule(FileName, Type, ImportedBy,
2667                                                ErrorStr);
2668
2669  if (!M) {
2670    // We couldn't load the module.
2671    std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
2672      + ErrorStr;
2673    Error(Msg);
2674    return Failure;
2675  }
2676
2677  if (!NewModule) {
2678    // We've already loaded this module.
2679    return Success;
2680  }
2681
2682  // FIXME: This seems rather a hack. Should CurrentDir be part of the
2683  // module?
2684  if (FileName != "-") {
2685    CurrentDir = llvm::sys::path::parent_path(FileName);
2686    if (CurrentDir.empty()) CurrentDir = ".";
2687  }
2688
2689  Module &F = *M;
2690  llvm::BitstreamCursor &Stream = F.Stream;
2691  Stream.init(F.StreamFile);
2692  F.SizeInBits = F.Buffer->getBufferSize() * 8;
2693
2694  // Sniff for the signature.
2695  if (Stream.Read(8) != 'C' ||
2696      Stream.Read(8) != 'P' ||
2697      Stream.Read(8) != 'C' ||
2698      Stream.Read(8) != 'H') {
2699    Diag(diag::err_not_a_pch_file) << FileName;
2700    return Failure;
2701  }
2702
2703  while (!Stream.AtEndOfStream()) {
2704    unsigned Code = Stream.ReadCode();
2705
2706    if (Code != llvm::bitc::ENTER_SUBBLOCK) {
2707      Error("invalid record at top-level of AST file");
2708      return Failure;
2709    }
2710
2711    unsigned BlockID = Stream.ReadSubBlockID();
2712
2713    // We only know the AST subblock ID.
2714    switch (BlockID) {
2715    case llvm::bitc::BLOCKINFO_BLOCK_ID:
2716      if (Stream.ReadBlockInfoBlock()) {
2717        Error("malformed BlockInfoBlock in AST file");
2718        return Failure;
2719      }
2720      break;
2721    case AST_BLOCK_ID:
2722      switch (ReadASTBlock(F)) {
2723      case Success:
2724        break;
2725
2726      case Failure:
2727        return Failure;
2728
2729      case IgnorePCH:
2730        // FIXME: We could consider reading through to the end of this
2731        // AST block, skipping subblocks, to see if there are other
2732        // AST blocks elsewhere.
2733
2734        // FIXME: We can't clear loaded slocentries anymore.
2735        //SourceMgr.ClearPreallocatedSLocEntries();
2736
2737        // Remove the stat cache.
2738        if (F.StatCache)
2739          FileMgr.removeStatCache((ASTStatCache*)F.StatCache);
2740
2741        return IgnorePCH;
2742      }
2743      break;
2744    default:
2745      if (Stream.SkipBlock()) {
2746        Error("malformed block record in AST file");
2747        return Failure;
2748      }
2749      break;
2750    }
2751  }
2752
2753  // Once read, set the Module bit base offset and update the size in
2754  // bits of all files we've seen.
2755  F.GlobalBitOffset = TotalModulesSizeInBits;
2756  TotalModulesSizeInBits += F.SizeInBits;
2757  GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
2758
2759  // Make sure that the files this module was built against are still available.
2760  if (!DisableValidation) {
2761    switch(validateFileEntries(*M)) {
2762    case Failure: return Failure;
2763    case IgnorePCH: return IgnorePCH;
2764    case Success: break;
2765    }
2766  }
2767
2768  // Preload SLocEntries.
2769  for (unsigned I = 0, N = M->PreloadSLocEntries.size(); I != N; ++I) {
2770    int Index = int(M->PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
2771    ASTReadResult Result = ReadSLocEntryRecord(Index);
2772    if (Result != Success)
2773      return Failure;
2774  }
2775
2776
2777  return Success;
2778}
2779
2780void ASTReader::InitializeContext() {
2781  // If there's a listener, notify them that we "read" the translation unit.
2782  if (DeserializationListener)
2783    DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
2784                                      Context.getTranslationUnitDecl());
2785
2786  // Make sure we load the declaration update records for the translation unit,
2787  // if there are any.
2788  loadDeclUpdateRecords(PREDEF_DECL_TRANSLATION_UNIT_ID,
2789                        Context.getTranslationUnitDecl());
2790
2791  // FIXME: Find a better way to deal with collisions between these
2792  // built-in types. Right now, we just ignore the problem.
2793
2794  // Load the special types.
2795  if (SpecialTypes.size() > NumSpecialTypeIDs) {
2796    if (Context.getBuiltinVaListType().isNull()) {
2797      Context.setBuiltinVaListType(
2798        GetType(SpecialTypes[SPECIAL_TYPE_BUILTIN_VA_LIST]));
2799    }
2800
2801    if (unsigned Proto = SpecialTypes[SPECIAL_TYPE_OBJC_PROTOCOL]) {
2802      if (Context.ObjCProtoType.isNull())
2803        Context.ObjCProtoType = GetType(Proto);
2804    }
2805
2806    if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
2807      if (!Context.CFConstantStringTypeDecl)
2808        Context.setCFConstantStringType(GetType(String));
2809    }
2810
2811    if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
2812      QualType FileType = GetType(File);
2813      if (FileType.isNull()) {
2814        Error("FILE type is NULL");
2815        return;
2816      }
2817
2818      if (!Context.FILEDecl) {
2819        if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
2820          Context.setFILEDecl(Typedef->getDecl());
2821        else {
2822          const TagType *Tag = FileType->getAs<TagType>();
2823          if (!Tag) {
2824            Error("Invalid FILE type in AST file");
2825            return;
2826          }
2827          Context.setFILEDecl(Tag->getDecl());
2828        }
2829      }
2830    }
2831
2832    if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_jmp_buf]) {
2833      QualType Jmp_bufType = GetType(Jmp_buf);
2834      if (Jmp_bufType.isNull()) {
2835        Error("jmp_buf type is NULL");
2836        return;
2837      }
2838
2839      if (!Context.jmp_bufDecl) {
2840        if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
2841          Context.setjmp_bufDecl(Typedef->getDecl());
2842        else {
2843          const TagType *Tag = Jmp_bufType->getAs<TagType>();
2844          if (!Tag) {
2845            Error("Invalid jmp_buf type in AST file");
2846            return;
2847          }
2848          Context.setjmp_bufDecl(Tag->getDecl());
2849        }
2850      }
2851    }
2852
2853    if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_sigjmp_buf]) {
2854      QualType Sigjmp_bufType = GetType(Sigjmp_buf);
2855      if (Sigjmp_bufType.isNull()) {
2856        Error("sigjmp_buf type is NULL");
2857        return;
2858      }
2859
2860      if (!Context.sigjmp_bufDecl) {
2861        if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
2862          Context.setsigjmp_bufDecl(Typedef->getDecl());
2863        else {
2864          const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
2865          assert(Tag && "Invalid sigjmp_buf type in AST file");
2866          Context.setsigjmp_bufDecl(Tag->getDecl());
2867        }
2868      }
2869    }
2870
2871    if (unsigned ObjCIdRedef
2872          = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
2873      if (Context.ObjCIdRedefinitionType.isNull())
2874        Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
2875    }
2876
2877    if (unsigned ObjCClassRedef
2878          = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
2879      if (Context.ObjCClassRedefinitionType.isNull())
2880        Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
2881    }
2882
2883    if (unsigned ObjCSelRedef
2884          = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
2885      if (Context.ObjCSelRedefinitionType.isNull())
2886        Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
2887    }
2888  }
2889
2890  ReadPragmaDiagnosticMappings(Context.getDiagnostics());
2891
2892  // If there were any CUDA special declarations, deserialize them.
2893  if (!CUDASpecialDeclRefs.empty()) {
2894    assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
2895    Context.setcudaConfigureCallDecl(
2896                           cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
2897  }
2898}
2899
2900/// \brief Retrieve the name of the original source file name
2901/// directly from the AST file, without actually loading the AST
2902/// file.
2903std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
2904                                             FileManager &FileMgr,
2905                                             Diagnostic &Diags) {
2906  // Open the AST file.
2907  std::string ErrStr;
2908  llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
2909  Buffer.reset(FileMgr.getBufferForFile(ASTFileName, &ErrStr));
2910  if (!Buffer) {
2911    Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
2912    return std::string();
2913  }
2914
2915  // Initialize the stream
2916  llvm::BitstreamReader StreamFile;
2917  llvm::BitstreamCursor Stream;
2918  StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
2919                  (const unsigned char *)Buffer->getBufferEnd());
2920  Stream.init(StreamFile);
2921
2922  // Sniff for the signature.
2923  if (Stream.Read(8) != 'C' ||
2924      Stream.Read(8) != 'P' ||
2925      Stream.Read(8) != 'C' ||
2926      Stream.Read(8) != 'H') {
2927    Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
2928    return std::string();
2929  }
2930
2931  RecordData Record;
2932  while (!Stream.AtEndOfStream()) {
2933    unsigned Code = Stream.ReadCode();
2934
2935    if (Code == llvm::bitc::ENTER_SUBBLOCK) {
2936      unsigned BlockID = Stream.ReadSubBlockID();
2937
2938      // We only know the AST subblock ID.
2939      switch (BlockID) {
2940      case AST_BLOCK_ID:
2941        if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2942          Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
2943          return std::string();
2944        }
2945        break;
2946
2947      default:
2948        if (Stream.SkipBlock()) {
2949          Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
2950          return std::string();
2951        }
2952        break;
2953      }
2954      continue;
2955    }
2956
2957    if (Code == llvm::bitc::END_BLOCK) {
2958      if (Stream.ReadBlockEnd()) {
2959        Diags.Report(diag::err_fe_pch_error_at_end_block) << ASTFileName;
2960        return std::string();
2961      }
2962      continue;
2963    }
2964
2965    if (Code == llvm::bitc::DEFINE_ABBREV) {
2966      Stream.ReadAbbrevRecord();
2967      continue;
2968    }
2969
2970    Record.clear();
2971    const char *BlobStart = 0;
2972    unsigned BlobLen = 0;
2973    if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
2974          == ORIGINAL_FILE_NAME)
2975      return std::string(BlobStart, BlobLen);
2976  }
2977
2978  return std::string();
2979}
2980
2981/// \brief Parse the record that corresponds to a LangOptions data
2982/// structure.
2983///
2984/// This routine parses the language options from the AST file and then gives
2985/// them to the AST listener if one is set.
2986///
2987/// \returns true if the listener deems the file unacceptable, false otherwise.
2988bool ASTReader::ParseLanguageOptions(
2989                             const SmallVectorImpl<uint64_t> &Record) {
2990  if (Listener) {
2991    LangOptions LangOpts;
2992
2993  #define PARSE_LANGOPT(Option)                  \
2994      LangOpts.Option = Record[Idx];             \
2995      ++Idx
2996
2997    unsigned Idx = 0;
2998    PARSE_LANGOPT(Trigraphs);
2999    PARSE_LANGOPT(BCPLComment);
3000    PARSE_LANGOPT(DollarIdents);
3001    PARSE_LANGOPT(AsmPreprocessor);
3002    PARSE_LANGOPT(GNUMode);
3003    PARSE_LANGOPT(GNUKeywords);
3004    PARSE_LANGOPT(ImplicitInt);
3005    PARSE_LANGOPT(Digraphs);
3006    PARSE_LANGOPT(HexFloats);
3007    PARSE_LANGOPT(C99);
3008    PARSE_LANGOPT(C1X);
3009    PARSE_LANGOPT(Microsoft);
3010    PARSE_LANGOPT(CPlusPlus);
3011    PARSE_LANGOPT(CPlusPlus0x);
3012    PARSE_LANGOPT(CXXOperatorNames);
3013    PARSE_LANGOPT(ObjC1);
3014    PARSE_LANGOPT(ObjC2);
3015    PARSE_LANGOPT(ObjCNonFragileABI);
3016    PARSE_LANGOPT(ObjCNonFragileABI2);
3017    PARSE_LANGOPT(AppleKext);
3018    PARSE_LANGOPT(ObjCDefaultSynthProperties);
3019    PARSE_LANGOPT(ObjCInferRelatedResultType);
3020    PARSE_LANGOPT(NoConstantCFStrings);
3021    PARSE_LANGOPT(PascalStrings);
3022    PARSE_LANGOPT(WritableStrings);
3023    PARSE_LANGOPT(LaxVectorConversions);
3024    PARSE_LANGOPT(AltiVec);
3025    PARSE_LANGOPT(Exceptions);
3026    PARSE_LANGOPT(ObjCExceptions);
3027    PARSE_LANGOPT(CXXExceptions);
3028    PARSE_LANGOPT(SjLjExceptions);
3029    PARSE_LANGOPT(MSBitfields);
3030    PARSE_LANGOPT(NeXTRuntime);
3031    PARSE_LANGOPT(Freestanding);
3032    PARSE_LANGOPT(NoBuiltin);
3033    PARSE_LANGOPT(ThreadsafeStatics);
3034    PARSE_LANGOPT(POSIXThreads);
3035    PARSE_LANGOPT(Blocks);
3036    PARSE_LANGOPT(EmitAllDecls);
3037    PARSE_LANGOPT(MathErrno);
3038    LangOpts.setSignedOverflowBehavior((LangOptions::SignedOverflowBehaviorTy)
3039                                       Record[Idx++]);
3040    PARSE_LANGOPT(HeinousExtensions);
3041    PARSE_LANGOPT(Optimize);
3042    PARSE_LANGOPT(OptimizeSize);
3043    PARSE_LANGOPT(Static);
3044    PARSE_LANGOPT(PICLevel);
3045    PARSE_LANGOPT(GNUInline);
3046    PARSE_LANGOPT(NoInline);
3047    PARSE_LANGOPT(Deprecated);
3048    PARSE_LANGOPT(AccessControl);
3049    PARSE_LANGOPT(CharIsSigned);
3050    PARSE_LANGOPT(ShortWChar);
3051    PARSE_LANGOPT(ShortEnums);
3052    LangOpts.setGCMode((LangOptions::GCMode)Record[Idx++]);
3053    LangOpts.setVisibilityMode((Visibility)Record[Idx++]);
3054    LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
3055                                   Record[Idx++]);
3056    PARSE_LANGOPT(InstantiationDepth);
3057    PARSE_LANGOPT(OpenCL);
3058    PARSE_LANGOPT(CUDA);
3059    PARSE_LANGOPT(CatchUndefined);
3060    PARSE_LANGOPT(DefaultFPContract);
3061    PARSE_LANGOPT(ElideConstructors);
3062    PARSE_LANGOPT(SpellChecking);
3063    PARSE_LANGOPT(MRTD);
3064    PARSE_LANGOPT(ObjCAutoRefCount);
3065  #undef PARSE_LANGOPT
3066
3067    return Listener->ReadLanguageOptions(LangOpts);
3068  }
3069
3070  return false;
3071}
3072
3073namespace {
3074  /// \brief Visitor used by ASTReader::ReadPreprocessedEntities() to load
3075  /// all of the preprocessed entities within a module.
3076  class ReadPreprocessedEntitiesVisitor {
3077    ASTReader &Reader;
3078
3079  public:
3080    explicit ReadPreprocessedEntitiesVisitor(ASTReader &Reader)
3081      : Reader(Reader) { }
3082
3083    static bool visit(Module &M, bool Preorder, void *UserData) {
3084      if (Preorder)
3085        return false;
3086
3087      ReadPreprocessedEntitiesVisitor *This
3088        = static_cast<ReadPreprocessedEntitiesVisitor *>(UserData);
3089
3090      if (!M.PreprocessorDetailCursor.getBitStreamReader())
3091        return false;
3092
3093      SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
3094      M.PreprocessorDetailCursor.JumpToBit(M.PreprocessorDetailStartOffset);
3095      while (This->Reader.LoadPreprocessedEntity(M)) { }
3096      return false;
3097    }
3098  };
3099}
3100
3101void ASTReader::ReadPreprocessedEntities() {
3102  ReadPreprocessedEntitiesVisitor Visitor(*this);
3103  ModuleMgr.visitDepthFirst(&ReadPreprocessedEntitiesVisitor::visit, &Visitor);
3104}
3105
3106PreprocessedEntity *ASTReader::ReadPreprocessedEntityAtOffset(uint64_t Offset) {
3107  RecordLocation Loc = getLocalBitOffset(Offset);
3108
3109  // Keep track of where we are in the stream, then jump back there
3110  // after reading this entity.
3111  SavedStreamPosition SavedPosition(Loc.F->PreprocessorDetailCursor);
3112  Loc.F->PreprocessorDetailCursor.JumpToBit(Loc.Offset);
3113  return LoadPreprocessedEntity(*Loc.F);
3114}
3115
3116namespace {
3117  /// \brief Visitor used to search for information about a header file.
3118  class HeaderFileInfoVisitor {
3119    ASTReader &Reader;
3120    const FileEntry *FE;
3121
3122    llvm::Optional<HeaderFileInfo> HFI;
3123
3124  public:
3125    HeaderFileInfoVisitor(ASTReader &Reader, const FileEntry *FE)
3126      : Reader(Reader), FE(FE) { }
3127
3128    static bool visit(Module &M, void *UserData) {
3129      HeaderFileInfoVisitor *This
3130        = static_cast<HeaderFileInfoVisitor *>(UserData);
3131
3132      HeaderFileInfoTrait Trait(This->Reader, M,
3133                                &This->Reader.getPreprocessor().getHeaderSearchInfo(),
3134                                M.HeaderFileFrameworkStrings,
3135                                This->FE->getName());
3136
3137      HeaderFileInfoLookupTable *Table
3138        = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
3139      if (!Table)
3140        return false;
3141
3142      // Look in the on-disk hash table for an entry for this file name.
3143      HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE->getName(),
3144                                                            &Trait);
3145      if (Pos == Table->end())
3146        return false;
3147
3148      This->HFI = *Pos;
3149      return true;
3150    }
3151
3152    llvm::Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
3153  };
3154}
3155
3156HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
3157  HeaderFileInfoVisitor Visitor(*this, FE);
3158  ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
3159  if (llvm::Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo()) {
3160    if (Listener)
3161      Listener->ReadHeaderFileInfo(*HFI, FE->getUID());
3162    return *HFI;
3163  }
3164
3165  return HeaderFileInfo();
3166}
3167
3168void ASTReader::ReadPragmaDiagnosticMappings(Diagnostic &Diag) {
3169  for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
3170    Module &F = *(*I);
3171    unsigned Idx = 0;
3172    while (Idx < F.PragmaDiagMappings.size()) {
3173      SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
3174      while (1) {
3175        assert(Idx < F.PragmaDiagMappings.size() &&
3176               "Invalid data, didn't find '-1' marking end of diag/map pairs");
3177        if (Idx >= F.PragmaDiagMappings.size()) {
3178          break; // Something is messed up but at least avoid infinite loop in
3179                 // release build.
3180        }
3181        unsigned DiagID = F.PragmaDiagMappings[Idx++];
3182        if (DiagID == (unsigned)-1) {
3183          break; // no more diag/map pairs for this location.
3184        }
3185        diag::Mapping Map = (diag::Mapping)F.PragmaDiagMappings[Idx++];
3186        Diag.setDiagnosticMapping(DiagID, Map, Loc);
3187      }
3188    }
3189  }
3190}
3191
3192/// \brief Get the correct cursor and offset for loading a type.
3193ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
3194  GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
3195  assert(I != GlobalTypeMap.end() && "Corrupted global type map");
3196  Module *M = I->second;
3197  return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
3198}
3199
3200/// \brief Read and return the type with the given index..
3201///
3202/// The index is the type ID, shifted and minus the number of predefs. This
3203/// routine actually reads the record corresponding to the type at the given
3204/// location. It is a helper routine for GetType, which deals with reading type
3205/// IDs.
3206QualType ASTReader::readTypeRecord(unsigned Index) {
3207  RecordLocation Loc = TypeCursorForIndex(Index);
3208  llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
3209
3210  // Keep track of where we are in the stream, then jump back there
3211  // after reading this type.
3212  SavedStreamPosition SavedPosition(DeclsCursor);
3213
3214  ReadingKindTracker ReadingKind(Read_Type, *this);
3215
3216  // Note that we are loading a type record.
3217  Deserializing AType(this);
3218
3219  unsigned Idx = 0;
3220  DeclsCursor.JumpToBit(Loc.Offset);
3221  RecordData Record;
3222  unsigned Code = DeclsCursor.ReadCode();
3223  switch ((TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
3224  case TYPE_EXT_QUAL: {
3225    if (Record.size() != 2) {
3226      Error("Incorrect encoding of extended qualifier type");
3227      return QualType();
3228    }
3229    QualType Base = readType(*Loc.F, Record, Idx);
3230    Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
3231    return Context.getQualifiedType(Base, Quals);
3232  }
3233
3234  case TYPE_COMPLEX: {
3235    if (Record.size() != 1) {
3236      Error("Incorrect encoding of complex type");
3237      return QualType();
3238    }
3239    QualType ElemType = readType(*Loc.F, Record, Idx);
3240    return Context.getComplexType(ElemType);
3241  }
3242
3243  case TYPE_POINTER: {
3244    if (Record.size() != 1) {
3245      Error("Incorrect encoding of pointer type");
3246      return QualType();
3247    }
3248    QualType PointeeType = readType(*Loc.F, Record, Idx);
3249    return Context.getPointerType(PointeeType);
3250  }
3251
3252  case TYPE_BLOCK_POINTER: {
3253    if (Record.size() != 1) {
3254      Error("Incorrect encoding of block pointer type");
3255      return QualType();
3256    }
3257    QualType PointeeType = readType(*Loc.F, Record, Idx);
3258    return Context.getBlockPointerType(PointeeType);
3259  }
3260
3261  case TYPE_LVALUE_REFERENCE: {
3262    if (Record.size() != 2) {
3263      Error("Incorrect encoding of lvalue reference type");
3264      return QualType();
3265    }
3266    QualType PointeeType = readType(*Loc.F, Record, Idx);
3267    return Context.getLValueReferenceType(PointeeType, Record[1]);
3268  }
3269
3270  case TYPE_RVALUE_REFERENCE: {
3271    if (Record.size() != 1) {
3272      Error("Incorrect encoding of rvalue reference type");
3273      return QualType();
3274    }
3275    QualType PointeeType = readType(*Loc.F, Record, Idx);
3276    return Context.getRValueReferenceType(PointeeType);
3277  }
3278
3279  case TYPE_MEMBER_POINTER: {
3280    if (Record.size() != 2) {
3281      Error("Incorrect encoding of member pointer type");
3282      return QualType();
3283    }
3284    QualType PointeeType = readType(*Loc.F, Record, Idx);
3285    QualType ClassType = readType(*Loc.F, Record, Idx);
3286    if (PointeeType.isNull() || ClassType.isNull())
3287      return QualType();
3288
3289    return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
3290  }
3291
3292  case TYPE_CONSTANT_ARRAY: {
3293    QualType ElementType = readType(*Loc.F, Record, Idx);
3294    ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
3295    unsigned IndexTypeQuals = Record[2];
3296    unsigned Idx = 3;
3297    llvm::APInt Size = ReadAPInt(Record, Idx);
3298    return Context.getConstantArrayType(ElementType, Size,
3299                                         ASM, IndexTypeQuals);
3300  }
3301
3302  case TYPE_INCOMPLETE_ARRAY: {
3303    QualType ElementType = readType(*Loc.F, Record, Idx);
3304    ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
3305    unsigned IndexTypeQuals = Record[2];
3306    return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
3307  }
3308
3309  case TYPE_VARIABLE_ARRAY: {
3310    QualType ElementType = readType(*Loc.F, Record, Idx);
3311    ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
3312    unsigned IndexTypeQuals = Record[2];
3313    SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
3314    SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
3315    return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
3316                                         ASM, IndexTypeQuals,
3317                                         SourceRange(LBLoc, RBLoc));
3318  }
3319
3320  case TYPE_VECTOR: {
3321    if (Record.size() != 3) {
3322      Error("incorrect encoding of vector type in AST file");
3323      return QualType();
3324    }
3325
3326    QualType ElementType = readType(*Loc.F, Record, Idx);
3327    unsigned NumElements = Record[1];
3328    unsigned VecKind = Record[2];
3329    return Context.getVectorType(ElementType, NumElements,
3330                                  (VectorType::VectorKind)VecKind);
3331  }
3332
3333  case TYPE_EXT_VECTOR: {
3334    if (Record.size() != 3) {
3335      Error("incorrect encoding of extended vector type in AST file");
3336      return QualType();
3337    }
3338
3339    QualType ElementType = readType(*Loc.F, Record, Idx);
3340    unsigned NumElements = Record[1];
3341    return Context.getExtVectorType(ElementType, NumElements);
3342  }
3343
3344  case TYPE_FUNCTION_NO_PROTO: {
3345    if (Record.size() != 6) {
3346      Error("incorrect encoding of no-proto function type");
3347      return QualType();
3348    }
3349    QualType ResultType = readType(*Loc.F, Record, Idx);
3350    FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
3351                               (CallingConv)Record[4], Record[5]);
3352    return Context.getFunctionNoProtoType(ResultType, Info);
3353  }
3354
3355  case TYPE_FUNCTION_PROTO: {
3356    QualType ResultType = readType(*Loc.F, Record, Idx);
3357
3358    FunctionProtoType::ExtProtoInfo EPI;
3359    EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
3360                                        /*hasregparm*/ Record[2],
3361                                        /*regparm*/ Record[3],
3362                                        static_cast<CallingConv>(Record[4]),
3363                                        /*produces*/ Record[5]);
3364
3365    unsigned Idx = 6;
3366    unsigned NumParams = Record[Idx++];
3367    SmallVector<QualType, 16> ParamTypes;
3368    for (unsigned I = 0; I != NumParams; ++I)
3369      ParamTypes.push_back(readType(*Loc.F, Record, Idx));
3370
3371    EPI.Variadic = Record[Idx++];
3372    EPI.TypeQuals = Record[Idx++];
3373    EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
3374    ExceptionSpecificationType EST =
3375        static_cast<ExceptionSpecificationType>(Record[Idx++]);
3376    EPI.ExceptionSpecType = EST;
3377    if (EST == EST_Dynamic) {
3378      EPI.NumExceptions = Record[Idx++];
3379      SmallVector<QualType, 2> Exceptions;
3380      for (unsigned I = 0; I != EPI.NumExceptions; ++I)
3381        Exceptions.push_back(readType(*Loc.F, Record, Idx));
3382      EPI.Exceptions = Exceptions.data();
3383    } else if (EST == EST_ComputedNoexcept) {
3384      EPI.NoexceptExpr = ReadExpr(*Loc.F);
3385    }
3386    return Context.getFunctionType(ResultType, ParamTypes.data(), NumParams,
3387                                    EPI);
3388  }
3389
3390  case TYPE_UNRESOLVED_USING: {
3391    unsigned Idx = 0;
3392    return Context.getTypeDeclType(
3393                  ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
3394  }
3395
3396  case TYPE_TYPEDEF: {
3397    if (Record.size() != 2) {
3398      Error("incorrect encoding of typedef type");
3399      return QualType();
3400    }
3401    unsigned Idx = 0;
3402    TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
3403    QualType Canonical = readType(*Loc.F, Record, Idx);
3404    if (!Canonical.isNull())
3405      Canonical = Context.getCanonicalType(Canonical);
3406    return Context.getTypedefType(Decl, Canonical);
3407  }
3408
3409  case TYPE_TYPEOF_EXPR:
3410    return Context.getTypeOfExprType(ReadExpr(*Loc.F));
3411
3412  case TYPE_TYPEOF: {
3413    if (Record.size() != 1) {
3414      Error("incorrect encoding of typeof(type) in AST file");
3415      return QualType();
3416    }
3417    QualType UnderlyingType = readType(*Loc.F, Record, Idx);
3418    return Context.getTypeOfType(UnderlyingType);
3419  }
3420
3421  case TYPE_DECLTYPE:
3422    return Context.getDecltypeType(ReadExpr(*Loc.F));
3423
3424  case TYPE_UNARY_TRANSFORM: {
3425    QualType BaseType = readType(*Loc.F, Record, Idx);
3426    QualType UnderlyingType = readType(*Loc.F, Record, Idx);
3427    UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
3428    return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
3429  }
3430
3431  case TYPE_AUTO:
3432    return Context.getAutoType(readType(*Loc.F, Record, Idx));
3433
3434  case TYPE_RECORD: {
3435    if (Record.size() != 2) {
3436      Error("incorrect encoding of record type");
3437      return QualType();
3438    }
3439    unsigned Idx = 0;
3440    bool IsDependent = Record[Idx++];
3441    QualType T
3442      = Context.getRecordType(ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx));
3443    const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
3444    return T;
3445  }
3446
3447  case TYPE_ENUM: {
3448    if (Record.size() != 2) {
3449      Error("incorrect encoding of enum type");
3450      return QualType();
3451    }
3452    unsigned Idx = 0;
3453    bool IsDependent = Record[Idx++];
3454    QualType T
3455      = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
3456    const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
3457    return T;
3458  }
3459
3460  case TYPE_ATTRIBUTED: {
3461    if (Record.size() != 3) {
3462      Error("incorrect encoding of attributed type");
3463      return QualType();
3464    }
3465    QualType modifiedType = readType(*Loc.F, Record, Idx);
3466    QualType equivalentType = readType(*Loc.F, Record, Idx);
3467    AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
3468    return Context.getAttributedType(kind, modifiedType, equivalentType);
3469  }
3470
3471  case TYPE_PAREN: {
3472    if (Record.size() != 1) {
3473      Error("incorrect encoding of paren type");
3474      return QualType();
3475    }
3476    QualType InnerType = readType(*Loc.F, Record, Idx);
3477    return Context.getParenType(InnerType);
3478  }
3479
3480  case TYPE_PACK_EXPANSION: {
3481    if (Record.size() != 2) {
3482      Error("incorrect encoding of pack expansion type");
3483      return QualType();
3484    }
3485    QualType Pattern = readType(*Loc.F, Record, Idx);
3486    if (Pattern.isNull())
3487      return QualType();
3488    llvm::Optional<unsigned> NumExpansions;
3489    if (Record[1])
3490      NumExpansions = Record[1] - 1;
3491    return Context.getPackExpansionType(Pattern, NumExpansions);
3492  }
3493
3494  case TYPE_ELABORATED: {
3495    unsigned Idx = 0;
3496    ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
3497    NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
3498    QualType NamedType = readType(*Loc.F, Record, Idx);
3499    return Context.getElaboratedType(Keyword, NNS, NamedType);
3500  }
3501
3502  case TYPE_OBJC_INTERFACE: {
3503    unsigned Idx = 0;
3504    ObjCInterfaceDecl *ItfD
3505      = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
3506    return Context.getObjCInterfaceType(ItfD);
3507  }
3508
3509  case TYPE_OBJC_OBJECT: {
3510    unsigned Idx = 0;
3511    QualType Base = readType(*Loc.F, Record, Idx);
3512    unsigned NumProtos = Record[Idx++];
3513    SmallVector<ObjCProtocolDecl*, 4> Protos;
3514    for (unsigned I = 0; I != NumProtos; ++I)
3515      Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
3516    return Context.getObjCObjectType(Base, Protos.data(), NumProtos);
3517  }
3518
3519  case TYPE_OBJC_OBJECT_POINTER: {
3520    unsigned Idx = 0;
3521    QualType Pointee = readType(*Loc.F, Record, Idx);
3522    return Context.getObjCObjectPointerType(Pointee);
3523  }
3524
3525  case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
3526    unsigned Idx = 0;
3527    QualType Parm = readType(*Loc.F, Record, Idx);
3528    QualType Replacement = readType(*Loc.F, Record, Idx);
3529    return
3530      Context.getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
3531                                            Replacement);
3532  }
3533
3534  case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
3535    unsigned Idx = 0;
3536    QualType Parm = readType(*Loc.F, Record, Idx);
3537    TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
3538    return Context.getSubstTemplateTypeParmPackType(
3539                                               cast<TemplateTypeParmType>(Parm),
3540                                                     ArgPack);
3541  }
3542
3543  case TYPE_INJECTED_CLASS_NAME: {
3544    CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
3545    QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
3546    // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
3547    // for AST reading, too much interdependencies.
3548    return
3549      QualType(new (Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
3550  }
3551
3552  case TYPE_TEMPLATE_TYPE_PARM: {
3553    unsigned Idx = 0;
3554    unsigned Depth = Record[Idx++];
3555    unsigned Index = Record[Idx++];
3556    bool Pack = Record[Idx++];
3557    TemplateTypeParmDecl *D
3558      = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
3559    return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
3560  }
3561
3562  case TYPE_DEPENDENT_NAME: {
3563    unsigned Idx = 0;
3564    ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
3565    NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
3566    const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
3567    QualType Canon = readType(*Loc.F, Record, Idx);
3568    if (!Canon.isNull())
3569      Canon = Context.getCanonicalType(Canon);
3570    return Context.getDependentNameType(Keyword, NNS, Name, Canon);
3571  }
3572
3573  case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
3574    unsigned Idx = 0;
3575    ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
3576    NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
3577    const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
3578    unsigned NumArgs = Record[Idx++];
3579    SmallVector<TemplateArgument, 8> Args;
3580    Args.reserve(NumArgs);
3581    while (NumArgs--)
3582      Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
3583    return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
3584                                                      Args.size(), Args.data());
3585  }
3586
3587  case TYPE_DEPENDENT_SIZED_ARRAY: {
3588    unsigned Idx = 0;
3589
3590    // ArrayType
3591    QualType ElementType = readType(*Loc.F, Record, Idx);
3592    ArrayType::ArraySizeModifier ASM
3593      = (ArrayType::ArraySizeModifier)Record[Idx++];
3594    unsigned IndexTypeQuals = Record[Idx++];
3595
3596    // DependentSizedArrayType
3597    Expr *NumElts = ReadExpr(*Loc.F);
3598    SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
3599
3600    return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
3601                                               IndexTypeQuals, Brackets);
3602  }
3603
3604  case TYPE_TEMPLATE_SPECIALIZATION: {
3605    unsigned Idx = 0;
3606    bool IsDependent = Record[Idx++];
3607    TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
3608    SmallVector<TemplateArgument, 8> Args;
3609    ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
3610    QualType Underlying = readType(*Loc.F, Record, Idx);
3611    QualType T;
3612    if (Underlying.isNull())
3613      T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
3614                                                          Args.size());
3615    else
3616      T = Context.getTemplateSpecializationType(Name, Args.data(),
3617                                                 Args.size(), Underlying);
3618    const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
3619    return T;
3620  }
3621  }
3622  // Suppress a GCC warning
3623  return QualType();
3624}
3625
3626class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
3627  ASTReader &Reader;
3628  Module &F;
3629  llvm::BitstreamCursor &DeclsCursor;
3630  const ASTReader::RecordData &Record;
3631  unsigned &Idx;
3632
3633  SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
3634                                    unsigned &I) {
3635    return Reader.ReadSourceLocation(F, R, I);
3636  }
3637
3638  template<typename T>
3639  T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
3640    return Reader.ReadDeclAs<T>(F, Record, Idx);
3641  }
3642
3643public:
3644  TypeLocReader(ASTReader &Reader, Module &F,
3645                const ASTReader::RecordData &Record, unsigned &Idx)
3646    : Reader(Reader), F(F), DeclsCursor(F.DeclsCursor), Record(Record), Idx(Idx)
3647  { }
3648
3649  // We want compile-time assurance that we've enumerated all of
3650  // these, so unfortunately we have to declare them first, then
3651  // define them out-of-line.
3652#define ABSTRACT_TYPELOC(CLASS, PARENT)
3653#define TYPELOC(CLASS, PARENT) \
3654  void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
3655#include "clang/AST/TypeLocNodes.def"
3656
3657  void VisitFunctionTypeLoc(FunctionTypeLoc);
3658  void VisitArrayTypeLoc(ArrayTypeLoc);
3659};
3660
3661void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
3662  // nothing to do
3663}
3664void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
3665  TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
3666  if (TL.needsExtraLocalData()) {
3667    TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
3668    TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
3669    TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
3670    TL.setModeAttr(Record[Idx++]);
3671  }
3672}
3673void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
3674  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3675}
3676void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
3677  TL.setStarLoc(ReadSourceLocation(Record, Idx));
3678}
3679void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
3680  TL.setCaretLoc(ReadSourceLocation(Record, Idx));
3681}
3682void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
3683  TL.setAmpLoc(ReadSourceLocation(Record, Idx));
3684}
3685void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
3686  TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
3687}
3688void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
3689  TL.setStarLoc(ReadSourceLocation(Record, Idx));
3690  TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
3691}
3692void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
3693  TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
3694  TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
3695  if (Record[Idx++])
3696    TL.setSizeExpr(Reader.ReadExpr(F));
3697  else
3698    TL.setSizeExpr(0);
3699}
3700void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
3701  VisitArrayTypeLoc(TL);
3702}
3703void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
3704  VisitArrayTypeLoc(TL);
3705}
3706void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
3707  VisitArrayTypeLoc(TL);
3708}
3709void TypeLocReader::VisitDependentSizedArrayTypeLoc(
3710                                            DependentSizedArrayTypeLoc TL) {
3711  VisitArrayTypeLoc(TL);
3712}
3713void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
3714                                        DependentSizedExtVectorTypeLoc TL) {
3715  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3716}
3717void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
3718  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3719}
3720void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
3721  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3722}
3723void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
3724  TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
3725  TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
3726  TL.setTrailingReturn(Record[Idx++]);
3727  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
3728    TL.setArg(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
3729  }
3730}
3731void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
3732  VisitFunctionTypeLoc(TL);
3733}
3734void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
3735  VisitFunctionTypeLoc(TL);
3736}
3737void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
3738  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3739}
3740void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
3741  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3742}
3743void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
3744  TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
3745  TL.setLParenLoc(ReadSourceLocation(Record, Idx));
3746  TL.setRParenLoc(ReadSourceLocation(Record, Idx));
3747}
3748void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
3749  TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
3750  TL.setLParenLoc(ReadSourceLocation(Record, Idx));
3751  TL.setRParenLoc(ReadSourceLocation(Record, Idx));
3752  TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
3753}
3754void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
3755  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3756}
3757void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
3758  TL.setKWLoc(ReadSourceLocation(Record, Idx));
3759  TL.setLParenLoc(ReadSourceLocation(Record, Idx));
3760  TL.setRParenLoc(ReadSourceLocation(Record, Idx));
3761  TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
3762}
3763void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
3764  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3765}
3766void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
3767  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3768}
3769void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
3770  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3771}
3772void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
3773  TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
3774  if (TL.hasAttrOperand()) {
3775    SourceRange range;
3776    range.setBegin(ReadSourceLocation(Record, Idx));
3777    range.setEnd(ReadSourceLocation(Record, Idx));
3778    TL.setAttrOperandParensRange(range);
3779  }
3780  if (TL.hasAttrExprOperand()) {
3781    if (Record[Idx++])
3782      TL.setAttrExprOperand(Reader.ReadExpr(F));
3783    else
3784      TL.setAttrExprOperand(0);
3785  } else if (TL.hasAttrEnumOperand())
3786    TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
3787}
3788void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
3789  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3790}
3791void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
3792                                            SubstTemplateTypeParmTypeLoc TL) {
3793  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3794}
3795void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
3796                                          SubstTemplateTypeParmPackTypeLoc TL) {
3797  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3798}
3799void TypeLocReader::VisitTemplateSpecializationTypeLoc(
3800                                           TemplateSpecializationTypeLoc TL) {
3801  TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
3802  TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
3803  TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
3804  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3805    TL.setArgLocInfo(i,
3806        Reader.GetTemplateArgumentLocInfo(F,
3807                                          TL.getTypePtr()->getArg(i).getKind(),
3808                                          Record, Idx));
3809}
3810void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
3811  TL.setLParenLoc(ReadSourceLocation(Record, Idx));
3812  TL.setRParenLoc(ReadSourceLocation(Record, Idx));
3813}
3814void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
3815  TL.setKeywordLoc(ReadSourceLocation(Record, Idx));
3816  TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
3817}
3818void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
3819  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3820}
3821void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
3822  TL.setKeywordLoc(ReadSourceLocation(Record, Idx));
3823  TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
3824  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3825}
3826void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
3827       DependentTemplateSpecializationTypeLoc TL) {
3828  TL.setKeywordLoc(ReadSourceLocation(Record, Idx));
3829  TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
3830  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3831  TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
3832  TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
3833  for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
3834    TL.setArgLocInfo(I,
3835        Reader.GetTemplateArgumentLocInfo(F,
3836                                          TL.getTypePtr()->getArg(I).getKind(),
3837                                          Record, Idx));
3838}
3839void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
3840  TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
3841}
3842void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
3843  TL.setNameLoc(ReadSourceLocation(Record, Idx));
3844}
3845void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
3846  TL.setHasBaseTypeAsWritten(Record[Idx++]);
3847  TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
3848  TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
3849  for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
3850    TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
3851}
3852void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
3853  TL.setStarLoc(ReadSourceLocation(Record, Idx));
3854}
3855
3856TypeSourceInfo *ASTReader::GetTypeSourceInfo(Module &F,
3857                                             const RecordData &Record,
3858                                             unsigned &Idx) {
3859  QualType InfoTy = readType(F, Record, Idx);
3860  if (InfoTy.isNull())
3861    return 0;
3862
3863  TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
3864  TypeLocReader TLR(*this, F, Record, Idx);
3865  for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
3866    TLR.Visit(TL);
3867  return TInfo;
3868}
3869
3870QualType ASTReader::GetType(TypeID ID) {
3871  unsigned FastQuals = ID & Qualifiers::FastMask;
3872  unsigned Index = ID >> Qualifiers::FastWidth;
3873
3874  if (Index < NUM_PREDEF_TYPE_IDS) {
3875    QualType T;
3876    switch ((PredefinedTypeIDs)Index) {
3877    case PREDEF_TYPE_NULL_ID: return QualType();
3878    case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
3879    case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
3880
3881    case PREDEF_TYPE_CHAR_U_ID:
3882    case PREDEF_TYPE_CHAR_S_ID:
3883      // FIXME: Check that the signedness of CharTy is correct!
3884      T = Context.CharTy;
3885      break;
3886
3887    case PREDEF_TYPE_UCHAR_ID:      T = Context.UnsignedCharTy;     break;
3888    case PREDEF_TYPE_USHORT_ID:     T = Context.UnsignedShortTy;    break;
3889    case PREDEF_TYPE_UINT_ID:       T = Context.UnsignedIntTy;      break;
3890    case PREDEF_TYPE_ULONG_ID:      T = Context.UnsignedLongTy;     break;
3891    case PREDEF_TYPE_ULONGLONG_ID:  T = Context.UnsignedLongLongTy; break;
3892    case PREDEF_TYPE_UINT128_ID:    T = Context.UnsignedInt128Ty;   break;
3893    case PREDEF_TYPE_SCHAR_ID:      T = Context.SignedCharTy;       break;
3894    case PREDEF_TYPE_WCHAR_ID:      T = Context.WCharTy;            break;
3895    case PREDEF_TYPE_SHORT_ID:      T = Context.ShortTy;            break;
3896    case PREDEF_TYPE_INT_ID:        T = Context.IntTy;              break;
3897    case PREDEF_TYPE_LONG_ID:       T = Context.LongTy;             break;
3898    case PREDEF_TYPE_LONGLONG_ID:   T = Context.LongLongTy;         break;
3899    case PREDEF_TYPE_INT128_ID:     T = Context.Int128Ty;           break;
3900    case PREDEF_TYPE_FLOAT_ID:      T = Context.FloatTy;            break;
3901    case PREDEF_TYPE_DOUBLE_ID:     T = Context.DoubleTy;           break;
3902    case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy;       break;
3903    case PREDEF_TYPE_OVERLOAD_ID:   T = Context.OverloadTy;         break;
3904    case PREDEF_TYPE_BOUND_MEMBER:  T = Context.BoundMemberTy;      break;
3905    case PREDEF_TYPE_DEPENDENT_ID:  T = Context.DependentTy;        break;
3906    case PREDEF_TYPE_UNKNOWN_ANY:   T = Context.UnknownAnyTy;       break;
3907    case PREDEF_TYPE_NULLPTR_ID:    T = Context.NullPtrTy;          break;
3908    case PREDEF_TYPE_CHAR16_ID:     T = Context.Char16Ty;           break;
3909    case PREDEF_TYPE_CHAR32_ID:     T = Context.Char32Ty;           break;
3910    case PREDEF_TYPE_OBJC_ID:       T = Context.ObjCBuiltinIdTy;    break;
3911    case PREDEF_TYPE_OBJC_CLASS:    T = Context.ObjCBuiltinClassTy; break;
3912    case PREDEF_TYPE_OBJC_SEL:      T = Context.ObjCBuiltinSelTy;   break;
3913    case PREDEF_TYPE_AUTO_DEDUCT:   T = Context.getAutoDeductType(); break;
3914
3915    case PREDEF_TYPE_AUTO_RREF_DEDUCT:
3916      T = Context.getAutoRRefDeductType();
3917      break;
3918    }
3919
3920    assert(!T.isNull() && "Unknown predefined type");
3921    return T.withFastQualifiers(FastQuals);
3922  }
3923
3924  Index -= NUM_PREDEF_TYPE_IDS;
3925  assert(Index < TypesLoaded.size() && "Type index out-of-range");
3926  if (TypesLoaded[Index].isNull()) {
3927    TypesLoaded[Index] = readTypeRecord(Index);
3928    if (TypesLoaded[Index].isNull())
3929      return QualType();
3930
3931    TypesLoaded[Index]->setFromAST();
3932    if (DeserializationListener)
3933      DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
3934                                        TypesLoaded[Index]);
3935  }
3936
3937  return TypesLoaded[Index].withFastQualifiers(FastQuals);
3938}
3939
3940QualType ASTReader::getLocalType(Module &F, unsigned LocalID) {
3941  return GetType(getGlobalTypeID(F, LocalID));
3942}
3943
3944serialization::TypeID
3945ASTReader::getGlobalTypeID(Module &F, unsigned LocalID) const {
3946  unsigned FastQuals = LocalID & Qualifiers::FastMask;
3947  unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
3948
3949  if (LocalIndex < NUM_PREDEF_TYPE_IDS)
3950    return LocalID;
3951
3952  ContinuousRangeMap<uint32_t, int, 2>::iterator I
3953    = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
3954  assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
3955
3956  unsigned GlobalIndex = LocalIndex + I->second;
3957  return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
3958}
3959
3960TemplateArgumentLocInfo
3961ASTReader::GetTemplateArgumentLocInfo(Module &F,
3962                                      TemplateArgument::ArgKind Kind,
3963                                      const RecordData &Record,
3964                                      unsigned &Index) {
3965  switch (Kind) {
3966  case TemplateArgument::Expression:
3967    return ReadExpr(F);
3968  case TemplateArgument::Type:
3969    return GetTypeSourceInfo(F, Record, Index);
3970  case TemplateArgument::Template: {
3971    NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
3972                                                                     Index);
3973    SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
3974    return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
3975                                   SourceLocation());
3976  }
3977  case TemplateArgument::TemplateExpansion: {
3978    NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
3979                                                                     Index);
3980    SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
3981    SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
3982    return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
3983                                   EllipsisLoc);
3984  }
3985  case TemplateArgument::Null:
3986  case TemplateArgument::Integral:
3987  case TemplateArgument::Declaration:
3988  case TemplateArgument::Pack:
3989    return TemplateArgumentLocInfo();
3990  }
3991  llvm_unreachable("unexpected template argument loc");
3992  return TemplateArgumentLocInfo();
3993}
3994
3995TemplateArgumentLoc
3996ASTReader::ReadTemplateArgumentLoc(Module &F,
3997                                   const RecordData &Record, unsigned &Index) {
3998  TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
3999
4000  if (Arg.getKind() == TemplateArgument::Expression) {
4001    if (Record[Index++]) // bool InfoHasSameExpr.
4002      return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
4003  }
4004  return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
4005                                                             Record, Index));
4006}
4007
4008Decl *ASTReader::GetExternalDecl(uint32_t ID) {
4009  return GetDecl(ID);
4010}
4011
4012uint64_t ASTReader::readCXXBaseSpecifiers(Module &M, const RecordData &Record,
4013                                          unsigned &Idx){
4014  if (Idx >= Record.size())
4015    return 0;
4016
4017  unsigned LocalID = Record[Idx++];
4018  return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
4019}
4020
4021CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
4022  RecordLocation Loc = getLocalBitOffset(Offset);
4023  llvm::BitstreamCursor &Cursor = Loc.F->DeclsCursor;
4024  SavedStreamPosition SavedPosition(Cursor);
4025  Cursor.JumpToBit(Loc.Offset);
4026  ReadingKindTracker ReadingKind(Read_Decl, *this);
4027  RecordData Record;
4028  unsigned Code = Cursor.ReadCode();
4029  unsigned RecCode = Cursor.ReadRecord(Code, Record);
4030  if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
4031    Error("Malformed AST file: missing C++ base specifiers");
4032    return 0;
4033  }
4034
4035  unsigned Idx = 0;
4036  unsigned NumBases = Record[Idx++];
4037  void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
4038  CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
4039  for (unsigned I = 0; I != NumBases; ++I)
4040    Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
4041  return Bases;
4042}
4043
4044serialization::DeclID
4045ASTReader::getGlobalDeclID(Module &F, unsigned LocalID) const {
4046  if (LocalID < NUM_PREDEF_DECL_IDS)
4047    return LocalID;
4048
4049  ContinuousRangeMap<uint32_t, int, 2>::iterator I
4050    = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
4051  assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
4052
4053  return LocalID + I->second;
4054}
4055
4056bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
4057                                   Module &M) const {
4058  GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(ID);
4059  assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
4060  return &M == I->second;
4061}
4062
4063Decl *ASTReader::GetDecl(DeclID ID) {
4064  if (ID < NUM_PREDEF_DECL_IDS) {
4065    switch ((PredefinedDeclIDs)ID) {
4066    case PREDEF_DECL_NULL_ID:
4067      return 0;
4068
4069    case PREDEF_DECL_TRANSLATION_UNIT_ID:
4070      return Context.getTranslationUnitDecl();
4071
4072    case PREDEF_DECL_OBJC_ID_ID:
4073      return Context.getObjCIdDecl();
4074
4075    case PREDEF_DECL_OBJC_SEL_ID:
4076      return Context.getObjCSelDecl();
4077
4078    case PREDEF_DECL_OBJC_CLASS_ID:
4079      return Context.getObjCClassDecl();
4080
4081    case PREDEF_DECL_INT_128_ID:
4082      return Context.getInt128Decl();
4083
4084    case PREDEF_DECL_UNSIGNED_INT_128_ID:
4085      return Context.getUInt128Decl();
4086
4087    case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
4088      return Context.getObjCInstanceTypeDecl();
4089    }
4090
4091    return 0;
4092  }
4093
4094  unsigned Index = ID - NUM_PREDEF_DECL_IDS;
4095
4096  if (Index > DeclsLoaded.size()) {
4097    Error("declaration ID out-of-range for AST file");
4098    return 0;
4099  }
4100
4101if (!DeclsLoaded[Index]) {
4102    ReadDeclRecord(ID);
4103    if (DeserializationListener)
4104      DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
4105  }
4106
4107  return DeclsLoaded[Index];
4108}
4109
4110serialization::DeclID ASTReader::ReadDeclID(Module &F,
4111                                            const RecordData &Record,
4112                                            unsigned &Idx) {
4113  if (Idx >= Record.size()) {
4114    Error("Corrupted AST file");
4115    return 0;
4116  }
4117
4118  return getGlobalDeclID(F, Record[Idx++]);
4119}
4120
4121/// \brief Resolve the offset of a statement into a statement.
4122///
4123/// This operation will read a new statement from the external
4124/// source each time it is called, and is meant to be used via a
4125/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
4126Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
4127  // Switch case IDs are per Decl.
4128  ClearSwitchCaseIDs();
4129
4130  // Offset here is a global offset across the entire chain.
4131  RecordLocation Loc = getLocalBitOffset(Offset);
4132  Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
4133  return ReadStmtFromStream(*Loc.F);
4134}
4135
4136namespace {
4137  class FindExternalLexicalDeclsVisitor {
4138    ASTReader &Reader;
4139    const DeclContext *DC;
4140    bool (*isKindWeWant)(Decl::Kind);
4141
4142    SmallVectorImpl<Decl*> &Decls;
4143    bool PredefsVisited[NUM_PREDEF_DECL_IDS];
4144
4145  public:
4146    FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
4147                                    bool (*isKindWeWant)(Decl::Kind),
4148                                    SmallVectorImpl<Decl*> &Decls)
4149      : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
4150    {
4151      for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
4152        PredefsVisited[I] = false;
4153    }
4154
4155    static bool visit(Module &M, bool Preorder, void *UserData) {
4156      if (Preorder)
4157        return false;
4158
4159      FindExternalLexicalDeclsVisitor *This
4160        = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
4161
4162      Module::DeclContextInfosMap::iterator Info
4163        = M.DeclContextInfos.find(This->DC);
4164      if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
4165        return false;
4166
4167      // Load all of the declaration IDs
4168      for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
4169                               *IDE = ID + Info->second.NumLexicalDecls;
4170           ID != IDE; ++ID) {
4171        if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
4172          continue;
4173
4174        // Don't add predefined declarations to the lexical context more
4175        // than once.
4176        if (ID->second < NUM_PREDEF_DECL_IDS) {
4177          if (This->PredefsVisited[ID->second])
4178            continue;
4179
4180          This->PredefsVisited[ID->second] = true;
4181        }
4182
4183        if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
4184          if (!This->DC->isDeclInLexicalTraversal(D))
4185            This->Decls.push_back(D);
4186        }
4187      }
4188
4189      return false;
4190    }
4191  };
4192}
4193
4194ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
4195                                         bool (*isKindWeWant)(Decl::Kind),
4196                                         SmallVectorImpl<Decl*> &Decls) {
4197  // There might be lexical decls in multiple modules, for the TU at
4198  // least. Walk all of the modules in the order they were loaded.
4199  FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
4200  ModuleMgr.visitDepthFirst(&FindExternalLexicalDeclsVisitor::visit, &Visitor);
4201  ++NumLexicalDeclContextsRead;
4202  return ELR_Success;
4203}
4204
4205namespace {
4206  /// \brief Module visitor used to perform name lookup into a
4207  /// declaration context.
4208  class DeclContextNameLookupVisitor {
4209    ASTReader &Reader;
4210    const DeclContext *DC;
4211    DeclarationName Name;
4212    SmallVectorImpl<NamedDecl *> &Decls;
4213
4214  public:
4215    DeclContextNameLookupVisitor(ASTReader &Reader,
4216                                 const DeclContext *DC, DeclarationName Name,
4217                                 SmallVectorImpl<NamedDecl *> &Decls)
4218      : Reader(Reader), DC(DC), Name(Name), Decls(Decls) { }
4219
4220    static bool visit(Module &M, void *UserData) {
4221      DeclContextNameLookupVisitor *This
4222        = static_cast<DeclContextNameLookupVisitor *>(UserData);
4223
4224      // Check whether we have any visible declaration information for
4225      // this context in this module.
4226      Module::DeclContextInfosMap::iterator Info
4227        = M.DeclContextInfos.find(This->DC);
4228      if (Info == M.DeclContextInfos.end() || !Info->second.NameLookupTableData)
4229        return false;
4230
4231      // Look for this name within this module.
4232      ASTDeclContextNameLookupTable *LookupTable =
4233        (ASTDeclContextNameLookupTable*)Info->second.NameLookupTableData;
4234      ASTDeclContextNameLookupTable::iterator Pos
4235        = LookupTable->find(This->Name);
4236      if (Pos == LookupTable->end())
4237        return false;
4238
4239      bool FoundAnything = false;
4240      ASTDeclContextNameLookupTrait::data_type Data = *Pos;
4241      for (; Data.first != Data.second; ++Data.first) {
4242        NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
4243        if (!ND)
4244          continue;
4245
4246        if (ND->getDeclName() != This->Name) {
4247          assert(!This->Name.getCXXNameType().isNull() &&
4248                 "Name mismatch without a type");
4249          continue;
4250        }
4251
4252        // Record this declaration.
4253        FoundAnything = true;
4254        This->Decls.push_back(ND);
4255      }
4256
4257      return FoundAnything;
4258    }
4259  };
4260}
4261
4262DeclContext::lookup_result
4263ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
4264                                          DeclarationName Name) {
4265  assert(DC->hasExternalVisibleStorage() &&
4266         "DeclContext has no visible decls in storage");
4267  if (!Name)
4268    return DeclContext::lookup_result(DeclContext::lookup_iterator(0),
4269                                      DeclContext::lookup_iterator(0));
4270
4271  SmallVector<NamedDecl *, 64> Decls;
4272  DeclContextNameLookupVisitor Visitor(*this, DC, Name, Decls);
4273  ModuleMgr.visit(&DeclContextNameLookupVisitor::visit, &Visitor);
4274  ++NumVisibleDeclContextsRead;
4275  SetExternalVisibleDeclsForName(DC, Name, Decls);
4276  return const_cast<DeclContext*>(DC)->lookup(Name);
4277}
4278
4279void ASTReader::PassInterestingDeclsToConsumer() {
4280  assert(Consumer);
4281  while (!InterestingDecls.empty()) {
4282    DeclGroupRef DG(InterestingDecls.front());
4283    InterestingDecls.pop_front();
4284    Consumer->HandleInterestingDecl(DG);
4285  }
4286}
4287
4288void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
4289  this->Consumer = Consumer;
4290
4291  if (!Consumer)
4292    return;
4293
4294  for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
4295    // Force deserialization of this decl, which will cause it to be queued for
4296    // passing to the consumer.
4297    GetDecl(ExternalDefinitions[I]);
4298  }
4299
4300  PassInterestingDeclsToConsumer();
4301}
4302
4303void ASTReader::PrintStats() {
4304  std::fprintf(stderr, "*** AST File Statistics:\n");
4305
4306  unsigned NumTypesLoaded
4307    = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
4308                                      QualType());
4309  unsigned NumDeclsLoaded
4310    = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
4311                                      (Decl *)0);
4312  unsigned NumIdentifiersLoaded
4313    = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
4314                                            IdentifiersLoaded.end(),
4315                                            (IdentifierInfo *)0);
4316  unsigned NumSelectorsLoaded
4317    = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
4318                                          SelectorsLoaded.end(),
4319                                          Selector());
4320
4321  std::fprintf(stderr, "  %u stat cache hits\n", NumStatHits);
4322  std::fprintf(stderr, "  %u stat cache misses\n", NumStatMisses);
4323  if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
4324    std::fprintf(stderr, "  %u/%u source location entries read (%f%%)\n",
4325                 NumSLocEntriesRead, TotalNumSLocEntries,
4326                 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
4327  if (!TypesLoaded.empty())
4328    std::fprintf(stderr, "  %u/%u types read (%f%%)\n",
4329                 NumTypesLoaded, (unsigned)TypesLoaded.size(),
4330                 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
4331  if (!DeclsLoaded.empty())
4332    std::fprintf(stderr, "  %u/%u declarations read (%f%%)\n",
4333                 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
4334                 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
4335  if (!IdentifiersLoaded.empty())
4336    std::fprintf(stderr, "  %u/%u identifiers read (%f%%)\n",
4337                 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
4338                 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
4339  if (!SelectorsLoaded.empty())
4340    std::fprintf(stderr, "  %u/%u selectors read (%f%%)\n",
4341                 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
4342                 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
4343  if (TotalNumStatements)
4344    std::fprintf(stderr, "  %u/%u statements read (%f%%)\n",
4345                 NumStatementsRead, TotalNumStatements,
4346                 ((float)NumStatementsRead/TotalNumStatements * 100));
4347  if (TotalNumMacros)
4348    std::fprintf(stderr, "  %u/%u macros read (%f%%)\n",
4349                 NumMacrosRead, TotalNumMacros,
4350                 ((float)NumMacrosRead/TotalNumMacros * 100));
4351  if (TotalLexicalDeclContexts)
4352    std::fprintf(stderr, "  %u/%u lexical declcontexts read (%f%%)\n",
4353                 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
4354                 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
4355                  * 100));
4356  if (TotalVisibleDeclContexts)
4357    std::fprintf(stderr, "  %u/%u visible declcontexts read (%f%%)\n",
4358                 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
4359                 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
4360                  * 100));
4361  if (TotalNumMethodPoolEntries) {
4362    std::fprintf(stderr, "  %u/%u method pool entries read (%f%%)\n",
4363                 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
4364                 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
4365                  * 100));
4366    std::fprintf(stderr, "  %u method pool misses\n", NumMethodPoolMisses);
4367  }
4368  std::fprintf(stderr, "\n");
4369  dump();
4370  std::fprintf(stderr, "\n");
4371}
4372
4373template<typename Key, typename Module, unsigned InitialCapacity>
4374static void
4375dumpModuleIDMap(StringRef Name,
4376                const ContinuousRangeMap<Key, Module *,
4377                                         InitialCapacity> &Map) {
4378  if (Map.begin() == Map.end())
4379    return;
4380
4381  typedef ContinuousRangeMap<Key, Module *, InitialCapacity> MapType;
4382  llvm::errs() << Name << ":\n";
4383  for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
4384       I != IEnd; ++I) {
4385    llvm::errs() << "  " << I->first << " -> " << I->second->FileName
4386      << "\n";
4387  }
4388}
4389
4390void ASTReader::dump() {
4391  llvm::errs() << "*** PCH/Module Remappings:\n";
4392  dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
4393  dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
4394  dumpModuleIDMap("Global type map", GlobalTypeMap);
4395  dumpModuleIDMap("Global declaration map", GlobalDeclMap);
4396  dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
4397  dumpModuleIDMap("Global selector map", GlobalSelectorMap);
4398  dumpModuleIDMap("Global macro definition map", GlobalMacroDefinitionMap);
4399  dumpModuleIDMap("Global preprocessed entity map",
4400                  GlobalPreprocessedEntityMap);
4401
4402  llvm::errs() << "\n*** PCH/Modules Loaded:";
4403  for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
4404                                       MEnd = ModuleMgr.end();
4405       M != MEnd; ++M)
4406    (*M)->dump();
4407}
4408
4409/// Return the amount of memory used by memory buffers, breaking down
4410/// by heap-backed versus mmap'ed memory.
4411void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
4412  for (ModuleConstIterator I = ModuleMgr.begin(),
4413      E = ModuleMgr.end(); I != E; ++I) {
4414    if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
4415      size_t bytes = buf->getBufferSize();
4416      switch (buf->getBufferKind()) {
4417        case llvm::MemoryBuffer::MemoryBuffer_Malloc:
4418          sizes.malloc_bytes += bytes;
4419          break;
4420        case llvm::MemoryBuffer::MemoryBuffer_MMap:
4421          sizes.mmap_bytes += bytes;
4422          break;
4423      }
4424    }
4425  }
4426}
4427
4428void ASTReader::InitializeSema(Sema &S) {
4429  SemaObj = &S;
4430  S.ExternalSource = this;
4431
4432  // Makes sure any declarations that were deserialized "too early"
4433  // still get added to the identifier's declaration chains.
4434  for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
4435    if (SemaObj->TUScope)
4436      SemaObj->TUScope->AddDecl(PreloadedDecls[I]);
4437
4438    SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
4439  }
4440  PreloadedDecls.clear();
4441
4442  // Load the offsets of the declarations that Sema references.
4443  // They will be lazily deserialized when needed.
4444  if (!SemaDeclRefs.empty()) {
4445    assert(SemaDeclRefs.size() == 2 && "More decl refs than expected!");
4446    if (!SemaObj->StdNamespace)
4447      SemaObj->StdNamespace = SemaDeclRefs[0];
4448    if (!SemaObj->StdBadAlloc)
4449      SemaObj->StdBadAlloc = SemaDeclRefs[1];
4450  }
4451
4452  if (!FPPragmaOptions.empty()) {
4453    assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
4454    SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
4455  }
4456
4457  if (!OpenCLExtensions.empty()) {
4458    unsigned I = 0;
4459#define OPENCLEXT(nm)  SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
4460#include "clang/Basic/OpenCLExtensions.def"
4461
4462    assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
4463  }
4464}
4465
4466IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
4467  IdentifierLookupVisitor Visitor(StringRef(NameStart, NameEnd - NameStart));
4468  ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor);
4469  return Visitor.getIdentifierInfo();
4470}
4471
4472namespace clang {
4473  /// \brief An identifier-lookup iterator that enumerates all of the
4474  /// identifiers stored within a set of AST files.
4475  class ASTIdentifierIterator : public IdentifierIterator {
4476    /// \brief The AST reader whose identifiers are being enumerated.
4477    const ASTReader &Reader;
4478
4479    /// \brief The current index into the chain of AST files stored in
4480    /// the AST reader.
4481    unsigned Index;
4482
4483    /// \brief The current position within the identifier lookup table
4484    /// of the current AST file.
4485    ASTIdentifierLookupTable::key_iterator Current;
4486
4487    /// \brief The end position within the identifier lookup table of
4488    /// the current AST file.
4489    ASTIdentifierLookupTable::key_iterator End;
4490
4491  public:
4492    explicit ASTIdentifierIterator(const ASTReader &Reader);
4493
4494    virtual StringRef Next();
4495  };
4496}
4497
4498ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
4499  : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
4500  ASTIdentifierLookupTable *IdTable
4501    = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
4502  Current = IdTable->key_begin();
4503  End = IdTable->key_end();
4504}
4505
4506StringRef ASTIdentifierIterator::Next() {
4507  while (Current == End) {
4508    // If we have exhausted all of our AST files, we're done.
4509    if (Index == 0)
4510      return StringRef();
4511
4512    --Index;
4513    ASTIdentifierLookupTable *IdTable
4514      = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
4515        IdentifierLookupTable;
4516    Current = IdTable->key_begin();
4517    End = IdTable->key_end();
4518  }
4519
4520  // We have any identifiers remaining in the current AST file; return
4521  // the next one.
4522  std::pair<const char*, unsigned> Key = *Current;
4523  ++Current;
4524  return StringRef(Key.first, Key.second);
4525}
4526
4527IdentifierIterator *ASTReader::getIdentifiers() const {
4528  return new ASTIdentifierIterator(*this);
4529}
4530
4531namespace clang { namespace serialization {
4532  class ReadMethodPoolVisitor {
4533    ASTReader &Reader;
4534    Selector Sel;
4535    llvm::SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
4536    llvm::SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
4537
4538    /// \brief Build an ObjCMethodList from a vector of Objective-C method
4539    /// declarations.
4540    ObjCMethodList
4541    buildObjCMethodList(const SmallVectorImpl<ObjCMethodDecl *> &Vec) const
4542    {
4543      ObjCMethodList List;
4544      ObjCMethodList *Prev = 0;
4545      for (unsigned I = 0, N = Vec.size(); I != N; ++I) {
4546        if (!List.Method) {
4547          // This is the first method, which is the easy case.
4548          List.Method = Vec[I];
4549          Prev = &List;
4550          continue;
4551        }
4552
4553        ObjCMethodList *Mem =
4554          Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
4555        Prev->Next = new (Mem) ObjCMethodList(Vec[I], 0);
4556        Prev = Prev->Next;
4557      }
4558
4559      return List;
4560    }
4561
4562  public:
4563    ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel)
4564      : Reader(Reader), Sel(Sel) { }
4565
4566    static bool visit(Module &M, void *UserData) {
4567      ReadMethodPoolVisitor *This
4568        = static_cast<ReadMethodPoolVisitor *>(UserData);
4569
4570      if (!M.SelectorLookupTable)
4571        return false;
4572
4573      ASTSelectorLookupTable *PoolTable
4574        = (ASTSelectorLookupTable*)M.SelectorLookupTable;
4575      ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
4576      if (Pos == PoolTable->end())
4577        return false;
4578
4579      ++This->Reader.NumSelectorsRead;
4580      // FIXME: Not quite happy with the statistics here. We probably should
4581      // disable this tracking when called via LoadSelector.
4582      // Also, should entries without methods count as misses?
4583      ++This->Reader.NumMethodPoolEntriesRead;
4584      ASTSelectorLookupTrait::data_type Data = *Pos;
4585      if (This->Reader.DeserializationListener)
4586        This->Reader.DeserializationListener->SelectorRead(Data.ID,
4587                                                           This->Sel);
4588
4589      This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
4590      This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
4591      return true;
4592    }
4593
4594    /// \brief Retrieve the instance methods found by this visitor.
4595    ObjCMethodList getInstanceMethods() const {
4596      return buildObjCMethodList(InstanceMethods);
4597    }
4598
4599    /// \brief Retrieve the instance methods found by this visitor.
4600    ObjCMethodList getFactoryMethods() const {
4601      return buildObjCMethodList(FactoryMethods);
4602    }
4603  };
4604} } // end namespace clang::serialization
4605
4606std::pair<ObjCMethodList, ObjCMethodList>
4607ASTReader::ReadMethodPool(Selector Sel) {
4608  ReadMethodPoolVisitor Visitor(*this, Sel);
4609  ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
4610  std::pair<ObjCMethodList, ObjCMethodList> Result;
4611  Result.first = Visitor.getInstanceMethods();
4612  Result.second = Visitor.getFactoryMethods();
4613
4614  if (!Result.first.Method && !Result.second.Method)
4615    ++NumMethodPoolMisses;
4616  return Result;
4617}
4618
4619void ASTReader::ReadKnownNamespaces(
4620                          SmallVectorImpl<NamespaceDecl *> &Namespaces) {
4621  Namespaces.clear();
4622
4623  for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
4624    if (NamespaceDecl *Namespace
4625                = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
4626      Namespaces.push_back(Namespace);
4627  }
4628}
4629
4630void ASTReader::ReadTentativeDefinitions(
4631                  SmallVectorImpl<VarDecl *> &TentativeDefs) {
4632  for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
4633    VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
4634    if (Var)
4635      TentativeDefs.push_back(Var);
4636  }
4637  TentativeDefinitions.clear();
4638}
4639
4640void ASTReader::ReadUnusedFileScopedDecls(
4641                               SmallVectorImpl<const DeclaratorDecl *> &Decls) {
4642  for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
4643    DeclaratorDecl *D
4644      = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
4645    if (D)
4646      Decls.push_back(D);
4647  }
4648  UnusedFileScopedDecls.clear();
4649}
4650
4651void ASTReader::ReadDelegatingConstructors(
4652                                 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
4653  for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
4654    CXXConstructorDecl *D
4655      = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
4656    if (D)
4657      Decls.push_back(D);
4658  }
4659  DelegatingCtorDecls.clear();
4660}
4661
4662void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
4663  for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
4664    TypedefNameDecl *D
4665      = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
4666    if (D)
4667      Decls.push_back(D);
4668  }
4669  ExtVectorDecls.clear();
4670}
4671
4672void ASTReader::ReadDynamicClasses(SmallVectorImpl<CXXRecordDecl *> &Decls) {
4673  for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
4674    CXXRecordDecl *D
4675      = dyn_cast_or_null<CXXRecordDecl>(GetDecl(DynamicClasses[I]));
4676    if (D)
4677      Decls.push_back(D);
4678  }
4679  DynamicClasses.clear();
4680}
4681
4682void
4683ASTReader::ReadLocallyScopedExternalDecls(SmallVectorImpl<NamedDecl *> &Decls) {
4684  for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
4685    NamedDecl *D
4686      = dyn_cast_or_null<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
4687    if (D)
4688      Decls.push_back(D);
4689  }
4690  LocallyScopedExternalDecls.clear();
4691}
4692
4693void ASTReader::ReadReferencedSelectors(
4694       SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
4695  if (ReferencedSelectorsData.empty())
4696    return;
4697
4698  // If there are @selector references added them to its pool. This is for
4699  // implementation of -Wselector.
4700  unsigned int DataSize = ReferencedSelectorsData.size()-1;
4701  unsigned I = 0;
4702  while (I < DataSize) {
4703    Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
4704    SourceLocation SelLoc
4705      = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
4706    Sels.push_back(std::make_pair(Sel, SelLoc));
4707  }
4708  ReferencedSelectorsData.clear();
4709}
4710
4711void ASTReader::ReadWeakUndeclaredIdentifiers(
4712       SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
4713  if (WeakUndeclaredIdentifiers.empty())
4714    return;
4715
4716  for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
4717    IdentifierInfo *WeakId
4718      = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
4719    IdentifierInfo *AliasId
4720      = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
4721    SourceLocation Loc
4722      = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
4723    bool Used = WeakUndeclaredIdentifiers[I++];
4724    WeakInfo WI(AliasId, Loc);
4725    WI.setUsed(Used);
4726    WeakIDs.push_back(std::make_pair(WeakId, WI));
4727  }
4728  WeakUndeclaredIdentifiers.clear();
4729}
4730
4731void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
4732  for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
4733    ExternalVTableUse VT;
4734    VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
4735    VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
4736    VT.DefinitionRequired = VTableUses[Idx++];
4737    VTables.push_back(VT);
4738  }
4739
4740  VTableUses.clear();
4741}
4742
4743void ASTReader::ReadPendingInstantiations(
4744       SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
4745  for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
4746    ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
4747    SourceLocation Loc
4748      = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
4749    Pending.push_back(std::make_pair(D, Loc));
4750  }
4751  PendingInstantiations.clear();
4752}
4753
4754void ASTReader::LoadSelector(Selector Sel) {
4755  // It would be complicated to avoid reading the methods anyway. So don't.
4756  ReadMethodPool(Sel);
4757}
4758
4759void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
4760  assert(ID && "Non-zero identifier ID required");
4761  assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
4762  IdentifiersLoaded[ID - 1] = II;
4763  if (DeserializationListener)
4764    DeserializationListener->IdentifierRead(ID, II);
4765}
4766
4767/// \brief Set the globally-visible declarations associated with the given
4768/// identifier.
4769///
4770/// If the AST reader is currently in a state where the given declaration IDs
4771/// cannot safely be resolved, they are queued until it is safe to resolve
4772/// them.
4773///
4774/// \param II an IdentifierInfo that refers to one or more globally-visible
4775/// declarations.
4776///
4777/// \param DeclIDs the set of declaration IDs with the name @p II that are
4778/// visible at global scope.
4779///
4780/// \param Nonrecursive should be true to indicate that the caller knows that
4781/// this call is non-recursive, and therefore the globally-visible declarations
4782/// will not be placed onto the pending queue.
4783void
4784ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
4785                              const SmallVectorImpl<uint32_t> &DeclIDs,
4786                                   bool Nonrecursive) {
4787  if (NumCurrentElementsDeserializing && !Nonrecursive) {
4788    PendingIdentifierInfos.push_back(PendingIdentifierInfo());
4789    PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
4790    PII.II = II;
4791    PII.DeclIDs.append(DeclIDs.begin(), DeclIDs.end());
4792    return;
4793  }
4794
4795  for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
4796    NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
4797    if (SemaObj) {
4798      if (SemaObj->TUScope) {
4799        // Introduce this declaration into the translation-unit scope
4800        // and add it to the declaration chain for this identifier, so
4801        // that (unqualified) name lookup will find it.
4802        SemaObj->TUScope->AddDecl(D);
4803      }
4804      SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
4805    } else {
4806      // Queue this declaration so that it will be added to the
4807      // translation unit scope and identifier's declaration chain
4808      // once a Sema object is known.
4809      PreloadedDecls.push_back(D);
4810    }
4811  }
4812}
4813
4814IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
4815  if (ID == 0)
4816    return 0;
4817
4818  if (IdentifiersLoaded.empty()) {
4819    Error("no identifier table in AST file");
4820    return 0;
4821  }
4822
4823  ID -= 1;
4824  if (!IdentifiersLoaded[ID]) {
4825    GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
4826    assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
4827    Module *M = I->second;
4828    unsigned Index = ID - M->BaseIdentifierID;
4829    const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
4830
4831    // All of the strings in the AST file are preceded by a 16-bit length.
4832    // Extract that 16-bit length to avoid having to execute strlen().
4833    // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
4834    //  unsigned integers.  This is important to avoid integer overflow when
4835    //  we cast them to 'unsigned'.
4836    const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
4837    unsigned StrLen = (((unsigned) StrLenPtr[0])
4838                       | (((unsigned) StrLenPtr[1]) << 8)) - 1;
4839    IdentifiersLoaded[ID]
4840      = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
4841    if (DeserializationListener)
4842      DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
4843  }
4844
4845  return IdentifiersLoaded[ID];
4846}
4847
4848IdentifierInfo *ASTReader::getLocalIdentifier(Module &M, unsigned LocalID) {
4849  return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
4850}
4851
4852IdentifierID ASTReader::getGlobalIdentifierID(Module &M, unsigned LocalID) {
4853  if (LocalID < NUM_PREDEF_IDENT_IDS)
4854    return LocalID;
4855
4856  ContinuousRangeMap<uint32_t, int, 2>::iterator I
4857    = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
4858  assert(I != M.IdentifierRemap.end()
4859         && "Invalid index into identifier index remap");
4860
4861  return LocalID + I->second;
4862}
4863
4864bool ASTReader::ReadSLocEntry(int ID) {
4865  return ReadSLocEntryRecord(ID) != Success;
4866}
4867
4868Selector ASTReader::getLocalSelector(Module &M, unsigned LocalID) {
4869  return DecodeSelector(getGlobalSelectorID(M, LocalID));
4870}
4871
4872Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
4873  if (ID == 0)
4874    return Selector();
4875
4876  if (ID > SelectorsLoaded.size()) {
4877    Error("selector ID out of range in AST file");
4878    return Selector();
4879  }
4880
4881  if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
4882    // Load this selector from the selector table.
4883    GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
4884    assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
4885    Module &M = *I->second;
4886    ASTSelectorLookupTrait Trait(*this, M);
4887    unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
4888    SelectorsLoaded[ID - 1] =
4889      Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
4890    if (DeserializationListener)
4891      DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
4892  }
4893
4894  return SelectorsLoaded[ID - 1];
4895}
4896
4897Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
4898  return DecodeSelector(ID);
4899}
4900
4901uint32_t ASTReader::GetNumExternalSelectors() {
4902  // ID 0 (the null selector) is considered an external selector.
4903  return getTotalNumSelectors() + 1;
4904}
4905
4906serialization::SelectorID
4907ASTReader::getGlobalSelectorID(Module &M, unsigned LocalID) const {
4908  if (LocalID < NUM_PREDEF_SELECTOR_IDS)
4909    return LocalID;
4910
4911  ContinuousRangeMap<uint32_t, int, 2>::iterator I
4912    = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
4913  assert(I != M.SelectorRemap.end()
4914         && "Invalid index into identifier index remap");
4915
4916  return LocalID + I->second;
4917}
4918
4919DeclarationName
4920ASTReader::ReadDeclarationName(Module &F,
4921                               const RecordData &Record, unsigned &Idx) {
4922  DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
4923  switch (Kind) {
4924  case DeclarationName::Identifier:
4925    return DeclarationName(GetIdentifierInfo(F, Record, Idx));
4926
4927  case DeclarationName::ObjCZeroArgSelector:
4928  case DeclarationName::ObjCOneArgSelector:
4929  case DeclarationName::ObjCMultiArgSelector:
4930    return DeclarationName(ReadSelector(F, Record, Idx));
4931
4932  case DeclarationName::CXXConstructorName:
4933    return Context.DeclarationNames.getCXXConstructorName(
4934                          Context.getCanonicalType(readType(F, Record, Idx)));
4935
4936  case DeclarationName::CXXDestructorName:
4937    return Context.DeclarationNames.getCXXDestructorName(
4938                          Context.getCanonicalType(readType(F, Record, Idx)));
4939
4940  case DeclarationName::CXXConversionFunctionName:
4941    return Context.DeclarationNames.getCXXConversionFunctionName(
4942                          Context.getCanonicalType(readType(F, Record, Idx)));
4943
4944  case DeclarationName::CXXOperatorName:
4945    return Context.DeclarationNames.getCXXOperatorName(
4946                                       (OverloadedOperatorKind)Record[Idx++]);
4947
4948  case DeclarationName::CXXLiteralOperatorName:
4949    return Context.DeclarationNames.getCXXLiteralOperatorName(
4950                                       GetIdentifierInfo(F, Record, Idx));
4951
4952  case DeclarationName::CXXUsingDirective:
4953    return DeclarationName::getUsingDirectiveName();
4954  }
4955
4956  // Required to silence GCC warning
4957  return DeclarationName();
4958}
4959
4960void ASTReader::ReadDeclarationNameLoc(Module &F,
4961                                       DeclarationNameLoc &DNLoc,
4962                                       DeclarationName Name,
4963                                      const RecordData &Record, unsigned &Idx) {
4964  switch (Name.getNameKind()) {
4965  case DeclarationName::CXXConstructorName:
4966  case DeclarationName::CXXDestructorName:
4967  case DeclarationName::CXXConversionFunctionName:
4968    DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
4969    break;
4970
4971  case DeclarationName::CXXOperatorName:
4972    DNLoc.CXXOperatorName.BeginOpNameLoc
4973        = ReadSourceLocation(F, Record, Idx).getRawEncoding();
4974    DNLoc.CXXOperatorName.EndOpNameLoc
4975        = ReadSourceLocation(F, Record, Idx).getRawEncoding();
4976    break;
4977
4978  case DeclarationName::CXXLiteralOperatorName:
4979    DNLoc.CXXLiteralOperatorName.OpNameLoc
4980        = ReadSourceLocation(F, Record, Idx).getRawEncoding();
4981    break;
4982
4983  case DeclarationName::Identifier:
4984  case DeclarationName::ObjCZeroArgSelector:
4985  case DeclarationName::ObjCOneArgSelector:
4986  case DeclarationName::ObjCMultiArgSelector:
4987  case DeclarationName::CXXUsingDirective:
4988    break;
4989  }
4990}
4991
4992void ASTReader::ReadDeclarationNameInfo(Module &F,
4993                                        DeclarationNameInfo &NameInfo,
4994                                      const RecordData &Record, unsigned &Idx) {
4995  NameInfo.setName(ReadDeclarationName(F, Record, Idx));
4996  NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
4997  DeclarationNameLoc DNLoc;
4998  ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
4999  NameInfo.setInfo(DNLoc);
5000}
5001
5002void ASTReader::ReadQualifierInfo(Module &F, QualifierInfo &Info,
5003                                  const RecordData &Record, unsigned &Idx) {
5004  Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
5005  unsigned NumTPLists = Record[Idx++];
5006  Info.NumTemplParamLists = NumTPLists;
5007  if (NumTPLists) {
5008    Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
5009    for (unsigned i=0; i != NumTPLists; ++i)
5010      Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
5011  }
5012}
5013
5014TemplateName
5015ASTReader::ReadTemplateName(Module &F, const RecordData &Record,
5016                            unsigned &Idx) {
5017  TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
5018  switch (Kind) {
5019  case TemplateName::Template:
5020      return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
5021
5022  case TemplateName::OverloadedTemplate: {
5023    unsigned size = Record[Idx++];
5024    UnresolvedSet<8> Decls;
5025    while (size--)
5026      Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
5027
5028    return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
5029  }
5030
5031  case TemplateName::QualifiedTemplate: {
5032    NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
5033    bool hasTemplKeyword = Record[Idx++];
5034    TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
5035    return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
5036  }
5037
5038  case TemplateName::DependentTemplate: {
5039    NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
5040    if (Record[Idx++])  // isIdentifier
5041      return Context.getDependentTemplateName(NNS,
5042                                               GetIdentifierInfo(F, Record,
5043                                                                 Idx));
5044    return Context.getDependentTemplateName(NNS,
5045                                         (OverloadedOperatorKind)Record[Idx++]);
5046  }
5047
5048  case TemplateName::SubstTemplateTemplateParm: {
5049    TemplateTemplateParmDecl *param
5050      = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
5051    if (!param) return TemplateName();
5052    TemplateName replacement = ReadTemplateName(F, Record, Idx);
5053    return Context.getSubstTemplateTemplateParm(param, replacement);
5054  }
5055
5056  case TemplateName::SubstTemplateTemplateParmPack: {
5057    TemplateTemplateParmDecl *Param
5058      = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
5059    if (!Param)
5060      return TemplateName();
5061
5062    TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
5063    if (ArgPack.getKind() != TemplateArgument::Pack)
5064      return TemplateName();
5065
5066    return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
5067  }
5068  }
5069
5070  assert(0 && "Unhandled template name kind!");
5071  return TemplateName();
5072}
5073
5074TemplateArgument
5075ASTReader::ReadTemplateArgument(Module &F,
5076                                const RecordData &Record, unsigned &Idx) {
5077  TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
5078  switch (Kind) {
5079  case TemplateArgument::Null:
5080    return TemplateArgument();
5081  case TemplateArgument::Type:
5082    return TemplateArgument(readType(F, Record, Idx));
5083  case TemplateArgument::Declaration:
5084    return TemplateArgument(ReadDecl(F, Record, Idx));
5085  case TemplateArgument::Integral: {
5086    llvm::APSInt Value = ReadAPSInt(Record, Idx);
5087    QualType T = readType(F, Record, Idx);
5088    return TemplateArgument(Value, T);
5089  }
5090  case TemplateArgument::Template:
5091    return TemplateArgument(ReadTemplateName(F, Record, Idx));
5092  case TemplateArgument::TemplateExpansion: {
5093    TemplateName Name = ReadTemplateName(F, Record, Idx);
5094    llvm::Optional<unsigned> NumTemplateExpansions;
5095    if (unsigned NumExpansions = Record[Idx++])
5096      NumTemplateExpansions = NumExpansions - 1;
5097    return TemplateArgument(Name, NumTemplateExpansions);
5098  }
5099  case TemplateArgument::Expression:
5100    return TemplateArgument(ReadExpr(F));
5101  case TemplateArgument::Pack: {
5102    unsigned NumArgs = Record[Idx++];
5103    TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
5104    for (unsigned I = 0; I != NumArgs; ++I)
5105      Args[I] = ReadTemplateArgument(F, Record, Idx);
5106    return TemplateArgument(Args, NumArgs);
5107  }
5108  }
5109
5110  assert(0 && "Unhandled template argument kind!");
5111  return TemplateArgument();
5112}
5113
5114TemplateParameterList *
5115ASTReader::ReadTemplateParameterList(Module &F,
5116                                     const RecordData &Record, unsigned &Idx) {
5117  SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
5118  SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
5119  SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
5120
5121  unsigned NumParams = Record[Idx++];
5122  SmallVector<NamedDecl *, 16> Params;
5123  Params.reserve(NumParams);
5124  while (NumParams--)
5125    Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
5126
5127  TemplateParameterList* TemplateParams =
5128    TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
5129                                  Params.data(), Params.size(), RAngleLoc);
5130  return TemplateParams;
5131}
5132
5133void
5134ASTReader::
5135ReadTemplateArgumentList(SmallVector<TemplateArgument, 8> &TemplArgs,
5136                         Module &F, const RecordData &Record,
5137                         unsigned &Idx) {
5138  unsigned NumTemplateArgs = Record[Idx++];
5139  TemplArgs.reserve(NumTemplateArgs);
5140  while (NumTemplateArgs--)
5141    TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
5142}
5143
5144/// \brief Read a UnresolvedSet structure.
5145void ASTReader::ReadUnresolvedSet(Module &F, UnresolvedSetImpl &Set,
5146                                  const RecordData &Record, unsigned &Idx) {
5147  unsigned NumDecls = Record[Idx++];
5148  while (NumDecls--) {
5149    NamedDecl *D = ReadDeclAs<NamedDecl>(F, Record, Idx);
5150    AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
5151    Set.addDecl(D, AS);
5152  }
5153}
5154
5155CXXBaseSpecifier
5156ASTReader::ReadCXXBaseSpecifier(Module &F,
5157                                const RecordData &Record, unsigned &Idx) {
5158  bool isVirtual = static_cast<bool>(Record[Idx++]);
5159  bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
5160  AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
5161  bool inheritConstructors = static_cast<bool>(Record[Idx++]);
5162  TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
5163  SourceRange Range = ReadSourceRange(F, Record, Idx);
5164  SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
5165  CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
5166                          EllipsisLoc);
5167  Result.setInheritConstructors(inheritConstructors);
5168  return Result;
5169}
5170
5171std::pair<CXXCtorInitializer **, unsigned>
5172ASTReader::ReadCXXCtorInitializers(Module &F, const RecordData &Record,
5173                                   unsigned &Idx) {
5174  CXXCtorInitializer **CtorInitializers = 0;
5175  unsigned NumInitializers = Record[Idx++];
5176  if (NumInitializers) {
5177    CtorInitializers
5178        = new (Context) CXXCtorInitializer*[NumInitializers];
5179    for (unsigned i=0; i != NumInitializers; ++i) {
5180      TypeSourceInfo *BaseClassInfo = 0;
5181      bool IsBaseVirtual = false;
5182      FieldDecl *Member = 0;
5183      IndirectFieldDecl *IndirectMember = 0;
5184      CXXConstructorDecl *Target = 0;
5185
5186      CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
5187      switch (Type) {
5188       case CTOR_INITIALIZER_BASE:
5189        BaseClassInfo = GetTypeSourceInfo(F, Record, Idx);
5190        IsBaseVirtual = Record[Idx++];
5191        break;
5192
5193       case CTOR_INITIALIZER_DELEGATING:
5194        Target = ReadDeclAs<CXXConstructorDecl>(F, Record, Idx);
5195        break;
5196
5197       case CTOR_INITIALIZER_MEMBER:
5198        Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
5199        break;
5200
5201       case CTOR_INITIALIZER_INDIRECT_MEMBER:
5202        IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
5203        break;
5204      }
5205
5206      SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
5207      Expr *Init = ReadExpr(F);
5208      SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
5209      SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
5210      bool IsWritten = Record[Idx++];
5211      unsigned SourceOrderOrNumArrayIndices;
5212      SmallVector<VarDecl *, 8> Indices;
5213      if (IsWritten) {
5214        SourceOrderOrNumArrayIndices = Record[Idx++];
5215      } else {
5216        SourceOrderOrNumArrayIndices = Record[Idx++];
5217        Indices.reserve(SourceOrderOrNumArrayIndices);
5218        for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
5219          Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
5220      }
5221
5222      CXXCtorInitializer *BOMInit;
5223      if (Type == CTOR_INITIALIZER_BASE) {
5224        BOMInit = new (Context) CXXCtorInitializer(Context, BaseClassInfo, IsBaseVirtual,
5225                                             LParenLoc, Init, RParenLoc,
5226                                             MemberOrEllipsisLoc);
5227      } else if (Type == CTOR_INITIALIZER_DELEGATING) {
5228        BOMInit = new (Context) CXXCtorInitializer(Context, MemberOrEllipsisLoc, LParenLoc,
5229                                             Target, Init, RParenLoc);
5230      } else if (IsWritten) {
5231        if (Member)
5232          BOMInit = new (Context) CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc,
5233                                               LParenLoc, Init, RParenLoc);
5234        else
5235          BOMInit = new (Context) CXXCtorInitializer(Context, IndirectMember,
5236                                               MemberOrEllipsisLoc, LParenLoc,
5237                                               Init, RParenLoc);
5238      } else {
5239        BOMInit = CXXCtorInitializer::Create(Context, Member, MemberOrEllipsisLoc,
5240                                             LParenLoc, Init, RParenLoc,
5241                                             Indices.data(), Indices.size());
5242      }
5243
5244      if (IsWritten)
5245        BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
5246      CtorInitializers[i] = BOMInit;
5247    }
5248  }
5249
5250  return std::make_pair(CtorInitializers, NumInitializers);
5251}
5252
5253NestedNameSpecifier *
5254ASTReader::ReadNestedNameSpecifier(Module &F,
5255                                   const RecordData &Record, unsigned &Idx) {
5256  unsigned N = Record[Idx++];
5257  NestedNameSpecifier *NNS = 0, *Prev = 0;
5258  for (unsigned I = 0; I != N; ++I) {
5259    NestedNameSpecifier::SpecifierKind Kind
5260      = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
5261    switch (Kind) {
5262    case NestedNameSpecifier::Identifier: {
5263      IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
5264      NNS = NestedNameSpecifier::Create(Context, Prev, II);
5265      break;
5266    }
5267
5268    case NestedNameSpecifier::Namespace: {
5269      NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
5270      NNS = NestedNameSpecifier::Create(Context, Prev, NS);
5271      break;
5272    }
5273
5274    case NestedNameSpecifier::NamespaceAlias: {
5275      NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
5276      NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
5277      break;
5278    }
5279
5280    case NestedNameSpecifier::TypeSpec:
5281    case NestedNameSpecifier::TypeSpecWithTemplate: {
5282      const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
5283      if (!T)
5284        return 0;
5285
5286      bool Template = Record[Idx++];
5287      NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
5288      break;
5289    }
5290
5291    case NestedNameSpecifier::Global: {
5292      NNS = NestedNameSpecifier::GlobalSpecifier(Context);
5293      // No associated value, and there can't be a prefix.
5294      break;
5295    }
5296    }
5297    Prev = NNS;
5298  }
5299  return NNS;
5300}
5301
5302NestedNameSpecifierLoc
5303ASTReader::ReadNestedNameSpecifierLoc(Module &F, const RecordData &Record,
5304                                      unsigned &Idx) {
5305  unsigned N = Record[Idx++];
5306  NestedNameSpecifierLocBuilder Builder;
5307  for (unsigned I = 0; I != N; ++I) {
5308    NestedNameSpecifier::SpecifierKind Kind
5309      = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
5310    switch (Kind) {
5311    case NestedNameSpecifier::Identifier: {
5312      IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
5313      SourceRange Range = ReadSourceRange(F, Record, Idx);
5314      Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
5315      break;
5316    }
5317
5318    case NestedNameSpecifier::Namespace: {
5319      NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
5320      SourceRange Range = ReadSourceRange(F, Record, Idx);
5321      Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
5322      break;
5323    }
5324
5325    case NestedNameSpecifier::NamespaceAlias: {
5326      NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
5327      SourceRange Range = ReadSourceRange(F, Record, Idx);
5328      Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
5329      break;
5330    }
5331
5332    case NestedNameSpecifier::TypeSpec:
5333    case NestedNameSpecifier::TypeSpecWithTemplate: {
5334      bool Template = Record[Idx++];
5335      TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
5336      if (!T)
5337        return NestedNameSpecifierLoc();
5338      SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
5339
5340      // FIXME: 'template' keyword location not saved anywhere, so we fake it.
5341      Builder.Extend(Context,
5342                     Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
5343                     T->getTypeLoc(), ColonColonLoc);
5344      break;
5345    }
5346
5347    case NestedNameSpecifier::Global: {
5348      SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
5349      Builder.MakeGlobal(Context, ColonColonLoc);
5350      break;
5351    }
5352    }
5353  }
5354
5355  return Builder.getWithLocInContext(Context);
5356}
5357
5358SourceRange
5359ASTReader::ReadSourceRange(Module &F, const RecordData &Record,
5360                           unsigned &Idx) {
5361  SourceLocation beg = ReadSourceLocation(F, Record, Idx);
5362  SourceLocation end = ReadSourceLocation(F, Record, Idx);
5363  return SourceRange(beg, end);
5364}
5365
5366/// \brief Read an integral value
5367llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
5368  unsigned BitWidth = Record[Idx++];
5369  unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
5370  llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
5371  Idx += NumWords;
5372  return Result;
5373}
5374
5375/// \brief Read a signed integral value
5376llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
5377  bool isUnsigned = Record[Idx++];
5378  return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
5379}
5380
5381/// \brief Read a floating-point value
5382llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
5383  return llvm::APFloat(ReadAPInt(Record, Idx));
5384}
5385
5386// \brief Read a string
5387std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
5388  unsigned Len = Record[Idx++];
5389  std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
5390  Idx += Len;
5391  return Result;
5392}
5393
5394VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
5395                                         unsigned &Idx) {
5396  unsigned Major = Record[Idx++];
5397  unsigned Minor = Record[Idx++];
5398  unsigned Subminor = Record[Idx++];
5399  if (Minor == 0)
5400    return VersionTuple(Major);
5401  if (Subminor == 0)
5402    return VersionTuple(Major, Minor - 1);
5403  return VersionTuple(Major, Minor - 1, Subminor - 1);
5404}
5405
5406CXXTemporary *ASTReader::ReadCXXTemporary(Module &F,
5407                                          const RecordData &Record,
5408                                          unsigned &Idx) {
5409  CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
5410  return CXXTemporary::Create(Context, Decl);
5411}
5412
5413DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
5414  return Diag(SourceLocation(), DiagID);
5415}
5416
5417DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
5418  return Diags.Report(Loc, DiagID);
5419}
5420
5421/// \brief Retrieve the identifier table associated with the
5422/// preprocessor.
5423IdentifierTable &ASTReader::getIdentifierTable() {
5424  return PP.getIdentifierTable();
5425}
5426
5427/// \brief Record that the given ID maps to the given switch-case
5428/// statement.
5429void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
5430  assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
5431  SwitchCaseStmts[ID] = SC;
5432}
5433
5434/// \brief Retrieve the switch-case statement with the given ID.
5435SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
5436  assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
5437  return SwitchCaseStmts[ID];
5438}
5439
5440void ASTReader::ClearSwitchCaseIDs() {
5441  SwitchCaseStmts.clear();
5442}
5443
5444void ASTReader::FinishedDeserializing() {
5445  assert(NumCurrentElementsDeserializing &&
5446         "FinishedDeserializing not paired with StartedDeserializing");
5447  if (NumCurrentElementsDeserializing == 1) {
5448    // If any identifiers with corresponding top-level declarations have
5449    // been loaded, load those declarations now.
5450    while (!PendingIdentifierInfos.empty()) {
5451      SetGloballyVisibleDecls(PendingIdentifierInfos.front().II,
5452                              PendingIdentifierInfos.front().DeclIDs, true);
5453      PendingIdentifierInfos.pop_front();
5454    }
5455
5456    // Ready to load previous declarations of Decls that were delayed.
5457    while (!PendingPreviousDecls.empty()) {
5458      loadAndAttachPreviousDecl(PendingPreviousDecls.front().first,
5459                                PendingPreviousDecls.front().second);
5460      PendingPreviousDecls.pop_front();
5461    }
5462
5463    // We are not in recursive loading, so it's safe to pass the "interesting"
5464    // decls to the consumer.
5465    if (Consumer)
5466      PassInterestingDeclsToConsumer();
5467
5468    assert(PendingForwardRefs.size() == 0 &&
5469           "Some forward refs did not get linked to the definition!");
5470  }
5471  --NumCurrentElementsDeserializing;
5472}
5473
5474ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
5475                     StringRef isysroot, bool DisableValidation,
5476                     bool DisableStatCache)
5477  : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
5478    SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
5479    Diags(PP.getDiagnostics()), SemaObj(0), PP(PP), Context(Context),
5480    Consumer(0), ModuleMgr(FileMgr.getFileSystemOptions()),
5481    RelocatablePCH(false), isysroot(isysroot),
5482    DisableValidation(DisableValidation),
5483    DisableStatCache(DisableStatCache), NumStatHits(0), NumStatMisses(0),
5484    NumSLocEntriesRead(0), TotalNumSLocEntries(0),
5485    NumStatementsRead(0), TotalNumStatements(0), NumMacrosRead(0),
5486    TotalNumMacros(0), NumSelectorsRead(0), NumMethodPoolEntriesRead(0),
5487    NumMethodPoolMisses(0), TotalNumMethodPoolEntries(0),
5488    NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
5489    NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
5490    TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
5491    NumCXXBaseSpecifiersLoaded(0)
5492{
5493  SourceMgr.setExternalSLocEntrySource(this);
5494}
5495
5496ASTReader::~ASTReader() {
5497  for (DeclContextVisibleUpdatesPending::iterator
5498           I = PendingVisibleUpdates.begin(),
5499           E = PendingVisibleUpdates.end();
5500       I != E; ++I) {
5501    for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
5502                                             F = I->second.end();
5503         J != F; ++J)
5504      delete static_cast<ASTDeclContextNameLookupTable*>(J->first);
5505  }
5506}
5507