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