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