ASTUnit.cpp revision 1872b3153a388b3a548c9f699cbc348128059be9
1//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
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// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Frontend/ASTUnit.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTConsumer.h"
17#include "clang/AST/DeclVisitor.h"
18#include "clang/AST/TypeOrdering.h"
19#include "clang/AST/StmtVisitor.h"
20#include "clang/Driver/Compilation.h"
21#include "clang/Driver/Driver.h"
22#include "clang/Driver/Job.h"
23#include "clang/Driver/ArgList.h"
24#include "clang/Driver/Options.h"
25#include "clang/Driver/Tool.h"
26#include "clang/Frontend/CompilerInstance.h"
27#include "clang/Frontend/FrontendActions.h"
28#include "clang/Frontend/FrontendDiagnostic.h"
29#include "clang/Frontend/FrontendOptions.h"
30#include "clang/Frontend/Utils.h"
31#include "clang/Serialization/ASTReader.h"
32#include "clang/Serialization/ASTWriter.h"
33#include "clang/Lex/HeaderSearch.h"
34#include "clang/Lex/Preprocessor.h"
35#include "clang/Basic/TargetOptions.h"
36#include "clang/Basic/TargetInfo.h"
37#include "clang/Basic/Diagnostic.h"
38#include "llvm/ADT/ArrayRef.h"
39#include "llvm/ADT/StringExtras.h"
40#include "llvm/ADT/StringSet.h"
41#include "llvm/Support/Atomic.h"
42#include "llvm/Support/MemoryBuffer.h"
43#include "llvm/Support/Host.h"
44#include "llvm/Support/Path.h"
45#include "llvm/Support/raw_ostream.h"
46#include "llvm/Support/Timer.h"
47#include "llvm/Support/FileSystem.h"
48#include "llvm/Support/Mutex.h"
49#include "llvm/Support/CrashRecoveryContext.h"
50#include <cstdlib>
51#include <cstdio>
52#include <sys/stat.h>
53using namespace clang;
54
55using llvm::TimeRecord;
56
57namespace {
58  class SimpleTimer {
59    bool WantTiming;
60    TimeRecord Start;
61    std::string Output;
62
63  public:
64    explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
65      if (WantTiming)
66        Start = TimeRecord::getCurrentTime();
67    }
68
69    void setOutput(const Twine &Output) {
70      if (WantTiming)
71        this->Output = Output.str();
72    }
73
74    ~SimpleTimer() {
75      if (WantTiming) {
76        TimeRecord Elapsed = TimeRecord::getCurrentTime();
77        Elapsed -= Start;
78        llvm::errs() << Output << ':';
79        Elapsed.print(Elapsed, llvm::errs());
80        llvm::errs() << '\n';
81      }
82    }
83  };
84
85  struct OnDiskData {
86    /// \brief The file in which the precompiled preamble is stored.
87    std::string PreambleFile;
88
89    /// \brief Temporary files that should be removed when the ASTUnit is
90    /// destroyed.
91    SmallVector<llvm::sys::Path, 4> TemporaryFiles;
92
93    /// \brief Erase temporary files.
94    void CleanTemporaryFiles();
95
96    /// \brief Erase the preamble file.
97    void CleanPreambleFile();
98
99    /// \brief Erase temporary files and the preamble file.
100    void Cleanup();
101  };
102}
103
104static void cleanupOnDiskMapAtExit(void);
105
106typedef llvm::DenseMap<const ASTUnit *, OnDiskData *> OnDiskDataMap;
107static OnDiskDataMap &getOnDiskDataMap() {
108  static OnDiskDataMap M;
109  static bool hasRegisteredAtExit = false;
110  if (!hasRegisteredAtExit) {
111    hasRegisteredAtExit = true;
112    atexit(cleanupOnDiskMapAtExit);
113  }
114  return M;
115}
116
117static void cleanupOnDiskMapAtExit(void) {
118  OnDiskDataMap &M = getOnDiskDataMap();
119  for (OnDiskDataMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
120    // We don't worry about freeing the memory associated with OnDiskDataMap.
121    // All we care about is erasing stale files.
122    I->second->Cleanup();
123  }
124}
125
126static OnDiskData &getOnDiskData(const ASTUnit *AU) {
127  OnDiskDataMap &M = getOnDiskDataMap();
128  OnDiskData *&D = M[AU];
129  if (!D)
130    D = new OnDiskData();
131  return *D;
132}
133
134static void erasePreambleFile(const ASTUnit *AU) {
135  getOnDiskData(AU).CleanPreambleFile();
136}
137
138static void removeOnDiskEntry(const ASTUnit *AU) {
139  OnDiskDataMap &M = getOnDiskDataMap();
140  OnDiskDataMap::iterator I = M.find(AU);
141  if (I != M.end()) {
142    I->second->Cleanup();
143    delete I->second;
144    M.erase(AU);
145  }
146}
147
148static void setPreambleFile(const ASTUnit *AU, llvm::StringRef preambleFile) {
149  getOnDiskData(AU).PreambleFile = preambleFile;
150}
151
152static const std::string &getPreambleFile(const ASTUnit *AU) {
153  return getOnDiskData(AU).PreambleFile;
154}
155
156void OnDiskData::CleanTemporaryFiles() {
157  for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
158    TemporaryFiles[I].eraseFromDisk();
159  TemporaryFiles.clear();
160}
161
162void OnDiskData::CleanPreambleFile() {
163  if (!PreambleFile.empty()) {
164    llvm::sys::Path(PreambleFile).eraseFromDisk();
165    PreambleFile.clear();
166  }
167}
168
169void OnDiskData::Cleanup() {
170  CleanTemporaryFiles();
171  CleanPreambleFile();
172}
173
174void ASTUnit::CleanTemporaryFiles() {
175  getOnDiskData(this).CleanTemporaryFiles();
176}
177
178void ASTUnit::addTemporaryFile(const llvm::sys::Path &TempFile) {
179  getOnDiskData(this).TemporaryFiles.push_back(TempFile);
180}
181
182/// \brief After failing to build a precompiled preamble (due to
183/// errors in the source that occurs in the preamble), the number of
184/// reparses during which we'll skip even trying to precompile the
185/// preamble.
186const unsigned DefaultPreambleRebuildInterval = 5;
187
188/// \brief Tracks the number of ASTUnit objects that are currently active.
189///
190/// Used for debugging purposes only.
191static llvm::sys::cas_flag ActiveASTUnitObjects;
192
193ASTUnit::ASTUnit(bool _MainFileIsAST)
194  : OnlyLocalDecls(false), CaptureDiagnostics(false),
195    MainFileIsAST(_MainFileIsAST),
196    TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
197    OwnsRemappedFileBuffers(true),
198    NumStoredDiagnosticsFromDriver(0),
199    PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
200    ShouldCacheCodeCompletionResults(false),
201    NestedMacroExpansions(true),
202    CompletionCacheTopLevelHashValue(0),
203    PreambleTopLevelHashValue(0),
204    CurrentTopLevelHashValue(0),
205    UnsafeToFree(false) {
206  if (getenv("LIBCLANG_OBJTRACKING")) {
207    llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
208    fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
209  }
210}
211
212ASTUnit::~ASTUnit() {
213  // Clean up the temporary files and the preamble file.
214  removeOnDiskEntry(this);
215
216  // Free the buffers associated with remapped files. We are required to
217  // perform this operation here because we explicitly request that the
218  // compiler instance *not* free these buffers for each invocation of the
219  // parser.
220  if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
221    PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
222    for (PreprocessorOptions::remapped_file_buffer_iterator
223           FB = PPOpts.remapped_file_buffer_begin(),
224           FBEnd = PPOpts.remapped_file_buffer_end();
225         FB != FBEnd;
226         ++FB)
227      delete FB->second;
228  }
229
230  delete SavedMainFileBuffer;
231  delete PreambleBuffer;
232
233  ClearCachedCompletionResults();
234
235  if (getenv("LIBCLANG_OBJTRACKING")) {
236    llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
237    fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
238  }
239}
240
241/// \brief Determine the set of code-completion contexts in which this
242/// declaration should be shown.
243static unsigned getDeclShowContexts(NamedDecl *ND,
244                                    const LangOptions &LangOpts,
245                                    bool &IsNestedNameSpecifier) {
246  IsNestedNameSpecifier = false;
247
248  if (isa<UsingShadowDecl>(ND))
249    ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
250  if (!ND)
251    return 0;
252
253  unsigned Contexts = 0;
254  if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
255      isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
256    // Types can appear in these contexts.
257    if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
258      Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
259                | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
260                | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
261                | (1 << (CodeCompletionContext::CCC_Statement - 1))
262                | (1 << (CodeCompletionContext::CCC_Type - 1))
263              | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
264
265    // In C++, types can appear in expressions contexts (for functional casts).
266    if (LangOpts.CPlusPlus)
267      Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
268
269    // In Objective-C, message sends can send interfaces. In Objective-C++,
270    // all types are available due to functional casts.
271    if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
272      Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
273
274    // In Objective-C, you can only be a subclass of another Objective-C class
275    if (isa<ObjCInterfaceDecl>(ND))
276      Contexts |= (1 << (CodeCompletionContext::CCC_ObjCInterfaceName - 1));
277
278    // Deal with tag names.
279    if (isa<EnumDecl>(ND)) {
280      Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
281
282      // Part of the nested-name-specifier in C++0x.
283      if (LangOpts.CPlusPlus0x)
284        IsNestedNameSpecifier = true;
285    } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
286      if (Record->isUnion())
287        Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
288      else
289        Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
290
291      if (LangOpts.CPlusPlus)
292        IsNestedNameSpecifier = true;
293    } else if (isa<ClassTemplateDecl>(ND))
294      IsNestedNameSpecifier = true;
295  } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
296    // Values can appear in these contexts.
297    Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
298             | (1 << (CodeCompletionContext::CCC_Expression - 1))
299             | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
300             | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
301  } else if (isa<ObjCProtocolDecl>(ND)) {
302    Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
303  } else if (isa<ObjCCategoryDecl>(ND)) {
304    Contexts = (1 << (CodeCompletionContext::CCC_ObjCCategoryName - 1));
305  } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
306    Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
307
308    // Part of the nested-name-specifier.
309    IsNestedNameSpecifier = true;
310  }
311
312  return Contexts;
313}
314
315void ASTUnit::CacheCodeCompletionResults() {
316  if (!TheSema)
317    return;
318
319  SimpleTimer Timer(WantTiming);
320  Timer.setOutput("Cache global code completions for " + getMainFileName());
321
322  // Clear out the previous results.
323  ClearCachedCompletionResults();
324
325  // Gather the set of global code completions.
326  typedef CodeCompletionResult Result;
327  SmallVector<Result, 8> Results;
328  CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
329  TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator, Results);
330
331  // Translate global code completions into cached completions.
332  llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
333
334  for (unsigned I = 0, N = Results.size(); I != N; ++I) {
335    switch (Results[I].Kind) {
336    case Result::RK_Declaration: {
337      bool IsNestedNameSpecifier = false;
338      CachedCodeCompletionResult CachedResult;
339      CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
340                                                    *CachedCompletionAllocator);
341      CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
342                                                        Ctx->getLangOptions(),
343                                                        IsNestedNameSpecifier);
344      CachedResult.Priority = Results[I].Priority;
345      CachedResult.Kind = Results[I].CursorKind;
346      CachedResult.Availability = Results[I].Availability;
347
348      // Keep track of the type of this completion in an ASTContext-agnostic
349      // way.
350      QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
351      if (UsageType.isNull()) {
352        CachedResult.TypeClass = STC_Void;
353        CachedResult.Type = 0;
354      } else {
355        CanQualType CanUsageType
356          = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
357        CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
358
359        // Determine whether we have already seen this type. If so, we save
360        // ourselves the work of formatting the type string by using the
361        // temporary, CanQualType-based hash table to find the associated value.
362        unsigned &TypeValue = CompletionTypes[CanUsageType];
363        if (TypeValue == 0) {
364          TypeValue = CompletionTypes.size();
365          CachedCompletionTypes[QualType(CanUsageType).getAsString()]
366            = TypeValue;
367        }
368
369        CachedResult.Type = TypeValue;
370      }
371
372      CachedCompletionResults.push_back(CachedResult);
373
374      /// Handle nested-name-specifiers in C++.
375      if (TheSema->Context.getLangOptions().CPlusPlus &&
376          IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
377        // The contexts in which a nested-name-specifier can appear in C++.
378        unsigned NNSContexts
379          = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
380          | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
381          | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
382          | (1 << (CodeCompletionContext::CCC_Statement - 1))
383          | (1 << (CodeCompletionContext::CCC_Expression - 1))
384          | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
385          | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
386          | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
387          | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
388          | (1 << (CodeCompletionContext::CCC_Type - 1))
389          | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
390          | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
391
392        if (isa<NamespaceDecl>(Results[I].Declaration) ||
393            isa<NamespaceAliasDecl>(Results[I].Declaration))
394          NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
395
396        if (unsigned RemainingContexts
397                                = NNSContexts & ~CachedResult.ShowInContexts) {
398          // If there any contexts where this completion can be a
399          // nested-name-specifier but isn't already an option, create a
400          // nested-name-specifier completion.
401          Results[I].StartsNestedNameSpecifier = true;
402          CachedResult.Completion
403            = Results[I].CreateCodeCompletionString(*TheSema,
404                                                    *CachedCompletionAllocator);
405          CachedResult.ShowInContexts = RemainingContexts;
406          CachedResult.Priority = CCP_NestedNameSpecifier;
407          CachedResult.TypeClass = STC_Void;
408          CachedResult.Type = 0;
409          CachedCompletionResults.push_back(CachedResult);
410        }
411      }
412      break;
413    }
414
415    case Result::RK_Keyword:
416    case Result::RK_Pattern:
417      // Ignore keywords and patterns; we don't care, since they are so
418      // easily regenerated.
419      break;
420
421    case Result::RK_Macro: {
422      CachedCodeCompletionResult CachedResult;
423      CachedResult.Completion
424        = Results[I].CreateCodeCompletionString(*TheSema,
425                                                *CachedCompletionAllocator);
426      CachedResult.ShowInContexts
427        = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
428        | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
429        | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
430        | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
431        | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
432        | (1 << (CodeCompletionContext::CCC_Statement - 1))
433        | (1 << (CodeCompletionContext::CCC_Expression - 1))
434        | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
435        | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
436        | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
437        | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
438        | (1 << (CodeCompletionContext::CCC_OtherWithMacros - 1));
439
440      CachedResult.Priority = Results[I].Priority;
441      CachedResult.Kind = Results[I].CursorKind;
442      CachedResult.Availability = Results[I].Availability;
443      CachedResult.TypeClass = STC_Void;
444      CachedResult.Type = 0;
445      CachedCompletionResults.push_back(CachedResult);
446      break;
447    }
448    }
449  }
450
451  // Save the current top-level hash value.
452  CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
453}
454
455void ASTUnit::ClearCachedCompletionResults() {
456  CachedCompletionResults.clear();
457  CachedCompletionTypes.clear();
458  CachedCompletionAllocator = 0;
459}
460
461namespace {
462
463/// \brief Gathers information from ASTReader that will be used to initialize
464/// a Preprocessor.
465class ASTInfoCollector : public ASTReaderListener {
466  Preprocessor &PP;
467  ASTContext &Context;
468  LangOptions &LangOpt;
469  HeaderSearch &HSI;
470  llvm::IntrusiveRefCntPtr<TargetInfo> &Target;
471  std::string &Predefines;
472  unsigned &Counter;
473
474  unsigned NumHeaderInfos;
475
476  bool InitializedLanguage;
477public:
478  ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
479                   HeaderSearch &HSI,
480                   llvm::IntrusiveRefCntPtr<TargetInfo> &Target,
481                   std::string &Predefines,
482                   unsigned &Counter)
483    : PP(PP), Context(Context), LangOpt(LangOpt), HSI(HSI), Target(Target),
484      Predefines(Predefines), Counter(Counter), NumHeaderInfos(0),
485      InitializedLanguage(false) {}
486
487  virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
488    if (InitializedLanguage)
489      return false;
490
491    LangOpt = LangOpts;
492
493    // Initialize the preprocessor.
494    PP.Initialize(*Target);
495
496    // Initialize the ASTContext
497    Context.InitBuiltinTypes(*Target);
498
499    InitializedLanguage = true;
500    return false;
501  }
502
503  virtual bool ReadTargetTriple(StringRef Triple) {
504    // If we've already initialized the target, don't do it again.
505    if (Target)
506      return false;
507
508    // FIXME: This is broken, we should store the TargetOptions in the AST file.
509    TargetOptions TargetOpts;
510    TargetOpts.ABI = "";
511    TargetOpts.CXXABI = "";
512    TargetOpts.CPU = "";
513    TargetOpts.Features.clear();
514    TargetOpts.Triple = Triple;
515    Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(), TargetOpts);
516    return false;
517  }
518
519  virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
520                                    StringRef OriginalFileName,
521                                    std::string &SuggestedPredefines,
522                                    FileManager &FileMgr) {
523    Predefines = Buffers[0].Data;
524    for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
525      Predefines += Buffers[I].Data;
526    }
527    return false;
528  }
529
530  virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
531    HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
532  }
533
534  virtual void ReadCounter(unsigned Value) {
535    Counter = Value;
536  }
537};
538
539class StoredDiagnosticConsumer : public DiagnosticConsumer {
540  SmallVectorImpl<StoredDiagnostic> &StoredDiags;
541
542public:
543  explicit StoredDiagnosticConsumer(
544                          SmallVectorImpl<StoredDiagnostic> &StoredDiags)
545    : StoredDiags(StoredDiags) { }
546
547  virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
548                                const Diagnostic &Info);
549
550  DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
551    // Just drop any diagnostics that come from cloned consumers; they'll
552    // have different source managers anyway.
553    return new IgnoringDiagConsumer();
554  }
555};
556
557/// \brief RAII object that optionally captures diagnostics, if
558/// there is no diagnostic client to capture them already.
559class CaptureDroppedDiagnostics {
560  DiagnosticsEngine &Diags;
561  StoredDiagnosticConsumer Client;
562  DiagnosticConsumer *PreviousClient;
563
564public:
565  CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
566                          SmallVectorImpl<StoredDiagnostic> &StoredDiags)
567    : Diags(Diags), Client(StoredDiags), PreviousClient(0)
568  {
569    if (RequestCapture || Diags.getClient() == 0) {
570      PreviousClient = Diags.takeClient();
571      Diags.setClient(&Client);
572    }
573  }
574
575  ~CaptureDroppedDiagnostics() {
576    if (Diags.getClient() == &Client) {
577      Diags.takeClient();
578      Diags.setClient(PreviousClient);
579    }
580  }
581};
582
583} // anonymous namespace
584
585void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
586                                              const Diagnostic &Info) {
587  // Default implementation (Warnings/errors count).
588  DiagnosticConsumer::HandleDiagnostic(Level, Info);
589
590  StoredDiags.push_back(StoredDiagnostic(Level, Info));
591}
592
593const std::string &ASTUnit::getOriginalSourceFileName() {
594  return OriginalSourceFile;
595}
596
597llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
598                                              std::string *ErrorStr) {
599  assert(FileMgr);
600  return FileMgr->getBufferForFile(Filename, ErrorStr);
601}
602
603/// \brief Configure the diagnostics object for use with ASTUnit.
604void ASTUnit::ConfigureDiags(llvm::IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
605                             const char **ArgBegin, const char **ArgEnd,
606                             ASTUnit &AST, bool CaptureDiagnostics) {
607  if (!Diags.getPtr()) {
608    // No diagnostics engine was provided, so create our own diagnostics object
609    // with the default options.
610    DiagnosticOptions DiagOpts;
611    DiagnosticConsumer *Client = 0;
612    if (CaptureDiagnostics)
613      Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
614    Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd- ArgBegin,
615                                                ArgBegin, Client);
616  } else if (CaptureDiagnostics) {
617    Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
618  }
619}
620
621ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
622                              llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
623                                  const FileSystemOptions &FileSystemOpts,
624                                  bool OnlyLocalDecls,
625                                  RemappedFile *RemappedFiles,
626                                  unsigned NumRemappedFiles,
627                                  bool CaptureDiagnostics) {
628  llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
629
630  // Recover resources if we crash before exiting this method.
631  llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
632    ASTUnitCleanup(AST.get());
633  llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
634    llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
635    DiagCleanup(Diags.getPtr());
636
637  ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
638
639  AST->OnlyLocalDecls = OnlyLocalDecls;
640  AST->CaptureDiagnostics = CaptureDiagnostics;
641  AST->Diagnostics = Diags;
642  AST->FileMgr = new FileManager(FileSystemOpts);
643  AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
644                                     AST->getFileManager());
645  AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
646
647  for (unsigned I = 0; I != NumRemappedFiles; ++I) {
648    FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
649    if (const llvm::MemoryBuffer *
650          memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
651      // Create the file entry for the file that we're mapping from.
652      const FileEntry *FromFile
653        = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
654                                               memBuf->getBufferSize(),
655                                               0);
656      if (!FromFile) {
657        AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
658          << RemappedFiles[I].first;
659        delete memBuf;
660        continue;
661      }
662
663      // Override the contents of the "from" file with the contents of
664      // the "to" file.
665      AST->getSourceManager().overrideFileContents(FromFile, memBuf);
666
667    } else {
668      const char *fname = fileOrBuf.get<const char *>();
669      const FileEntry *ToFile = AST->FileMgr->getFile(fname);
670      if (!ToFile) {
671        AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
672        << RemappedFiles[I].first << fname;
673        continue;
674      }
675
676      // Create the file entry for the file that we're mapping from.
677      const FileEntry *FromFile
678        = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
679                                               ToFile->getSize(),
680                                               0);
681      if (!FromFile) {
682        AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
683          << RemappedFiles[I].first;
684        delete memBuf;
685        continue;
686      }
687
688      // Override the contents of the "from" file with the contents of
689      // the "to" file.
690      AST->getSourceManager().overrideFileContents(FromFile, ToFile);
691    }
692  }
693
694  // Gather Info for preprocessor construction later on.
695
696  HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
697  std::string Predefines;
698  unsigned Counter;
699
700  llvm::OwningPtr<ASTReader> Reader;
701
702  AST->PP = new Preprocessor(AST->getDiagnostics(), AST->ASTFileLangOpts,
703                             /*Target=*/0, AST->getSourceManager(), HeaderInfo,
704                             *AST,
705                             /*IILookup=*/0,
706                             /*OwnsHeaderSearch=*/false,
707                             /*DelayInitialization=*/true);
708  Preprocessor &PP = *AST->PP;
709
710  AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
711                            AST->getSourceManager(),
712                            /*Target=*/0,
713                            PP.getIdentifierTable(),
714                            PP.getSelectorTable(),
715                            PP.getBuiltinInfo(),
716                            /* size_reserve = */0,
717                            /*DelayInitialization=*/true);
718  ASTContext &Context = *AST->Ctx;
719
720  Reader.reset(new ASTReader(PP, Context));
721
722  // Recover resources if we crash before exiting this method.
723  llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
724    ReaderCleanup(Reader.get());
725
726  Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
727                                           AST->ASTFileLangOpts, HeaderInfo,
728                                           AST->Target, Predefines, Counter));
729
730  switch (Reader->ReadAST(Filename, serialization::MK_MainFile)) {
731  case ASTReader::Success:
732    break;
733
734  case ASTReader::Failure:
735  case ASTReader::IgnorePCH:
736    AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
737    return NULL;
738  }
739
740  AST->OriginalSourceFile = Reader->getOriginalSourceFile();
741
742  PP.setPredefines(Reader->getSuggestedPredefines());
743  PP.setCounterValue(Counter);
744
745  // Attach the AST reader to the AST context as an external AST
746  // source, so that declarations will be deserialized from the
747  // AST file as needed.
748  ASTReader *ReaderPtr = Reader.get();
749  llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
750
751  // Unregister the cleanup for ASTReader.  It will get cleaned up
752  // by the ASTUnit cleanup.
753  ReaderCleanup.unregister();
754
755  Context.setExternalSource(Source);
756
757  // Create an AST consumer, even though it isn't used.
758  AST->Consumer.reset(new ASTConsumer);
759
760  // Create a semantic analysis object and tell the AST reader about it.
761  AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
762  AST->TheSema->Initialize();
763  ReaderPtr->InitializeSema(*AST->TheSema);
764
765  return AST.take();
766}
767
768namespace {
769
770/// \brief Preprocessor callback class that updates a hash value with the names
771/// of all macros that have been defined by the translation unit.
772class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
773  unsigned &Hash;
774
775public:
776  explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
777
778  virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
779    Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
780  }
781};
782
783/// \brief Add the given declaration to the hash of all top-level entities.
784void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
785  if (!D)
786    return;
787
788  DeclContext *DC = D->getDeclContext();
789  if (!DC)
790    return;
791
792  if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
793    return;
794
795  if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
796    if (ND->getIdentifier())
797      Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
798    else if (DeclarationName Name = ND->getDeclName()) {
799      std::string NameStr = Name.getAsString();
800      Hash = llvm::HashString(NameStr, Hash);
801    }
802    return;
803  }
804
805  if (ObjCForwardProtocolDecl *Forward
806      = dyn_cast<ObjCForwardProtocolDecl>(D)) {
807    for (ObjCForwardProtocolDecl::protocol_iterator
808         P = Forward->protocol_begin(),
809         PEnd = Forward->protocol_end();
810         P != PEnd; ++P)
811      AddTopLevelDeclarationToHash(*P, Hash);
812    return;
813  }
814
815  if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(D)) {
816    AddTopLevelDeclarationToHash(Class->getForwardInterfaceDecl(), Hash);
817    return;
818  }
819}
820
821class TopLevelDeclTrackerConsumer : public ASTConsumer {
822  ASTUnit &Unit;
823  unsigned &Hash;
824
825public:
826  TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
827    : Unit(_Unit), Hash(Hash) {
828    Hash = 0;
829  }
830
831  void HandleTopLevelDecl(DeclGroupRef D) {
832    for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
833      Decl *D = *it;
834      // FIXME: Currently ObjC method declarations are incorrectly being
835      // reported as top-level declarations, even though their DeclContext
836      // is the containing ObjC @interface/@implementation.  This is a
837      // fundamental problem in the parser right now.
838      if (isa<ObjCMethodDecl>(D))
839        continue;
840
841      AddTopLevelDeclarationToHash(D, Hash);
842      Unit.addTopLevelDecl(D);
843    }
844  }
845
846  // We're not interested in "interesting" decls.
847  void HandleInterestingDecl(DeclGroupRef) {}
848};
849
850class TopLevelDeclTrackerAction : public ASTFrontendAction {
851public:
852  ASTUnit &Unit;
853
854  virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
855                                         StringRef InFile) {
856    CI.getPreprocessor().addPPCallbacks(
857     new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
858    return new TopLevelDeclTrackerConsumer(Unit,
859                                           Unit.getCurrentTopLevelHashValue());
860  }
861
862public:
863  TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
864
865  virtual bool hasCodeCompletionSupport() const { return false; }
866  virtual TranslationUnitKind getTranslationUnitKind()  {
867    return Unit.getTranslationUnitKind();
868  }
869};
870
871class PrecompilePreambleConsumer : public PCHGenerator {
872  ASTUnit &Unit;
873  unsigned &Hash;
874  std::vector<Decl *> TopLevelDecls;
875
876public:
877  PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
878                             StringRef isysroot, raw_ostream *Out)
879    : PCHGenerator(PP, "", /*IsModule=*/false, isysroot, Out), Unit(Unit),
880      Hash(Unit.getCurrentTopLevelHashValue()) {
881    Hash = 0;
882  }
883
884  virtual void HandleTopLevelDecl(DeclGroupRef D) {
885    for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
886      Decl *D = *it;
887      // FIXME: Currently ObjC method declarations are incorrectly being
888      // reported as top-level declarations, even though their DeclContext
889      // is the containing ObjC @interface/@implementation.  This is a
890      // fundamental problem in the parser right now.
891      if (isa<ObjCMethodDecl>(D))
892        continue;
893      AddTopLevelDeclarationToHash(D, Hash);
894      TopLevelDecls.push_back(D);
895    }
896  }
897
898  virtual void HandleTranslationUnit(ASTContext &Ctx) {
899    PCHGenerator::HandleTranslationUnit(Ctx);
900    if (!Unit.getDiagnostics().hasErrorOccurred()) {
901      // Translate the top-level declarations we captured during
902      // parsing into declaration IDs in the precompiled
903      // preamble. This will allow us to deserialize those top-level
904      // declarations when requested.
905      for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
906        Unit.addTopLevelDeclFromPreamble(
907                                      getWriter().getDeclID(TopLevelDecls[I]));
908    }
909  }
910};
911
912class PrecompilePreambleAction : public ASTFrontendAction {
913  ASTUnit &Unit;
914
915public:
916  explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
917
918  virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
919                                         StringRef InFile) {
920    std::string Sysroot;
921    std::string OutputFile;
922    raw_ostream *OS = 0;
923    if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
924                                                       OutputFile,
925                                                       OS))
926      return 0;
927
928    if (!CI.getFrontendOpts().RelocatablePCH)
929      Sysroot.clear();
930
931    CI.getPreprocessor().addPPCallbacks(
932     new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
933    return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
934                                          OS);
935  }
936
937  virtual bool hasCodeCompletionSupport() const { return false; }
938  virtual bool hasASTFileSupport() const { return false; }
939  virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
940};
941
942}
943
944/// Parse the source file into a translation unit using the given compiler
945/// invocation, replacing the current translation unit.
946///
947/// \returns True if a failure occurred that causes the ASTUnit not to
948/// contain any translation-unit information, false otherwise.
949bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
950  delete SavedMainFileBuffer;
951  SavedMainFileBuffer = 0;
952
953  if (!Invocation) {
954    delete OverrideMainBuffer;
955    return true;
956  }
957
958  // Create the compiler instance to use for building the AST.
959  llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
960
961  // Recover resources if we crash before exiting this method.
962  llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
963    CICleanup(Clang.get());
964
965  llvm::IntrusiveRefCntPtr<CompilerInvocation>
966    CCInvocation(new CompilerInvocation(*Invocation));
967
968  Clang->setInvocation(CCInvocation.getPtr());
969  OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
970
971  // Set up diagnostics, capturing any diagnostics that would
972  // otherwise be dropped.
973  Clang->setDiagnostics(&getDiagnostics());
974
975  // Create the target instance.
976  Clang->getTargetOpts().Features = TargetFeatures;
977  Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
978                   Clang->getTargetOpts()));
979  if (!Clang->hasTarget()) {
980    delete OverrideMainBuffer;
981    return true;
982  }
983
984  // Inform the target of the language options.
985  //
986  // FIXME: We shouldn't need to do this, the target should be immutable once
987  // created. This complexity should be lifted elsewhere.
988  Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
989
990  assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
991         "Invocation must have exactly one source file!");
992  assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
993         "FIXME: AST inputs not yet supported here!");
994  assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
995         "IR inputs not support here!");
996
997  // Configure the various subsystems.
998  // FIXME: Should we retain the previous file manager?
999  FileSystemOpts = Clang->getFileSystemOpts();
1000  FileMgr = new FileManager(FileSystemOpts);
1001  SourceMgr = new SourceManager(getDiagnostics(), *FileMgr);
1002  TheSema.reset();
1003  Ctx = 0;
1004  PP = 0;
1005
1006  // Clear out old caches and data.
1007  TopLevelDecls.clear();
1008  CleanTemporaryFiles();
1009
1010  if (!OverrideMainBuffer) {
1011    StoredDiagnostics.erase(stored_diag_afterDriver_begin(), stored_diag_end());
1012    TopLevelDeclsInPreamble.clear();
1013  }
1014
1015  // Create a file manager object to provide access to and cache the filesystem.
1016  Clang->setFileManager(&getFileManager());
1017
1018  // Create the source manager.
1019  Clang->setSourceManager(&getSourceManager());
1020
1021  // If the main file has been overridden due to the use of a preamble,
1022  // make that override happen and introduce the preamble.
1023  PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
1024  PreprocessorOpts.DetailedRecordIncludesNestedMacroExpansions
1025    = NestedMacroExpansions;
1026  if (OverrideMainBuffer) {
1027    PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1028    PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1029    PreprocessorOpts.PrecompiledPreambleBytes.second
1030                                                    = PreambleEndsAtStartOfLine;
1031    PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
1032    PreprocessorOpts.DisablePCHValidation = true;
1033
1034    // The stored diagnostic has the old source manager in it; update
1035    // the locations to refer into the new source manager. Since we've
1036    // been careful to make sure that the source manager's state
1037    // before and after are identical, so that we can reuse the source
1038    // location itself.
1039    for (unsigned I = NumStoredDiagnosticsFromDriver,
1040                  N = StoredDiagnostics.size();
1041         I < N; ++I) {
1042      FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
1043                        getSourceManager());
1044      StoredDiagnostics[I].setLocation(Loc);
1045    }
1046
1047    // Keep track of the override buffer;
1048    SavedMainFileBuffer = OverrideMainBuffer;
1049  }
1050
1051  llvm::OwningPtr<TopLevelDeclTrackerAction> Act(
1052    new TopLevelDeclTrackerAction(*this));
1053
1054  // Recover resources if we crash before exiting this method.
1055  llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1056    ActCleanup(Act.get());
1057
1058  if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
1059                            Clang->getFrontendOpts().Inputs[0].first))
1060    goto error;
1061
1062  if (OverrideMainBuffer) {
1063    std::string ModName = getPreambleFile(this);
1064    TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1065                               getSourceManager(), PreambleDiagnostics,
1066                               StoredDiagnostics);
1067  }
1068
1069  Act->Execute();
1070
1071  // Steal the created target, context, and preprocessor.
1072  TheSema.reset(Clang->takeSema());
1073  Consumer.reset(Clang->takeASTConsumer());
1074  Ctx = &Clang->getASTContext();
1075  PP = &Clang->getPreprocessor();
1076  Clang->setSourceManager(0);
1077  Clang->setFileManager(0);
1078  Target = &Clang->getTarget();
1079
1080  Act->EndSourceFile();
1081
1082  return false;
1083
1084error:
1085  // Remove the overridden buffer we used for the preamble.
1086  if (OverrideMainBuffer) {
1087    delete OverrideMainBuffer;
1088    SavedMainFileBuffer = 0;
1089  }
1090
1091  StoredDiagnostics.clear();
1092  NumStoredDiagnosticsFromDriver = 0;
1093  return true;
1094}
1095
1096/// \brief Simple function to retrieve a path for a preamble precompiled header.
1097static std::string GetPreamblePCHPath() {
1098  // FIXME: This is lame; sys::Path should provide this function (in particular,
1099  // it should know how to find the temporary files dir).
1100  // FIXME: This is really lame. I copied this code from the Driver!
1101  // FIXME: This is a hack so that we can override the preamble file during
1102  // crash-recovery testing, which is the only case where the preamble files
1103  // are not necessarily cleaned up.
1104  const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1105  if (TmpFile)
1106    return TmpFile;
1107
1108  std::string Error;
1109  const char *TmpDir = ::getenv("TMPDIR");
1110  if (!TmpDir)
1111    TmpDir = ::getenv("TEMP");
1112  if (!TmpDir)
1113    TmpDir = ::getenv("TMP");
1114#ifdef LLVM_ON_WIN32
1115  if (!TmpDir)
1116    TmpDir = ::getenv("USERPROFILE");
1117#endif
1118  if (!TmpDir)
1119    TmpDir = "/tmp";
1120  llvm::sys::Path P(TmpDir);
1121  P.createDirectoryOnDisk(true);
1122  P.appendComponent("preamble");
1123  P.appendSuffix("pch");
1124  if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
1125    return std::string();
1126
1127  return P.str();
1128}
1129
1130/// \brief Compute the preamble for the main file, providing the source buffer
1131/// that corresponds to the main file along with a pair (bytes, start-of-line)
1132/// that describes the preamble.
1133std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
1134ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1135                         unsigned MaxLines, bool &CreatedBuffer) {
1136  FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
1137  PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
1138  CreatedBuffer = false;
1139
1140  // Try to determine if the main file has been remapped, either from the
1141  // command line (to another file) or directly through the compiler invocation
1142  // (to a memory buffer).
1143  llvm::MemoryBuffer *Buffer = 0;
1144  llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
1145  if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1146    // Check whether there is a file-file remapping of the main file
1147    for (PreprocessorOptions::remapped_file_iterator
1148          M = PreprocessorOpts.remapped_file_begin(),
1149          E = PreprocessorOpts.remapped_file_end();
1150         M != E;
1151         ++M) {
1152      llvm::sys::PathWithStatus MPath(M->first);
1153      if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1154        if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1155          // We found a remapping. Try to load the resulting, remapped source.
1156          if (CreatedBuffer) {
1157            delete Buffer;
1158            CreatedBuffer = false;
1159          }
1160
1161          Buffer = getBufferForFile(M->second);
1162          if (!Buffer)
1163            return std::make_pair((llvm::MemoryBuffer*)0,
1164                                  std::make_pair(0, true));
1165          CreatedBuffer = true;
1166        }
1167      }
1168    }
1169
1170    // Check whether there is a file-buffer remapping. It supercedes the
1171    // file-file remapping.
1172    for (PreprocessorOptions::remapped_file_buffer_iterator
1173           M = PreprocessorOpts.remapped_file_buffer_begin(),
1174           E = PreprocessorOpts.remapped_file_buffer_end();
1175         M != E;
1176         ++M) {
1177      llvm::sys::PathWithStatus MPath(M->first);
1178      if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1179        if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1180          // We found a remapping.
1181          if (CreatedBuffer) {
1182            delete Buffer;
1183            CreatedBuffer = false;
1184          }
1185
1186          Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
1187        }
1188      }
1189    }
1190  }
1191
1192  // If the main source file was not remapped, load it now.
1193  if (!Buffer) {
1194    Buffer = getBufferForFile(FrontendOpts.Inputs[0].second);
1195    if (!Buffer)
1196      return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
1197
1198    CreatedBuffer = true;
1199  }
1200
1201  return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
1202                                                       Invocation.getLangOpts(),
1203                                                       MaxLines));
1204}
1205
1206static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
1207                                                      unsigned NewSize,
1208                                                      StringRef NewName) {
1209  llvm::MemoryBuffer *Result
1210    = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1211  memcpy(const_cast<char*>(Result->getBufferStart()),
1212         Old->getBufferStart(), Old->getBufferSize());
1213  memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
1214         ' ', NewSize - Old->getBufferSize() - 1);
1215  const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
1216
1217  return Result;
1218}
1219
1220/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1221/// the source file.
1222///
1223/// This routine will compute the preamble of the main source file. If a
1224/// non-trivial preamble is found, it will precompile that preamble into a
1225/// precompiled header so that the precompiled preamble can be used to reduce
1226/// reparsing time. If a precompiled preamble has already been constructed,
1227/// this routine will determine if it is still valid and, if so, avoid
1228/// rebuilding the precompiled preamble.
1229///
1230/// \param AllowRebuild When true (the default), this routine is
1231/// allowed to rebuild the precompiled preamble if it is found to be
1232/// out-of-date.
1233///
1234/// \param MaxLines When non-zero, the maximum number of lines that
1235/// can occur within the preamble.
1236///
1237/// \returns If the precompiled preamble can be used, returns a newly-allocated
1238/// buffer that should be used in place of the main file when doing so.
1239/// Otherwise, returns a NULL pointer.
1240llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
1241                              const CompilerInvocation &PreambleInvocationIn,
1242                                                           bool AllowRebuild,
1243                                                           unsigned MaxLines) {
1244
1245  llvm::IntrusiveRefCntPtr<CompilerInvocation>
1246    PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1247  FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
1248  PreprocessorOptions &PreprocessorOpts
1249    = PreambleInvocation->getPreprocessorOpts();
1250
1251  bool CreatedPreambleBuffer = false;
1252  std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
1253    = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
1254
1255  // If ComputePreamble() Take ownership of the preamble buffer.
1256  llvm::OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
1257  if (CreatedPreambleBuffer)
1258    OwnedPreambleBuffer.reset(NewPreamble.first);
1259
1260  if (!NewPreamble.second.first) {
1261    // We couldn't find a preamble in the main source. Clear out the current
1262    // preamble, if we have one. It's obviously no good any more.
1263    Preamble.clear();
1264    erasePreambleFile(this);
1265
1266    // The next time we actually see a preamble, precompile it.
1267    PreambleRebuildCounter = 1;
1268    return 0;
1269  }
1270
1271  if (!Preamble.empty()) {
1272    // We've previously computed a preamble. Check whether we have the same
1273    // preamble now that we did before, and that there's enough space in
1274    // the main-file buffer within the precompiled preamble to fit the
1275    // new main file.
1276    if (Preamble.size() == NewPreamble.second.first &&
1277        PreambleEndsAtStartOfLine == NewPreamble.second.second &&
1278        NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
1279        memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
1280               NewPreamble.second.first) == 0) {
1281      // The preamble has not changed. We may be able to re-use the precompiled
1282      // preamble.
1283
1284      // Check that none of the files used by the preamble have changed.
1285      bool AnyFileChanged = false;
1286
1287      // First, make a record of those files that have been overridden via
1288      // remapping or unsaved_files.
1289      llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1290      for (PreprocessorOptions::remapped_file_iterator
1291                R = PreprocessorOpts.remapped_file_begin(),
1292             REnd = PreprocessorOpts.remapped_file_end();
1293           !AnyFileChanged && R != REnd;
1294           ++R) {
1295        struct stat StatBuf;
1296        if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
1297          // If we can't stat the file we're remapping to, assume that something
1298          // horrible happened.
1299          AnyFileChanged = true;
1300          break;
1301        }
1302
1303        OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1304                                                   StatBuf.st_mtime);
1305      }
1306      for (PreprocessorOptions::remapped_file_buffer_iterator
1307                R = PreprocessorOpts.remapped_file_buffer_begin(),
1308             REnd = PreprocessorOpts.remapped_file_buffer_end();
1309           !AnyFileChanged && R != REnd;
1310           ++R) {
1311        // FIXME: Should we actually compare the contents of file->buffer
1312        // remappings?
1313        OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1314                                                   0);
1315      }
1316
1317      // Check whether anything has changed.
1318      for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1319             F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1320           !AnyFileChanged && F != FEnd;
1321           ++F) {
1322        llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1323          = OverriddenFiles.find(F->first());
1324        if (Overridden != OverriddenFiles.end()) {
1325          // This file was remapped; check whether the newly-mapped file
1326          // matches up with the previous mapping.
1327          if (Overridden->second != F->second)
1328            AnyFileChanged = true;
1329          continue;
1330        }
1331
1332        // The file was not remapped; check whether it has changed on disk.
1333        struct stat StatBuf;
1334        if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
1335          // If we can't stat the file, assume that something horrible happened.
1336          AnyFileChanged = true;
1337        } else if (StatBuf.st_size != F->second.first ||
1338                   StatBuf.st_mtime != F->second.second)
1339          AnyFileChanged = true;
1340      }
1341
1342      if (!AnyFileChanged) {
1343        // Okay! We can re-use the precompiled preamble.
1344
1345        // Set the state of the diagnostic object to mimic its state
1346        // after parsing the preamble.
1347        // FIXME: This won't catch any #pragma push warning changes that
1348        // have occurred in the preamble.
1349        getDiagnostics().Reset();
1350        ProcessWarningOptions(getDiagnostics(),
1351                              PreambleInvocation->getDiagnosticOpts());
1352        getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1353
1354        // Create a version of the main file buffer that is padded to
1355        // buffer size we reserved when creating the preamble.
1356        return CreatePaddedMainFileBuffer(NewPreamble.first,
1357                                          PreambleReservedSize,
1358                                          FrontendOpts.Inputs[0].second);
1359      }
1360    }
1361
1362    // If we aren't allowed to rebuild the precompiled preamble, just
1363    // return now.
1364    if (!AllowRebuild)
1365      return 0;
1366
1367    // We can't reuse the previously-computed preamble. Build a new one.
1368    Preamble.clear();
1369    PreambleDiagnostics.clear();
1370    erasePreambleFile(this);
1371    PreambleRebuildCounter = 1;
1372  } else if (!AllowRebuild) {
1373    // We aren't allowed to rebuild the precompiled preamble; just
1374    // return now.
1375    return 0;
1376  }
1377
1378  // If the preamble rebuild counter > 1, it's because we previously
1379  // failed to build a preamble and we're not yet ready to try
1380  // again. Decrement the counter and return a failure.
1381  if (PreambleRebuildCounter > 1) {
1382    --PreambleRebuildCounter;
1383    return 0;
1384  }
1385
1386  // Create a temporary file for the precompiled preamble. In rare
1387  // circumstances, this can fail.
1388  std::string PreamblePCHPath = GetPreamblePCHPath();
1389  if (PreamblePCHPath.empty()) {
1390    // Try again next time.
1391    PreambleRebuildCounter = 1;
1392    return 0;
1393  }
1394
1395  // We did not previously compute a preamble, or it can't be reused anyway.
1396  SimpleTimer PreambleTimer(WantTiming);
1397  PreambleTimer.setOutput("Precompiling preamble");
1398
1399  // Create a new buffer that stores the preamble. The buffer also contains
1400  // extra space for the original contents of the file (which will be present
1401  // when we actually parse the file) along with more room in case the file
1402  // grows.
1403  PreambleReservedSize = NewPreamble.first->getBufferSize();
1404  if (PreambleReservedSize < 4096)
1405    PreambleReservedSize = 8191;
1406  else
1407    PreambleReservedSize *= 2;
1408
1409  // Save the preamble text for later; we'll need to compare against it for
1410  // subsequent reparses.
1411  StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].second;
1412  Preamble.assign(FileMgr->getFile(MainFilename),
1413                  NewPreamble.first->getBufferStart(),
1414                  NewPreamble.first->getBufferStart()
1415                                                  + NewPreamble.second.first);
1416  PreambleEndsAtStartOfLine = NewPreamble.second.second;
1417
1418  delete PreambleBuffer;
1419  PreambleBuffer
1420    = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
1421                                                FrontendOpts.Inputs[0].second);
1422  memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
1423         NewPreamble.first->getBufferStart(), Preamble.size());
1424  memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
1425         ' ', PreambleReservedSize - Preamble.size() - 1);
1426  const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
1427
1428  // Remap the main source file to the preamble buffer.
1429  llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
1430  PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1431
1432  // Tell the compiler invocation to generate a temporary precompiled header.
1433  FrontendOpts.ProgramAction = frontend::GeneratePCH;
1434  // FIXME: Generate the precompiled header into memory?
1435  FrontendOpts.OutputFile = PreamblePCHPath;
1436  PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1437  PreprocessorOpts.PrecompiledPreambleBytes.second = false;
1438
1439  // Create the compiler instance to use for building the precompiled preamble.
1440  llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1441
1442  // Recover resources if we crash before exiting this method.
1443  llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1444    CICleanup(Clang.get());
1445
1446  Clang->setInvocation(&*PreambleInvocation);
1447  OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
1448
1449  // Set up diagnostics, capturing all of the diagnostics produced.
1450  Clang->setDiagnostics(&getDiagnostics());
1451
1452  // Create the target instance.
1453  Clang->getTargetOpts().Features = TargetFeatures;
1454  Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1455                                               Clang->getTargetOpts()));
1456  if (!Clang->hasTarget()) {
1457    llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1458    Preamble.clear();
1459    PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1460    PreprocessorOpts.eraseRemappedFile(
1461                               PreprocessorOpts.remapped_file_buffer_end() - 1);
1462    return 0;
1463  }
1464
1465  // Inform the target of the language options.
1466  //
1467  // FIXME: We shouldn't need to do this, the target should be immutable once
1468  // created. This complexity should be lifted elsewhere.
1469  Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1470
1471  assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1472         "Invocation must have exactly one source file!");
1473  assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
1474         "FIXME: AST inputs not yet supported here!");
1475  assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1476         "IR inputs not support here!");
1477
1478  // Clear out old caches and data.
1479  getDiagnostics().Reset();
1480  ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
1481  StoredDiagnostics.erase(stored_diag_afterDriver_begin(), stored_diag_end());
1482  TopLevelDecls.clear();
1483  TopLevelDeclsInPreamble.clear();
1484
1485  // Create a file manager object to provide access to and cache the filesystem.
1486  Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
1487
1488  // Create the source manager.
1489  Clang->setSourceManager(new SourceManager(getDiagnostics(),
1490                                            Clang->getFileManager()));
1491
1492  llvm::OwningPtr<PrecompilePreambleAction> Act;
1493  Act.reset(new PrecompilePreambleAction(*this));
1494  if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
1495                            Clang->getFrontendOpts().Inputs[0].first)) {
1496    llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1497    Preamble.clear();
1498    PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1499    PreprocessorOpts.eraseRemappedFile(
1500                               PreprocessorOpts.remapped_file_buffer_end() - 1);
1501    return 0;
1502  }
1503
1504  Act->Execute();
1505  Act->EndSourceFile();
1506
1507  if (Diagnostics->hasErrorOccurred()) {
1508    // There were errors parsing the preamble, so no precompiled header was
1509    // generated. Forget that we even tried.
1510    // FIXME: Should we leave a note for ourselves to try again?
1511    llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1512    Preamble.clear();
1513    TopLevelDeclsInPreamble.clear();
1514    PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1515    PreprocessorOpts.eraseRemappedFile(
1516                               PreprocessorOpts.remapped_file_buffer_end() - 1);
1517    return 0;
1518  }
1519
1520  // Transfer any diagnostics generated when parsing the preamble into the set
1521  // of preamble diagnostics.
1522  PreambleDiagnostics.clear();
1523  PreambleDiagnostics.insert(PreambleDiagnostics.end(),
1524                            stored_diag_afterDriver_begin(), stored_diag_end());
1525  StoredDiagnostics.erase(stored_diag_afterDriver_begin(), stored_diag_end());
1526
1527  // Keep track of the preamble we precompiled.
1528  setPreambleFile(this, FrontendOpts.OutputFile);
1529  NumWarningsInPreamble = getDiagnostics().getNumWarnings();
1530
1531  // Keep track of all of the files that the source manager knows about,
1532  // so we can verify whether they have changed or not.
1533  FilesInPreamble.clear();
1534  SourceManager &SourceMgr = Clang->getSourceManager();
1535  const llvm::MemoryBuffer *MainFileBuffer
1536    = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1537  for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1538                                     FEnd = SourceMgr.fileinfo_end();
1539       F != FEnd;
1540       ++F) {
1541    const FileEntry *File = F->second->OrigEntry;
1542    if (!File || F->second->getRawBuffer() == MainFileBuffer)
1543      continue;
1544
1545    FilesInPreamble[File->getName()]
1546      = std::make_pair(F->second->getSize(), File->getModificationTime());
1547  }
1548
1549  PreambleRebuildCounter = 1;
1550  PreprocessorOpts.eraseRemappedFile(
1551                               PreprocessorOpts.remapped_file_buffer_end() - 1);
1552
1553  // If the hash of top-level entities differs from the hash of the top-level
1554  // entities the last time we rebuilt the preamble, clear out the completion
1555  // cache.
1556  if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1557    CompletionCacheTopLevelHashValue = 0;
1558    PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1559  }
1560
1561  return CreatePaddedMainFileBuffer(NewPreamble.first,
1562                                    PreambleReservedSize,
1563                                    FrontendOpts.Inputs[0].second);
1564}
1565
1566void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1567  std::vector<Decl *> Resolved;
1568  Resolved.reserve(TopLevelDeclsInPreamble.size());
1569  ExternalASTSource &Source = *getASTContext().getExternalSource();
1570  for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1571    // Resolve the declaration ID to an actual declaration, possibly
1572    // deserializing the declaration in the process.
1573    Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1574    if (D)
1575      Resolved.push_back(D);
1576  }
1577  TopLevelDeclsInPreamble.clear();
1578  TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1579}
1580
1581StringRef ASTUnit::getMainFileName() const {
1582  return Invocation->getFrontendOpts().Inputs[0].second;
1583}
1584
1585ASTUnit *ASTUnit::create(CompilerInvocation *CI,
1586                         llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags) {
1587  llvm::OwningPtr<ASTUnit> AST;
1588  AST.reset(new ASTUnit(false));
1589  ConfigureDiags(Diags, 0, 0, *AST, /*CaptureDiagnostics=*/false);
1590  AST->Diagnostics = Diags;
1591  AST->Invocation = CI;
1592  AST->FileSystemOpts = CI->getFileSystemOpts();
1593  AST->FileMgr = new FileManager(AST->FileSystemOpts);
1594  AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr);
1595
1596  return AST.take();
1597}
1598
1599ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
1600                              llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1601                                             ASTFrontendAction *Action,
1602                                             ASTUnit *Unit) {
1603  assert(CI && "A CompilerInvocation is required");
1604
1605  llvm::OwningPtr<ASTUnit> OwnAST;
1606  ASTUnit *AST = Unit;
1607  if (!AST) {
1608    // Create the AST unit.
1609    OwnAST.reset(create(CI, Diags));
1610    AST = OwnAST.get();
1611  }
1612
1613  AST->OnlyLocalDecls = false;
1614  AST->CaptureDiagnostics = false;
1615  AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
1616  AST->ShouldCacheCodeCompletionResults = false;
1617
1618  // Recover resources if we crash before exiting this method.
1619  llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1620    ASTUnitCleanup(OwnAST.get());
1621  llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1622    llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1623    DiagCleanup(Diags.getPtr());
1624
1625  // We'll manage file buffers ourselves.
1626  CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1627  CI->getFrontendOpts().DisableFree = false;
1628  ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1629
1630  // Save the target features.
1631  AST->TargetFeatures = CI->getTargetOpts().Features;
1632
1633  // Create the compiler instance to use for building the AST.
1634  llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1635
1636  // Recover resources if we crash before exiting this method.
1637  llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1638    CICleanup(Clang.get());
1639
1640  Clang->setInvocation(CI);
1641  AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
1642
1643  // Set up diagnostics, capturing any diagnostics that would
1644  // otherwise be dropped.
1645  Clang->setDiagnostics(&AST->getDiagnostics());
1646
1647  // Create the target instance.
1648  Clang->getTargetOpts().Features = AST->TargetFeatures;
1649  Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1650                   Clang->getTargetOpts()));
1651  if (!Clang->hasTarget())
1652    return 0;
1653
1654  // Inform the target of the language options.
1655  //
1656  // FIXME: We shouldn't need to do this, the target should be immutable once
1657  // created. This complexity should be lifted elsewhere.
1658  Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1659
1660  assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1661         "Invocation must have exactly one source file!");
1662  assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
1663         "FIXME: AST inputs not yet supported here!");
1664  assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1665         "IR inputs not supported here!");
1666
1667  // Configure the various subsystems.
1668  AST->TheSema.reset();
1669  AST->Ctx = 0;
1670  AST->PP = 0;
1671
1672  // Create a file manager object to provide access to and cache the filesystem.
1673  Clang->setFileManager(&AST->getFileManager());
1674
1675  // Create the source manager.
1676  Clang->setSourceManager(&AST->getSourceManager());
1677
1678  ASTFrontendAction *Act = Action;
1679
1680  llvm::OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
1681  if (!Act) {
1682    TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1683    Act = TrackerAct.get();
1684  }
1685
1686  // Recover resources if we crash before exiting this method.
1687  llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1688    ActCleanup(TrackerAct.get());
1689
1690  if (!Act->BeginSourceFile(*Clang.get(),
1691                            Clang->getFrontendOpts().Inputs[0].second,
1692                            Clang->getFrontendOpts().Inputs[0].first))
1693    return 0;
1694
1695  Act->Execute();
1696
1697  // Steal the created target, context, and preprocessor.
1698  AST->TheSema.reset(Clang->takeSema());
1699  AST->Consumer.reset(Clang->takeASTConsumer());
1700  AST->Ctx = &Clang->getASTContext();
1701  AST->PP = &Clang->getPreprocessor();
1702  Clang->setSourceManager(0);
1703  Clang->setFileManager(0);
1704  AST->Target = &Clang->getTarget();
1705
1706  Act->EndSourceFile();
1707
1708  if (OwnAST)
1709    return OwnAST.take();
1710  else
1711    return AST;
1712}
1713
1714bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1715  if (!Invocation)
1716    return true;
1717
1718  // We'll manage file buffers ourselves.
1719  Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1720  Invocation->getFrontendOpts().DisableFree = false;
1721  ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1722
1723  // Save the target features.
1724  TargetFeatures = Invocation->getTargetOpts().Features;
1725
1726  llvm::MemoryBuffer *OverrideMainBuffer = 0;
1727  if (PrecompilePreamble) {
1728    PreambleRebuildCounter = 2;
1729    OverrideMainBuffer
1730      = getMainBufferWithPrecompiledPreamble(*Invocation);
1731  }
1732
1733  SimpleTimer ParsingTimer(WantTiming);
1734  ParsingTimer.setOutput("Parsing " + getMainFileName());
1735
1736  // Recover resources if we crash before exiting this method.
1737  llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1738    MemBufferCleanup(OverrideMainBuffer);
1739
1740  return Parse(OverrideMainBuffer);
1741}
1742
1743ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1744                              llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1745                                             bool OnlyLocalDecls,
1746                                             bool CaptureDiagnostics,
1747                                             bool PrecompilePreamble,
1748                                             TranslationUnitKind TUKind,
1749                                             bool CacheCodeCompletionResults,
1750                                             bool NestedMacroExpansions) {
1751  // Create the AST unit.
1752  llvm::OwningPtr<ASTUnit> AST;
1753  AST.reset(new ASTUnit(false));
1754  ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
1755  AST->Diagnostics = Diags;
1756  AST->OnlyLocalDecls = OnlyLocalDecls;
1757  AST->CaptureDiagnostics = CaptureDiagnostics;
1758  AST->TUKind = TUKind;
1759  AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1760  AST->Invocation = CI;
1761  AST->NestedMacroExpansions = NestedMacroExpansions;
1762
1763  // Recover resources if we crash before exiting this method.
1764  llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1765    ASTUnitCleanup(AST.get());
1766  llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1767    llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1768    DiagCleanup(Diags.getPtr());
1769
1770  return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
1771}
1772
1773ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1774                                      const char **ArgEnd,
1775                                    llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1776                                      StringRef ResourceFilesPath,
1777                                      bool OnlyLocalDecls,
1778                                      bool CaptureDiagnostics,
1779                                      RemappedFile *RemappedFiles,
1780                                      unsigned NumRemappedFiles,
1781                                      bool RemappedFilesKeepOriginalName,
1782                                      bool PrecompilePreamble,
1783                                      TranslationUnitKind TUKind,
1784                                      bool CacheCodeCompletionResults,
1785                                      bool NestedMacroExpansions) {
1786  if (!Diags.getPtr()) {
1787    // No diagnostics engine was provided, so create our own diagnostics object
1788    // with the default options.
1789    DiagnosticOptions DiagOpts;
1790    Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1791                                                ArgBegin);
1792  }
1793
1794  SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1795
1796  llvm::IntrusiveRefCntPtr<CompilerInvocation> CI;
1797
1798  {
1799
1800    CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
1801                                      StoredDiagnostics);
1802
1803    CI = clang::createInvocationFromCommandLine(
1804                                           llvm::makeArrayRef(ArgBegin, ArgEnd),
1805                                           Diags);
1806    if (!CI)
1807      return 0;
1808  }
1809
1810  // Override any files that need remapping
1811  for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1812    FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1813    if (const llvm::MemoryBuffer *
1814            memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1815      CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1816    } else {
1817      const char *fname = fileOrBuf.get<const char *>();
1818      CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1819    }
1820  }
1821  CI->getPreprocessorOpts().RemappedFilesKeepOriginalName =
1822                                                  RemappedFilesKeepOriginalName;
1823
1824  // Override the resources path.
1825  CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1826
1827  // Create the AST unit.
1828  llvm::OwningPtr<ASTUnit> AST;
1829  AST.reset(new ASTUnit(false));
1830  ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
1831  AST->Diagnostics = Diags;
1832
1833  AST->FileSystemOpts = CI->getFileSystemOpts();
1834  AST->FileMgr = new FileManager(AST->FileSystemOpts);
1835  AST->OnlyLocalDecls = OnlyLocalDecls;
1836  AST->CaptureDiagnostics = CaptureDiagnostics;
1837  AST->TUKind = TUKind;
1838  AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1839  AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1840  AST->StoredDiagnostics.swap(StoredDiagnostics);
1841  AST->Invocation = CI;
1842  AST->NestedMacroExpansions = NestedMacroExpansions;
1843
1844  // Recover resources if we crash before exiting this method.
1845  llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1846    ASTUnitCleanup(AST.get());
1847  llvm::CrashRecoveryContextCleanupRegistrar<CompilerInvocation,
1848    llvm::CrashRecoveryContextReleaseRefCleanup<CompilerInvocation> >
1849    CICleanup(CI.getPtr());
1850  llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1851    llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1852    DiagCleanup(Diags.getPtr());
1853
1854  return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take();
1855}
1856
1857bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1858  if (!Invocation)
1859    return true;
1860
1861  SimpleTimer ParsingTimer(WantTiming);
1862  ParsingTimer.setOutput("Reparsing " + getMainFileName());
1863
1864  // Remap files.
1865  PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1866  PPOpts.DisableStatCache = true;
1867  for (PreprocessorOptions::remapped_file_buffer_iterator
1868         R = PPOpts.remapped_file_buffer_begin(),
1869         REnd = PPOpts.remapped_file_buffer_end();
1870       R != REnd;
1871       ++R) {
1872    delete R->second;
1873  }
1874  Invocation->getPreprocessorOpts().clearRemappedFiles();
1875  for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1876    FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1877    if (const llvm::MemoryBuffer *
1878            memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1879      Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1880                                                        memBuf);
1881    } else {
1882      const char *fname = fileOrBuf.get<const char *>();
1883      Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1884                                                        fname);
1885    }
1886  }
1887
1888  // If we have a preamble file lying around, or if we might try to
1889  // build a precompiled preamble, do so now.
1890  llvm::MemoryBuffer *OverrideMainBuffer = 0;
1891  if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
1892    OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
1893
1894  // Clear out the diagnostics state.
1895  if (!OverrideMainBuffer) {
1896    getDiagnostics().Reset();
1897    ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1898  }
1899
1900  // Parse the sources
1901  bool Result = Parse(OverrideMainBuffer);
1902
1903  // If we're caching global code-completion results, and the top-level
1904  // declarations have changed, clear out the code-completion cache.
1905  if (!Result && ShouldCacheCodeCompletionResults &&
1906      CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1907    CacheCodeCompletionResults();
1908
1909  // We now need to clear out the completion allocator for
1910  // clang_getCursorCompletionString; it'll be recreated if necessary.
1911  CursorCompletionAllocator = 0;
1912
1913  return Result;
1914}
1915
1916//----------------------------------------------------------------------------//
1917// Code completion
1918//----------------------------------------------------------------------------//
1919
1920namespace {
1921  /// \brief Code completion consumer that combines the cached code-completion
1922  /// results from an ASTUnit with the code-completion results provided to it,
1923  /// then passes the result on to
1924  class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1925    unsigned long long NormalContexts;
1926    ASTUnit &AST;
1927    CodeCompleteConsumer &Next;
1928
1929  public:
1930    AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
1931                                  bool IncludeMacros, bool IncludeCodePatterns,
1932                                  bool IncludeGlobals)
1933      : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
1934                             Next.isOutputBinary()), AST(AST), Next(Next)
1935    {
1936      // Compute the set of contexts in which we will look when we don't have
1937      // any information about the specific context.
1938      NormalContexts
1939        = (1LL << (CodeCompletionContext::CCC_TopLevel - 1))
1940        | (1LL << (CodeCompletionContext::CCC_ObjCInterface - 1))
1941        | (1LL << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1942        | (1LL << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1943        | (1LL << (CodeCompletionContext::CCC_Statement - 1))
1944        | (1LL << (CodeCompletionContext::CCC_Expression - 1))
1945        | (1LL << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1946        | (1LL << (CodeCompletionContext::CCC_DotMemberAccess - 1))
1947        | (1LL << (CodeCompletionContext::CCC_ArrowMemberAccess - 1))
1948        | (1LL << (CodeCompletionContext::CCC_ObjCPropertyAccess - 1))
1949        | (1LL << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
1950        | (1LL << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
1951        | (1LL << (CodeCompletionContext::CCC_Recovery - 1));
1952
1953      if (AST.getASTContext().getLangOptions().CPlusPlus)
1954        NormalContexts |= (1LL << (CodeCompletionContext::CCC_EnumTag - 1))
1955                   | (1LL << (CodeCompletionContext::CCC_UnionTag - 1))
1956                   | (1LL << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
1957    }
1958
1959    virtual void ProcessCodeCompleteResults(Sema &S,
1960                                            CodeCompletionContext Context,
1961                                            CodeCompletionResult *Results,
1962                                            unsigned NumResults);
1963
1964    virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1965                                           OverloadCandidate *Candidates,
1966                                           unsigned NumCandidates) {
1967      Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1968    }
1969
1970    virtual CodeCompletionAllocator &getAllocator() {
1971      return Next.getAllocator();
1972    }
1973  };
1974}
1975
1976/// \brief Helper function that computes which global names are hidden by the
1977/// local code-completion results.
1978static void CalculateHiddenNames(const CodeCompletionContext &Context,
1979                                 CodeCompletionResult *Results,
1980                                 unsigned NumResults,
1981                                 ASTContext &Ctx,
1982                          llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
1983  bool OnlyTagNames = false;
1984  switch (Context.getKind()) {
1985  case CodeCompletionContext::CCC_Recovery:
1986  case CodeCompletionContext::CCC_TopLevel:
1987  case CodeCompletionContext::CCC_ObjCInterface:
1988  case CodeCompletionContext::CCC_ObjCImplementation:
1989  case CodeCompletionContext::CCC_ObjCIvarList:
1990  case CodeCompletionContext::CCC_ClassStructUnion:
1991  case CodeCompletionContext::CCC_Statement:
1992  case CodeCompletionContext::CCC_Expression:
1993  case CodeCompletionContext::CCC_ObjCMessageReceiver:
1994  case CodeCompletionContext::CCC_DotMemberAccess:
1995  case CodeCompletionContext::CCC_ArrowMemberAccess:
1996  case CodeCompletionContext::CCC_ObjCPropertyAccess:
1997  case CodeCompletionContext::CCC_Namespace:
1998  case CodeCompletionContext::CCC_Type:
1999  case CodeCompletionContext::CCC_Name:
2000  case CodeCompletionContext::CCC_PotentiallyQualifiedName:
2001  case CodeCompletionContext::CCC_ParenthesizedExpression:
2002  case CodeCompletionContext::CCC_ObjCInterfaceName:
2003    break;
2004
2005  case CodeCompletionContext::CCC_EnumTag:
2006  case CodeCompletionContext::CCC_UnionTag:
2007  case CodeCompletionContext::CCC_ClassOrStructTag:
2008    OnlyTagNames = true;
2009    break;
2010
2011  case CodeCompletionContext::CCC_ObjCProtocolName:
2012  case CodeCompletionContext::CCC_MacroName:
2013  case CodeCompletionContext::CCC_MacroNameUse:
2014  case CodeCompletionContext::CCC_PreprocessorExpression:
2015  case CodeCompletionContext::CCC_PreprocessorDirective:
2016  case CodeCompletionContext::CCC_NaturalLanguage:
2017  case CodeCompletionContext::CCC_SelectorName:
2018  case CodeCompletionContext::CCC_TypeQualifiers:
2019  case CodeCompletionContext::CCC_Other:
2020  case CodeCompletionContext::CCC_OtherWithMacros:
2021  case CodeCompletionContext::CCC_ObjCInstanceMessage:
2022  case CodeCompletionContext::CCC_ObjCClassMessage:
2023  case CodeCompletionContext::CCC_ObjCCategoryName:
2024    // We're looking for nothing, or we're looking for names that cannot
2025    // be hidden.
2026    return;
2027  }
2028
2029  typedef CodeCompletionResult Result;
2030  for (unsigned I = 0; I != NumResults; ++I) {
2031    if (Results[I].Kind != Result::RK_Declaration)
2032      continue;
2033
2034    unsigned IDNS
2035      = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2036
2037    bool Hiding = false;
2038    if (OnlyTagNames)
2039      Hiding = (IDNS & Decl::IDNS_Tag);
2040    else {
2041      unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
2042                             Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2043                             Decl::IDNS_NonMemberOperator);
2044      if (Ctx.getLangOptions().CPlusPlus)
2045        HiddenIDNS |= Decl::IDNS_Tag;
2046      Hiding = (IDNS & HiddenIDNS);
2047    }
2048
2049    if (!Hiding)
2050      continue;
2051
2052    DeclarationName Name = Results[I].Declaration->getDeclName();
2053    if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2054      HiddenNames.insert(Identifier->getName());
2055    else
2056      HiddenNames.insert(Name.getAsString());
2057  }
2058}
2059
2060
2061void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2062                                            CodeCompletionContext Context,
2063                                            CodeCompletionResult *Results,
2064                                            unsigned NumResults) {
2065  // Merge the results we were given with the results we cached.
2066  bool AddedResult = false;
2067  unsigned InContexts
2068    = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
2069                                        : (1ULL << (Context.getKind() - 1)));
2070  // Contains the set of names that are hidden by "local" completion results.
2071  llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
2072  typedef CodeCompletionResult Result;
2073  SmallVector<Result, 8> AllResults;
2074  for (ASTUnit::cached_completion_iterator
2075            C = AST.cached_completion_begin(),
2076         CEnd = AST.cached_completion_end();
2077       C != CEnd; ++C) {
2078    // If the context we are in matches any of the contexts we are
2079    // interested in, we'll add this result.
2080    if ((C->ShowInContexts & InContexts) == 0)
2081      continue;
2082
2083    // If we haven't added any results previously, do so now.
2084    if (!AddedResult) {
2085      CalculateHiddenNames(Context, Results, NumResults, S.Context,
2086                           HiddenNames);
2087      AllResults.insert(AllResults.end(), Results, Results + NumResults);
2088      AddedResult = true;
2089    }
2090
2091    // Determine whether this global completion result is hidden by a local
2092    // completion result. If so, skip it.
2093    if (C->Kind != CXCursor_MacroDefinition &&
2094        HiddenNames.count(C->Completion->getTypedText()))
2095      continue;
2096
2097    // Adjust priority based on similar type classes.
2098    unsigned Priority = C->Priority;
2099    CXCursorKind CursorKind = C->Kind;
2100    CodeCompletionString *Completion = C->Completion;
2101    if (!Context.getPreferredType().isNull()) {
2102      if (C->Kind == CXCursor_MacroDefinition) {
2103        Priority = getMacroUsagePriority(C->Completion->getTypedText(),
2104                                         S.getLangOptions(),
2105                               Context.getPreferredType()->isAnyPointerType());
2106      } else if (C->Type) {
2107        CanQualType Expected
2108          = S.Context.getCanonicalType(
2109                               Context.getPreferredType().getUnqualifiedType());
2110        SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2111        if (ExpectedSTC == C->TypeClass) {
2112          // We know this type is similar; check for an exact match.
2113          llvm::StringMap<unsigned> &CachedCompletionTypes
2114            = AST.getCachedCompletionTypes();
2115          llvm::StringMap<unsigned>::iterator Pos
2116            = CachedCompletionTypes.find(QualType(Expected).getAsString());
2117          if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2118            Priority /= CCF_ExactTypeMatch;
2119          else
2120            Priority /= CCF_SimilarTypeMatch;
2121        }
2122      }
2123    }
2124
2125    // Adjust the completion string, if required.
2126    if (C->Kind == CXCursor_MacroDefinition &&
2127        Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2128      // Create a new code-completion string that just contains the
2129      // macro name, without its arguments.
2130      CodeCompletionBuilder Builder(getAllocator(), CCP_CodePattern,
2131                                    C->Availability);
2132      Builder.AddTypedTextChunk(C->Completion->getTypedText());
2133      CursorKind = CXCursor_NotImplemented;
2134      Priority = CCP_CodePattern;
2135      Completion = Builder.TakeString();
2136    }
2137
2138    AllResults.push_back(Result(Completion, Priority, CursorKind,
2139                                C->Availability));
2140  }
2141
2142  // If we did not add any cached completion results, just forward the
2143  // results we were given to the next consumer.
2144  if (!AddedResult) {
2145    Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2146    return;
2147  }
2148
2149  Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2150                                  AllResults.size());
2151}
2152
2153
2154
2155void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
2156                           RemappedFile *RemappedFiles,
2157                           unsigned NumRemappedFiles,
2158                           bool IncludeMacros,
2159                           bool IncludeCodePatterns,
2160                           CodeCompleteConsumer &Consumer,
2161                           DiagnosticsEngine &Diag, LangOptions &LangOpts,
2162                           SourceManager &SourceMgr, FileManager &FileMgr,
2163                   SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2164             SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
2165  if (!Invocation)
2166    return;
2167
2168  SimpleTimer CompletionTimer(WantTiming);
2169  CompletionTimer.setOutput("Code completion @ " + File + ":" +
2170                            Twine(Line) + ":" + Twine(Column));
2171
2172  llvm::IntrusiveRefCntPtr<CompilerInvocation>
2173    CCInvocation(new CompilerInvocation(*Invocation));
2174
2175  FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2176  PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
2177
2178  FrontendOpts.ShowMacrosInCodeCompletion
2179    = IncludeMacros && CachedCompletionResults.empty();
2180  FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
2181  FrontendOpts.ShowGlobalSymbolsInCodeCompletion
2182    = CachedCompletionResults.empty();
2183  FrontendOpts.CodeCompletionAt.FileName = File;
2184  FrontendOpts.CodeCompletionAt.Line = Line;
2185  FrontendOpts.CodeCompletionAt.Column = Column;
2186
2187  // Set the language options appropriately.
2188  LangOpts = CCInvocation->getLangOpts();
2189
2190  llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
2191
2192  // Recover resources if we crash before exiting this method.
2193  llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2194    CICleanup(Clang.get());
2195
2196  Clang->setInvocation(&*CCInvocation);
2197  OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
2198
2199  // Set up diagnostics, capturing any diagnostics produced.
2200  Clang->setDiagnostics(&Diag);
2201  ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
2202  CaptureDroppedDiagnostics Capture(true,
2203                                    Clang->getDiagnostics(),
2204                                    StoredDiagnostics);
2205
2206  // Create the target instance.
2207  Clang->getTargetOpts().Features = TargetFeatures;
2208  Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2209                                               Clang->getTargetOpts()));
2210  if (!Clang->hasTarget()) {
2211    Clang->setInvocation(0);
2212    return;
2213  }
2214
2215  // Inform the target of the language options.
2216  //
2217  // FIXME: We shouldn't need to do this, the target should be immutable once
2218  // created. This complexity should be lifted elsewhere.
2219  Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
2220
2221  assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2222         "Invocation must have exactly one source file!");
2223  assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
2224         "FIXME: AST inputs not yet supported here!");
2225  assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
2226         "IR inputs not support here!");
2227
2228
2229  // Use the source and file managers that we were given.
2230  Clang->setFileManager(&FileMgr);
2231  Clang->setSourceManager(&SourceMgr);
2232
2233  // Remap files.
2234  PreprocessorOpts.clearRemappedFiles();
2235  PreprocessorOpts.RetainRemappedFileBuffers = true;
2236  for (unsigned I = 0; I != NumRemappedFiles; ++I) {
2237    FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2238    if (const llvm::MemoryBuffer *
2239            memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2240      PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2241      OwnedBuffers.push_back(memBuf);
2242    } else {
2243      const char *fname = fileOrBuf.get<const char *>();
2244      PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2245    }
2246  }
2247
2248  // Use the code completion consumer we were given, but adding any cached
2249  // code-completion results.
2250  AugmentedCodeCompleteConsumer *AugmentedConsumer
2251    = new AugmentedCodeCompleteConsumer(*this, Consumer,
2252                                        FrontendOpts.ShowMacrosInCodeCompletion,
2253                                FrontendOpts.ShowCodePatternsInCodeCompletion,
2254                                FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
2255  Clang->setCodeCompletionConsumer(AugmentedConsumer);
2256
2257  // If we have a precompiled preamble, try to use it. We only allow
2258  // the use of the precompiled preamble if we're if the completion
2259  // point is within the main file, after the end of the precompiled
2260  // preamble.
2261  llvm::MemoryBuffer *OverrideMainBuffer = 0;
2262  if (!getPreambleFile(this).empty()) {
2263    using llvm::sys::FileStatus;
2264    llvm::sys::PathWithStatus CompleteFilePath(File);
2265    llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2266    if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2267      if (const FileStatus *MainStatus = MainPath.getFileStatus())
2268        if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2269            Line > 1)
2270          OverrideMainBuffer
2271            = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
2272                                                   Line - 1);
2273  }
2274
2275  // If the main file has been overridden due to the use of a preamble,
2276  // make that override happen and introduce the preamble.
2277  PreprocessorOpts.DisableStatCache = true;
2278  StoredDiagnostics.insert(StoredDiagnostics.end(),
2279                           stored_diag_begin(),
2280                           stored_diag_afterDriver_begin());
2281  if (OverrideMainBuffer) {
2282    PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2283    PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2284    PreprocessorOpts.PrecompiledPreambleBytes.second
2285                                                    = PreambleEndsAtStartOfLine;
2286    PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
2287    PreprocessorOpts.DisablePCHValidation = true;
2288
2289    OwnedBuffers.push_back(OverrideMainBuffer);
2290  } else {
2291    PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2292    PreprocessorOpts.PrecompiledPreambleBytes.second = false;
2293  }
2294
2295  // Disable the preprocessing record
2296  PreprocessorOpts.DetailedRecord = false;
2297
2298  llvm::OwningPtr<SyntaxOnlyAction> Act;
2299  Act.reset(new SyntaxOnlyAction);
2300  if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
2301                           Clang->getFrontendOpts().Inputs[0].first)) {
2302    if (OverrideMainBuffer) {
2303      std::string ModName = getPreambleFile(this);
2304      TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
2305                                 getSourceManager(), PreambleDiagnostics,
2306                                 StoredDiagnostics);
2307    }
2308    Act->Execute();
2309    Act->EndSourceFile();
2310  }
2311}
2312
2313CXSaveError ASTUnit::Save(StringRef File) {
2314  if (getDiagnostics().hasUnrecoverableErrorOccurred())
2315    return CXSaveError_TranslationErrors;
2316
2317  // Write to a temporary file and later rename it to the actual file, to avoid
2318  // possible race conditions.
2319  llvm::SmallString<128> TempPath;
2320  TempPath = File;
2321  TempPath += "-%%%%%%%%";
2322  int fd;
2323  if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2324                                 /*makeAbsolute=*/false))
2325    return CXSaveError_Unknown;
2326
2327  // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2328  // unconditionally create a stat cache when we parse the file?
2329  llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
2330
2331  serialize(Out);
2332  Out.close();
2333  if (Out.has_error())
2334    return CXSaveError_Unknown;
2335
2336  if (llvm::error_code ec = llvm::sys::fs::rename(TempPath.str(), File)) {
2337    bool exists;
2338    llvm::sys::fs::remove(TempPath.str(), exists);
2339    return CXSaveError_Unknown;
2340  }
2341
2342  return CXSaveError_None;
2343}
2344
2345bool ASTUnit::serialize(raw_ostream &OS) {
2346  if (getDiagnostics().hasErrorOccurred())
2347    return true;
2348
2349  std::vector<unsigned char> Buffer;
2350  llvm::BitstreamWriter Stream(Buffer);
2351  ASTWriter Writer(Stream);
2352  // FIXME: Handle modules
2353  Writer.WriteAST(getSema(), 0, std::string(), /*IsModule=*/false, "");
2354
2355  // Write the generated bitstream to "Out".
2356  if (!Buffer.empty())
2357    OS.write((char *)&Buffer.front(), Buffer.size());
2358
2359  return false;
2360}
2361
2362typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2363
2364static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2365  unsigned Raw = L.getRawEncoding();
2366  const unsigned MacroBit = 1U << 31;
2367  L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2368      ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2369}
2370
2371void ASTUnit::TranslateStoredDiagnostics(
2372                          ASTReader *MMan,
2373                          StringRef ModName,
2374                          SourceManager &SrcMgr,
2375                          const SmallVectorImpl<StoredDiagnostic> &Diags,
2376                          SmallVectorImpl<StoredDiagnostic> &Out) {
2377  // The stored diagnostic has the old source manager in it; update
2378  // the locations to refer into the new source manager. We also need to remap
2379  // all the locations to the new view. This includes the diag location, any
2380  // associated source ranges, and the source ranges of associated fix-its.
2381  // FIXME: There should be a cleaner way to do this.
2382
2383  SmallVector<StoredDiagnostic, 4> Result;
2384  Result.reserve(Diags.size());
2385  assert(MMan && "Don't have a module manager");
2386  serialization::Module *Mod = MMan->ModuleMgr.lookup(ModName);
2387  assert(Mod && "Don't have preamble module");
2388  SLocRemap &Remap = Mod->SLocRemap;
2389  for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2390    // Rebuild the StoredDiagnostic.
2391    const StoredDiagnostic &SD = Diags[I];
2392    SourceLocation L = SD.getLocation();
2393    TranslateSLoc(L, Remap);
2394    FullSourceLoc Loc(L, SrcMgr);
2395
2396    SmallVector<CharSourceRange, 4> Ranges;
2397    Ranges.reserve(SD.range_size());
2398    for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2399                                          E = SD.range_end();
2400         I != E; ++I) {
2401      SourceLocation BL = I->getBegin();
2402      TranslateSLoc(BL, Remap);
2403      SourceLocation EL = I->getEnd();
2404      TranslateSLoc(EL, Remap);
2405      Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2406    }
2407
2408    SmallVector<FixItHint, 2> FixIts;
2409    FixIts.reserve(SD.fixit_size());
2410    for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2411                                          E = SD.fixit_end();
2412         I != E; ++I) {
2413      FixIts.push_back(FixItHint());
2414      FixItHint &FH = FixIts.back();
2415      FH.CodeToInsert = I->CodeToInsert;
2416      SourceLocation BL = I->RemoveRange.getBegin();
2417      TranslateSLoc(BL, Remap);
2418      SourceLocation EL = I->RemoveRange.getEnd();
2419      TranslateSLoc(EL, Remap);
2420      FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2421                                       I->RemoveRange.isTokenRange());
2422    }
2423
2424    Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2425                                      SD.getMessage(), Loc, Ranges, FixIts));
2426  }
2427  Result.swap(Out);
2428}
2429
2430SourceLocation ASTUnit::getLocation(const FileEntry *File,
2431                                    unsigned Line, unsigned Col) const {
2432  const SourceManager &SM = getSourceManager();
2433  SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
2434  return SM.getMacroArgExpandedLocation(Loc);
2435}
2436
2437SourceLocation ASTUnit::getLocation(const FileEntry *File,
2438                                    unsigned Offset) const {
2439  const SourceManager &SM = getSourceManager();
2440  SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
2441  return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2442}
2443
2444/// \brief If \arg Loc is a loaded location from the preamble, returns
2445/// the corresponding local location of the main file, otherwise it returns
2446/// \arg Loc.
2447SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2448  FileID PreambleID;
2449  if (SourceMgr)
2450    PreambleID = SourceMgr->getPreambleFileID();
2451
2452  if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2453    return Loc;
2454
2455  unsigned Offs;
2456  if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2457    SourceLocation FileLoc
2458        = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2459    return FileLoc.getLocWithOffset(Offs);
2460  }
2461
2462  return Loc;
2463}
2464
2465/// \brief If \arg Loc is a local location of the main file but inside the
2466/// preamble chunk, returns the corresponding loaded location from the
2467/// preamble, otherwise it returns \arg Loc.
2468SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2469  FileID PreambleID;
2470  if (SourceMgr)
2471    PreambleID = SourceMgr->getPreambleFileID();
2472
2473  if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2474    return Loc;
2475
2476  unsigned Offs;
2477  if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2478      Offs < Preamble.size()) {
2479    SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2480    return FileLoc.getLocWithOffset(Offs);
2481  }
2482
2483  return Loc;
2484}
2485
2486bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2487  FileID FID;
2488  if (SourceMgr)
2489    FID = SourceMgr->getPreambleFileID();
2490
2491  if (Loc.isInvalid() || FID.isInvalid())
2492    return false;
2493
2494  return SourceMgr->isInFileID(Loc, FID);
2495}
2496
2497bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2498  FileID FID;
2499  if (SourceMgr)
2500    FID = SourceMgr->getMainFileID();
2501
2502  if (Loc.isInvalid() || FID.isInvalid())
2503    return false;
2504
2505  return SourceMgr->isInFileID(Loc, FID);
2506}
2507
2508SourceLocation ASTUnit::getEndOfPreambleFileID() {
2509  FileID FID;
2510  if (SourceMgr)
2511    FID = SourceMgr->getPreambleFileID();
2512
2513  if (FID.isInvalid())
2514    return SourceLocation();
2515
2516  return SourceMgr->getLocForEndOfFile(FID);
2517}
2518
2519SourceLocation ASTUnit::getStartOfMainFileID() {
2520  FileID FID;
2521  if (SourceMgr)
2522    FID = SourceMgr->getMainFileID();
2523
2524  if (FID.isInvalid())
2525    return SourceLocation();
2526
2527  return SourceMgr->getLocForStartOfFile(FID);
2528}
2529
2530void ASTUnit::PreambleData::countLines() const {
2531  NumLines = 0;
2532  if (empty())
2533    return;
2534
2535  for (std::vector<char>::const_iterator
2536         I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2537    if (*I == '\n')
2538      ++NumLines;
2539  }
2540  if (Buffer.back() != '\n')
2541    ++NumLines;
2542}
2543
2544#ifndef NDEBUG
2545ASTUnit::ConcurrencyState::ConcurrencyState() {
2546  Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2547}
2548
2549ASTUnit::ConcurrencyState::~ConcurrencyState() {
2550  delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2551}
2552
2553void ASTUnit::ConcurrencyState::start() {
2554  bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2555  assert(acquired && "Concurrent access to ASTUnit!");
2556}
2557
2558void ASTUnit::ConcurrencyState::finish() {
2559  static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2560}
2561
2562#else // NDEBUG
2563
2564ASTUnit::ConcurrencyState::ConcurrencyState() {}
2565ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2566void ASTUnit::ConcurrencyState::start() {}
2567void ASTUnit::ConcurrencyState::finish() {}
2568
2569#endif
2570