ASTReader.cpp revision 76dc8890b6c5223de80be8284adbfc63ceeb3a55
1//===--- ASTReader.cpp - AST File Reader ------------------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file defines the ASTReader class, which reads AST files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Serialization/ASTReader.h"
15#include "clang/Serialization/ASTDeserializationListener.h"
16#include "ASTCommon.h"
17#include "clang/Frontend/FrontendDiagnostic.h"
18#include "clang/Frontend/Utils.h"
19#include "clang/Sema/Sema.h"
20#include "clang/Sema/Scope.h"
21#include "clang/AST/ASTConsumer.h"
22#include "clang/AST/ASTContext.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/Type.h"
27#include "clang/AST/TypeLocVisitor.h"
28#include "clang/Lex/MacroInfo.h"
29#include "clang/Lex/PreprocessingRecord.h"
30#include "clang/Lex/Preprocessor.h"
31#include "clang/Lex/HeaderSearch.h"
32#include "clang/Basic/OnDiskHashTable.h"
33#include "clang/Basic/SourceManager.h"
34#include "clang/Basic/SourceManagerInternals.h"
35#include "clang/Basic/FileManager.h"
36#include "clang/Basic/TargetInfo.h"
37#include "clang/Basic/Version.h"
38#include "llvm/ADT/StringExtras.h"
39#include "llvm/Bitcode/BitstreamReader.h"
40#include "llvm/Support/MemoryBuffer.h"
41#include "llvm/Support/ErrorHandling.h"
42#include "llvm/System/Path.h"
43#include <algorithm>
44#include <iterator>
45#include <cstdio>
46#include <sys/stat.h>
47using namespace clang;
48using namespace clang::serialization;
49
50//===----------------------------------------------------------------------===//
51// PCH validator implementation
52//===----------------------------------------------------------------------===//
53
54ASTReaderListener::~ASTReaderListener() {}
55
56bool
57PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts) {
58  const LangOptions &PPLangOpts = PP.getLangOptions();
59#define PARSE_LANGOPT_BENIGN(Option)
60#define PARSE_LANGOPT_IMPORTANT(Option, DiagID)                    \
61  if (PPLangOpts.Option != LangOpts.Option) {                      \
62    Reader.Diag(DiagID) << LangOpts.Option << PPLangOpts.Option;   \
63    return true;                                                   \
64  }
65
66  PARSE_LANGOPT_BENIGN(Trigraphs);
67  PARSE_LANGOPT_BENIGN(BCPLComment);
68  PARSE_LANGOPT_BENIGN(DollarIdents);
69  PARSE_LANGOPT_BENIGN(AsmPreprocessor);
70  PARSE_LANGOPT_IMPORTANT(GNUMode, diag::warn_pch_gnu_extensions);
71  PARSE_LANGOPT_IMPORTANT(GNUKeywords, diag::warn_pch_gnu_keywords);
72  PARSE_LANGOPT_BENIGN(ImplicitInt);
73  PARSE_LANGOPT_BENIGN(Digraphs);
74  PARSE_LANGOPT_BENIGN(HexFloats);
75  PARSE_LANGOPT_IMPORTANT(C99, diag::warn_pch_c99);
76  PARSE_LANGOPT_IMPORTANT(Microsoft, diag::warn_pch_microsoft_extensions);
77  PARSE_LANGOPT_IMPORTANT(CPlusPlus, diag::warn_pch_cplusplus);
78  PARSE_LANGOPT_IMPORTANT(CPlusPlus0x, diag::warn_pch_cplusplus0x);
79  PARSE_LANGOPT_BENIGN(CXXOperatorName);
80  PARSE_LANGOPT_IMPORTANT(ObjC1, diag::warn_pch_objective_c);
81  PARSE_LANGOPT_IMPORTANT(ObjC2, diag::warn_pch_objective_c2);
82  PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI, diag::warn_pch_nonfragile_abi);
83  PARSE_LANGOPT_IMPORTANT(ObjCNonFragileABI2, diag::warn_pch_nonfragile_abi2);
84  PARSE_LANGOPT_IMPORTANT(NoConstantCFStrings,
85                          diag::warn_pch_no_constant_cfstrings);
86  PARSE_LANGOPT_BENIGN(PascalStrings);
87  PARSE_LANGOPT_BENIGN(WritableStrings);
88  PARSE_LANGOPT_IMPORTANT(LaxVectorConversions,
89                          diag::warn_pch_lax_vector_conversions);
90  PARSE_LANGOPT_IMPORTANT(AltiVec, diag::warn_pch_altivec);
91  PARSE_LANGOPT_IMPORTANT(Exceptions, diag::warn_pch_exceptions);
92  PARSE_LANGOPT_IMPORTANT(SjLjExceptions, diag::warn_pch_sjlj_exceptions);
93  PARSE_LANGOPT_IMPORTANT(NeXTRuntime, diag::warn_pch_objc_runtime);
94  PARSE_LANGOPT_IMPORTANT(Freestanding, diag::warn_pch_freestanding);
95  PARSE_LANGOPT_IMPORTANT(NoBuiltin, diag::warn_pch_builtins);
96  PARSE_LANGOPT_IMPORTANT(ThreadsafeStatics,
97                          diag::warn_pch_thread_safe_statics);
98  PARSE_LANGOPT_IMPORTANT(POSIXThreads, diag::warn_pch_posix_threads);
99  PARSE_LANGOPT_IMPORTANT(Blocks, diag::warn_pch_blocks);
100  PARSE_LANGOPT_BENIGN(EmitAllDecls);
101  PARSE_LANGOPT_IMPORTANT(MathErrno, diag::warn_pch_math_errno);
102  PARSE_LANGOPT_BENIGN(getSignedOverflowBehavior());
103  PARSE_LANGOPT_IMPORTANT(HeinousExtensions,
104                          diag::warn_pch_heinous_extensions);
105  // FIXME: Most of the options below are benign if the macro wasn't
106  // used. Unfortunately, this means that a PCH compiled without
107  // optimization can't be used with optimization turned on, even
108  // though the only thing that changes is whether __OPTIMIZE__ was
109  // defined... but if __OPTIMIZE__ never showed up in the header, it
110  // doesn't matter. We could consider making this some special kind
111  // of check.
112  PARSE_LANGOPT_IMPORTANT(Optimize, diag::warn_pch_optimize);
113  PARSE_LANGOPT_IMPORTANT(OptimizeSize, diag::warn_pch_optimize_size);
114  PARSE_LANGOPT_IMPORTANT(Static, diag::warn_pch_static);
115  PARSE_LANGOPT_IMPORTANT(PICLevel, diag::warn_pch_pic_level);
116  PARSE_LANGOPT_IMPORTANT(GNUInline, diag::warn_pch_gnu_inline);
117  PARSE_LANGOPT_IMPORTANT(NoInline, diag::warn_pch_no_inline);
118  PARSE_LANGOPT_IMPORTANT(AccessControl, diag::warn_pch_access_control);
119  PARSE_LANGOPT_IMPORTANT(CharIsSigned, diag::warn_pch_char_signed);
120  PARSE_LANGOPT_IMPORTANT(ShortWChar, diag::warn_pch_short_wchar);
121  if ((PPLangOpts.getGCMode() != 0) != (LangOpts.getGCMode() != 0)) {
122    Reader.Diag(diag::warn_pch_gc_mode)
123      << LangOpts.getGCMode() << PPLangOpts.getGCMode();
124    return true;
125  }
126  PARSE_LANGOPT_BENIGN(getVisibilityMode());
127  PARSE_LANGOPT_IMPORTANT(getStackProtectorMode(),
128                          diag::warn_pch_stack_protector);
129  PARSE_LANGOPT_BENIGN(InstantiationDepth);
130  PARSE_LANGOPT_IMPORTANT(OpenCL, diag::warn_pch_opencl);
131  PARSE_LANGOPT_BENIGN(CatchUndefined);
132  PARSE_LANGOPT_IMPORTANT(ElideConstructors, diag::warn_pch_elide_constructors);
133  PARSE_LANGOPT_BENIGN(SpellChecking);
134#undef PARSE_LANGOPT_IMPORTANT
135#undef PARSE_LANGOPT_BENIGN
136
137  return false;
138}
139
140bool PCHValidator::ReadTargetTriple(llvm::StringRef Triple) {
141  if (Triple == PP.getTargetInfo().getTriple().str())
142    return false;
143
144  Reader.Diag(diag::warn_pch_target_triple)
145    << Triple << PP.getTargetInfo().getTriple().str();
146  return true;
147}
148
149struct EmptyStringRef {
150  bool operator ()(llvm::StringRef r) const { return r.empty(); }
151};
152struct EmptyBlock {
153  bool operator ()(const PCHPredefinesBlock &r) const { return r.Data.empty(); }
154};
155
156static bool EqualConcatenations(llvm::SmallVector<llvm::StringRef, 2> L,
157                                PCHPredefinesBlocks R) {
158  // First, sum up the lengths.
159  unsigned LL = 0, RL = 0;
160  for (unsigned I = 0, N = L.size(); I != N; ++I) {
161    LL += L[I].size();
162  }
163  for (unsigned I = 0, N = R.size(); I != N; ++I) {
164    RL += R[I].Data.size();
165  }
166  if (LL != RL)
167    return false;
168  if (LL == 0 && RL == 0)
169    return true;
170
171  // Kick out empty parts, they confuse the algorithm below.
172  L.erase(std::remove_if(L.begin(), L.end(), EmptyStringRef()), L.end());
173  R.erase(std::remove_if(R.begin(), R.end(), EmptyBlock()), R.end());
174
175  // Do it the hard way. At this point, both vectors must be non-empty.
176  llvm::StringRef LR = L[0], RR = R[0].Data;
177  unsigned LI = 0, RI = 0, LN = L.size(), RN = R.size();
178  (void) RN;
179  for (;;) {
180    // Compare the current pieces.
181    if (LR.size() == RR.size()) {
182      // If they're the same length, it's pretty easy.
183      if (LR != RR)
184        return false;
185      // Both pieces are done, advance.
186      ++LI;
187      ++RI;
188      // If either string is done, they're both done, since they're the same
189      // length.
190      if (LI == LN) {
191        assert(RI == RN && "Strings not the same length after all?");
192        return true;
193      }
194      LR = L[LI];
195      RR = R[RI].Data;
196    } else if (LR.size() < RR.size()) {
197      // Right piece is longer.
198      if (!RR.startswith(LR))
199        return false;
200      ++LI;
201      assert(LI != LN && "Strings not the same length after all?");
202      RR = RR.substr(LR.size());
203      LR = L[LI];
204    } else {
205      // Left piece is longer.
206      if (!LR.startswith(RR))
207        return false;
208      ++RI;
209      assert(RI != RN && "Strings not the same length after all?");
210      LR = LR.substr(RR.size());
211      RR = R[RI].Data;
212    }
213  }
214}
215
216static std::pair<FileID, llvm::StringRef::size_type>
217FindMacro(const PCHPredefinesBlocks &Buffers, llvm::StringRef MacroDef) {
218  std::pair<FileID, llvm::StringRef::size_type> Res;
219  for (unsigned I = 0, N = Buffers.size(); I != N; ++I) {
220    Res.second = Buffers[I].Data.find(MacroDef);
221    if (Res.second != llvm::StringRef::npos) {
222      Res.first = Buffers[I].BufferID;
223      break;
224    }
225  }
226  return Res;
227}
228
229bool PCHValidator::ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
230                                        llvm::StringRef OriginalFileName,
231                                        std::string &SuggestedPredefines) {
232  // We are in the context of an implicit include, so the predefines buffer will
233  // have a #include entry for the PCH file itself (as normalized by the
234  // preprocessor initialization). Find it and skip over it in the checking
235  // below.
236  llvm::SmallString<256> PCHInclude;
237  PCHInclude += "#include \"";
238  PCHInclude += NormalizeDashIncludePath(OriginalFileName);
239  PCHInclude += "\"\n";
240  std::pair<llvm::StringRef,llvm::StringRef> Split =
241    llvm::StringRef(PP.getPredefines()).split(PCHInclude.str());
242  llvm::StringRef Left =  Split.first, Right = Split.second;
243  if (Left == PP.getPredefines()) {
244    Error("Missing PCH include entry!");
245    return true;
246  }
247
248  // If the concatenation of all the PCH buffers is equal to the adjusted
249  // command line, we're done.
250  llvm::SmallVector<llvm::StringRef, 2> CommandLine;
251  CommandLine.push_back(Left);
252  CommandLine.push_back(Right);
253  if (EqualConcatenations(CommandLine, Buffers))
254    return false;
255
256  SourceManager &SourceMgr = PP.getSourceManager();
257
258  // The predefines buffers are different. Determine what the differences are,
259  // and whether they require us to reject the PCH file.
260  llvm::SmallVector<llvm::StringRef, 8> PCHLines;
261  for (unsigned I = 0, N = Buffers.size(); I != N; ++I)
262    Buffers[I].Data.split(PCHLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
263
264  llvm::SmallVector<llvm::StringRef, 8> CmdLineLines;
265  Left.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
266  Right.split(CmdLineLines, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
267
268  // Sort both sets of predefined buffer lines, since we allow some extra
269  // definitions and they may appear at any point in the output.
270  std::sort(CmdLineLines.begin(), CmdLineLines.end());
271  std::sort(PCHLines.begin(), PCHLines.end());
272
273  // Determine which predefines that were used to build the PCH file are missing
274  // from the command line.
275  std::vector<llvm::StringRef> MissingPredefines;
276  std::set_difference(PCHLines.begin(), PCHLines.end(),
277                      CmdLineLines.begin(), CmdLineLines.end(),
278                      std::back_inserter(MissingPredefines));
279
280  bool MissingDefines = false;
281  bool ConflictingDefines = false;
282  for (unsigned I = 0, N = MissingPredefines.size(); I != N; ++I) {
283    llvm::StringRef Missing = MissingPredefines[I];
284    if (!Missing.startswith("#define ")) {
285      Reader.Diag(diag::warn_pch_compiler_options_mismatch);
286      return true;
287    }
288
289    // This is a macro definition. Determine the name of the macro we're
290    // defining.
291    std::string::size_type StartOfMacroName = strlen("#define ");
292    std::string::size_type EndOfMacroName
293      = Missing.find_first_of("( \n\r", StartOfMacroName);
294    assert(EndOfMacroName != std::string::npos &&
295           "Couldn't find the end of the macro name");
296    llvm::StringRef MacroName = Missing.slice(StartOfMacroName, EndOfMacroName);
297
298    // Determine whether this macro was given a different definition on the
299    // command line.
300    std::string MacroDefStart = "#define " + MacroName.str();
301    std::string::size_type MacroDefLen = MacroDefStart.size();
302    llvm::SmallVector<llvm::StringRef, 8>::iterator ConflictPos
303      = std::lower_bound(CmdLineLines.begin(), CmdLineLines.end(),
304                         MacroDefStart);
305    for (; ConflictPos != CmdLineLines.end(); ++ConflictPos) {
306      if (!ConflictPos->startswith(MacroDefStart)) {
307        // Different macro; we're done.
308        ConflictPos = CmdLineLines.end();
309        break;
310      }
311
312      assert(ConflictPos->size() > MacroDefLen &&
313             "Invalid #define in predefines buffer?");
314      if ((*ConflictPos)[MacroDefLen] != ' ' &&
315          (*ConflictPos)[MacroDefLen] != '(')
316        continue; // Longer macro name; keep trying.
317
318      // We found a conflicting macro definition.
319      break;
320    }
321
322    if (ConflictPos != CmdLineLines.end()) {
323      Reader.Diag(diag::warn_cmdline_conflicting_macro_def)
324          << MacroName;
325
326      // Show the definition of this macro within the PCH file.
327      std::pair<FileID, llvm::StringRef::size_type> MacroLoc =
328          FindMacro(Buffers, Missing);
329      assert(MacroLoc.second!=llvm::StringRef::npos && "Unable to find macro!");
330      SourceLocation PCHMissingLoc =
331          SourceMgr.getLocForStartOfFile(MacroLoc.first)
332            .getFileLocWithOffset(MacroLoc.second);
333      Reader.Diag(PCHMissingLoc, diag::note_pch_macro_defined_as) << MacroName;
334
335      ConflictingDefines = true;
336      continue;
337    }
338
339    // If the macro doesn't conflict, then we'll just pick up the macro
340    // definition from the PCH file. Warn the user that they made a mistake.
341    if (ConflictingDefines)
342      continue; // Don't complain if there are already conflicting defs
343
344    if (!MissingDefines) {
345      Reader.Diag(diag::warn_cmdline_missing_macro_defs);
346      MissingDefines = true;
347    }
348
349    // Show the definition of this macro within the PCH file.
350    std::pair<FileID, llvm::StringRef::size_type> MacroLoc =
351        FindMacro(Buffers, Missing);
352    assert(MacroLoc.second!=llvm::StringRef::npos && "Unable to find macro!");
353    SourceLocation PCHMissingLoc =
354        SourceMgr.getLocForStartOfFile(MacroLoc.first)
355          .getFileLocWithOffset(MacroLoc.second);
356    Reader.Diag(PCHMissingLoc, diag::note_using_macro_def_from_pch);
357  }
358
359  if (ConflictingDefines)
360    return true;
361
362  // Determine what predefines were introduced based on command-line
363  // parameters that were not present when building the PCH
364  // file. Extra #defines are okay, so long as the identifiers being
365  // defined were not used within the precompiled header.
366  std::vector<llvm::StringRef> ExtraPredefines;
367  std::set_difference(CmdLineLines.begin(), CmdLineLines.end(),
368                      PCHLines.begin(), PCHLines.end(),
369                      std::back_inserter(ExtraPredefines));
370  for (unsigned I = 0, N = ExtraPredefines.size(); I != N; ++I) {
371    llvm::StringRef &Extra = ExtraPredefines[I];
372    if (!Extra.startswith("#define ")) {
373      Reader.Diag(diag::warn_pch_compiler_options_mismatch);
374      return true;
375    }
376
377    // This is an extra macro definition. Determine the name of the
378    // macro we're defining.
379    std::string::size_type StartOfMacroName = strlen("#define ");
380    std::string::size_type EndOfMacroName
381      = Extra.find_first_of("( \n\r", StartOfMacroName);
382    assert(EndOfMacroName != std::string::npos &&
383           "Couldn't find the end of the macro name");
384    llvm::StringRef MacroName = Extra.slice(StartOfMacroName, EndOfMacroName);
385
386    // Check whether this name was used somewhere in the PCH file. If
387    // so, defining it as a macro could change behavior, so we reject
388    // the PCH file.
389    if (IdentifierInfo *II = Reader.get(MacroName)) {
390      Reader.Diag(diag::warn_macro_name_used_in_pch) << II;
391      return true;
392    }
393
394    // Add this definition to the suggested predefines buffer.
395    SuggestedPredefines += Extra;
396    SuggestedPredefines += '\n';
397  }
398
399  // If we get here, it's because the predefines buffer had compatible
400  // contents. Accept the PCH file.
401  return false;
402}
403
404void PCHValidator::ReadHeaderFileInfo(const HeaderFileInfo &HFI,
405                                      unsigned ID) {
406  PP.getHeaderSearchInfo().setHeaderFileInfoForUID(HFI, ID);
407  ++NumHeaderInfos;
408}
409
410void PCHValidator::ReadCounter(unsigned Value) {
411  PP.setCounterValue(Value);
412}
413
414//===----------------------------------------------------------------------===//
415// AST reader implementation
416//===----------------------------------------------------------------------===//
417
418void
419ASTReader::setDeserializationListener(ASTDeserializationListener *Listener) {
420  DeserializationListener = Listener;
421  if (DeserializationListener)
422    DeserializationListener->SetReader(this);
423}
424
425
426namespace {
427class ASTSelectorLookupTrait {
428  ASTReader &Reader;
429
430public:
431  struct data_type {
432    SelectorID ID;
433    ObjCMethodList Instance, Factory;
434  };
435
436  typedef Selector external_key_type;
437  typedef external_key_type internal_key_type;
438
439  explicit ASTSelectorLookupTrait(ASTReader &Reader) : Reader(Reader) { }
440
441  static bool EqualKey(const internal_key_type& a,
442                       const internal_key_type& b) {
443    return a == b;
444  }
445
446  static unsigned ComputeHash(Selector Sel) {
447    return serialization::ComputeHash(Sel);
448  }
449
450  // This hopefully will just get inlined and removed by the optimizer.
451  static const internal_key_type&
452  GetInternalKey(const external_key_type& x) { return x; }
453
454  static std::pair<unsigned, unsigned>
455  ReadKeyDataLength(const unsigned char*& d) {
456    using namespace clang::io;
457    unsigned KeyLen = ReadUnalignedLE16(d);
458    unsigned DataLen = ReadUnalignedLE16(d);
459    return std::make_pair(KeyLen, DataLen);
460  }
461
462  internal_key_type ReadKey(const unsigned char* d, unsigned) {
463    using namespace clang::io;
464    SelectorTable &SelTable = Reader.getContext()->Selectors;
465    unsigned N = ReadUnalignedLE16(d);
466    IdentifierInfo *FirstII
467      = Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
468    if (N == 0)
469      return SelTable.getNullarySelector(FirstII);
470    else if (N == 1)
471      return SelTable.getUnarySelector(FirstII);
472
473    llvm::SmallVector<IdentifierInfo *, 16> Args;
474    Args.push_back(FirstII);
475    for (unsigned I = 1; I != N; ++I)
476      Args.push_back(Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d)));
477
478    return SelTable.getSelector(N, Args.data());
479  }
480
481  data_type ReadData(Selector, const unsigned char* d, unsigned DataLen) {
482    using namespace clang::io;
483
484    data_type Result;
485
486    Result.ID = ReadUnalignedLE32(d);
487    unsigned NumInstanceMethods = ReadUnalignedLE16(d);
488    unsigned NumFactoryMethods = ReadUnalignedLE16(d);
489
490    // Load instance methods
491    ObjCMethodList *Prev = 0;
492    for (unsigned I = 0; I != NumInstanceMethods; ++I) {
493      ObjCMethodDecl *Method
494        = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
495      if (!Result.Instance.Method) {
496        // This is the first method, which is the easy case.
497        Result.Instance.Method = Method;
498        Prev = &Result.Instance;
499        continue;
500      }
501
502      ObjCMethodList *Mem =
503        Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
504      Prev->Next = new (Mem) ObjCMethodList(Method, 0);
505      Prev = Prev->Next;
506    }
507
508    // Load factory methods
509    Prev = 0;
510    for (unsigned I = 0; I != NumFactoryMethods; ++I) {
511      ObjCMethodDecl *Method
512        = cast<ObjCMethodDecl>(Reader.GetDecl(ReadUnalignedLE32(d)));
513      if (!Result.Factory.Method) {
514        // This is the first method, which is the easy case.
515        Result.Factory.Method = Method;
516        Prev = &Result.Factory;
517        continue;
518      }
519
520      ObjCMethodList *Mem =
521        Reader.getSema()->BumpAlloc.Allocate<ObjCMethodList>();
522      Prev->Next = new (Mem) ObjCMethodList(Method, 0);
523      Prev = Prev->Next;
524    }
525
526    return Result;
527  }
528};
529
530} // end anonymous namespace
531
532/// \brief The on-disk hash table used for the global method pool.
533typedef OnDiskChainedHashTable<ASTSelectorLookupTrait>
534  ASTSelectorLookupTable;
535
536namespace {
537class ASTIdentifierLookupTrait {
538  ASTReader &Reader;
539  llvm::BitstreamCursor &Stream;
540
541  // If we know the IdentifierInfo in advance, it is here and we will
542  // not build a new one. Used when deserializing information about an
543  // identifier that was constructed before the AST file was read.
544  IdentifierInfo *KnownII;
545
546public:
547  typedef IdentifierInfo * data_type;
548
549  typedef const std::pair<const char*, unsigned> external_key_type;
550
551  typedef external_key_type internal_key_type;
552
553  ASTIdentifierLookupTrait(ASTReader &Reader, llvm::BitstreamCursor &Stream,
554                           IdentifierInfo *II = 0)
555    : Reader(Reader), Stream(Stream), KnownII(II) { }
556
557  static bool EqualKey(const internal_key_type& a,
558                       const internal_key_type& b) {
559    return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0
560                                  : false;
561  }
562
563  static unsigned ComputeHash(const internal_key_type& a) {
564    return llvm::HashString(llvm::StringRef(a.first, a.second));
565  }
566
567  // This hopefully will just get inlined and removed by the optimizer.
568  static const internal_key_type&
569  GetInternalKey(const external_key_type& x) { return x; }
570
571  static std::pair<unsigned, unsigned>
572  ReadKeyDataLength(const unsigned char*& d) {
573    using namespace clang::io;
574    unsigned DataLen = ReadUnalignedLE16(d);
575    unsigned KeyLen = ReadUnalignedLE16(d);
576    return std::make_pair(KeyLen, DataLen);
577  }
578
579  static std::pair<const char*, unsigned>
580  ReadKey(const unsigned char* d, unsigned n) {
581    assert(n >= 2 && d[n-1] == '\0');
582    return std::make_pair((const char*) d, n-1);
583  }
584
585  IdentifierInfo *ReadData(const internal_key_type& k,
586                           const unsigned char* d,
587                           unsigned DataLen) {
588    using namespace clang::io;
589    IdentID ID = ReadUnalignedLE32(d);
590    bool IsInteresting = ID & 0x01;
591
592    // Wipe out the "is interesting" bit.
593    ID = ID >> 1;
594
595    if (!IsInteresting) {
596      // For uninteresting identifiers, just build the IdentifierInfo
597      // and associate it with the persistent ID.
598      IdentifierInfo *II = KnownII;
599      if (!II)
600        II = &Reader.getIdentifierTable().getOwn(k.first, k.first + k.second);
601      Reader.SetIdentifierInfo(ID, II);
602      II->setIsFromAST();
603      return II;
604    }
605
606    unsigned Bits = ReadUnalignedLE16(d);
607    bool CPlusPlusOperatorKeyword = Bits & 0x01;
608    Bits >>= 1;
609    bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
610    Bits >>= 1;
611    bool Poisoned = Bits & 0x01;
612    Bits >>= 1;
613    bool ExtensionToken = Bits & 0x01;
614    Bits >>= 1;
615    bool hasMacroDefinition = Bits & 0x01;
616    Bits >>= 1;
617    unsigned ObjCOrBuiltinID = Bits & 0x3FF;
618    Bits >>= 10;
619
620    assert(Bits == 0 && "Extra bits in the identifier?");
621    DataLen -= 6;
622
623    // Build the IdentifierInfo itself and link the identifier ID with
624    // the new IdentifierInfo.
625    IdentifierInfo *II = KnownII;
626    if (!II)
627      II = &Reader.getIdentifierTable().getOwn(k.first, k.first + k.second);
628    Reader.SetIdentifierInfo(ID, II);
629
630    // Set or check the various bits in the IdentifierInfo structure.
631    // Token IDs are read-only.
632    if (HasRevertedTokenIDToIdentifier)
633      II->RevertTokenIDToIdentifier();
634    II->setObjCOrBuiltinID(ObjCOrBuiltinID);
635    assert(II->isExtensionToken() == ExtensionToken &&
636           "Incorrect extension token flag");
637    (void)ExtensionToken;
638    II->setIsPoisoned(Poisoned);
639    assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
640           "Incorrect C++ operator keyword flag");
641    (void)CPlusPlusOperatorKeyword;
642
643    // If this identifier is a macro, deserialize the macro
644    // definition.
645    if (hasMacroDefinition) {
646      uint32_t Offset = ReadUnalignedLE32(d);
647      Reader.ReadMacroRecord(Stream, Offset);
648      DataLen -= 4;
649    }
650
651    // Read all of the declarations visible at global scope with this
652    // name.
653    if (Reader.getContext() == 0) return II;
654    if (DataLen > 0) {
655      llvm::SmallVector<uint32_t, 4> DeclIDs;
656      for (; DataLen > 0; DataLen -= 4)
657        DeclIDs.push_back(ReadUnalignedLE32(d));
658      Reader.SetGloballyVisibleDecls(II, DeclIDs);
659    }
660
661    II->setIsFromAST();
662    return II;
663  }
664};
665
666} // end anonymous namespace
667
668/// \brief The on-disk hash table used to contain information about
669/// all of the identifiers in the program.
670typedef OnDiskChainedHashTable<ASTIdentifierLookupTrait>
671  ASTIdentifierLookupTable;
672
673namespace {
674class ASTDeclContextNameLookupTrait {
675  ASTReader &Reader;
676
677public:
678  /// \brief Pair of begin/end iterators for DeclIDs.
679  typedef std::pair<DeclID *, DeclID *> data_type;
680
681  /// \brief Special internal key for declaration names.
682  /// The hash table creates keys for comparison; we do not create
683  /// a DeclarationName for the internal key to avoid deserializing types.
684  struct DeclNameKey {
685    DeclarationName::NameKind Kind;
686    uint64_t Data;
687    DeclNameKey() : Kind((DeclarationName::NameKind)0), Data(0) { }
688  };
689
690  typedef DeclarationName external_key_type;
691  typedef DeclNameKey internal_key_type;
692
693  explicit ASTDeclContextNameLookupTrait(ASTReader &Reader) : Reader(Reader) { }
694
695  static bool EqualKey(const internal_key_type& a,
696                       const internal_key_type& b) {
697    return a.Kind == b.Kind && a.Data == b.Data;
698  }
699
700  unsigned ComputeHash(const DeclNameKey &Key) const {
701    llvm::FoldingSetNodeID ID;
702    ID.AddInteger(Key.Kind);
703
704    switch (Key.Kind) {
705    case DeclarationName::Identifier:
706    case DeclarationName::CXXLiteralOperatorName:
707      ID.AddString(((IdentifierInfo*)Key.Data)->getName());
708      break;
709    case DeclarationName::ObjCZeroArgSelector:
710    case DeclarationName::ObjCOneArgSelector:
711    case DeclarationName::ObjCMultiArgSelector:
712      ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
713      break;
714    case DeclarationName::CXXConstructorName:
715    case DeclarationName::CXXDestructorName:
716    case DeclarationName::CXXConversionFunctionName:
717      ID.AddInteger((TypeID)Key.Data);
718      break;
719    case DeclarationName::CXXOperatorName:
720      ID.AddInteger((OverloadedOperatorKind)Key.Data);
721      break;
722    case DeclarationName::CXXUsingDirective:
723      break;
724    }
725
726    return ID.ComputeHash();
727  }
728
729  internal_key_type GetInternalKey(const external_key_type& Name) const {
730    DeclNameKey Key;
731    Key.Kind = Name.getNameKind();
732    switch (Name.getNameKind()) {
733    case DeclarationName::Identifier:
734      Key.Data = (uint64_t)Name.getAsIdentifierInfo();
735      break;
736    case DeclarationName::ObjCZeroArgSelector:
737    case DeclarationName::ObjCOneArgSelector:
738    case DeclarationName::ObjCMultiArgSelector:
739      Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
740      break;
741    case DeclarationName::CXXConstructorName:
742    case DeclarationName::CXXDestructorName:
743    case DeclarationName::CXXConversionFunctionName:
744      Key.Data = Reader.GetTypeID(Name.getCXXNameType());
745      break;
746    case DeclarationName::CXXOperatorName:
747      Key.Data = Name.getCXXOverloadedOperator();
748      break;
749    case DeclarationName::CXXLiteralOperatorName:
750      Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
751      break;
752    case DeclarationName::CXXUsingDirective:
753      break;
754    }
755
756    return Key;
757  }
758
759  external_key_type GetExternalKey(const internal_key_type& Key) const {
760    ASTContext *Context = Reader.getContext();
761    switch (Key.Kind) {
762    case DeclarationName::Identifier:
763      return DeclarationName((IdentifierInfo*)Key.Data);
764
765    case DeclarationName::ObjCZeroArgSelector:
766    case DeclarationName::ObjCOneArgSelector:
767    case DeclarationName::ObjCMultiArgSelector:
768      return DeclarationName(Selector(Key.Data));
769
770    case DeclarationName::CXXConstructorName:
771      return Context->DeclarationNames.getCXXConstructorName(
772                           Context->getCanonicalType(Reader.GetType(Key.Data)));
773
774    case DeclarationName::CXXDestructorName:
775      return Context->DeclarationNames.getCXXDestructorName(
776                           Context->getCanonicalType(Reader.GetType(Key.Data)));
777
778    case DeclarationName::CXXConversionFunctionName:
779      return Context->DeclarationNames.getCXXConversionFunctionName(
780                           Context->getCanonicalType(Reader.GetType(Key.Data)));
781
782    case DeclarationName::CXXOperatorName:
783      return Context->DeclarationNames.getCXXOperatorName(
784                                         (OverloadedOperatorKind)Key.Data);
785
786    case DeclarationName::CXXLiteralOperatorName:
787      return Context->DeclarationNames.getCXXLiteralOperatorName(
788                                                     (IdentifierInfo*)Key.Data);
789
790    case DeclarationName::CXXUsingDirective:
791      return DeclarationName::getUsingDirectiveName();
792    }
793
794    llvm_unreachable("Invalid Name Kind ?");
795  }
796
797  static std::pair<unsigned, unsigned>
798  ReadKeyDataLength(const unsigned char*& d) {
799    using namespace clang::io;
800    unsigned KeyLen = ReadUnalignedLE16(d);
801    unsigned DataLen = ReadUnalignedLE16(d);
802    return std::make_pair(KeyLen, DataLen);
803  }
804
805  internal_key_type ReadKey(const unsigned char* d, unsigned) {
806    using namespace clang::io;
807
808    DeclNameKey Key;
809    Key.Kind = (DeclarationName::NameKind)*d++;
810    switch (Key.Kind) {
811    case DeclarationName::Identifier:
812      Key.Data = (uint64_t)Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
813      break;
814    case DeclarationName::ObjCZeroArgSelector:
815    case DeclarationName::ObjCOneArgSelector:
816    case DeclarationName::ObjCMultiArgSelector:
817      Key.Data =
818         (uint64_t)Reader.DecodeSelector(ReadUnalignedLE32(d)).getAsOpaquePtr();
819      break;
820    case DeclarationName::CXXConstructorName:
821    case DeclarationName::CXXDestructorName:
822    case DeclarationName::CXXConversionFunctionName:
823      Key.Data = ReadUnalignedLE32(d); // TypeID
824      break;
825    case DeclarationName::CXXOperatorName:
826      Key.Data = *d++; // OverloadedOperatorKind
827      break;
828    case DeclarationName::CXXLiteralOperatorName:
829      Key.Data = (uint64_t)Reader.DecodeIdentifierInfo(ReadUnalignedLE32(d));
830      break;
831    case DeclarationName::CXXUsingDirective:
832      break;
833    }
834
835    return Key;
836  }
837
838  data_type ReadData(internal_key_type, const unsigned char* d,
839                     unsigned DataLen) {
840    using namespace clang::io;
841    unsigned NumDecls = ReadUnalignedLE16(d);
842    DeclID *Start = (DeclID *)d;
843    return std::make_pair(Start, Start + NumDecls);
844  }
845};
846
847} // end anonymous namespace
848
849/// \brief The on-disk hash table used for the DeclContext's Name lookup table.
850typedef OnDiskChainedHashTable<ASTDeclContextNameLookupTrait>
851  ASTDeclContextNameLookupTable;
852
853bool ASTReader::ReadDeclContextStorage(llvm::BitstreamCursor &Cursor,
854                                   const std::pair<uint64_t, uint64_t> &Offsets,
855                                       DeclContextInfo &Info) {
856  SavedStreamPosition SavedPosition(Cursor);
857  // First the lexical decls.
858  if (Offsets.first != 0) {
859    Cursor.JumpToBit(Offsets.first);
860
861    RecordData Record;
862    const char *Blob;
863    unsigned BlobLen;
864    unsigned Code = Cursor.ReadCode();
865    unsigned RecCode = Cursor.ReadRecord(Code, Record, &Blob, &BlobLen);
866    if (RecCode != DECL_CONTEXT_LEXICAL) {
867      Error("Expected lexical block");
868      return true;
869    }
870
871    Info.LexicalDecls = reinterpret_cast<const DeclID*>(Blob);
872    Info.NumLexicalDecls = BlobLen / sizeof(DeclID);
873  } else {
874    Info.LexicalDecls = 0;
875    Info.NumLexicalDecls = 0;
876  }
877
878  // Now the lookup table.
879  if (Offsets.second != 0) {
880    Cursor.JumpToBit(Offsets.second);
881
882    RecordData Record;
883    const char *Blob;
884    unsigned BlobLen;
885    unsigned Code = Cursor.ReadCode();
886    unsigned RecCode = Cursor.ReadRecord(Code, Record, &Blob, &BlobLen);
887    if (RecCode != DECL_CONTEXT_VISIBLE) {
888      Error("Expected visible lookup table block");
889      return true;
890    }
891    Info.NameLookupTableData
892      = ASTDeclContextNameLookupTable::Create(
893                    (const unsigned char *)Blob + Record[0],
894                    (const unsigned char *)Blob,
895                    ASTDeclContextNameLookupTrait(*this));
896  } else {
897    Info.NameLookupTableData = 0;
898  }
899
900  return false;
901}
902
903void ASTReader::Error(const char *Msg) {
904  Diag(diag::err_fe_pch_malformed) << Msg;
905}
906
907/// \brief Tell the AST listener about the predefines buffers in the chain.
908bool ASTReader::CheckPredefinesBuffers() {
909  if (Listener)
910    return Listener->ReadPredefinesBuffer(PCHPredefinesBuffers,
911                                          ActualOriginalFileName,
912                                          SuggestedPredefines);
913  return false;
914}
915
916//===----------------------------------------------------------------------===//
917// Source Manager Deserialization
918//===----------------------------------------------------------------------===//
919
920/// \brief Read the line table in the source manager block.
921/// \returns true if ther was an error.
922bool ASTReader::ParseLineTable(llvm::SmallVectorImpl<uint64_t> &Record) {
923  unsigned Idx = 0;
924  LineTableInfo &LineTable = SourceMgr.getLineTable();
925
926  // Parse the file names
927  std::map<int, int> FileIDs;
928  for (int I = 0, N = Record[Idx++]; I != N; ++I) {
929    // Extract the file name
930    unsigned FilenameLen = Record[Idx++];
931    std::string Filename(&Record[Idx], &Record[Idx] + FilenameLen);
932    Idx += FilenameLen;
933    MaybeAddSystemRootToFilename(Filename);
934    FileIDs[I] = LineTable.getLineTableFilenameID(Filename.c_str(),
935                                                  Filename.size());
936  }
937
938  // Parse the line entries
939  std::vector<LineEntry> Entries;
940  while (Idx < Record.size()) {
941    int FID = Record[Idx++];
942
943    // Extract the line entries
944    unsigned NumEntries = Record[Idx++];
945    assert(NumEntries && "Numentries is 00000");
946    Entries.clear();
947    Entries.reserve(NumEntries);
948    for (unsigned I = 0; I != NumEntries; ++I) {
949      unsigned FileOffset = Record[Idx++];
950      unsigned LineNo = Record[Idx++];
951      int FilenameID = FileIDs[Record[Idx++]];
952      SrcMgr::CharacteristicKind FileKind
953        = (SrcMgr::CharacteristicKind)Record[Idx++];
954      unsigned IncludeOffset = Record[Idx++];
955      Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
956                                       FileKind, IncludeOffset));
957    }
958    LineTable.AddEntry(FID, Entries);
959  }
960
961  return false;
962}
963
964namespace {
965
966class ASTStatData {
967public:
968  const bool hasStat;
969  const ino_t ino;
970  const dev_t dev;
971  const mode_t mode;
972  const time_t mtime;
973  const off_t size;
974
975  ASTStatData(ino_t i, dev_t d, mode_t mo, time_t m, off_t s)
976  : hasStat(true), ino(i), dev(d), mode(mo), mtime(m), size(s) {}
977
978  ASTStatData()
979    : hasStat(false), ino(0), dev(0), mode(0), mtime(0), size(0) {}
980};
981
982class ASTStatLookupTrait {
983 public:
984  typedef const char *external_key_type;
985  typedef const char *internal_key_type;
986
987  typedef ASTStatData data_type;
988
989  static unsigned ComputeHash(const char *path) {
990    return llvm::HashString(path);
991  }
992
993  static internal_key_type GetInternalKey(const char *path) { return path; }
994
995  static bool EqualKey(internal_key_type a, internal_key_type b) {
996    return strcmp(a, b) == 0;
997  }
998
999  static std::pair<unsigned, unsigned>
1000  ReadKeyDataLength(const unsigned char*& d) {
1001    unsigned KeyLen = (unsigned) clang::io::ReadUnalignedLE16(d);
1002    unsigned DataLen = (unsigned) *d++;
1003    return std::make_pair(KeyLen + 1, DataLen);
1004  }
1005
1006  static internal_key_type ReadKey(const unsigned char *d, unsigned) {
1007    return (const char *)d;
1008  }
1009
1010  static data_type ReadData(const internal_key_type, const unsigned char *d,
1011                            unsigned /*DataLen*/) {
1012    using namespace clang::io;
1013
1014    if (*d++ == 1)
1015      return data_type();
1016
1017    ino_t ino = (ino_t) ReadUnalignedLE32(d);
1018    dev_t dev = (dev_t) ReadUnalignedLE32(d);
1019    mode_t mode = (mode_t) ReadUnalignedLE16(d);
1020    time_t mtime = (time_t) ReadUnalignedLE64(d);
1021    off_t size = (off_t) ReadUnalignedLE64(d);
1022    return data_type(ino, dev, mode, mtime, size);
1023  }
1024};
1025
1026/// \brief stat() cache for precompiled headers.
1027///
1028/// This cache is very similar to the stat cache used by pretokenized
1029/// headers.
1030class ASTStatCache : public StatSysCallCache {
1031  typedef OnDiskChainedHashTable<ASTStatLookupTrait> CacheTy;
1032  CacheTy *Cache;
1033
1034  unsigned &NumStatHits, &NumStatMisses;
1035public:
1036  ASTStatCache(const unsigned char *Buckets,
1037               const unsigned char *Base,
1038               unsigned &NumStatHits,
1039               unsigned &NumStatMisses)
1040    : Cache(0), NumStatHits(NumStatHits), NumStatMisses(NumStatMisses) {
1041    Cache = CacheTy::Create(Buckets, Base);
1042  }
1043
1044  ~ASTStatCache() { delete Cache; }
1045
1046  int stat(const char *path, struct stat *buf) {
1047    // Do the lookup for the file's data in the AST file.
1048    CacheTy::iterator I = Cache->find(path);
1049
1050    // If we don't get a hit in the AST file just forward to 'stat'.
1051    if (I == Cache->end()) {
1052      ++NumStatMisses;
1053      return StatSysCallCache::stat(path, buf);
1054    }
1055
1056    ++NumStatHits;
1057    ASTStatData Data = *I;
1058
1059    if (!Data.hasStat)
1060      return 1;
1061
1062    buf->st_ino = Data.ino;
1063    buf->st_dev = Data.dev;
1064    buf->st_mtime = Data.mtime;
1065    buf->st_mode = Data.mode;
1066    buf->st_size = Data.size;
1067    return 0;
1068  }
1069};
1070} // end anonymous namespace
1071
1072
1073/// \brief Read a source manager block
1074ASTReader::ASTReadResult ASTReader::ReadSourceManagerBlock(PerFileData &F) {
1075  using namespace SrcMgr;
1076
1077  llvm::BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
1078
1079  // Set the source-location entry cursor to the current position in
1080  // the stream. This cursor will be used to read the contents of the
1081  // source manager block initially, and then lazily read
1082  // source-location entries as needed.
1083  SLocEntryCursor = F.Stream;
1084
1085  // The stream itself is going to skip over the source manager block.
1086  if (F.Stream.SkipBlock()) {
1087    Error("malformed block record in AST file");
1088    return Failure;
1089  }
1090
1091  // Enter the source manager block.
1092  if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1093    Error("malformed source manager block record in AST file");
1094    return Failure;
1095  }
1096
1097  RecordData Record;
1098  while (true) {
1099    unsigned Code = SLocEntryCursor.ReadCode();
1100    if (Code == llvm::bitc::END_BLOCK) {
1101      if (SLocEntryCursor.ReadBlockEnd()) {
1102        Error("error at end of Source Manager block in AST file");
1103        return Failure;
1104      }
1105      return Success;
1106    }
1107
1108    if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1109      // No known subblocks, always skip them.
1110      SLocEntryCursor.ReadSubBlockID();
1111      if (SLocEntryCursor.SkipBlock()) {
1112        Error("malformed block record in AST file");
1113        return Failure;
1114      }
1115      continue;
1116    }
1117
1118    if (Code == llvm::bitc::DEFINE_ABBREV) {
1119      SLocEntryCursor.ReadAbbrevRecord();
1120      continue;
1121    }
1122
1123    // Read a record.
1124    const char *BlobStart;
1125    unsigned BlobLen;
1126    Record.clear();
1127    switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1128    default:  // Default behavior: ignore.
1129      break;
1130
1131    case SM_LINE_TABLE:
1132      if (ParseLineTable(Record))
1133        return Failure;
1134      break;
1135
1136    case SM_SLOC_FILE_ENTRY:
1137    case SM_SLOC_BUFFER_ENTRY:
1138    case SM_SLOC_INSTANTIATION_ENTRY:
1139      // Once we hit one of the source location entries, we're done.
1140      return Success;
1141    }
1142  }
1143}
1144
1145/// \brief Get a cursor that's correctly positioned for reading the source
1146/// location entry with the given ID.
1147llvm::BitstreamCursor &ASTReader::SLocCursorForID(unsigned ID) {
1148  assert(ID != 0 && ID <= TotalNumSLocEntries &&
1149         "SLocCursorForID should only be called for real IDs.");
1150
1151  ID -= 1;
1152  PerFileData *F = 0;
1153  for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1154    F = Chain[N - I - 1];
1155    if (ID < F->LocalNumSLocEntries)
1156      break;
1157    ID -= F->LocalNumSLocEntries;
1158  }
1159  assert(F && F->LocalNumSLocEntries > ID && "Chain corrupted");
1160
1161  F->SLocEntryCursor.JumpToBit(F->SLocOffsets[ID]);
1162  return F->SLocEntryCursor;
1163}
1164
1165/// \brief Read in the source location entry with the given ID.
1166ASTReader::ASTReadResult ASTReader::ReadSLocEntryRecord(unsigned ID) {
1167  if (ID == 0)
1168    return Success;
1169
1170  if (ID > TotalNumSLocEntries) {
1171    Error("source location entry ID out-of-range for AST file");
1172    return Failure;
1173  }
1174
1175  llvm::BitstreamCursor &SLocEntryCursor = SLocCursorForID(ID);
1176
1177  ++NumSLocEntriesRead;
1178  unsigned Code = SLocEntryCursor.ReadCode();
1179  if (Code == llvm::bitc::END_BLOCK ||
1180      Code == llvm::bitc::ENTER_SUBBLOCK ||
1181      Code == llvm::bitc::DEFINE_ABBREV) {
1182    Error("incorrectly-formatted source location entry in AST file");
1183    return Failure;
1184  }
1185
1186  RecordData Record;
1187  const char *BlobStart;
1188  unsigned BlobLen;
1189  switch (SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1190  default:
1191    Error("incorrectly-formatted source location entry in AST file");
1192    return Failure;
1193
1194  case SM_SLOC_FILE_ENTRY: {
1195    std::string Filename(BlobStart, BlobStart + BlobLen);
1196    MaybeAddSystemRootToFilename(Filename);
1197    const FileEntry *File = FileMgr.getFile(Filename);
1198    if (File == 0) {
1199      std::string ErrorStr = "could not find file '";
1200      ErrorStr += Filename;
1201      ErrorStr += "' referenced by AST file";
1202      Error(ErrorStr.c_str());
1203      return Failure;
1204    }
1205
1206    if (Record.size() < 10) {
1207      Error("source location entry is incorrect");
1208      return Failure;
1209    }
1210
1211    if (!DisableValidation &&
1212        ((off_t)Record[4] != File->getSize()
1213#if !defined(LLVM_ON_WIN32)
1214        // In our regression testing, the Windows file system seems to
1215        // have inconsistent modification times that sometimes
1216        // erroneously trigger this error-handling path.
1217         || (time_t)Record[5] != File->getModificationTime()
1218#endif
1219        )) {
1220      Diag(diag::err_fe_pch_file_modified)
1221        << Filename;
1222      return Failure;
1223    }
1224
1225    FileID FID = SourceMgr.createFileID(File,
1226                                SourceLocation::getFromRawEncoding(Record[1]),
1227                                       (SrcMgr::CharacteristicKind)Record[2],
1228                                        ID, Record[0]);
1229    if (Record[3])
1230      const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile())
1231        .setHasLineDirectives();
1232
1233    // Reconstruct header-search information for this file.
1234    HeaderFileInfo HFI;
1235    HFI.isImport = Record[6];
1236    HFI.DirInfo = Record[7];
1237    HFI.NumIncludes = Record[8];
1238    HFI.ControllingMacroID = Record[9];
1239    if (Listener)
1240      Listener->ReadHeaderFileInfo(HFI, File->getUID());
1241    break;
1242  }
1243
1244  case SM_SLOC_BUFFER_ENTRY: {
1245    const char *Name = BlobStart;
1246    unsigned Offset = Record[0];
1247    unsigned Code = SLocEntryCursor.ReadCode();
1248    Record.clear();
1249    unsigned RecCode
1250      = SLocEntryCursor.ReadRecord(Code, Record, &BlobStart, &BlobLen);
1251
1252    if (RecCode != SM_SLOC_BUFFER_BLOB) {
1253      Error("AST record has invalid code");
1254      return Failure;
1255    }
1256
1257    llvm::MemoryBuffer *Buffer
1258    = llvm::MemoryBuffer::getMemBuffer(llvm::StringRef(BlobStart, BlobLen - 1),
1259                                       Name);
1260    FileID BufferID = SourceMgr.createFileIDForMemBuffer(Buffer, ID, Offset);
1261
1262    if (strcmp(Name, "<built-in>") == 0) {
1263      PCHPredefinesBlock Block = {
1264        BufferID,
1265        llvm::StringRef(BlobStart, BlobLen - 1)
1266      };
1267      PCHPredefinesBuffers.push_back(Block);
1268    }
1269
1270    break;
1271  }
1272
1273  case SM_SLOC_INSTANTIATION_ENTRY: {
1274    SourceLocation SpellingLoc
1275      = SourceLocation::getFromRawEncoding(Record[1]);
1276    SourceMgr.createInstantiationLoc(SpellingLoc,
1277                              SourceLocation::getFromRawEncoding(Record[2]),
1278                              SourceLocation::getFromRawEncoding(Record[3]),
1279                                     Record[4],
1280                                     ID,
1281                                     Record[0]);
1282    break;
1283  }
1284  }
1285
1286  return Success;
1287}
1288
1289/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1290/// specified cursor.  Read the abbreviations that are at the top of the block
1291/// and then leave the cursor pointing into the block.
1292bool ASTReader::ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor,
1293                                 unsigned BlockID) {
1294  if (Cursor.EnterSubBlock(BlockID)) {
1295    Error("malformed block record in AST file");
1296    return Failure;
1297  }
1298
1299  while (true) {
1300    unsigned Code = Cursor.ReadCode();
1301
1302    // We expect all abbrevs to be at the start of the block.
1303    if (Code != llvm::bitc::DEFINE_ABBREV)
1304      return false;
1305    Cursor.ReadAbbrevRecord();
1306  }
1307}
1308
1309void ASTReader::ReadMacroRecord(llvm::BitstreamCursor &Stream, uint64_t Offset){
1310  assert(PP && "Forgot to set Preprocessor ?");
1311
1312  // Keep track of where we are in the stream, then jump back there
1313  // after reading this macro.
1314  SavedStreamPosition SavedPosition(Stream);
1315
1316  Stream.JumpToBit(Offset);
1317  RecordData Record;
1318  llvm::SmallVector<IdentifierInfo*, 16> MacroArgs;
1319  MacroInfo *Macro = 0;
1320
1321  while (true) {
1322    unsigned Code = Stream.ReadCode();
1323    switch (Code) {
1324    case llvm::bitc::END_BLOCK:
1325      return;
1326
1327    case llvm::bitc::ENTER_SUBBLOCK:
1328      // No known subblocks, always skip them.
1329      Stream.ReadSubBlockID();
1330      if (Stream.SkipBlock()) {
1331        Error("malformed block record in AST file");
1332        return;
1333      }
1334      continue;
1335
1336    case llvm::bitc::DEFINE_ABBREV:
1337      Stream.ReadAbbrevRecord();
1338      continue;
1339    default: break;
1340    }
1341
1342    // Read a record.
1343    Record.clear();
1344    PreprocessorRecordTypes RecType =
1345      (PreprocessorRecordTypes)Stream.ReadRecord(Code, Record);
1346    switch (RecType) {
1347    case PP_MACRO_OBJECT_LIKE:
1348    case PP_MACRO_FUNCTION_LIKE: {
1349      // If we already have a macro, that means that we've hit the end
1350      // of the definition of the macro we were looking for. We're
1351      // done.
1352      if (Macro)
1353        return;
1354
1355      IdentifierInfo *II = DecodeIdentifierInfo(Record[0]);
1356      if (II == 0) {
1357        Error("macro must have a name in AST file");
1358        return;
1359      }
1360      SourceLocation Loc = SourceLocation::getFromRawEncoding(Record[1]);
1361      bool isUsed = Record[2];
1362
1363      MacroInfo *MI = PP->AllocateMacroInfo(Loc);
1364      MI->setIsUsed(isUsed);
1365      MI->setIsFromAST();
1366
1367      unsigned NextIndex = 3;
1368      if (RecType == PP_MACRO_FUNCTION_LIKE) {
1369        // Decode function-like macro info.
1370        bool isC99VarArgs = Record[3];
1371        bool isGNUVarArgs = Record[4];
1372        MacroArgs.clear();
1373        unsigned NumArgs = Record[5];
1374        NextIndex = 6 + NumArgs;
1375        for (unsigned i = 0; i != NumArgs; ++i)
1376          MacroArgs.push_back(DecodeIdentifierInfo(Record[6+i]));
1377
1378        // Install function-like macro info.
1379        MI->setIsFunctionLike();
1380        if (isC99VarArgs) MI->setIsC99Varargs();
1381        if (isGNUVarArgs) MI->setIsGNUVarargs();
1382        MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
1383                            PP->getPreprocessorAllocator());
1384      }
1385
1386      // Finally, install the macro.
1387      PP->setMacroInfo(II, MI);
1388
1389      // Remember that we saw this macro last so that we add the tokens that
1390      // form its body to it.
1391      Macro = MI;
1392
1393      if (NextIndex + 1 == Record.size() && PP->getPreprocessingRecord()) {
1394        // We have a macro definition. Load it now.
1395        PP->getPreprocessingRecord()->RegisterMacroDefinition(Macro,
1396                                        getMacroDefinition(Record[NextIndex]));
1397      }
1398
1399      ++NumMacrosRead;
1400      break;
1401    }
1402
1403    case PP_TOKEN: {
1404      // If we see a TOKEN before a PP_MACRO_*, then the file is
1405      // erroneous, just pretend we didn't see this.
1406      if (Macro == 0) break;
1407
1408      Token Tok;
1409      Tok.startToken();
1410      Tok.setLocation(SourceLocation::getFromRawEncoding(Record[0]));
1411      Tok.setLength(Record[1]);
1412      if (IdentifierInfo *II = DecodeIdentifierInfo(Record[2]))
1413        Tok.setIdentifierInfo(II);
1414      Tok.setKind((tok::TokenKind)Record[3]);
1415      Tok.setFlag((Token::TokenFlags)Record[4]);
1416      Macro->AddTokenToBody(Tok);
1417      break;
1418    }
1419
1420    case PP_MACRO_INSTANTIATION: {
1421      // If we already have a macro, that means that we've hit the end
1422      // of the definition of the macro we were looking for. We're
1423      // done.
1424      if (Macro)
1425        return;
1426
1427      if (!PP->getPreprocessingRecord()) {
1428        Error("missing preprocessing record in AST file");
1429        return;
1430      }
1431
1432      PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1433      if (PPRec.getPreprocessedEntity(Record[0]))
1434        return;
1435
1436      MacroInstantiation *MI
1437        = new (PPRec) MacroInstantiation(DecodeIdentifierInfo(Record[3]),
1438                               SourceRange(
1439                                 SourceLocation::getFromRawEncoding(Record[1]),
1440                                 SourceLocation::getFromRawEncoding(Record[2])),
1441                                         getMacroDefinition(Record[4]));
1442      PPRec.SetPreallocatedEntity(Record[0], MI);
1443      return;
1444    }
1445
1446    case PP_MACRO_DEFINITION: {
1447      // If we already have a macro, that means that we've hit the end
1448      // of the definition of the macro we were looking for. We're
1449      // done.
1450      if (Macro)
1451        return;
1452
1453      if (!PP->getPreprocessingRecord()) {
1454        Error("missing preprocessing record in AST file");
1455        return;
1456      }
1457
1458      PreprocessingRecord &PPRec = *PP->getPreprocessingRecord();
1459      if (PPRec.getPreprocessedEntity(Record[0]))
1460        return;
1461
1462      if (Record[1] >= MacroDefinitionsLoaded.size()) {
1463        Error("out-of-bounds macro definition record");
1464        return;
1465      }
1466
1467      MacroDefinition *MD
1468        = new (PPRec) MacroDefinition(DecodeIdentifierInfo(Record[4]),
1469                                SourceLocation::getFromRawEncoding(Record[5]),
1470                              SourceRange(
1471                                SourceLocation::getFromRawEncoding(Record[2]),
1472                                SourceLocation::getFromRawEncoding(Record[3])));
1473      PPRec.SetPreallocatedEntity(Record[0], MD);
1474      MacroDefinitionsLoaded[Record[1]] = MD;
1475      return;
1476    }
1477  }
1478  }
1479}
1480
1481void ASTReader::ReadDefinedMacros() {
1482  for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1483    llvm::BitstreamCursor &MacroCursor = Chain[N - I - 1]->MacroCursor;
1484
1485    // If there was no preprocessor block, skip this file.
1486    if (!MacroCursor.getBitStreamReader())
1487      continue;
1488
1489    llvm::BitstreamCursor Cursor = MacroCursor;
1490    if (Cursor.EnterSubBlock(PREPROCESSOR_BLOCK_ID)) {
1491      Error("malformed preprocessor block record in AST file");
1492      return;
1493    }
1494
1495    RecordData Record;
1496    while (true) {
1497      unsigned Code = Cursor.ReadCode();
1498      if (Code == llvm::bitc::END_BLOCK) {
1499        if (Cursor.ReadBlockEnd()) {
1500          Error("error at end of preprocessor block in AST file");
1501          return;
1502        }
1503        break;
1504      }
1505
1506      if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1507        // No known subblocks, always skip them.
1508        Cursor.ReadSubBlockID();
1509        if (Cursor.SkipBlock()) {
1510          Error("malformed block record in AST file");
1511          return;
1512        }
1513        continue;
1514      }
1515
1516      if (Code == llvm::bitc::DEFINE_ABBREV) {
1517        Cursor.ReadAbbrevRecord();
1518        continue;
1519      }
1520
1521      // Read a record.
1522      const char *BlobStart;
1523      unsigned BlobLen;
1524      Record.clear();
1525      switch (Cursor.ReadRecord(Code, Record, &BlobStart, &BlobLen)) {
1526      default:  // Default behavior: ignore.
1527        break;
1528
1529      case PP_MACRO_OBJECT_LIKE:
1530      case PP_MACRO_FUNCTION_LIKE:
1531        DecodeIdentifierInfo(Record[0]);
1532        break;
1533
1534      case PP_TOKEN:
1535        // Ignore tokens.
1536        break;
1537
1538      case PP_MACRO_INSTANTIATION:
1539      case PP_MACRO_DEFINITION:
1540        // Read the macro record.
1541        ReadMacroRecord(Chain[N - I - 1]->Stream, Cursor.GetCurrentBitNo());
1542        break;
1543      }
1544    }
1545  }
1546}
1547
1548MacroDefinition *ASTReader::getMacroDefinition(MacroID ID) {
1549  if (ID == 0 || ID >= MacroDefinitionsLoaded.size())
1550    return 0;
1551
1552  if (!MacroDefinitionsLoaded[ID]) {
1553    unsigned Index = ID;
1554    for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
1555      PerFileData &F = *Chain[N - I - 1];
1556      if (Index < F.LocalNumMacroDefinitions) {
1557        ReadMacroRecord(F.Stream, F.MacroDefinitionOffsets[Index]);
1558        break;
1559      }
1560      Index -= F.LocalNumMacroDefinitions;
1561    }
1562    assert(MacroDefinitionsLoaded[ID] && "Broken chain");
1563  }
1564
1565  return MacroDefinitionsLoaded[ID];
1566}
1567
1568/// \brief If we are loading a relocatable PCH file, and the filename is
1569/// not an absolute path, add the system root to the beginning of the file
1570/// name.
1571void ASTReader::MaybeAddSystemRootToFilename(std::string &Filename) {
1572  // If this is not a relocatable PCH file, there's nothing to do.
1573  if (!RelocatablePCH)
1574    return;
1575
1576  if (Filename.empty() || llvm::sys::Path(Filename).isAbsolute())
1577    return;
1578
1579  if (isysroot == 0) {
1580    // If no system root was given, default to '/'
1581    Filename.insert(Filename.begin(), '/');
1582    return;
1583  }
1584
1585  unsigned Length = strlen(isysroot);
1586  if (isysroot[Length - 1] != '/')
1587    Filename.insert(Filename.begin(), '/');
1588
1589  Filename.insert(Filename.begin(), isysroot, isysroot + Length);
1590}
1591
1592ASTReader::ASTReadResult
1593ASTReader::ReadASTBlock(PerFileData &F) {
1594  llvm::BitstreamCursor &Stream = F.Stream;
1595
1596  if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
1597    Error("malformed block record in AST file");
1598    return Failure;
1599  }
1600
1601  // Read all of the records and blocks for the ASt file.
1602  RecordData Record;
1603  bool First = true;
1604  while (!Stream.AtEndOfStream()) {
1605    unsigned Code = Stream.ReadCode();
1606    if (Code == llvm::bitc::END_BLOCK) {
1607      if (Stream.ReadBlockEnd()) {
1608        Error("error at end of module block in AST file");
1609        return Failure;
1610      }
1611
1612      return Success;
1613    }
1614
1615    if (Code == llvm::bitc::ENTER_SUBBLOCK) {
1616      switch (Stream.ReadSubBlockID()) {
1617      case DECLTYPES_BLOCK_ID:
1618        // We lazily load the decls block, but we want to set up the
1619        // DeclsCursor cursor to point into it.  Clone our current bitcode
1620        // cursor to it, enter the block and read the abbrevs in that block.
1621        // With the main cursor, we just skip over it.
1622        F.DeclsCursor = Stream;
1623        if (Stream.SkipBlock() ||  // Skip with the main cursor.
1624            // Read the abbrevs.
1625            ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
1626          Error("malformed block record in AST file");
1627          return Failure;
1628        }
1629        break;
1630
1631      case PREPROCESSOR_BLOCK_ID:
1632        F.MacroCursor = Stream;
1633        if (PP)
1634          PP->setExternalSource(this);
1635
1636        if (Stream.SkipBlock()) {
1637          Error("malformed block record in AST file");
1638          return Failure;
1639        }
1640        break;
1641
1642      case SOURCE_MANAGER_BLOCK_ID:
1643        switch (ReadSourceManagerBlock(F)) {
1644        case Success:
1645          break;
1646
1647        case Failure:
1648          Error("malformed source manager block in AST file");
1649          return Failure;
1650
1651        case IgnorePCH:
1652          return IgnorePCH;
1653        }
1654        break;
1655      }
1656      First = false;
1657      continue;
1658    }
1659
1660    if (Code == llvm::bitc::DEFINE_ABBREV) {
1661      Stream.ReadAbbrevRecord();
1662      continue;
1663    }
1664
1665    // Read and process a record.
1666    Record.clear();
1667    const char *BlobStart = 0;
1668    unsigned BlobLen = 0;
1669    switch ((ASTRecordTypes)Stream.ReadRecord(Code, Record,
1670                                                   &BlobStart, &BlobLen)) {
1671    default:  // Default behavior: ignore.
1672      break;
1673
1674    case METADATA: {
1675      if (Record[0] != VERSION_MAJOR && !DisableValidation) {
1676        Diag(Record[0] < VERSION_MAJOR? diag::warn_pch_version_too_old
1677                                           : diag::warn_pch_version_too_new);
1678        return IgnorePCH;
1679      }
1680
1681      RelocatablePCH = Record[4];
1682      if (Listener) {
1683        std::string TargetTriple(BlobStart, BlobLen);
1684        if (Listener->ReadTargetTriple(TargetTriple))
1685          return IgnorePCH;
1686      }
1687      break;
1688    }
1689
1690    case CHAINED_METADATA: {
1691      if (!First) {
1692        Error("CHAINED_METADATA is not first record in block");
1693        return Failure;
1694      }
1695      if (Record[0] != VERSION_MAJOR && !DisableValidation) {
1696        Diag(Record[0] < VERSION_MAJOR? diag::warn_pch_version_too_old
1697                                           : diag::warn_pch_version_too_new);
1698        return IgnorePCH;
1699      }
1700
1701      // Load the chained file.
1702      switch(ReadASTCore(llvm::StringRef(BlobStart, BlobLen))) {
1703      case Failure: return Failure;
1704        // If we have to ignore the dependency, we'll have to ignore this too.
1705      case IgnorePCH: return IgnorePCH;
1706      case Success: break;
1707      }
1708      break;
1709    }
1710
1711    case TYPE_OFFSET:
1712      if (F.LocalNumTypes != 0) {
1713        Error("duplicate TYPE_OFFSET record in AST file");
1714        return Failure;
1715      }
1716      F.TypeOffsets = (const uint32_t *)BlobStart;
1717      F.LocalNumTypes = Record[0];
1718      break;
1719
1720    case DECL_OFFSET:
1721      if (F.LocalNumDecls != 0) {
1722        Error("duplicate DECL_OFFSET record in AST file");
1723        return Failure;
1724      }
1725      F.DeclOffsets = (const uint32_t *)BlobStart;
1726      F.LocalNumDecls = Record[0];
1727      break;
1728
1729    case TU_UPDATE_LEXICAL: {
1730      DeclContextInfo Info = {
1731        /* No visible information */ 0,
1732        reinterpret_cast<const DeclID *>(BlobStart),
1733        BlobLen / sizeof(DeclID)
1734      };
1735      DeclContextOffsets[Context->getTranslationUnitDecl()].push_back(Info);
1736      break;
1737    }
1738
1739    case UPDATE_VISIBLE: {
1740      serialization::DeclID ID = Record[0];
1741      void *Table = ASTDeclContextNameLookupTable::Create(
1742                        (const unsigned char *)BlobStart + Record[1],
1743                        (const unsigned char *)BlobStart,
1744                        ASTDeclContextNameLookupTrait(*this));
1745      if (ID == 1) { // Is it the TU?
1746        DeclContextInfo Info = {
1747          Table, /* No lexical inforamtion */ 0, 0
1748        };
1749        DeclContextOffsets[Context->getTranslationUnitDecl()].push_back(Info);
1750      } else
1751        PendingVisibleUpdates[ID].push_back(Table);
1752      break;
1753    }
1754
1755    case REDECLS_UPDATE_LATEST: {
1756      assert(Record.size() % 2 == 0 && "Expected pairs of DeclIDs");
1757      for (unsigned i = 0, e = Record.size(); i < e; i += 2) {
1758        DeclID First = Record[i], Latest = Record[i+1];
1759        assert((FirstLatestDeclIDs.find(First) == FirstLatestDeclIDs.end() ||
1760                Latest > FirstLatestDeclIDs[First]) &&
1761               "The new latest is supposed to come after the previous latest");
1762        FirstLatestDeclIDs[First] = Latest;
1763      }
1764      break;
1765    }
1766
1767    case LANGUAGE_OPTIONS:
1768      if (ParseLanguageOptions(Record) && !DisableValidation)
1769        return IgnorePCH;
1770      break;
1771
1772    case IDENTIFIER_TABLE:
1773      F.IdentifierTableData = BlobStart;
1774      if (Record[0]) {
1775        F.IdentifierLookupTable
1776          = ASTIdentifierLookupTable::Create(
1777                       (const unsigned char *)F.IdentifierTableData + Record[0],
1778                       (const unsigned char *)F.IdentifierTableData,
1779                       ASTIdentifierLookupTrait(*this, F.Stream));
1780        if (PP)
1781          PP->getIdentifierTable().setExternalIdentifierLookup(this);
1782      }
1783      break;
1784
1785    case IDENTIFIER_OFFSET:
1786      if (F.LocalNumIdentifiers != 0) {
1787        Error("duplicate IDENTIFIER_OFFSET record in AST file");
1788        return Failure;
1789      }
1790      F.IdentifierOffsets = (const uint32_t *)BlobStart;
1791      F.LocalNumIdentifiers = Record[0];
1792      break;
1793
1794    case EXTERNAL_DEFINITIONS:
1795      // Optimization for the first block.
1796      if (ExternalDefinitions.empty())
1797        ExternalDefinitions.swap(Record);
1798      else
1799        ExternalDefinitions.insert(ExternalDefinitions.end(),
1800                                   Record.begin(), Record.end());
1801      break;
1802
1803    case SPECIAL_TYPES:
1804      // Optimization for the first block
1805      if (SpecialTypes.empty())
1806        SpecialTypes.swap(Record);
1807      else
1808        SpecialTypes.insert(SpecialTypes.end(), Record.begin(), Record.end());
1809      break;
1810
1811    case STATISTICS:
1812      TotalNumStatements += Record[0];
1813      TotalNumMacros += Record[1];
1814      TotalLexicalDeclContexts += Record[2];
1815      TotalVisibleDeclContexts += Record[3];
1816      break;
1817
1818    case TENTATIVE_DEFINITIONS:
1819      // Optimization for the first block.
1820      if (TentativeDefinitions.empty())
1821        TentativeDefinitions.swap(Record);
1822      else
1823        TentativeDefinitions.insert(TentativeDefinitions.end(),
1824                                    Record.begin(), Record.end());
1825      break;
1826
1827    case UNUSED_FILESCOPED_DECLS:
1828      // Optimization for the first block.
1829      if (UnusedFileScopedDecls.empty())
1830        UnusedFileScopedDecls.swap(Record);
1831      else
1832        UnusedFileScopedDecls.insert(UnusedFileScopedDecls.end(),
1833                                     Record.begin(), Record.end());
1834      break;
1835
1836    case WEAK_UNDECLARED_IDENTIFIERS:
1837      // Later blocks overwrite earlier ones.
1838      WeakUndeclaredIdentifiers.swap(Record);
1839      break;
1840
1841    case LOCALLY_SCOPED_EXTERNAL_DECLS:
1842      // Optimization for the first block.
1843      if (LocallyScopedExternalDecls.empty())
1844        LocallyScopedExternalDecls.swap(Record);
1845      else
1846        LocallyScopedExternalDecls.insert(LocallyScopedExternalDecls.end(),
1847                                          Record.begin(), Record.end());
1848      break;
1849
1850    case SELECTOR_OFFSETS:
1851      F.SelectorOffsets = (const uint32_t *)BlobStart;
1852      F.LocalNumSelectors = Record[0];
1853      break;
1854
1855    case METHOD_POOL:
1856      F.SelectorLookupTableData = (const unsigned char *)BlobStart;
1857      if (Record[0])
1858        F.SelectorLookupTable
1859          = ASTSelectorLookupTable::Create(
1860                        F.SelectorLookupTableData + Record[0],
1861                        F.SelectorLookupTableData,
1862                        ASTSelectorLookupTrait(*this));
1863      TotalNumMethodPoolEntries += Record[1];
1864      break;
1865
1866    case REFERENCED_SELECTOR_POOL:
1867      if (ReferencedSelectorsData.empty())
1868        ReferencedSelectorsData.swap(Record);
1869      else
1870        ReferencedSelectorsData.insert(ReferencedSelectorsData.end(),
1871            Record.begin(), Record.end());
1872      break;
1873
1874    case PP_COUNTER_VALUE:
1875      if (!Record.empty() && Listener)
1876        Listener->ReadCounter(Record[0]);
1877      break;
1878
1879    case SOURCE_LOCATION_OFFSETS:
1880      F.SLocOffsets = (const uint32_t *)BlobStart;
1881      F.LocalNumSLocEntries = Record[0];
1882      F.LocalSLocSize = Record[1];
1883      break;
1884
1885    case SOURCE_LOCATION_PRELOADS:
1886      if (PreloadSLocEntries.empty())
1887        PreloadSLocEntries.swap(Record);
1888      else
1889        PreloadSLocEntries.insert(PreloadSLocEntries.end(),
1890            Record.begin(), Record.end());
1891      break;
1892
1893    case STAT_CACHE: {
1894      ASTStatCache *MyStatCache =
1895        new ASTStatCache((const unsigned char *)BlobStart + Record[0],
1896                         (const unsigned char *)BlobStart,
1897                         NumStatHits, NumStatMisses);
1898      FileMgr.addStatCache(MyStatCache);
1899      F.StatCache = MyStatCache;
1900      break;
1901    }
1902
1903    case EXT_VECTOR_DECLS:
1904      // Optimization for the first block.
1905      if (ExtVectorDecls.empty())
1906        ExtVectorDecls.swap(Record);
1907      else
1908        ExtVectorDecls.insert(ExtVectorDecls.end(),
1909                              Record.begin(), Record.end());
1910      break;
1911
1912    case VTABLE_USES:
1913      // Later tables overwrite earlier ones.
1914      VTableUses.swap(Record);
1915      break;
1916
1917    case DYNAMIC_CLASSES:
1918      // Optimization for the first block.
1919      if (DynamicClasses.empty())
1920        DynamicClasses.swap(Record);
1921      else
1922        DynamicClasses.insert(DynamicClasses.end(),
1923                              Record.begin(), Record.end());
1924      break;
1925
1926    case PENDING_IMPLICIT_INSTANTIATIONS:
1927      // Optimization for the first block.
1928      if (PendingInstantiations.empty())
1929        PendingInstantiations.swap(Record);
1930      else
1931        PendingInstantiations.insert(PendingInstantiations.end(),
1932                                     Record.begin(), Record.end());
1933      break;
1934
1935    case SEMA_DECL_REFS:
1936      // Later tables overwrite earlier ones.
1937      SemaDeclRefs.swap(Record);
1938      break;
1939
1940    case ORIGINAL_FILE_NAME:
1941      // The primary AST will be the last to get here, so it will be the one
1942      // that's used.
1943      ActualOriginalFileName.assign(BlobStart, BlobLen);
1944      OriginalFileName = ActualOriginalFileName;
1945      MaybeAddSystemRootToFilename(OriginalFileName);
1946      break;
1947
1948    case VERSION_CONTROL_BRANCH_REVISION: {
1949      const std::string &CurBranch = getClangFullRepositoryVersion();
1950      llvm::StringRef ASTBranch(BlobStart, BlobLen);
1951      if (llvm::StringRef(CurBranch) != ASTBranch && !DisableValidation) {
1952        Diag(diag::warn_pch_different_branch) << ASTBranch << CurBranch;
1953        return IgnorePCH;
1954      }
1955      break;
1956    }
1957
1958    case MACRO_DEFINITION_OFFSETS:
1959      F.MacroDefinitionOffsets = (const uint32_t *)BlobStart;
1960      F.NumPreallocatedPreprocessingEntities = Record[0];
1961      F.LocalNumMacroDefinitions = Record[1];
1962      break;
1963
1964    case DECL_REPLACEMENTS: {
1965      if (Record.size() % 2 != 0) {
1966        Error("invalid DECL_REPLACEMENTS block in AST file");
1967        return Failure;
1968      }
1969      for (unsigned I = 0, N = Record.size(); I != N; I += 2)
1970        ReplacedDecls[static_cast<DeclID>(Record[I])] =
1971            std::make_pair(&F, Record[I+1]);
1972      break;
1973    }
1974
1975    case ADDITIONAL_TEMPLATE_SPECIALIZATIONS: {
1976      AdditionalTemplateSpecializations &ATS =
1977          AdditionalTemplateSpecializationsPending[Record[0]];
1978      ATS.insert(ATS.end(), Record.begin()+1, Record.end());
1979      break;
1980    }
1981    }
1982    First = false;
1983  }
1984  Error("premature end of bitstream in AST file");
1985  return Failure;
1986}
1987
1988ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName) {
1989  switch(ReadASTCore(FileName)) {
1990  case Failure: return Failure;
1991  case IgnorePCH: return IgnorePCH;
1992  case Success: break;
1993  }
1994
1995  // Here comes stuff that we only do once the entire chain is loaded.
1996
1997  // Allocate space for loaded slocentries, identifiers, decls and types.
1998  unsigned TotalNumIdentifiers = 0, TotalNumTypes = 0, TotalNumDecls = 0,
1999           TotalNumPreallocatedPreprocessingEntities = 0, TotalNumMacroDefs = 0,
2000           TotalNumSelectors = 0;
2001  for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2002    TotalNumSLocEntries += Chain[I]->LocalNumSLocEntries;
2003    NextSLocOffset += Chain[I]->LocalSLocSize;
2004    TotalNumIdentifiers += Chain[I]->LocalNumIdentifiers;
2005    TotalNumTypes += Chain[I]->LocalNumTypes;
2006    TotalNumDecls += Chain[I]->LocalNumDecls;
2007    TotalNumPreallocatedPreprocessingEntities +=
2008        Chain[I]->NumPreallocatedPreprocessingEntities;
2009    TotalNumMacroDefs += Chain[I]->LocalNumMacroDefinitions;
2010    TotalNumSelectors += Chain[I]->LocalNumSelectors;
2011  }
2012  SourceMgr.PreallocateSLocEntries(this, TotalNumSLocEntries, NextSLocOffset);
2013  IdentifiersLoaded.resize(TotalNumIdentifiers);
2014  TypesLoaded.resize(TotalNumTypes);
2015  DeclsLoaded.resize(TotalNumDecls);
2016  MacroDefinitionsLoaded.resize(TotalNumMacroDefs);
2017  if (PP) {
2018    if (TotalNumIdentifiers > 0)
2019      PP->getHeaderSearchInfo().SetExternalLookup(this);
2020    if (TotalNumPreallocatedPreprocessingEntities > 0) {
2021      if (!PP->getPreprocessingRecord())
2022        PP->createPreprocessingRecord();
2023      PP->getPreprocessingRecord()->SetExternalSource(*this,
2024                                     TotalNumPreallocatedPreprocessingEntities);
2025    }
2026  }
2027  SelectorsLoaded.resize(TotalNumSelectors);
2028  // Preload SLocEntries.
2029  for (unsigned I = 0, N = PreloadSLocEntries.size(); I != N; ++I) {
2030    ASTReadResult Result = ReadSLocEntryRecord(PreloadSLocEntries[I]);
2031    if (Result != Success)
2032      return Result;
2033  }
2034
2035  // Check the predefines buffers.
2036  if (!DisableValidation && CheckPredefinesBuffers())
2037    return IgnorePCH;
2038
2039  if (PP) {
2040    // Initialization of keywords and pragmas occurs before the
2041    // AST file is read, so there may be some identifiers that were
2042    // loaded into the IdentifierTable before we intercepted the
2043    // creation of identifiers. Iterate through the list of known
2044    // identifiers and determine whether we have to establish
2045    // preprocessor definitions or top-level identifier declaration
2046    // chains for those identifiers.
2047    //
2048    // We copy the IdentifierInfo pointers to a small vector first,
2049    // since de-serializing declarations or macro definitions can add
2050    // new entries into the identifier table, invalidating the
2051    // iterators.
2052    llvm::SmallVector<IdentifierInfo *, 128> Identifiers;
2053    for (IdentifierTable::iterator Id = PP->getIdentifierTable().begin(),
2054                                IdEnd = PP->getIdentifierTable().end();
2055         Id != IdEnd; ++Id)
2056      Identifiers.push_back(Id->second);
2057    // We need to search the tables in all files.
2058    for (unsigned J = 0, M = Chain.size(); J != M; ++J) {
2059      ASTIdentifierLookupTable *IdTable
2060        = (ASTIdentifierLookupTable *)Chain[J]->IdentifierLookupTable;
2061      // Not all AST files necessarily have identifier tables, only the useful
2062      // ones.
2063      if (!IdTable)
2064        continue;
2065      for (unsigned I = 0, N = Identifiers.size(); I != N; ++I) {
2066        IdentifierInfo *II = Identifiers[I];
2067        // Look in the on-disk hash tables for an entry for this identifier
2068        ASTIdentifierLookupTrait Info(*this, Chain[J]->Stream, II);
2069        std::pair<const char*,unsigned> Key(II->getNameStart(),II->getLength());
2070        ASTIdentifierLookupTable::iterator Pos = IdTable->find(Key, &Info);
2071        if (Pos == IdTable->end())
2072          continue;
2073
2074        // Dereferencing the iterator has the effect of populating the
2075        // IdentifierInfo node with the various declarations it needs.
2076        (void)*Pos;
2077      }
2078    }
2079  }
2080
2081  if (Context)
2082    InitializeContext(*Context);
2083
2084  return Success;
2085}
2086
2087ASTReader::ASTReadResult ASTReader::ReadASTCore(llvm::StringRef FileName) {
2088  Chain.push_back(new PerFileData());
2089  PerFileData &F = *Chain.back();
2090
2091  // Set the AST file name.
2092  F.FileName = FileName;
2093
2094  // Open the AST file.
2095  //
2096  // FIXME: This shouldn't be here, we should just take a raw_ostream.
2097  std::string ErrStr;
2098  F.Buffer.reset(llvm::MemoryBuffer::getFileOrSTDIN(FileName, &ErrStr));
2099  if (!F.Buffer) {
2100    Error(ErrStr.c_str());
2101    return IgnorePCH;
2102  }
2103
2104  // Initialize the stream
2105  F.StreamFile.init((const unsigned char *)F.Buffer->getBufferStart(),
2106                    (const unsigned char *)F.Buffer->getBufferEnd());
2107  llvm::BitstreamCursor &Stream = F.Stream;
2108  Stream.init(F.StreamFile);
2109  F.SizeInBits = F.Buffer->getBufferSize() * 8;
2110
2111  // Sniff for the signature.
2112  if (Stream.Read(8) != 'C' ||
2113      Stream.Read(8) != 'P' ||
2114      Stream.Read(8) != 'C' ||
2115      Stream.Read(8) != 'H') {
2116    Diag(diag::err_not_a_pch_file) << FileName;
2117    return Failure;
2118  }
2119
2120  while (!Stream.AtEndOfStream()) {
2121    unsigned Code = Stream.ReadCode();
2122
2123    if (Code != llvm::bitc::ENTER_SUBBLOCK) {
2124      Error("invalid record at top-level of AST file");
2125      return Failure;
2126    }
2127
2128    unsigned BlockID = Stream.ReadSubBlockID();
2129
2130    // We only know the AST subblock ID.
2131    switch (BlockID) {
2132    case llvm::bitc::BLOCKINFO_BLOCK_ID:
2133      if (Stream.ReadBlockInfoBlock()) {
2134        Error("malformed BlockInfoBlock in AST file");
2135        return Failure;
2136      }
2137      break;
2138    case AST_BLOCK_ID:
2139      switch (ReadASTBlock(F)) {
2140      case Success:
2141        break;
2142
2143      case Failure:
2144        return Failure;
2145
2146      case IgnorePCH:
2147        // FIXME: We could consider reading through to the end of this
2148        // AST block, skipping subblocks, to see if there are other
2149        // AST blocks elsewhere.
2150
2151        // Clear out any preallocated source location entries, so that
2152        // the source manager does not try to resolve them later.
2153        SourceMgr.ClearPreallocatedSLocEntries();
2154
2155        // Remove the stat cache.
2156        if (F.StatCache)
2157          FileMgr.removeStatCache((ASTStatCache*)F.StatCache);
2158
2159        return IgnorePCH;
2160      }
2161      break;
2162    default:
2163      if (Stream.SkipBlock()) {
2164        Error("malformed block record in AST file");
2165        return Failure;
2166      }
2167      break;
2168    }
2169  }
2170
2171  return Success;
2172}
2173
2174void ASTReader::setPreprocessor(Preprocessor &pp) {
2175  PP = &pp;
2176
2177  unsigned TotalNum = 0;
2178  for (unsigned I = 0, N = Chain.size(); I != N; ++I)
2179    TotalNum += Chain[I]->NumPreallocatedPreprocessingEntities;
2180  if (TotalNum) {
2181    if (!PP->getPreprocessingRecord())
2182      PP->createPreprocessingRecord();
2183    PP->getPreprocessingRecord()->SetExternalSource(*this, TotalNum);
2184  }
2185}
2186
2187void ASTReader::InitializeContext(ASTContext &Ctx) {
2188  Context = &Ctx;
2189  assert(Context && "Passed null context!");
2190
2191  assert(PP && "Forgot to set Preprocessor ?");
2192  PP->getIdentifierTable().setExternalIdentifierLookup(this);
2193  PP->getHeaderSearchInfo().SetExternalLookup(this);
2194  PP->setExternalSource(this);
2195
2196  // Load the translation unit declaration
2197  GetTranslationUnitDecl();
2198
2199  // Load the special types.
2200  Context->setBuiltinVaListType(
2201    GetType(SpecialTypes[SPECIAL_TYPE_BUILTIN_VA_LIST]));
2202  if (unsigned Id = SpecialTypes[SPECIAL_TYPE_OBJC_ID])
2203    Context->setObjCIdType(GetType(Id));
2204  if (unsigned Sel = SpecialTypes[SPECIAL_TYPE_OBJC_SELECTOR])
2205    Context->setObjCSelType(GetType(Sel));
2206  if (unsigned Proto = SpecialTypes[SPECIAL_TYPE_OBJC_PROTOCOL])
2207    Context->setObjCProtoType(GetType(Proto));
2208  if (unsigned Class = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS])
2209    Context->setObjCClassType(GetType(Class));
2210
2211  if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING])
2212    Context->setCFConstantStringType(GetType(String));
2213  if (unsigned FastEnum
2214        = SpecialTypes[SPECIAL_TYPE_OBJC_FAST_ENUMERATION_STATE])
2215    Context->setObjCFastEnumerationStateType(GetType(FastEnum));
2216  if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
2217    QualType FileType = GetType(File);
2218    if (FileType.isNull()) {
2219      Error("FILE type is NULL");
2220      return;
2221    }
2222    if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
2223      Context->setFILEDecl(Typedef->getDecl());
2224    else {
2225      const TagType *Tag = FileType->getAs<TagType>();
2226      if (!Tag) {
2227        Error("Invalid FILE type in AST file");
2228        return;
2229      }
2230      Context->setFILEDecl(Tag->getDecl());
2231    }
2232  }
2233  if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_jmp_buf]) {
2234    QualType Jmp_bufType = GetType(Jmp_buf);
2235    if (Jmp_bufType.isNull()) {
2236      Error("jmp_bug type is NULL");
2237      return;
2238    }
2239    if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
2240      Context->setjmp_bufDecl(Typedef->getDecl());
2241    else {
2242      const TagType *Tag = Jmp_bufType->getAs<TagType>();
2243      if (!Tag) {
2244        Error("Invalid jmp_buf type in AST file");
2245        return;
2246      }
2247      Context->setjmp_bufDecl(Tag->getDecl());
2248    }
2249  }
2250  if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_sigjmp_buf]) {
2251    QualType Sigjmp_bufType = GetType(Sigjmp_buf);
2252    if (Sigjmp_bufType.isNull()) {
2253      Error("sigjmp_buf type is NULL");
2254      return;
2255    }
2256    if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
2257      Context->setsigjmp_bufDecl(Typedef->getDecl());
2258    else {
2259      const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
2260      assert(Tag && "Invalid sigjmp_buf type in AST file");
2261      Context->setsigjmp_bufDecl(Tag->getDecl());
2262    }
2263  }
2264  if (unsigned ObjCIdRedef
2265        = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION])
2266    Context->ObjCIdRedefinitionType = GetType(ObjCIdRedef);
2267  if (unsigned ObjCClassRedef
2268      = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION])
2269    Context->ObjCClassRedefinitionType = GetType(ObjCClassRedef);
2270  if (unsigned String = SpecialTypes[SPECIAL_TYPE_BLOCK_DESCRIPTOR])
2271    Context->setBlockDescriptorType(GetType(String));
2272  if (unsigned String
2273      = SpecialTypes[SPECIAL_TYPE_BLOCK_EXTENDED_DESCRIPTOR])
2274    Context->setBlockDescriptorExtendedType(GetType(String));
2275  if (unsigned ObjCSelRedef
2276      = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION])
2277    Context->ObjCSelRedefinitionType = GetType(ObjCSelRedef);
2278  if (unsigned String = SpecialTypes[SPECIAL_TYPE_NS_CONSTANT_STRING])
2279    Context->setNSConstantStringType(GetType(String));
2280
2281  if (SpecialTypes[SPECIAL_TYPE_INT128_INSTALLED])
2282    Context->setInt128Installed();
2283}
2284
2285/// \brief Retrieve the name of the original source file name
2286/// directly from the AST file, without actually loading the AST
2287/// file.
2288std::string ASTReader::getOriginalSourceFile(const std::string &ASTFileName,
2289                                             Diagnostic &Diags) {
2290  // Open the AST file.
2291  std::string ErrStr;
2292  llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
2293  Buffer.reset(llvm::MemoryBuffer::getFile(ASTFileName.c_str(), &ErrStr));
2294  if (!Buffer) {
2295    Diags.Report(diag::err_fe_unable_to_read_pch_file) << ErrStr;
2296    return std::string();
2297  }
2298
2299  // Initialize the stream
2300  llvm::BitstreamReader StreamFile;
2301  llvm::BitstreamCursor Stream;
2302  StreamFile.init((const unsigned char *)Buffer->getBufferStart(),
2303                  (const unsigned char *)Buffer->getBufferEnd());
2304  Stream.init(StreamFile);
2305
2306  // Sniff for the signature.
2307  if (Stream.Read(8) != 'C' ||
2308      Stream.Read(8) != 'P' ||
2309      Stream.Read(8) != 'C' ||
2310      Stream.Read(8) != 'H') {
2311    Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
2312    return std::string();
2313  }
2314
2315  RecordData Record;
2316  while (!Stream.AtEndOfStream()) {
2317    unsigned Code = Stream.ReadCode();
2318
2319    if (Code == llvm::bitc::ENTER_SUBBLOCK) {
2320      unsigned BlockID = Stream.ReadSubBlockID();
2321
2322      // We only know the AST subblock ID.
2323      switch (BlockID) {
2324      case AST_BLOCK_ID:
2325        if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2326          Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
2327          return std::string();
2328        }
2329        break;
2330
2331      default:
2332        if (Stream.SkipBlock()) {
2333          Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
2334          return std::string();
2335        }
2336        break;
2337      }
2338      continue;
2339    }
2340
2341    if (Code == llvm::bitc::END_BLOCK) {
2342      if (Stream.ReadBlockEnd()) {
2343        Diags.Report(diag::err_fe_pch_error_at_end_block) << ASTFileName;
2344        return std::string();
2345      }
2346      continue;
2347    }
2348
2349    if (Code == llvm::bitc::DEFINE_ABBREV) {
2350      Stream.ReadAbbrevRecord();
2351      continue;
2352    }
2353
2354    Record.clear();
2355    const char *BlobStart = 0;
2356    unsigned BlobLen = 0;
2357    if (Stream.ReadRecord(Code, Record, &BlobStart, &BlobLen)
2358          == ORIGINAL_FILE_NAME)
2359      return std::string(BlobStart, BlobLen);
2360  }
2361
2362  return std::string();
2363}
2364
2365/// \brief Parse the record that corresponds to a LangOptions data
2366/// structure.
2367///
2368/// This routine parses the language options from the AST file and then gives
2369/// them to the AST listener if one is set.
2370///
2371/// \returns true if the listener deems the file unacceptable, false otherwise.
2372bool ASTReader::ParseLanguageOptions(
2373                             const llvm::SmallVectorImpl<uint64_t> &Record) {
2374  if (Listener) {
2375    LangOptions LangOpts;
2376
2377  #define PARSE_LANGOPT(Option)                  \
2378      LangOpts.Option = Record[Idx];             \
2379      ++Idx
2380
2381    unsigned Idx = 0;
2382    PARSE_LANGOPT(Trigraphs);
2383    PARSE_LANGOPT(BCPLComment);
2384    PARSE_LANGOPT(DollarIdents);
2385    PARSE_LANGOPT(AsmPreprocessor);
2386    PARSE_LANGOPT(GNUMode);
2387    PARSE_LANGOPT(GNUKeywords);
2388    PARSE_LANGOPT(ImplicitInt);
2389    PARSE_LANGOPT(Digraphs);
2390    PARSE_LANGOPT(HexFloats);
2391    PARSE_LANGOPT(C99);
2392    PARSE_LANGOPT(Microsoft);
2393    PARSE_LANGOPT(CPlusPlus);
2394    PARSE_LANGOPT(CPlusPlus0x);
2395    PARSE_LANGOPT(CXXOperatorNames);
2396    PARSE_LANGOPT(ObjC1);
2397    PARSE_LANGOPT(ObjC2);
2398    PARSE_LANGOPT(ObjCNonFragileABI);
2399    PARSE_LANGOPT(ObjCNonFragileABI2);
2400    PARSE_LANGOPT(NoConstantCFStrings);
2401    PARSE_LANGOPT(PascalStrings);
2402    PARSE_LANGOPT(WritableStrings);
2403    PARSE_LANGOPT(LaxVectorConversions);
2404    PARSE_LANGOPT(AltiVec);
2405    PARSE_LANGOPT(Exceptions);
2406    PARSE_LANGOPT(SjLjExceptions);
2407    PARSE_LANGOPT(NeXTRuntime);
2408    PARSE_LANGOPT(Freestanding);
2409    PARSE_LANGOPT(NoBuiltin);
2410    PARSE_LANGOPT(ThreadsafeStatics);
2411    PARSE_LANGOPT(POSIXThreads);
2412    PARSE_LANGOPT(Blocks);
2413    PARSE_LANGOPT(EmitAllDecls);
2414    PARSE_LANGOPT(MathErrno);
2415    LangOpts.setSignedOverflowBehavior((LangOptions::SignedOverflowBehaviorTy)
2416                                       Record[Idx++]);
2417    PARSE_LANGOPT(HeinousExtensions);
2418    PARSE_LANGOPT(Optimize);
2419    PARSE_LANGOPT(OptimizeSize);
2420    PARSE_LANGOPT(Static);
2421    PARSE_LANGOPT(PICLevel);
2422    PARSE_LANGOPT(GNUInline);
2423    PARSE_LANGOPT(NoInline);
2424    PARSE_LANGOPT(AccessControl);
2425    PARSE_LANGOPT(CharIsSigned);
2426    PARSE_LANGOPT(ShortWChar);
2427    LangOpts.setGCMode((LangOptions::GCMode)Record[Idx++]);
2428    LangOpts.setVisibilityMode((LangOptions::VisibilityMode)Record[Idx++]);
2429    LangOpts.setStackProtectorMode((LangOptions::StackProtectorMode)
2430                                   Record[Idx++]);
2431    PARSE_LANGOPT(InstantiationDepth);
2432    PARSE_LANGOPT(OpenCL);
2433    PARSE_LANGOPT(CatchUndefined);
2434    // FIXME: Missing ElideConstructors?!
2435  #undef PARSE_LANGOPT
2436
2437    return Listener->ReadLanguageOptions(LangOpts);
2438  }
2439
2440  return false;
2441}
2442
2443void ASTReader::ReadPreprocessedEntities() {
2444  ReadDefinedMacros();
2445}
2446
2447/// \brief Get the correct cursor and offset for loading a type.
2448ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
2449  PerFileData *F = 0;
2450  for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2451    F = Chain[N - I - 1];
2452    if (Index < F->LocalNumTypes)
2453      break;
2454    Index -= F->LocalNumTypes;
2455  }
2456  assert(F && F->LocalNumTypes > Index && "Broken chain");
2457  return RecordLocation(&F->DeclsCursor, F->TypeOffsets[Index]);
2458}
2459
2460/// \brief Read and return the type with the given index..
2461///
2462/// The index is the type ID, shifted and minus the number of predefs. This
2463/// routine actually reads the record corresponding to the type at the given
2464/// location. It is a helper routine for GetType, which deals with reading type
2465/// IDs.
2466QualType ASTReader::ReadTypeRecord(unsigned Index) {
2467  RecordLocation Loc = TypeCursorForIndex(Index);
2468  llvm::BitstreamCursor &DeclsCursor = *Loc.first;
2469
2470  // Keep track of where we are in the stream, then jump back there
2471  // after reading this type.
2472  SavedStreamPosition SavedPosition(DeclsCursor);
2473
2474  ReadingKindTracker ReadingKind(Read_Type, *this);
2475
2476  // Note that we are loading a type record.
2477  Deserializing AType(this);
2478
2479  DeclsCursor.JumpToBit(Loc.second);
2480  RecordData Record;
2481  unsigned Code = DeclsCursor.ReadCode();
2482  switch ((TypeCode)DeclsCursor.ReadRecord(Code, Record)) {
2483  case TYPE_EXT_QUAL: {
2484    if (Record.size() != 2) {
2485      Error("Incorrect encoding of extended qualifier type");
2486      return QualType();
2487    }
2488    QualType Base = GetType(Record[0]);
2489    Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[1]);
2490    return Context->getQualifiedType(Base, Quals);
2491  }
2492
2493  case TYPE_COMPLEX: {
2494    if (Record.size() != 1) {
2495      Error("Incorrect encoding of complex type");
2496      return QualType();
2497    }
2498    QualType ElemType = GetType(Record[0]);
2499    return Context->getComplexType(ElemType);
2500  }
2501
2502  case TYPE_POINTER: {
2503    if (Record.size() != 1) {
2504      Error("Incorrect encoding of pointer type");
2505      return QualType();
2506    }
2507    QualType PointeeType = GetType(Record[0]);
2508    return Context->getPointerType(PointeeType);
2509  }
2510
2511  case TYPE_BLOCK_POINTER: {
2512    if (Record.size() != 1) {
2513      Error("Incorrect encoding of block pointer type");
2514      return QualType();
2515    }
2516    QualType PointeeType = GetType(Record[0]);
2517    return Context->getBlockPointerType(PointeeType);
2518  }
2519
2520  case TYPE_LVALUE_REFERENCE: {
2521    if (Record.size() != 1) {
2522      Error("Incorrect encoding of lvalue reference type");
2523      return QualType();
2524    }
2525    QualType PointeeType = GetType(Record[0]);
2526    return Context->getLValueReferenceType(PointeeType);
2527  }
2528
2529  case TYPE_RVALUE_REFERENCE: {
2530    if (Record.size() != 1) {
2531      Error("Incorrect encoding of rvalue reference type");
2532      return QualType();
2533    }
2534    QualType PointeeType = GetType(Record[0]);
2535    return Context->getRValueReferenceType(PointeeType);
2536  }
2537
2538  case TYPE_MEMBER_POINTER: {
2539    if (Record.size() != 2) {
2540      Error("Incorrect encoding of member pointer type");
2541      return QualType();
2542    }
2543    QualType PointeeType = GetType(Record[0]);
2544    QualType ClassType = GetType(Record[1]);
2545    return Context->getMemberPointerType(PointeeType, ClassType.getTypePtr());
2546  }
2547
2548  case TYPE_CONSTANT_ARRAY: {
2549    QualType ElementType = GetType(Record[0]);
2550    ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2551    unsigned IndexTypeQuals = Record[2];
2552    unsigned Idx = 3;
2553    llvm::APInt Size = ReadAPInt(Record, Idx);
2554    return Context->getConstantArrayType(ElementType, Size,
2555                                         ASM, IndexTypeQuals);
2556  }
2557
2558  case TYPE_INCOMPLETE_ARRAY: {
2559    QualType ElementType = GetType(Record[0]);
2560    ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2561    unsigned IndexTypeQuals = Record[2];
2562    return Context->getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
2563  }
2564
2565  case TYPE_VARIABLE_ARRAY: {
2566    QualType ElementType = GetType(Record[0]);
2567    ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
2568    unsigned IndexTypeQuals = Record[2];
2569    SourceLocation LBLoc = SourceLocation::getFromRawEncoding(Record[3]);
2570    SourceLocation RBLoc = SourceLocation::getFromRawEncoding(Record[4]);
2571    return Context->getVariableArrayType(ElementType, ReadExpr(DeclsCursor),
2572                                         ASM, IndexTypeQuals,
2573                                         SourceRange(LBLoc, RBLoc));
2574  }
2575
2576  case TYPE_VECTOR: {
2577    if (Record.size() != 3) {
2578      Error("incorrect encoding of vector type in AST file");
2579      return QualType();
2580    }
2581
2582    QualType ElementType = GetType(Record[0]);
2583    unsigned NumElements = Record[1];
2584    unsigned AltiVecSpec = Record[2];
2585    return Context->getVectorType(ElementType, NumElements,
2586                                  (VectorType::AltiVecSpecific)AltiVecSpec);
2587  }
2588
2589  case TYPE_EXT_VECTOR: {
2590    if (Record.size() != 3) {
2591      Error("incorrect encoding of extended vector type in AST file");
2592      return QualType();
2593    }
2594
2595    QualType ElementType = GetType(Record[0]);
2596    unsigned NumElements = Record[1];
2597    return Context->getExtVectorType(ElementType, NumElements);
2598  }
2599
2600  case TYPE_FUNCTION_NO_PROTO: {
2601    if (Record.size() != 4) {
2602      Error("incorrect encoding of no-proto function type");
2603      return QualType();
2604    }
2605    QualType ResultType = GetType(Record[0]);
2606    FunctionType::ExtInfo Info(Record[1], Record[2], (CallingConv)Record[3]);
2607    return Context->getFunctionNoProtoType(ResultType, Info);
2608  }
2609
2610  case TYPE_FUNCTION_PROTO: {
2611    QualType ResultType = GetType(Record[0]);
2612    bool NoReturn = Record[1];
2613    unsigned RegParm = Record[2];
2614    CallingConv CallConv = (CallingConv)Record[3];
2615    unsigned Idx = 4;
2616    unsigned NumParams = Record[Idx++];
2617    llvm::SmallVector<QualType, 16> ParamTypes;
2618    for (unsigned I = 0; I != NumParams; ++I)
2619      ParamTypes.push_back(GetType(Record[Idx++]));
2620    bool isVariadic = Record[Idx++];
2621    unsigned Quals = Record[Idx++];
2622    bool hasExceptionSpec = Record[Idx++];
2623    bool hasAnyExceptionSpec = Record[Idx++];
2624    unsigned NumExceptions = Record[Idx++];
2625    llvm::SmallVector<QualType, 2> Exceptions;
2626    for (unsigned I = 0; I != NumExceptions; ++I)
2627      Exceptions.push_back(GetType(Record[Idx++]));
2628    return Context->getFunctionType(ResultType, ParamTypes.data(), NumParams,
2629                                    isVariadic, Quals, hasExceptionSpec,
2630                                    hasAnyExceptionSpec, NumExceptions,
2631                                    Exceptions.data(),
2632                                    FunctionType::ExtInfo(NoReturn, RegParm,
2633                                                          CallConv));
2634  }
2635
2636  case TYPE_UNRESOLVED_USING:
2637    return Context->getTypeDeclType(
2638             cast<UnresolvedUsingTypenameDecl>(GetDecl(Record[0])));
2639
2640  case TYPE_TYPEDEF: {
2641    if (Record.size() != 2) {
2642      Error("incorrect encoding of typedef type");
2643      return QualType();
2644    }
2645    TypedefDecl *Decl = cast<TypedefDecl>(GetDecl(Record[0]));
2646    QualType Canonical = GetType(Record[1]);
2647    return Context->getTypedefType(Decl, Canonical);
2648  }
2649
2650  case TYPE_TYPEOF_EXPR:
2651    return Context->getTypeOfExprType(ReadExpr(DeclsCursor));
2652
2653  case TYPE_TYPEOF: {
2654    if (Record.size() != 1) {
2655      Error("incorrect encoding of typeof(type) in AST file");
2656      return QualType();
2657    }
2658    QualType UnderlyingType = GetType(Record[0]);
2659    return Context->getTypeOfType(UnderlyingType);
2660  }
2661
2662  case TYPE_DECLTYPE:
2663    return Context->getDecltypeType(ReadExpr(DeclsCursor));
2664
2665  case TYPE_RECORD: {
2666    if (Record.size() != 2) {
2667      Error("incorrect encoding of record type");
2668      return QualType();
2669    }
2670    bool IsDependent = Record[0];
2671    QualType T = Context->getRecordType(cast<RecordDecl>(GetDecl(Record[1])));
2672    T->Dependent = IsDependent;
2673    return T;
2674  }
2675
2676  case TYPE_ENUM: {
2677    if (Record.size() != 2) {
2678      Error("incorrect encoding of enum type");
2679      return QualType();
2680    }
2681    bool IsDependent = Record[0];
2682    QualType T = Context->getEnumType(cast<EnumDecl>(GetDecl(Record[1])));
2683    T->Dependent = IsDependent;
2684    return T;
2685  }
2686
2687  case TYPE_ELABORATED: {
2688    unsigned Idx = 0;
2689    ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2690    NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2691    QualType NamedType = GetType(Record[Idx++]);
2692    return Context->getElaboratedType(Keyword, NNS, NamedType);
2693  }
2694
2695  case TYPE_OBJC_INTERFACE: {
2696    unsigned Idx = 0;
2697    ObjCInterfaceDecl *ItfD = cast<ObjCInterfaceDecl>(GetDecl(Record[Idx++]));
2698    return Context->getObjCInterfaceType(ItfD);
2699  }
2700
2701  case TYPE_OBJC_OBJECT: {
2702    unsigned Idx = 0;
2703    QualType Base = GetType(Record[Idx++]);
2704    unsigned NumProtos = Record[Idx++];
2705    llvm::SmallVector<ObjCProtocolDecl*, 4> Protos;
2706    for (unsigned I = 0; I != NumProtos; ++I)
2707      Protos.push_back(cast<ObjCProtocolDecl>(GetDecl(Record[Idx++])));
2708    return Context->getObjCObjectType(Base, Protos.data(), NumProtos);
2709  }
2710
2711  case TYPE_OBJC_OBJECT_POINTER: {
2712    unsigned Idx = 0;
2713    QualType Pointee = GetType(Record[Idx++]);
2714    return Context->getObjCObjectPointerType(Pointee);
2715  }
2716
2717  case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
2718    unsigned Idx = 0;
2719    QualType Parm = GetType(Record[Idx++]);
2720    QualType Replacement = GetType(Record[Idx++]);
2721    return
2722      Context->getSubstTemplateTypeParmType(cast<TemplateTypeParmType>(Parm),
2723                                            Replacement);
2724  }
2725
2726  case TYPE_INJECTED_CLASS_NAME: {
2727    CXXRecordDecl *D = cast<CXXRecordDecl>(GetDecl(Record[0]));
2728    QualType TST = GetType(Record[1]); // probably derivable
2729    // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
2730    // for AST reading, too much interdependencies.
2731    return
2732      QualType(new (*Context, TypeAlignment) InjectedClassNameType(D, TST), 0);
2733  }
2734
2735  case TYPE_TEMPLATE_TYPE_PARM: {
2736    unsigned Idx = 0;
2737    unsigned Depth = Record[Idx++];
2738    unsigned Index = Record[Idx++];
2739    bool Pack = Record[Idx++];
2740    IdentifierInfo *Name = GetIdentifierInfo(Record, Idx);
2741    return Context->getTemplateTypeParmType(Depth, Index, Pack, Name);
2742  }
2743
2744  case TYPE_DEPENDENT_NAME: {
2745    unsigned Idx = 0;
2746    ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2747    NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2748    const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
2749    QualType Canon = GetType(Record[Idx++]);
2750    return Context->getDependentNameType(Keyword, NNS, Name, Canon);
2751  }
2752
2753  case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
2754    unsigned Idx = 0;
2755    ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
2756    NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
2757    const IdentifierInfo *Name = this->GetIdentifierInfo(Record, Idx);
2758    unsigned NumArgs = Record[Idx++];
2759    llvm::SmallVector<TemplateArgument, 8> Args;
2760    Args.reserve(NumArgs);
2761    while (NumArgs--)
2762      Args.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
2763    return Context->getDependentTemplateSpecializationType(Keyword, NNS, Name,
2764                                                      Args.size(), Args.data());
2765  }
2766
2767  case TYPE_DEPENDENT_SIZED_ARRAY: {
2768    unsigned Idx = 0;
2769
2770    // ArrayType
2771    QualType ElementType = GetType(Record[Idx++]);
2772    ArrayType::ArraySizeModifier ASM
2773      = (ArrayType::ArraySizeModifier)Record[Idx++];
2774    unsigned IndexTypeQuals = Record[Idx++];
2775
2776    // DependentSizedArrayType
2777    Expr *NumElts = ReadExpr(DeclsCursor);
2778    SourceRange Brackets = ReadSourceRange(Record, Idx);
2779
2780    return Context->getDependentSizedArrayType(ElementType, NumElts, ASM,
2781                                               IndexTypeQuals, Brackets);
2782  }
2783
2784  case TYPE_TEMPLATE_SPECIALIZATION: {
2785    unsigned Idx = 0;
2786    bool IsDependent = Record[Idx++];
2787    TemplateName Name = ReadTemplateName(Record, Idx);
2788    llvm::SmallVector<TemplateArgument, 8> Args;
2789    ReadTemplateArgumentList(Args, DeclsCursor, Record, Idx);
2790    QualType Canon = GetType(Record[Idx++]);
2791    QualType T;
2792    if (Canon.isNull())
2793      T = Context->getCanonicalTemplateSpecializationType(Name, Args.data(),
2794                                                          Args.size());
2795    else
2796      T = Context->getTemplateSpecializationType(Name, Args.data(),
2797                                                 Args.size(), Canon);
2798    T->Dependent = IsDependent;
2799    return T;
2800  }
2801  }
2802  // Suppress a GCC warning
2803  return QualType();
2804}
2805
2806namespace {
2807
2808class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
2809  ASTReader &Reader;
2810  llvm::BitstreamCursor &DeclsCursor;
2811  const ASTReader::RecordData &Record;
2812  unsigned &Idx;
2813
2814public:
2815  TypeLocReader(ASTReader &Reader, llvm::BitstreamCursor &Cursor,
2816                const ASTReader::RecordData &Record, unsigned &Idx)
2817    : Reader(Reader), DeclsCursor(Cursor), Record(Record), Idx(Idx) { }
2818
2819  // We want compile-time assurance that we've enumerated all of
2820  // these, so unfortunately we have to declare them first, then
2821  // define them out-of-line.
2822#define ABSTRACT_TYPELOC(CLASS, PARENT)
2823#define TYPELOC(CLASS, PARENT) \
2824  void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
2825#include "clang/AST/TypeLocNodes.def"
2826
2827  void VisitFunctionTypeLoc(FunctionTypeLoc);
2828  void VisitArrayTypeLoc(ArrayTypeLoc);
2829};
2830
2831}
2832
2833void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
2834  // nothing to do
2835}
2836void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
2837  TL.setBuiltinLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2838  if (TL.needsExtraLocalData()) {
2839    TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
2840    TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
2841    TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
2842    TL.setModeAttr(Record[Idx++]);
2843  }
2844}
2845void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
2846  TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2847}
2848void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
2849  TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2850}
2851void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2852  TL.setCaretLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2853}
2854void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2855  TL.setAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2856}
2857void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2858  TL.setAmpAmpLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2859}
2860void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2861  TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2862}
2863void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
2864  TL.setLBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2865  TL.setRBracketLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2866  if (Record[Idx++])
2867    TL.setSizeExpr(Reader.ReadExpr(DeclsCursor));
2868  else
2869    TL.setSizeExpr(0);
2870}
2871void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
2872  VisitArrayTypeLoc(TL);
2873}
2874void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
2875  VisitArrayTypeLoc(TL);
2876}
2877void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
2878  VisitArrayTypeLoc(TL);
2879}
2880void TypeLocReader::VisitDependentSizedArrayTypeLoc(
2881                                            DependentSizedArrayTypeLoc TL) {
2882  VisitArrayTypeLoc(TL);
2883}
2884void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
2885                                        DependentSizedExtVectorTypeLoc TL) {
2886  TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2887}
2888void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
2889  TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2890}
2891void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
2892  TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2893}
2894void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2895  TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2896  TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2897  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) {
2898    TL.setArg(i, cast_or_null<ParmVarDecl>(Reader.GetDecl(Record[Idx++])));
2899  }
2900}
2901void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
2902  VisitFunctionTypeLoc(TL);
2903}
2904void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
2905  VisitFunctionTypeLoc(TL);
2906}
2907void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
2908  TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2909}
2910void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2911  TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2912}
2913void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
2914  TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2915  TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2916  TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2917}
2918void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
2919  TL.setTypeofLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2920  TL.setLParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2921  TL.setRParenLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2922  TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(DeclsCursor, Record, Idx));
2923}
2924void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
2925  TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2926}
2927void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
2928  TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2929}
2930void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
2931  TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2932}
2933void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2934  TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2935}
2936void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
2937                                            SubstTemplateTypeParmTypeLoc TL) {
2938  TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2939}
2940void TypeLocReader::VisitTemplateSpecializationTypeLoc(
2941                                           TemplateSpecializationTypeLoc TL) {
2942  TL.setTemplateNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2943  TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2944  TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2945  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2946    TL.setArgLocInfo(i,
2947        Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(i).getKind(),
2948                                          DeclsCursor, Record, Idx));
2949}
2950void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
2951  TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2952  TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
2953}
2954void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
2955  TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2956}
2957void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
2958  TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2959  TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
2960  TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2961}
2962void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
2963       DependentTemplateSpecializationTypeLoc TL) {
2964  TL.setKeywordLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2965  TL.setQualifierRange(Reader.ReadSourceRange(Record, Idx));
2966  TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2967  TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2968  TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2969  for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
2970    TL.setArgLocInfo(I,
2971        Reader.GetTemplateArgumentLocInfo(TL.getTypePtr()->getArg(I).getKind(),
2972                                          DeclsCursor, Record, Idx));
2973}
2974void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2975  TL.setNameLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2976}
2977void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
2978  TL.setHasBaseTypeAsWritten(Record[Idx++]);
2979  TL.setLAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2980  TL.setRAngleLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2981  for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
2982    TL.setProtocolLoc(i, SourceLocation::getFromRawEncoding(Record[Idx++]));
2983}
2984void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2985  TL.setStarLoc(SourceLocation::getFromRawEncoding(Record[Idx++]));
2986}
2987
2988TypeSourceInfo *ASTReader::GetTypeSourceInfo(llvm::BitstreamCursor &DeclsCursor,
2989                                             const RecordData &Record,
2990                                             unsigned &Idx) {
2991  QualType InfoTy = GetType(Record[Idx++]);
2992  if (InfoTy.isNull())
2993    return 0;
2994
2995  TypeSourceInfo *TInfo = getContext()->CreateTypeSourceInfo(InfoTy);
2996  TypeLocReader TLR(*this, DeclsCursor, Record, Idx);
2997  for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
2998    TLR.Visit(TL);
2999  return TInfo;
3000}
3001
3002QualType ASTReader::GetType(TypeID ID) {
3003  unsigned FastQuals = ID & Qualifiers::FastMask;
3004  unsigned Index = ID >> Qualifiers::FastWidth;
3005
3006  if (Index < NUM_PREDEF_TYPE_IDS) {
3007    QualType T;
3008    switch ((PredefinedTypeIDs)Index) {
3009    case PREDEF_TYPE_NULL_ID: return QualType();
3010    case PREDEF_TYPE_VOID_ID: T = Context->VoidTy; break;
3011    case PREDEF_TYPE_BOOL_ID: T = Context->BoolTy; break;
3012
3013    case PREDEF_TYPE_CHAR_U_ID:
3014    case PREDEF_TYPE_CHAR_S_ID:
3015      // FIXME: Check that the signedness of CharTy is correct!
3016      T = Context->CharTy;
3017      break;
3018
3019    case PREDEF_TYPE_UCHAR_ID:      T = Context->UnsignedCharTy;     break;
3020    case PREDEF_TYPE_USHORT_ID:     T = Context->UnsignedShortTy;    break;
3021    case PREDEF_TYPE_UINT_ID:       T = Context->UnsignedIntTy;      break;
3022    case PREDEF_TYPE_ULONG_ID:      T = Context->UnsignedLongTy;     break;
3023    case PREDEF_TYPE_ULONGLONG_ID:  T = Context->UnsignedLongLongTy; break;
3024    case PREDEF_TYPE_UINT128_ID:    T = Context->UnsignedInt128Ty;   break;
3025    case PREDEF_TYPE_SCHAR_ID:      T = Context->SignedCharTy;       break;
3026    case PREDEF_TYPE_WCHAR_ID:      T = Context->WCharTy;            break;
3027    case PREDEF_TYPE_SHORT_ID:      T = Context->ShortTy;            break;
3028    case PREDEF_TYPE_INT_ID:        T = Context->IntTy;              break;
3029    case PREDEF_TYPE_LONG_ID:       T = Context->LongTy;             break;
3030    case PREDEF_TYPE_LONGLONG_ID:   T = Context->LongLongTy;         break;
3031    case PREDEF_TYPE_INT128_ID:     T = Context->Int128Ty;           break;
3032    case PREDEF_TYPE_FLOAT_ID:      T = Context->FloatTy;            break;
3033    case PREDEF_TYPE_DOUBLE_ID:     T = Context->DoubleTy;           break;
3034    case PREDEF_TYPE_LONGDOUBLE_ID: T = Context->LongDoubleTy;       break;
3035    case PREDEF_TYPE_OVERLOAD_ID:   T = Context->OverloadTy;         break;
3036    case PREDEF_TYPE_DEPENDENT_ID:  T = Context->DependentTy;        break;
3037    case PREDEF_TYPE_NULLPTR_ID:    T = Context->NullPtrTy;          break;
3038    case PREDEF_TYPE_CHAR16_ID:     T = Context->Char16Ty;           break;
3039    case PREDEF_TYPE_CHAR32_ID:     T = Context->Char32Ty;           break;
3040    case PREDEF_TYPE_OBJC_ID:       T = Context->ObjCBuiltinIdTy;    break;
3041    case PREDEF_TYPE_OBJC_CLASS:    T = Context->ObjCBuiltinClassTy; break;
3042    case PREDEF_TYPE_OBJC_SEL:      T = Context->ObjCBuiltinSelTy;   break;
3043    }
3044
3045    assert(!T.isNull() && "Unknown predefined type");
3046    return T.withFastQualifiers(FastQuals);
3047  }
3048
3049  Index -= NUM_PREDEF_TYPE_IDS;
3050  assert(Index < TypesLoaded.size() && "Type index out-of-range");
3051  if (TypesLoaded[Index].isNull()) {
3052    TypesLoaded[Index] = ReadTypeRecord(Index);
3053    TypesLoaded[Index]->setFromAST();
3054    TypeIdxs[TypesLoaded[Index]] = TypeIdx::fromTypeID(ID);
3055    if (DeserializationListener)
3056      DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
3057                                        TypesLoaded[Index]);
3058  }
3059
3060  return TypesLoaded[Index].withFastQualifiers(FastQuals);
3061}
3062
3063TypeID ASTReader::GetTypeID(QualType T) const {
3064  return MakeTypeID(T,
3065              std::bind1st(std::mem_fun(&ASTReader::GetTypeIdx), this));
3066}
3067
3068TypeIdx ASTReader::GetTypeIdx(QualType T) const {
3069  if (T.isNull())
3070    return TypeIdx();
3071  assert(!T.getLocalFastQualifiers());
3072
3073  TypeIdxMap::const_iterator I = TypeIdxs.find(T);
3074  // GetTypeIdx is mostly used for computing the hash of DeclarationNames and
3075  // comparing keys of ASTDeclContextNameLookupTable.
3076  // If the type didn't come from the AST file use a specially marked index
3077  // so that any hash/key comparison fail since no such index is stored
3078  // in a AST file.
3079  if (I == TypeIdxs.end())
3080    return TypeIdx(-1);
3081  return I->second;
3082}
3083
3084TemplateArgumentLocInfo
3085ASTReader::GetTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
3086                                      llvm::BitstreamCursor &DeclsCursor,
3087                                      const RecordData &Record,
3088                                      unsigned &Index) {
3089  switch (Kind) {
3090  case TemplateArgument::Expression:
3091    return ReadExpr(DeclsCursor);
3092  case TemplateArgument::Type:
3093    return GetTypeSourceInfo(DeclsCursor, Record, Index);
3094  case TemplateArgument::Template: {
3095    SourceRange QualifierRange = ReadSourceRange(Record, Index);
3096    SourceLocation TemplateNameLoc = ReadSourceLocation(Record, Index);
3097    return TemplateArgumentLocInfo(QualifierRange, TemplateNameLoc);
3098  }
3099  case TemplateArgument::Null:
3100  case TemplateArgument::Integral:
3101  case TemplateArgument::Declaration:
3102  case TemplateArgument::Pack:
3103    return TemplateArgumentLocInfo();
3104  }
3105  llvm_unreachable("unexpected template argument loc");
3106  return TemplateArgumentLocInfo();
3107}
3108
3109TemplateArgumentLoc
3110ASTReader::ReadTemplateArgumentLoc(llvm::BitstreamCursor &DeclsCursor,
3111                                   const RecordData &Record, unsigned &Index) {
3112  TemplateArgument Arg = ReadTemplateArgument(DeclsCursor, Record, Index);
3113
3114  if (Arg.getKind() == TemplateArgument::Expression) {
3115    if (Record[Index++]) // bool InfoHasSameExpr.
3116      return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
3117  }
3118  return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(Arg.getKind(),
3119                                                             DeclsCursor,
3120                                                             Record, Index));
3121}
3122
3123Decl *ASTReader::GetExternalDecl(uint32_t ID) {
3124  return GetDecl(ID);
3125}
3126
3127TranslationUnitDecl *ASTReader::GetTranslationUnitDecl() {
3128  if (!DeclsLoaded[0]) {
3129    ReadDeclRecord(0, 1);
3130    if (DeserializationListener)
3131      DeserializationListener->DeclRead(1, DeclsLoaded[0]);
3132  }
3133
3134  return cast<TranslationUnitDecl>(DeclsLoaded[0]);
3135}
3136
3137Decl *ASTReader::GetDecl(DeclID ID) {
3138  if (ID == 0)
3139    return 0;
3140
3141  if (ID > DeclsLoaded.size()) {
3142    Error("declaration ID out-of-range for AST file");
3143    return 0;
3144  }
3145
3146  unsigned Index = ID - 1;
3147  if (!DeclsLoaded[Index]) {
3148    ReadDeclRecord(Index, ID);
3149    if (DeserializationListener)
3150      DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
3151  }
3152
3153  return DeclsLoaded[Index];
3154}
3155
3156/// \brief Resolve the offset of a statement into a statement.
3157///
3158/// This operation will read a new statement from the external
3159/// source each time it is called, and is meant to be used via a
3160/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
3161Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
3162  // Offset here is a global offset across the entire chain.
3163  for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3164    PerFileData &F = *Chain[N - I - 1];
3165    if (Offset < F.SizeInBits) {
3166      // Since we know that this statement is part of a decl, make sure to use
3167      // the decl cursor to read it.
3168      F.DeclsCursor.JumpToBit(Offset);
3169      return ReadStmtFromStream(F.DeclsCursor);
3170    }
3171    Offset -= F.SizeInBits;
3172  }
3173  llvm_unreachable("Broken chain");
3174}
3175
3176bool ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
3177                                         llvm::SmallVectorImpl<Decl*> &Decls) {
3178  assert(DC->hasExternalLexicalStorage() &&
3179         "DeclContext has no lexical decls in storage");
3180
3181  // There might be lexical decls in multiple parts of the chain, for the TU
3182  // at least.
3183  DeclContextInfos &Infos = DeclContextOffsets[DC];
3184  for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end();
3185       I != E; ++I) {
3186    // IDs can be 0 if this context doesn't contain declarations.
3187    if (!I->LexicalDecls)
3188      continue;
3189
3190    // Load all of the declaration IDs
3191    for (const DeclID *ID = I->LexicalDecls,
3192                           *IDE = ID + I->NumLexicalDecls;
3193         ID != IDE; ++ID)
3194      Decls.push_back(GetDecl(*ID));
3195  }
3196
3197  ++NumLexicalDeclContextsRead;
3198  return false;
3199}
3200
3201DeclContext::lookup_result
3202ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
3203                                          DeclarationName Name) {
3204  assert(DC->hasExternalVisibleStorage() &&
3205         "DeclContext has no visible decls in storage");
3206  if (!Name)
3207    return DeclContext::lookup_result(DeclContext::lookup_iterator(0),
3208                                      DeclContext::lookup_iterator(0));
3209
3210  llvm::SmallVector<NamedDecl *, 64> Decls;
3211  // There might be visible decls in multiple parts of the chain, for the TU
3212  // and namespaces. For any given name, the last available results replace
3213  // all earlier ones. For this reason, we walk in reverse.
3214  DeclContextInfos &Infos = DeclContextOffsets[DC];
3215  for (DeclContextInfos::reverse_iterator I = Infos.rbegin(), E = Infos.rend();
3216       I != E; ++I) {
3217    if (!I->NameLookupTableData)
3218      continue;
3219
3220    ASTDeclContextNameLookupTable *LookupTable =
3221        (ASTDeclContextNameLookupTable*)I->NameLookupTableData;
3222    ASTDeclContextNameLookupTable::iterator Pos = LookupTable->find(Name);
3223    if (Pos == LookupTable->end())
3224      continue;
3225
3226    ASTDeclContextNameLookupTrait::data_type Data = *Pos;
3227    for (; Data.first != Data.second; ++Data.first)
3228      Decls.push_back(cast<NamedDecl>(GetDecl(*Data.first)));
3229    break;
3230  }
3231
3232  ++NumVisibleDeclContextsRead;
3233
3234  SetExternalVisibleDeclsForName(DC, Name, Decls);
3235  return const_cast<DeclContext*>(DC)->lookup(Name);
3236}
3237
3238void ASTReader::MaterializeVisibleDecls(const DeclContext *DC) {
3239  assert(DC->hasExternalVisibleStorage() &&
3240         "DeclContext has no visible decls in storage");
3241
3242  llvm::SmallVector<NamedDecl *, 64> Decls;
3243  // There might be visible decls in multiple parts of the chain, for the TU
3244  // and namespaces.
3245  DeclContextInfos &Infos = DeclContextOffsets[DC];
3246  for (DeclContextInfos::iterator I = Infos.begin(), E = Infos.end();
3247       I != E; ++I) {
3248    if (!I->NameLookupTableData)
3249      continue;
3250
3251    ASTDeclContextNameLookupTable *LookupTable =
3252        (ASTDeclContextNameLookupTable*)I->NameLookupTableData;
3253    for (ASTDeclContextNameLookupTable::item_iterator
3254           ItemI = LookupTable->item_begin(),
3255           ItemEnd = LookupTable->item_end() ; ItemI != ItemEnd; ++ItemI) {
3256      ASTDeclContextNameLookupTable::item_iterator::value_type Val
3257          = *ItemI;
3258      ASTDeclContextNameLookupTrait::data_type Data = Val.second;
3259      Decls.clear();
3260      for (; Data.first != Data.second; ++Data.first)
3261        Decls.push_back(cast<NamedDecl>(GetDecl(*Data.first)));
3262      MaterializeVisibleDeclsForName(DC, Val.first, Decls);
3263    }
3264  }
3265}
3266
3267void ASTReader::PassInterestingDeclsToConsumer() {
3268  assert(Consumer);
3269  while (!InterestingDecls.empty()) {
3270    DeclGroupRef DG(InterestingDecls.front());
3271    InterestingDecls.pop_front();
3272    Consumer->HandleInterestingDecl(DG);
3273  }
3274}
3275
3276void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
3277  this->Consumer = Consumer;
3278
3279  if (!Consumer)
3280    return;
3281
3282  for (unsigned I = 0, N = ExternalDefinitions.size(); I != N; ++I) {
3283    // Force deserialization of this decl, which will cause it to be queued for
3284    // passing to the consumer.
3285    GetDecl(ExternalDefinitions[I]);
3286  }
3287
3288  PassInterestingDeclsToConsumer();
3289}
3290
3291void ASTReader::PrintStats() {
3292  std::fprintf(stderr, "*** AST File Statistics:\n");
3293
3294  unsigned NumTypesLoaded
3295    = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
3296                                      QualType());
3297  unsigned NumDeclsLoaded
3298    = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
3299                                      (Decl *)0);
3300  unsigned NumIdentifiersLoaded
3301    = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
3302                                            IdentifiersLoaded.end(),
3303                                            (IdentifierInfo *)0);
3304  unsigned NumSelectorsLoaded
3305    = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
3306                                          SelectorsLoaded.end(),
3307                                          Selector());
3308
3309  std::fprintf(stderr, "  %u stat cache hits\n", NumStatHits);
3310  std::fprintf(stderr, "  %u stat cache misses\n", NumStatMisses);
3311  if (TotalNumSLocEntries)
3312    std::fprintf(stderr, "  %u/%u source location entries read (%f%%)\n",
3313                 NumSLocEntriesRead, TotalNumSLocEntries,
3314                 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
3315  if (!TypesLoaded.empty())
3316    std::fprintf(stderr, "  %u/%u types read (%f%%)\n",
3317                 NumTypesLoaded, (unsigned)TypesLoaded.size(),
3318                 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
3319  if (!DeclsLoaded.empty())
3320    std::fprintf(stderr, "  %u/%u declarations read (%f%%)\n",
3321                 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
3322                 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
3323  if (!IdentifiersLoaded.empty())
3324    std::fprintf(stderr, "  %u/%u identifiers read (%f%%)\n",
3325                 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
3326                 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
3327  if (!SelectorsLoaded.empty())
3328    std::fprintf(stderr, "  %u/%u selectors read (%f%%)\n",
3329                 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
3330                 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
3331  if (TotalNumStatements)
3332    std::fprintf(stderr, "  %u/%u statements read (%f%%)\n",
3333                 NumStatementsRead, TotalNumStatements,
3334                 ((float)NumStatementsRead/TotalNumStatements * 100));
3335  if (TotalNumMacros)
3336    std::fprintf(stderr, "  %u/%u macros read (%f%%)\n",
3337                 NumMacrosRead, TotalNumMacros,
3338                 ((float)NumMacrosRead/TotalNumMacros * 100));
3339  if (TotalLexicalDeclContexts)
3340    std::fprintf(stderr, "  %u/%u lexical declcontexts read (%f%%)\n",
3341                 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
3342                 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
3343                  * 100));
3344  if (TotalVisibleDeclContexts)
3345    std::fprintf(stderr, "  %u/%u visible declcontexts read (%f%%)\n",
3346                 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
3347                 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
3348                  * 100));
3349  if (TotalNumMethodPoolEntries) {
3350    std::fprintf(stderr, "  %u/%u method pool entries read (%f%%)\n",
3351                 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
3352                 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
3353                  * 100));
3354    std::fprintf(stderr, "  %u method pool misses\n", NumMethodPoolMisses);
3355  }
3356  std::fprintf(stderr, "\n");
3357}
3358
3359void ASTReader::InitializeSema(Sema &S) {
3360  SemaObj = &S;
3361  S.ExternalSource = this;
3362
3363  // Makes sure any declarations that were deserialized "too early"
3364  // still get added to the identifier's declaration chains.
3365  for (unsigned I = 0, N = PreloadedDecls.size(); I != N; ++I) {
3366    if (SemaObj->TUScope)
3367      SemaObj->TUScope->AddDecl(PreloadedDecls[I]);
3368
3369    SemaObj->IdResolver.AddDecl(PreloadedDecls[I]);
3370  }
3371  PreloadedDecls.clear();
3372
3373  // If there were any tentative definitions, deserialize them and add
3374  // them to Sema's list of tentative definitions.
3375  for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
3376    VarDecl *Var = cast<VarDecl>(GetDecl(TentativeDefinitions[I]));
3377    SemaObj->TentativeDefinitions.push_back(Var);
3378  }
3379
3380  // If there were any unused file scoped decls, deserialize them and add to
3381  // Sema's list of unused file scoped decls.
3382  for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
3383    DeclaratorDecl *D = cast<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
3384    SemaObj->UnusedFileScopedDecls.push_back(D);
3385  }
3386
3387  // If there were any weak undeclared identifiers, deserialize them and add to
3388  // Sema's list of weak undeclared identifiers.
3389  if (!WeakUndeclaredIdentifiers.empty()) {
3390    unsigned Idx = 0;
3391    for (unsigned I = 0, N = WeakUndeclaredIdentifiers[Idx++]; I != N; ++I) {
3392      IdentifierInfo *WeakId = GetIdentifierInfo(WeakUndeclaredIdentifiers,Idx);
3393      IdentifierInfo *AliasId=GetIdentifierInfo(WeakUndeclaredIdentifiers,Idx);
3394      SourceLocation Loc = ReadSourceLocation(WeakUndeclaredIdentifiers, Idx);
3395      bool Used = WeakUndeclaredIdentifiers[Idx++];
3396      Sema::WeakInfo WI(AliasId, Loc);
3397      WI.setUsed(Used);
3398      SemaObj->WeakUndeclaredIdentifiers.insert(std::make_pair(WeakId, WI));
3399    }
3400  }
3401
3402  // If there were any locally-scoped external declarations,
3403  // deserialize them and add them to Sema's table of locally-scoped
3404  // external declarations.
3405  for (unsigned I = 0, N = LocallyScopedExternalDecls.size(); I != N; ++I) {
3406    NamedDecl *D = cast<NamedDecl>(GetDecl(LocallyScopedExternalDecls[I]));
3407    SemaObj->LocallyScopedExternalDecls[D->getDeclName()] = D;
3408  }
3409
3410  // If there were any ext_vector type declarations, deserialize them
3411  // and add them to Sema's vector of such declarations.
3412  for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I)
3413    SemaObj->ExtVectorDecls.push_back(
3414                               cast<TypedefDecl>(GetDecl(ExtVectorDecls[I])));
3415
3416  // FIXME: Do VTable uses and dynamic classes deserialize too much ?
3417  // Can we cut them down before writing them ?
3418
3419  // If there were any VTable uses, deserialize the information and add it
3420  // to Sema's vector and map of VTable uses.
3421  if (!VTableUses.empty()) {
3422    unsigned Idx = 0;
3423    for (unsigned I = 0, N = VTableUses[Idx++]; I != N; ++I) {
3424      CXXRecordDecl *Class = cast<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
3425      SourceLocation Loc = ReadSourceLocation(VTableUses, Idx);
3426      bool DefinitionRequired = VTableUses[Idx++];
3427      SemaObj->VTableUses.push_back(std::make_pair(Class, Loc));
3428      SemaObj->VTablesUsed[Class] = DefinitionRequired;
3429    }
3430  }
3431
3432  // If there were any dynamic classes declarations, deserialize them
3433  // and add them to Sema's vector of such declarations.
3434  for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I)
3435    SemaObj->DynamicClasses.push_back(
3436                               cast<CXXRecordDecl>(GetDecl(DynamicClasses[I])));
3437
3438  // If there were any pending implicit instantiations, deserialize them
3439  // and add them to Sema's queue of such instantiations.
3440  assert(PendingInstantiations.size() % 2 == 0 && "Expected pairs of entries");
3441  for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
3442    ValueDecl *D=cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
3443    SourceLocation Loc = ReadSourceLocation(PendingInstantiations, Idx);
3444    SemaObj->PendingInstantiations.push_back(std::make_pair(D, Loc));
3445  }
3446
3447  // Load the offsets of the declarations that Sema references.
3448  // They will be lazily deserialized when needed.
3449  if (!SemaDeclRefs.empty()) {
3450    assert(SemaDeclRefs.size() == 2 && "More decl refs than expected!");
3451    SemaObj->StdNamespace = SemaDeclRefs[0];
3452    SemaObj->StdBadAlloc = SemaDeclRefs[1];
3453  }
3454
3455  // If there are @selector references added them to its pool. This is for
3456  // implementation of -Wselector.
3457  if (!ReferencedSelectorsData.empty()) {
3458    unsigned int DataSize = ReferencedSelectorsData.size()-1;
3459    unsigned I = 0;
3460    while (I < DataSize) {
3461      Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
3462      SourceLocation SelLoc =
3463        SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
3464      SemaObj->ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
3465    }
3466  }
3467}
3468
3469IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
3470  // Try to find this name within our on-disk hash tables. We start with the
3471  // most recent one, since that one contains the most up-to-date info.
3472  for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3473    ASTIdentifierLookupTable *IdTable
3474        = (ASTIdentifierLookupTable *)Chain[I]->IdentifierLookupTable;
3475    if (!IdTable)
3476      continue;
3477    std::pair<const char*, unsigned> Key(NameStart, NameEnd - NameStart);
3478    ASTIdentifierLookupTable::iterator Pos = IdTable->find(Key);
3479    if (Pos == IdTable->end())
3480      continue;
3481
3482    // Dereferencing the iterator has the effect of building the
3483    // IdentifierInfo node and populating it with the various
3484    // declarations it needs.
3485    return *Pos;
3486  }
3487  return 0;
3488}
3489
3490std::pair<ObjCMethodList, ObjCMethodList>
3491ASTReader::ReadMethodPool(Selector Sel) {
3492  // Find this selector in a hash table. We want to find the most recent entry.
3493  for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3494    PerFileData &F = *Chain[I];
3495    if (!F.SelectorLookupTable)
3496      continue;
3497
3498    ASTSelectorLookupTable *PoolTable
3499      = (ASTSelectorLookupTable*)F.SelectorLookupTable;
3500    ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
3501    if (Pos != PoolTable->end()) {
3502      ++NumSelectorsRead;
3503      // FIXME: Not quite happy with the statistics here. We probably should
3504      // disable this tracking when called via LoadSelector.
3505      // Also, should entries without methods count as misses?
3506      ++NumMethodPoolEntriesRead;
3507      ASTSelectorLookupTrait::data_type Data = *Pos;
3508      if (DeserializationListener)
3509        DeserializationListener->SelectorRead(Data.ID, Sel);
3510      return std::make_pair(Data.Instance, Data.Factory);
3511    }
3512  }
3513
3514  ++NumMethodPoolMisses;
3515  return std::pair<ObjCMethodList, ObjCMethodList>();
3516}
3517
3518void ASTReader::LoadSelector(Selector Sel) {
3519  // It would be complicated to avoid reading the methods anyway. So don't.
3520  ReadMethodPool(Sel);
3521}
3522
3523void ASTReader::SetIdentifierInfo(unsigned ID, IdentifierInfo *II) {
3524  assert(ID && "Non-zero identifier ID required");
3525  assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
3526  IdentifiersLoaded[ID - 1] = II;
3527  if (DeserializationListener)
3528    DeserializationListener->IdentifierRead(ID, II);
3529}
3530
3531/// \brief Set the globally-visible declarations associated with the given
3532/// identifier.
3533///
3534/// If the AST reader is currently in a state where the given declaration IDs
3535/// cannot safely be resolved, they are queued until it is safe to resolve
3536/// them.
3537///
3538/// \param II an IdentifierInfo that refers to one or more globally-visible
3539/// declarations.
3540///
3541/// \param DeclIDs the set of declaration IDs with the name @p II that are
3542/// visible at global scope.
3543///
3544/// \param Nonrecursive should be true to indicate that the caller knows that
3545/// this call is non-recursive, and therefore the globally-visible declarations
3546/// will not be placed onto the pending queue.
3547void
3548ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
3549                              const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
3550                                   bool Nonrecursive) {
3551  if (NumCurrentElementsDeserializing && !Nonrecursive) {
3552    PendingIdentifierInfos.push_back(PendingIdentifierInfo());
3553    PendingIdentifierInfo &PII = PendingIdentifierInfos.back();
3554    PII.II = II;
3555    PII.DeclIDs.append(DeclIDs.begin(), DeclIDs.end());
3556    return;
3557  }
3558
3559  for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
3560    NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
3561    if (SemaObj) {
3562      if (SemaObj->TUScope) {
3563        // Introduce this declaration into the translation-unit scope
3564        // and add it to the declaration chain for this identifier, so
3565        // that (unqualified) name lookup will find it.
3566        SemaObj->TUScope->AddDecl(D);
3567      }
3568      SemaObj->IdResolver.AddDeclToIdentifierChain(II, D);
3569    } else {
3570      // Queue this declaration so that it will be added to the
3571      // translation unit scope and identifier's declaration chain
3572      // once a Sema object is known.
3573      PreloadedDecls.push_back(D);
3574    }
3575  }
3576}
3577
3578IdentifierInfo *ASTReader::DecodeIdentifierInfo(unsigned ID) {
3579  if (ID == 0)
3580    return 0;
3581
3582  if (IdentifiersLoaded.empty()) {
3583    Error("no identifier table in AST file");
3584    return 0;
3585  }
3586
3587  assert(PP && "Forgot to set Preprocessor ?");
3588  ID -= 1;
3589  if (!IdentifiersLoaded[ID]) {
3590    unsigned Index = ID;
3591    const char *Str = 0;
3592    for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3593      PerFileData *F = Chain[N - I - 1];
3594      if (Index < F->LocalNumIdentifiers) {
3595         uint32_t Offset = F->IdentifierOffsets[Index];
3596         Str = F->IdentifierTableData + Offset;
3597         break;
3598      }
3599      Index -= F->LocalNumIdentifiers;
3600    }
3601    assert(Str && "Broken Chain");
3602
3603    // All of the strings in the AST file are preceded by a 16-bit length.
3604    // Extract that 16-bit length to avoid having to execute strlen().
3605    // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
3606    //  unsigned integers.  This is important to avoid integer overflow when
3607    //  we cast them to 'unsigned'.
3608    const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
3609    unsigned StrLen = (((unsigned) StrLenPtr[0])
3610                       | (((unsigned) StrLenPtr[1]) << 8)) - 1;
3611    IdentifiersLoaded[ID]
3612      = &PP->getIdentifierTable().get(Str, StrLen);
3613    if (DeserializationListener)
3614      DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
3615  }
3616
3617  return IdentifiersLoaded[ID];
3618}
3619
3620void ASTReader::ReadSLocEntry(unsigned ID) {
3621  ReadSLocEntryRecord(ID);
3622}
3623
3624Selector ASTReader::DecodeSelector(unsigned ID) {
3625  if (ID == 0)
3626    return Selector();
3627
3628  if (ID > SelectorsLoaded.size()) {
3629    Error("selector ID out of range in AST file");
3630    return Selector();
3631  }
3632
3633  if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == 0) {
3634    // Load this selector from the selector table.
3635    unsigned Idx = ID - 1;
3636    for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
3637      PerFileData &F = *Chain[N - I - 1];
3638      if (Idx < F.LocalNumSelectors) {
3639        ASTSelectorLookupTrait Trait(*this);
3640        SelectorsLoaded[ID - 1] =
3641           Trait.ReadKey(F.SelectorLookupTableData + F.SelectorOffsets[Idx], 0);
3642        if (DeserializationListener)
3643          DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
3644        break;
3645      }
3646      Idx -= F.LocalNumSelectors;
3647    }
3648  }
3649
3650  return SelectorsLoaded[ID - 1];
3651}
3652
3653Selector ASTReader::GetExternalSelector(uint32_t ID) {
3654  return DecodeSelector(ID);
3655}
3656
3657uint32_t ASTReader::GetNumExternalSelectors() {
3658  // ID 0 (the null selector) is considered an external selector.
3659  return getTotalNumSelectors() + 1;
3660}
3661
3662DeclarationName
3663ASTReader::ReadDeclarationName(const RecordData &Record, unsigned &Idx) {
3664  DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
3665  switch (Kind) {
3666  case DeclarationName::Identifier:
3667    return DeclarationName(GetIdentifierInfo(Record, Idx));
3668
3669  case DeclarationName::ObjCZeroArgSelector:
3670  case DeclarationName::ObjCOneArgSelector:
3671  case DeclarationName::ObjCMultiArgSelector:
3672    return DeclarationName(GetSelector(Record, Idx));
3673
3674  case DeclarationName::CXXConstructorName:
3675    return Context->DeclarationNames.getCXXConstructorName(
3676                          Context->getCanonicalType(GetType(Record[Idx++])));
3677
3678  case DeclarationName::CXXDestructorName:
3679    return Context->DeclarationNames.getCXXDestructorName(
3680                          Context->getCanonicalType(GetType(Record[Idx++])));
3681
3682  case DeclarationName::CXXConversionFunctionName:
3683    return Context->DeclarationNames.getCXXConversionFunctionName(
3684                          Context->getCanonicalType(GetType(Record[Idx++])));
3685
3686  case DeclarationName::CXXOperatorName:
3687    return Context->DeclarationNames.getCXXOperatorName(
3688                                       (OverloadedOperatorKind)Record[Idx++]);
3689
3690  case DeclarationName::CXXLiteralOperatorName:
3691    return Context->DeclarationNames.getCXXLiteralOperatorName(
3692                                       GetIdentifierInfo(Record, Idx));
3693
3694  case DeclarationName::CXXUsingDirective:
3695    return DeclarationName::getUsingDirectiveName();
3696  }
3697
3698  // Required to silence GCC warning
3699  return DeclarationName();
3700}
3701
3702TemplateName
3703ASTReader::ReadTemplateName(const RecordData &Record, unsigned &Idx) {
3704  TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
3705  switch (Kind) {
3706  case TemplateName::Template:
3707    return TemplateName(cast_or_null<TemplateDecl>(GetDecl(Record[Idx++])));
3708
3709  case TemplateName::OverloadedTemplate: {
3710    unsigned size = Record[Idx++];
3711    UnresolvedSet<8> Decls;
3712    while (size--)
3713      Decls.addDecl(cast<NamedDecl>(GetDecl(Record[Idx++])));
3714
3715    return Context->getOverloadedTemplateName(Decls.begin(), Decls.end());
3716  }
3717
3718  case TemplateName::QualifiedTemplate: {
3719    NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3720    bool hasTemplKeyword = Record[Idx++];
3721    TemplateDecl *Template = cast<TemplateDecl>(GetDecl(Record[Idx++]));
3722    return Context->getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
3723  }
3724
3725  case TemplateName::DependentTemplate: {
3726    NestedNameSpecifier *NNS = ReadNestedNameSpecifier(Record, Idx);
3727    if (Record[Idx++])  // isIdentifier
3728      return Context->getDependentTemplateName(NNS,
3729                                               GetIdentifierInfo(Record, Idx));
3730    return Context->getDependentTemplateName(NNS,
3731                                         (OverloadedOperatorKind)Record[Idx++]);
3732  }
3733  }
3734
3735  assert(0 && "Unhandled template name kind!");
3736  return TemplateName();
3737}
3738
3739TemplateArgument
3740ASTReader::ReadTemplateArgument(llvm::BitstreamCursor &DeclsCursor,
3741                                const RecordData &Record, unsigned &Idx) {
3742  switch ((TemplateArgument::ArgKind)Record[Idx++]) {
3743  case TemplateArgument::Null:
3744    return TemplateArgument();
3745  case TemplateArgument::Type:
3746    return TemplateArgument(GetType(Record[Idx++]));
3747  case TemplateArgument::Declaration:
3748    return TemplateArgument(GetDecl(Record[Idx++]));
3749  case TemplateArgument::Integral: {
3750    llvm::APSInt Value = ReadAPSInt(Record, Idx);
3751    QualType T = GetType(Record[Idx++]);
3752    return TemplateArgument(Value, T);
3753  }
3754  case TemplateArgument::Template:
3755    return TemplateArgument(ReadTemplateName(Record, Idx));
3756  case TemplateArgument::Expression:
3757    return TemplateArgument(ReadExpr(DeclsCursor));
3758  case TemplateArgument::Pack: {
3759    unsigned NumArgs = Record[Idx++];
3760    llvm::SmallVector<TemplateArgument, 8> Args;
3761    Args.reserve(NumArgs);
3762    while (NumArgs--)
3763      Args.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
3764    TemplateArgument TemplArg;
3765    TemplArg.setArgumentPack(Args.data(), Args.size(), /*CopyArgs=*/true);
3766    return TemplArg;
3767  }
3768  }
3769
3770  assert(0 && "Unhandled template argument kind!");
3771  return TemplateArgument();
3772}
3773
3774TemplateParameterList *
3775ASTReader::ReadTemplateParameterList(const RecordData &Record, unsigned &Idx) {
3776  SourceLocation TemplateLoc = ReadSourceLocation(Record, Idx);
3777  SourceLocation LAngleLoc = ReadSourceLocation(Record, Idx);
3778  SourceLocation RAngleLoc = ReadSourceLocation(Record, Idx);
3779
3780  unsigned NumParams = Record[Idx++];
3781  llvm::SmallVector<NamedDecl *, 16> Params;
3782  Params.reserve(NumParams);
3783  while (NumParams--)
3784    Params.push_back(cast<NamedDecl>(GetDecl(Record[Idx++])));
3785
3786  TemplateParameterList* TemplateParams =
3787    TemplateParameterList::Create(*Context, TemplateLoc, LAngleLoc,
3788                                  Params.data(), Params.size(), RAngleLoc);
3789  return TemplateParams;
3790}
3791
3792void
3793ASTReader::
3794ReadTemplateArgumentList(llvm::SmallVector<TemplateArgument, 8> &TemplArgs,
3795                         llvm::BitstreamCursor &DeclsCursor,
3796                         const RecordData &Record, unsigned &Idx) {
3797  unsigned NumTemplateArgs = Record[Idx++];
3798  TemplArgs.reserve(NumTemplateArgs);
3799  while (NumTemplateArgs--)
3800    TemplArgs.push_back(ReadTemplateArgument(DeclsCursor, Record, Idx));
3801}
3802
3803/// \brief Read a UnresolvedSet structure.
3804void ASTReader::ReadUnresolvedSet(UnresolvedSetImpl &Set,
3805                                  const RecordData &Record, unsigned &Idx) {
3806  unsigned NumDecls = Record[Idx++];
3807  while (NumDecls--) {
3808    NamedDecl *D = cast<NamedDecl>(GetDecl(Record[Idx++]));
3809    AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
3810    Set.addDecl(D, AS);
3811  }
3812}
3813
3814CXXBaseSpecifier
3815ASTReader::ReadCXXBaseSpecifier(llvm::BitstreamCursor &DeclsCursor,
3816                                const RecordData &Record, unsigned &Idx) {
3817  bool isVirtual = static_cast<bool>(Record[Idx++]);
3818  bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
3819  AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
3820  TypeSourceInfo *TInfo = GetTypeSourceInfo(DeclsCursor, Record, Idx);
3821  SourceRange Range = ReadSourceRange(Record, Idx);
3822  return CXXBaseSpecifier(Range, isVirtual, isBaseOfClass, AS, TInfo);
3823}
3824
3825std::pair<CXXBaseOrMemberInitializer **, unsigned>
3826ASTReader::ReadCXXBaseOrMemberInitializers(llvm::BitstreamCursor &Cursor,
3827                                           const RecordData &Record,
3828                                           unsigned &Idx) {
3829  CXXBaseOrMemberInitializer **BaseOrMemberInitializers = 0;
3830  unsigned NumInitializers = Record[Idx++];
3831  if (NumInitializers) {
3832    ASTContext &C = *getContext();
3833
3834    BaseOrMemberInitializers
3835        = new (C) CXXBaseOrMemberInitializer*[NumInitializers];
3836    for (unsigned i=0; i != NumInitializers; ++i) {
3837      TypeSourceInfo *BaseClassInfo = 0;
3838      bool IsBaseVirtual = false;
3839      FieldDecl *Member = 0;
3840
3841      bool IsBaseInitializer = Record[Idx++];
3842      if (IsBaseInitializer) {
3843        BaseClassInfo = GetTypeSourceInfo(Cursor, Record, Idx);
3844        IsBaseVirtual = Record[Idx++];
3845      } else {
3846        Member = cast<FieldDecl>(GetDecl(Record[Idx++]));
3847      }
3848      SourceLocation MemberLoc = ReadSourceLocation(Record, Idx);
3849      Expr *Init = ReadExpr(Cursor);
3850      FieldDecl *AnonUnionMember
3851          = cast_or_null<FieldDecl>(GetDecl(Record[Idx++]));
3852      SourceLocation LParenLoc = ReadSourceLocation(Record, Idx);
3853      SourceLocation RParenLoc = ReadSourceLocation(Record, Idx);
3854      bool IsWritten = Record[Idx++];
3855      unsigned SourceOrderOrNumArrayIndices;
3856      llvm::SmallVector<VarDecl *, 8> Indices;
3857      if (IsWritten) {
3858        SourceOrderOrNumArrayIndices = Record[Idx++];
3859      } else {
3860        SourceOrderOrNumArrayIndices = Record[Idx++];
3861        Indices.reserve(SourceOrderOrNumArrayIndices);
3862        for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
3863          Indices.push_back(cast<VarDecl>(GetDecl(Record[Idx++])));
3864      }
3865
3866      CXXBaseOrMemberInitializer *BOMInit;
3867      if (IsBaseInitializer) {
3868        BOMInit = new (C) CXXBaseOrMemberInitializer(C, BaseClassInfo,
3869                                                     IsBaseVirtual, LParenLoc,
3870                                                     Init, RParenLoc);
3871      } else if (IsWritten) {
3872        BOMInit = new (C) CXXBaseOrMemberInitializer(C, Member, MemberLoc,
3873                                                     LParenLoc, Init, RParenLoc);
3874      } else {
3875        BOMInit = CXXBaseOrMemberInitializer::Create(C, Member, MemberLoc,
3876                                                     LParenLoc, Init, RParenLoc,
3877                                                     Indices.data(),
3878                                                     Indices.size());
3879      }
3880
3881      if (IsWritten)
3882        BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
3883      BOMInit->setAnonUnionMember(AnonUnionMember);
3884      BaseOrMemberInitializers[i] = BOMInit;
3885    }
3886  }
3887
3888  return std::make_pair(BaseOrMemberInitializers, NumInitializers);
3889}
3890
3891NestedNameSpecifier *
3892ASTReader::ReadNestedNameSpecifier(const RecordData &Record, unsigned &Idx) {
3893  unsigned N = Record[Idx++];
3894  NestedNameSpecifier *NNS = 0, *Prev = 0;
3895  for (unsigned I = 0; I != N; ++I) {
3896    NestedNameSpecifier::SpecifierKind Kind
3897      = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
3898    switch (Kind) {
3899    case NestedNameSpecifier::Identifier: {
3900      IdentifierInfo *II = GetIdentifierInfo(Record, Idx);
3901      NNS = NestedNameSpecifier::Create(*Context, Prev, II);
3902      break;
3903    }
3904
3905    case NestedNameSpecifier::Namespace: {
3906      NamespaceDecl *NS = cast<NamespaceDecl>(GetDecl(Record[Idx++]));
3907      NNS = NestedNameSpecifier::Create(*Context, Prev, NS);
3908      break;
3909    }
3910
3911    case NestedNameSpecifier::TypeSpec:
3912    case NestedNameSpecifier::TypeSpecWithTemplate: {
3913      Type *T = GetType(Record[Idx++]).getTypePtr();
3914      bool Template = Record[Idx++];
3915      NNS = NestedNameSpecifier::Create(*Context, Prev, Template, T);
3916      break;
3917    }
3918
3919    case NestedNameSpecifier::Global: {
3920      NNS = NestedNameSpecifier::GlobalSpecifier(*Context);
3921      // No associated value, and there can't be a prefix.
3922      break;
3923    }
3924    }
3925    Prev = NNS;
3926  }
3927  return NNS;
3928}
3929
3930SourceRange
3931ASTReader::ReadSourceRange(const RecordData &Record, unsigned &Idx) {
3932  SourceLocation beg = SourceLocation::getFromRawEncoding(Record[Idx++]);
3933  SourceLocation end = SourceLocation::getFromRawEncoding(Record[Idx++]);
3934  return SourceRange(beg, end);
3935}
3936
3937/// \brief Read an integral value
3938llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
3939  unsigned BitWidth = Record[Idx++];
3940  unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
3941  llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
3942  Idx += NumWords;
3943  return Result;
3944}
3945
3946/// \brief Read a signed integral value
3947llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
3948  bool isUnsigned = Record[Idx++];
3949  return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
3950}
3951
3952/// \brief Read a floating-point value
3953llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record, unsigned &Idx) {
3954  return llvm::APFloat(ReadAPInt(Record, Idx));
3955}
3956
3957// \brief Read a string
3958std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
3959  unsigned Len = Record[Idx++];
3960  std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
3961  Idx += Len;
3962  return Result;
3963}
3964
3965CXXTemporary *ASTReader::ReadCXXTemporary(const RecordData &Record,
3966                                          unsigned &Idx) {
3967  CXXDestructorDecl *Decl = cast<CXXDestructorDecl>(GetDecl(Record[Idx++]));
3968  return CXXTemporary::Create(*Context, Decl);
3969}
3970
3971DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
3972  return Diag(SourceLocation(), DiagID);
3973}
3974
3975DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
3976  return Diags.Report(FullSourceLoc(Loc, SourceMgr), DiagID);
3977}
3978
3979/// \brief Retrieve the identifier table associated with the
3980/// preprocessor.
3981IdentifierTable &ASTReader::getIdentifierTable() {
3982  assert(PP && "Forgot to set Preprocessor ?");
3983  return PP->getIdentifierTable();
3984}
3985
3986/// \brief Record that the given ID maps to the given switch-case
3987/// statement.
3988void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
3989  assert(SwitchCaseStmts[ID] == 0 && "Already have a SwitchCase with this ID");
3990  SwitchCaseStmts[ID] = SC;
3991}
3992
3993/// \brief Retrieve the switch-case statement with the given ID.
3994SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
3995  assert(SwitchCaseStmts[ID] != 0 && "No SwitchCase with this ID");
3996  return SwitchCaseStmts[ID];
3997}
3998
3999/// \brief Record that the given label statement has been
4000/// deserialized and has the given ID.
4001void ASTReader::RecordLabelStmt(LabelStmt *S, unsigned ID) {
4002  assert(LabelStmts.find(ID) == LabelStmts.end() &&
4003         "Deserialized label twice");
4004  LabelStmts[ID] = S;
4005
4006  // If we've already seen any goto statements that point to this
4007  // label, resolve them now.
4008  typedef std::multimap<unsigned, GotoStmt *>::iterator GotoIter;
4009  std::pair<GotoIter, GotoIter> Gotos = UnresolvedGotoStmts.equal_range(ID);
4010  for (GotoIter Goto = Gotos.first; Goto != Gotos.second; ++Goto)
4011    Goto->second->setLabel(S);
4012  UnresolvedGotoStmts.erase(Gotos.first, Gotos.second);
4013
4014  // If we've already seen any address-label statements that point to
4015  // this label, resolve them now.
4016  typedef std::multimap<unsigned, AddrLabelExpr *>::iterator AddrLabelIter;
4017  std::pair<AddrLabelIter, AddrLabelIter> AddrLabels
4018    = UnresolvedAddrLabelExprs.equal_range(ID);
4019  for (AddrLabelIter AddrLabel = AddrLabels.first;
4020       AddrLabel != AddrLabels.second; ++AddrLabel)
4021    AddrLabel->second->setLabel(S);
4022  UnresolvedAddrLabelExprs.erase(AddrLabels.first, AddrLabels.second);
4023}
4024
4025/// \brief Set the label of the given statement to the label
4026/// identified by ID.
4027///
4028/// Depending on the order in which the label and other statements
4029/// referencing that label occur, this operation may complete
4030/// immediately (updating the statement) or it may queue the
4031/// statement to be back-patched later.
4032void ASTReader::SetLabelOf(GotoStmt *S, unsigned ID) {
4033  std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
4034  if (Label != LabelStmts.end()) {
4035    // We've already seen this label, so set the label of the goto and
4036    // we're done.
4037    S->setLabel(Label->second);
4038  } else {
4039    // We haven't seen this label yet, so add this goto to the set of
4040    // unresolved goto statements.
4041    UnresolvedGotoStmts.insert(std::make_pair(ID, S));
4042  }
4043}
4044
4045/// \brief Set the label of the given expression to the label
4046/// identified by ID.
4047///
4048/// Depending on the order in which the label and other statements
4049/// referencing that label occur, this operation may complete
4050/// immediately (updating the statement) or it may queue the
4051/// statement to be back-patched later.
4052void ASTReader::SetLabelOf(AddrLabelExpr *S, unsigned ID) {
4053  std::map<unsigned, LabelStmt *>::iterator Label = LabelStmts.find(ID);
4054  if (Label != LabelStmts.end()) {
4055    // We've already seen this label, so set the label of the
4056    // label-address expression and we're done.
4057    S->setLabel(Label->second);
4058  } else {
4059    // We haven't seen this label yet, so add this label-address
4060    // expression to the set of unresolved label-address expressions.
4061    UnresolvedAddrLabelExprs.insert(std::make_pair(ID, S));
4062  }
4063}
4064
4065void ASTReader::FinishedDeserializing() {
4066  assert(NumCurrentElementsDeserializing &&
4067         "FinishedDeserializing not paired with StartedDeserializing");
4068  if (NumCurrentElementsDeserializing == 1) {
4069    // If any identifiers with corresponding top-level declarations have
4070    // been loaded, load those declarations now.
4071    while (!PendingIdentifierInfos.empty()) {
4072      SetGloballyVisibleDecls(PendingIdentifierInfos.front().II,
4073                              PendingIdentifierInfos.front().DeclIDs, true);
4074      PendingIdentifierInfos.pop_front();
4075    }
4076
4077    // We are not in recursive loading, so it's safe to pass the "interesting"
4078    // decls to the consumer.
4079    if (Consumer)
4080      PassInterestingDeclsToConsumer();
4081  }
4082  --NumCurrentElementsDeserializing;
4083}
4084
4085ASTReader::ASTReader(Preprocessor &PP, ASTContext *Context,
4086                     const char *isysroot, bool DisableValidation)
4087  : Listener(new PCHValidator(PP, *this)), DeserializationListener(0),
4088    SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
4089    Diags(PP.getDiagnostics()), SemaObj(0), PP(&PP), Context(Context),
4090    Consumer(0), isysroot(isysroot), DisableValidation(DisableValidation),
4091    NumStatHits(0), NumStatMisses(0), NumSLocEntriesRead(0),
4092    TotalNumSLocEntries(0), NextSLocOffset(0), NumStatementsRead(0),
4093    TotalNumStatements(0), NumMacrosRead(0), TotalNumMacros(0),
4094    NumSelectorsRead(0), NumMethodPoolEntriesRead(0), NumMethodPoolMisses(0),
4095    TotalNumMethodPoolEntries(0), NumLexicalDeclContextsRead(0),
4096    TotalLexicalDeclContexts(0), NumVisibleDeclContextsRead(0),
4097    TotalVisibleDeclContexts(0), NumCurrentElementsDeserializing(0) {
4098  RelocatablePCH = false;
4099}
4100
4101ASTReader::ASTReader(SourceManager &SourceMgr, FileManager &FileMgr,
4102                     Diagnostic &Diags, const char *isysroot,
4103                     bool DisableValidation)
4104  : DeserializationListener(0), SourceMgr(SourceMgr), FileMgr(FileMgr),
4105    Diags(Diags), SemaObj(0), PP(0), Context(0), Consumer(0),
4106    isysroot(isysroot), DisableValidation(DisableValidation), NumStatHits(0),
4107    NumStatMisses(0), NumSLocEntriesRead(0), TotalNumSLocEntries(0),
4108    NextSLocOffset(0), NumStatementsRead(0), TotalNumStatements(0),
4109    NumMacrosRead(0), TotalNumMacros(0), NumSelectorsRead(0),
4110    NumMethodPoolEntriesRead(0), NumMethodPoolMisses(0),
4111    TotalNumMethodPoolEntries(0), NumLexicalDeclContextsRead(0),
4112    TotalLexicalDeclContexts(0), NumVisibleDeclContextsRead(0),
4113    TotalVisibleDeclContexts(0), NumCurrentElementsDeserializing(0) {
4114  RelocatablePCH = false;
4115}
4116
4117ASTReader::~ASTReader() {
4118  for (unsigned i = 0, e = Chain.size(); i != e; ++i)
4119    delete Chain[e - i - 1];
4120  // Delete all visible decl lookup tables
4121  for (DeclContextOffsetsMap::iterator I = DeclContextOffsets.begin(),
4122                                       E = DeclContextOffsets.end();
4123       I != E; ++I) {
4124    for (DeclContextInfos::iterator J = I->second.begin(), F = I->second.end();
4125         J != F; ++J) {
4126      if (J->NameLookupTableData)
4127        delete static_cast<ASTDeclContextNameLookupTable*>(
4128            J->NameLookupTableData);
4129    }
4130  }
4131  for (DeclContextVisibleUpdatesPending::iterator
4132           I = PendingVisibleUpdates.begin(),
4133           E = PendingVisibleUpdates.end();
4134       I != E; ++I) {
4135    for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
4136                                             F = I->second.end();
4137         J != F; ++J)
4138      delete static_cast<ASTDeclContextNameLookupTable*>(*J);
4139  }
4140}
4141
4142ASTReader::PerFileData::PerFileData()
4143  : SizeInBits(0), LocalNumSLocEntries(0), SLocOffsets(0), LocalSLocSize(0),
4144    LocalNumIdentifiers(0), IdentifierOffsets(0), IdentifierTableData(0),
4145    IdentifierLookupTable(0), LocalNumMacroDefinitions(0),
4146    MacroDefinitionOffsets(0), LocalNumSelectors(0), SelectorOffsets(0),
4147    SelectorLookupTableData(0), SelectorLookupTable(0), LocalNumDecls(0),
4148    DeclOffsets(0), LocalNumTypes(0), TypeOffsets(0), StatCache(0),
4149    NumPreallocatedPreprocessingEntities(0)
4150{}
4151
4152ASTReader::PerFileData::~PerFileData() {
4153  delete static_cast<ASTIdentifierLookupTable *>(IdentifierLookupTable);
4154  delete static_cast<ASTSelectorLookupTable *>(SelectorLookupTable);
4155}
4156
4157