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