blob: 0b740e7a116409ca3338b214941b532b6c8ed8c2 [file] [log] [blame]
Argyrios Kyrtzidis3a08ec12009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000015#include "clang/AST/ASTConsumer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
18#include "clang/AST/StmtVisitor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/TypeOrdering.h"
20#include "clang/Basic/Diagnostic.h"
21#include "clang/Basic/TargetInfo.h"
22#include "clang/Basic/TargetOptions.h"
Ben Langmuirc8130a72014-02-20 21:59:23 +000023#include "clang/Basic/VirtualFileSystem.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000024#include "clang/Frontend/CompilerInstance.h"
25#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000026#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000027#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +000028#include "clang/Frontend/MultiplexConsumer.h"
Douglas Gregor36e3b5c2010-10-11 21:37:58 +000029#include "clang/Frontend/Utils.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000030#include "clang/Lex/HeaderSearch.h"
31#include "clang/Lex/Preprocessor.h"
Douglas Gregor1452ff12012-10-24 17:46:57 +000032#include "clang/Lex/PreprocessorOptions.h"
David Blaikie0a4e61f2013-09-13 18:32:52 +000033#include "clang/Sema/Sema.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000034#include "clang/Serialization/ASTReader.h"
35#include "clang/Serialization/ASTWriter.h"
Chris Lattnerce6c42f2011-03-23 04:04:01 +000036#include "llvm/ADT/ArrayRef.h"
Douglas Gregordf7a79a2011-02-16 18:16:54 +000037#include "llvm/ADT/StringExtras.h"
Douglas Gregor40a5a7d2010-08-16 23:08:34 +000038#include "llvm/ADT/StringSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000039#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000040#include "llvm/Support/Host.h"
41#include "llvm/Support/MemoryBuffer.h"
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +000042#include "llvm/Support/Mutex.h"
Ted Kremenekbd307a52011-10-27 19:44:25 +000043#include "llvm/Support/MutexGuard.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000044#include "llvm/Support/Path.h"
45#include "llvm/Support/Timer.h"
46#include "llvm/Support/raw_ostream.h"
Benjamin Kramer4527fb22014-03-02 17:08:31 +000047#include <atomic>
Zhongxing Xu318e4032010-07-23 02:15:08 +000048#include <cstdio>
Chandler Carruth3a022472012-12-04 09:13:33 +000049#include <cstdlib>
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000050using namespace clang;
51
Douglas Gregor16896c42010-10-28 15:44:59 +000052using llvm::TimeRecord;
53
54namespace {
55 class SimpleTimer {
56 bool WantTiming;
57 TimeRecord Start;
58 std::string Output;
59
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000060 public:
Douglas Gregor1cbdd952010-11-01 13:48:43 +000061 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor16896c42010-10-28 15:44:59 +000062 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000063 Start = TimeRecord::getCurrentTime();
Douglas Gregor16896c42010-10-28 15:44:59 +000064 }
65
Chris Lattner0e62c1c2011-07-23 10:55:15 +000066 void setOutput(const Twine &Output) {
Douglas Gregor16896c42010-10-28 15:44:59 +000067 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000068 this->Output = Output.str();
Douglas Gregor16896c42010-10-28 15:44:59 +000069 }
70
Douglas Gregor16896c42010-10-28 15:44:59 +000071 ~SimpleTimer() {
72 if (WantTiming) {
73 TimeRecord Elapsed = TimeRecord::getCurrentTime();
74 Elapsed -= Start;
75 llvm::errs() << Output << ':';
76 Elapsed.print(Elapsed, llvm::errs());
77 llvm::errs() << '\n';
78 }
79 }
80 };
Ted Kremenek06b4f912011-10-27 17:55:18 +000081
82 struct OnDiskData {
83 /// \brief The file in which the precompiled preamble is stored.
84 std::string PreambleFile;
85
Rafael Espindolabc7d9492013-06-26 03:52:38 +000086 /// \brief Temporary files that should be removed when the ASTUnit is
Ted Kremenek06b4f912011-10-27 17:55:18 +000087 /// destroyed.
Rafael Espindolabc7d9492013-06-26 03:52:38 +000088 SmallVector<std::string, 4> TemporaryFiles;
89
Ted Kremenek06b4f912011-10-27 17:55:18 +000090 /// \brief Erase temporary files.
91 void CleanTemporaryFiles();
92
93 /// \brief Erase the preamble file.
94 void CleanPreambleFile();
95
96 /// \brief Erase temporary files and the preamble file.
97 void Cleanup();
98 };
99}
100
Ted Kremenekbd307a52011-10-27 19:44:25 +0000101static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
102 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
103 return M;
104}
105
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000106static void cleanupOnDiskMapAtExit();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000107
108typedef llvm::DenseMap<const ASTUnit *, OnDiskData *> OnDiskDataMap;
109static OnDiskDataMap &getOnDiskDataMap() {
110 static OnDiskDataMap M;
111 static bool hasRegisteredAtExit = false;
112 if (!hasRegisteredAtExit) {
113 hasRegisteredAtExit = true;
114 atexit(cleanupOnDiskMapAtExit);
115 }
116 return M;
117}
118
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000119static void cleanupOnDiskMapAtExit() {
Argyrios Kyrtzidis4cf2ffe2012-07-03 16:30:52 +0000120 // Use the mutex because there can be an alive thread destroying an ASTUnit.
121 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek06b4f912011-10-27 17:55:18 +0000122 OnDiskDataMap &M = getOnDiskDataMap();
123 for (OnDiskDataMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
124 // We don't worry about freeing the memory associated with OnDiskDataMap.
125 // All we care about is erasing stale files.
126 I->second->Cleanup();
127 }
128}
129
130static OnDiskData &getOnDiskData(const ASTUnit *AU) {
Ted Kremenekbd307a52011-10-27 19:44:25 +0000131 // We require the mutex since we are modifying the structure of the
132 // DenseMap.
133 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek06b4f912011-10-27 17:55:18 +0000134 OnDiskDataMap &M = getOnDiskDataMap();
135 OnDiskData *&D = M[AU];
136 if (!D)
137 D = new OnDiskData();
138 return *D;
139}
140
141static void erasePreambleFile(const ASTUnit *AU) {
142 getOnDiskData(AU).CleanPreambleFile();
143}
144
145static void removeOnDiskEntry(const ASTUnit *AU) {
Ted Kremenekbd307a52011-10-27 19:44:25 +0000146 // We require the mutex since we are modifying the structure of the
147 // DenseMap.
148 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek06b4f912011-10-27 17:55:18 +0000149 OnDiskDataMap &M = getOnDiskDataMap();
150 OnDiskDataMap::iterator I = M.find(AU);
151 if (I != M.end()) {
152 I->second->Cleanup();
153 delete I->second;
154 M.erase(AU);
155 }
156}
157
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000158static void setPreambleFile(const ASTUnit *AU, StringRef preambleFile) {
Ted Kremenek06b4f912011-10-27 17:55:18 +0000159 getOnDiskData(AU).PreambleFile = preambleFile;
160}
161
162static const std::string &getPreambleFile(const ASTUnit *AU) {
163 return getOnDiskData(AU).PreambleFile;
164}
165
166void OnDiskData::CleanTemporaryFiles() {
167 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
Rafael Espindolabc7d9492013-06-26 03:52:38 +0000168 llvm::sys::fs::remove(TemporaryFiles[I]);
169 TemporaryFiles.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000170}
171
172void OnDiskData::CleanPreambleFile() {
173 if (!PreambleFile.empty()) {
Rafael Espindolabc4aa552013-06-26 04:02:37 +0000174 llvm::sys::fs::remove(PreambleFile);
Ted Kremenek06b4f912011-10-27 17:55:18 +0000175 PreambleFile.clear();
176 }
177}
178
179void OnDiskData::Cleanup() {
180 CleanTemporaryFiles();
181 CleanPreambleFile();
182}
183
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000184struct ASTUnit::ASTWriterData {
185 SmallString<128> Buffer;
186 llvm::BitstreamWriter Stream;
187 ASTWriter Writer;
188
189 ASTWriterData() : Stream(Buffer), Writer(Stream) { }
190};
191
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000192void ASTUnit::clearFileLevelDecls() {
Reid Kleckner588c9372014-02-19 23:44:52 +0000193 llvm::DeleteContainerSeconds(FileDecls);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000194}
195
Ted Kremenek06b4f912011-10-27 17:55:18 +0000196void ASTUnit::CleanTemporaryFiles() {
197 getOnDiskData(this).CleanTemporaryFiles();
198}
199
Rafael Espindolabc7d9492013-06-26 03:52:38 +0000200void ASTUnit::addTemporaryFile(StringRef TempFile) {
Ted Kremenek06b4f912011-10-27 17:55:18 +0000201 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
Douglas Gregor16896c42010-10-28 15:44:59 +0000202}
203
Douglas Gregorbb420ab2010-08-04 05:53:38 +0000204/// \brief After failing to build a precompiled preamble (due to
205/// errors in the source that occurs in the preamble), the number of
206/// reparses during which we'll skip even trying to precompile the
207/// preamble.
208const unsigned DefaultPreambleRebuildInterval = 5;
209
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000210/// \brief Tracks the number of ASTUnit objects that are currently active.
211///
212/// Used for debugging purposes only.
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000213static std::atomic<unsigned> ActiveASTUnitObjects;
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000214
Douglas Gregord03e8232010-04-05 21:10:19 +0000215ASTUnit::ASTUnit(bool _MainFileIsAST)
Craig Topper49a27902014-05-22 04:46:25 +0000216 : Reader(nullptr), HadModuleLoaderFatalFailure(false),
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +0000217 OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000218 MainFileIsAST(_MainFileIsAST),
Douglas Gregor69f74f82011-08-25 22:30:56 +0000219 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis4954bc12011-03-05 01:03:48 +0000220 OwnsRemappedFileBuffers(true),
Douglas Gregor16896c42010-10-28 15:44:59 +0000221 NumStoredDiagnosticsFromDriver(0),
Craig Topper49a27902014-05-22 04:46:25 +0000222 PreambleRebuildCounter(0), SavedMainFileBuffer(nullptr),
223 PreambleBuffer(nullptr), NumWarningsInPreamble(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +0000224 ShouldCacheCodeCompletionResults(false),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000225 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000226 CompletionCacheTopLevelHashValue(0),
227 PreambleTopLevelHashValue(0),
228 CurrentTopLevelHashValue(0),
Douglas Gregor4740c452010-08-19 00:45:44 +0000229 UnsafeToFree(false) {
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000230 if (getenv("LIBCLANG_OBJTRACKING"))
231 fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000232}
Douglas Gregord03e8232010-04-05 21:10:19 +0000233
Daniel Dunbar764c0822009-12-01 09:51:01 +0000234ASTUnit::~ASTUnit() {
Douglas Gregor6b930962013-05-03 22:58:43 +0000235 // If we loaded from an AST file, balance out the BeginSourceFile call.
236 if (MainFileIsAST && getDiagnostics().getClient()) {
237 getDiagnostics().getClient()->EndSourceFile();
238 }
239
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000240 clearFileLevelDecls();
241
Ted Kremenek06b4f912011-10-27 17:55:18 +0000242 // Clean up the temporary files and the preamble file.
243 removeOnDiskEntry(this);
244
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000245 // Free the buffers associated with remapped files. We are required to
246 // perform this operation here because we explicitly request that the
247 // compiler instance *not* free these buffers for each invocation of the
248 // parser.
Alp Tokerf994cef2014-07-05 03:08:06 +0000249 if (Invocation.get() && OwnsRemappedFileBuffers) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000250 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Alp Toker1b070d22014-07-07 07:47:20 +0000251 for (const auto &RB : PPOpts.RemappedFileBuffers)
252 delete RB.second;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000253 }
Douglas Gregor96c04262010-07-27 14:52:07 +0000254
255 delete SavedMainFileBuffer;
Douglas Gregora0734c52010-08-19 01:33:06 +0000256 delete PreambleBuffer;
257
Douglas Gregor16896c42010-10-28 15:44:59 +0000258 ClearCachedCompletionResults();
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000259
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000260 if (getenv("LIBCLANG_OBJTRACKING"))
261 fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000262}
263
Argyrios Kyrtzidisda6e0542012-01-17 18:48:07 +0000264void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
265
Douglas Gregor39982192010-08-15 06:18:01 +0000266/// \brief Determine the set of code-completion contexts in which this
267/// declaration should be shown.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000268static unsigned getDeclShowContexts(const NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000269 const LangOptions &LangOpts,
270 bool &IsNestedNameSpecifier) {
271 IsNestedNameSpecifier = false;
272
Douglas Gregor39982192010-08-15 06:18:01 +0000273 if (isa<UsingShadowDecl>(ND))
274 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
275 if (!ND)
276 return 0;
277
Richard Smith697cc9e2012-08-14 03:13:00 +0000278 uint64_t Contexts = 0;
Douglas Gregor39982192010-08-15 06:18:01 +0000279 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
280 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
281 // Types can appear in these contexts.
282 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000283 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
284 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
285 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
286 | (1LL << CodeCompletionContext::CCC_Statement)
287 | (1LL << CodeCompletionContext::CCC_Type)
288 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor39982192010-08-15 06:18:01 +0000289
290 // In C++, types can appear in expressions contexts (for functional casts).
291 if (LangOpts.CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +0000292 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor39982192010-08-15 06:18:01 +0000293
294 // In Objective-C, message sends can send interfaces. In Objective-C++,
295 // all types are available due to functional casts.
296 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000297 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor21325842011-07-07 16:03:39 +0000298
299 // In Objective-C, you can only be a subclass of another Objective-C class
300 if (isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000301 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor39982192010-08-15 06:18:01 +0000302
303 // Deal with tag names.
304 if (isa<EnumDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000305 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000306
Douglas Gregor59cab552010-08-16 23:05:20 +0000307 // Part of the nested-name-specifier in C++0x.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000308 if (LangOpts.CPlusPlus11)
Douglas Gregor59cab552010-08-16 23:05:20 +0000309 IsNestedNameSpecifier = true;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000310 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
Douglas Gregor39982192010-08-15 06:18:01 +0000311 if (Record->isUnion())
Richard Smith697cc9e2012-08-14 03:13:00 +0000312 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000313 else
Richard Smith697cc9e2012-08-14 03:13:00 +0000314 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000315
Douglas Gregor39982192010-08-15 06:18:01 +0000316 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000317 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000318 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000319 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000320 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
321 // Values can appear in these contexts.
Richard Smith697cc9e2012-08-14 03:13:00 +0000322 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
323 | (1LL << CodeCompletionContext::CCC_Expression)
324 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
325 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor39982192010-08-15 06:18:01 +0000326 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000327 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor21325842011-07-07 16:03:39 +0000328 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000329 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor39982192010-08-15 06:18:01 +0000330 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000331 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor39982192010-08-15 06:18:01 +0000332
333 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000334 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000335 }
336
337 return Contexts;
338}
339
Douglas Gregorb14904c2010-08-13 22:48:40 +0000340void ASTUnit::CacheCodeCompletionResults() {
341 if (!TheSema)
342 return;
343
Douglas Gregor16896c42010-10-28 15:44:59 +0000344 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000345 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000346
347 // Clear out the previous results.
348 ClearCachedCompletionResults();
349
350 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000351 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000352 SmallVector<Result, 8> Results;
Douglas Gregor162b7122011-02-16 19:08:06 +0000353 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000354 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000355 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000356 CCTUInfo, Results);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000357
358 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000359 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
360
Douglas Gregorb14904c2010-08-13 22:48:40 +0000361 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
362 switch (Results[I].Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000363 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000364 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000365 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000366 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000367 *CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000368 CCTUInfo,
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000369 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor39982192010-08-15 06:18:01 +0000370 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000371 Ctx->getLangOpts(),
Douglas Gregor59cab552010-08-16 23:05:20 +0000372 IsNestedNameSpecifier);
Douglas Gregor39982192010-08-15 06:18:01 +0000373 CachedResult.Priority = Results[I].Priority;
374 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000375 CachedResult.Availability = Results[I].Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000376
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000377 // Keep track of the type of this completion in an ASTContext-agnostic
378 // way.
Douglas Gregor24747402010-08-16 16:46:30 +0000379 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000380 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000381 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000382 CachedResult.Type = 0;
383 } else {
384 CanQualType CanUsageType
385 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
386 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
387
388 // Determine whether we have already seen this type. If so, we save
389 // ourselves the work of formatting the type string by using the
390 // temporary, CanQualType-based hash table to find the associated value.
391 unsigned &TypeValue = CompletionTypes[CanUsageType];
392 if (TypeValue == 0) {
393 TypeValue = CompletionTypes.size();
394 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
395 = TypeValue;
396 }
397
398 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000399 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000400
Douglas Gregor39982192010-08-15 06:18:01 +0000401 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000402
403 /// Handle nested-name-specifiers in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000404 if (TheSema->Context.getLangOpts().CPlusPlus &&
Douglas Gregor59cab552010-08-16 23:05:20 +0000405 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
406 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith697cc9e2012-08-14 03:13:00 +0000407 uint64_t NNSContexts
408 = (1LL << CodeCompletionContext::CCC_TopLevel)
409 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
410 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
411 | (1LL << CodeCompletionContext::CCC_Statement)
412 | (1LL << CodeCompletionContext::CCC_Expression)
413 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
414 | (1LL << CodeCompletionContext::CCC_EnumTag)
415 | (1LL << CodeCompletionContext::CCC_UnionTag)
416 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
417 | (1LL << CodeCompletionContext::CCC_Type)
418 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
419 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor59cab552010-08-16 23:05:20 +0000420
421 if (isa<NamespaceDecl>(Results[I].Declaration) ||
422 isa<NamespaceAliasDecl>(Results[I].Declaration))
Richard Smith697cc9e2012-08-14 03:13:00 +0000423 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor59cab552010-08-16 23:05:20 +0000424
425 if (unsigned RemainingContexts
426 = NNSContexts & ~CachedResult.ShowInContexts) {
427 // If there any contexts where this completion can be a
428 // nested-name-specifier but isn't already an option, create a
429 // nested-name-specifier completion.
430 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000431 CachedResult.Completion
432 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000433 *CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000434 CCTUInfo,
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000435 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor59cab552010-08-16 23:05:20 +0000436 CachedResult.ShowInContexts = RemainingContexts;
437 CachedResult.Priority = CCP_NestedNameSpecifier;
438 CachedResult.TypeClass = STC_Void;
439 CachedResult.Type = 0;
440 CachedCompletionResults.push_back(CachedResult);
441 }
442 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000443 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000444 }
445
Douglas Gregorb14904c2010-08-13 22:48:40 +0000446 case Result::RK_Keyword:
447 case Result::RK_Pattern:
448 // Ignore keywords and patterns; we don't care, since they are so
449 // easily regenerated.
450 break;
451
452 case Result::RK_Macro: {
453 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000454 CachedResult.Completion
455 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000456 *CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000457 CCTUInfo,
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000458 IncludeBriefCommentsInCodeCompletion);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000459 CachedResult.ShowInContexts
Richard Smith697cc9e2012-08-14 03:13:00 +0000460 = (1LL << CodeCompletionContext::CCC_TopLevel)
461 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
462 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
463 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
464 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
465 | (1LL << CodeCompletionContext::CCC_Statement)
466 | (1LL << CodeCompletionContext::CCC_Expression)
467 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
468 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
469 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
470 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
471 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000472
Douglas Gregorb14904c2010-08-13 22:48:40 +0000473 CachedResult.Priority = Results[I].Priority;
474 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000475 CachedResult.Availability = Results[I].Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000476 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000477 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000478 CachedCompletionResults.push_back(CachedResult);
479 break;
480 }
481 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000482 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000483
484 // Save the current top-level hash value.
485 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000486}
487
488void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregorb14904c2010-08-13 22:48:40 +0000489 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000490 CachedCompletionTypes.clear();
Craig Topper49a27902014-05-22 04:46:25 +0000491 CachedCompletionAllocator = nullptr;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000492}
493
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000494namespace {
495
Sebastian Redl2c499f62010-08-18 23:56:43 +0000496/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000497/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000498class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor83297df2011-09-01 23:39:15 +0000499 Preprocessor &PP;
Douglas Gregore8bbc122011-09-02 00:18:52 +0000500 ASTContext &Context;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000501 LangOptions &LangOpt;
Alp Toker80758082014-07-06 05:26:44 +0000502 std::shared_ptr<TargetOptions> &TargetOpts;
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000503 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000504 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000505
Douglas Gregore8bbc122011-09-02 00:18:52 +0000506 bool InitializedLanguage;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000507public:
Alp Toker80758082014-07-06 05:26:44 +0000508 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
509 std::shared_ptr<TargetOptions> &TargetOpts,
510 IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
511 : PP(PP), Context(Context), LangOpt(LangOpt), TargetOpts(TargetOpts),
512 Target(Target), Counter(Counter), InitializedLanguage(false) {}
Mike Stump11289f42009-09-09 15:08:12 +0000513
Craig Topperafa7cb32014-03-13 06:07:04 +0000514 bool ReadLanguageOptions(const LangOptions &LangOpts,
515 bool Complain) override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000516 if (InitializedLanguage)
Douglas Gregor83297df2011-09-01 23:39:15 +0000517 return false;
518
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000519 LangOpt = LangOpts;
520 InitializedLanguage = true;
521
522 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000523 return false;
524 }
Mike Stump11289f42009-09-09 15:08:12 +0000525
Craig Topperafa7cb32014-03-13 06:07:04 +0000526 bool ReadTargetOptions(const TargetOptions &TargetOpts,
527 bool Complain) override {
Douglas Gregor83297df2011-09-01 23:39:15 +0000528 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000529 if (Target)
Douglas Gregor83297df2011-09-01 23:39:15 +0000530 return false;
Alp Toker80758082014-07-06 05:26:44 +0000531
532 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
533 Target =
534 TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000535
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000536 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000537 return false;
538 }
Mike Stump11289f42009-09-09 15:08:12 +0000539
Craig Topperafa7cb32014-03-13 06:07:04 +0000540 void ReadCounter(const serialization::ModuleFile &M,
541 unsigned Value) override {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000542 Counter = Value;
543 }
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000544
545private:
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000546 void updated() {
547 if (!Target || !InitializedLanguage)
548 return;
549
550 // Inform the target of the language options.
551 //
552 // FIXME: We shouldn't need to do this, the target should be immutable once
553 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +0000554 Target->adjust(LangOpt);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000555
556 // Initialize the preprocessor.
557 PP.Initialize(*Target);
558
559 // Initialize the ASTContext
560 Context.InitBuiltinTypes(*Target);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000561
562 // We didn't have access to the comment options when the ASTContext was
563 // constructed, so register them now.
564 Context.getCommentCommandTraits().registerCommentOptions(
565 LangOpt.CommentOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000566 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000567};
568
Douglas Gregor6b930962013-05-03 22:58:43 +0000569 /// \brief Diagnostic consumer that saves each diagnostic it is given.
David Blaikief18d91a2011-09-26 00:01:39 +0000570class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000571 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregor6b930962013-05-03 22:58:43 +0000572 SourceManager *SourceMgr;
573
Douglas Gregor33cdd812010-02-18 18:08:43 +0000574public:
David Blaikief18d91a2011-09-26 00:01:39 +0000575 explicit StoredDiagnosticConsumer(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000576 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Craig Topper49a27902014-05-22 04:46:25 +0000577 : StoredDiags(StoredDiags), SourceMgr(nullptr) {}
Douglas Gregor6b930962013-05-03 22:58:43 +0000578
Craig Topperafa7cb32014-03-13 06:07:04 +0000579 void BeginSourceFile(const LangOptions &LangOpts,
Craig Topper49a27902014-05-22 04:46:25 +0000580 const Preprocessor *PP = nullptr) override {
Douglas Gregor6b930962013-05-03 22:58:43 +0000581 if (PP)
582 SourceMgr = &PP->getSourceManager();
583 }
584
Craig Topperafa7cb32014-03-13 06:07:04 +0000585 void HandleDiagnostic(DiagnosticsEngine::Level Level,
586 const Diagnostic &Info) override;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000587};
588
589/// \brief RAII object that optionally captures diagnostics, if
590/// there is no diagnostic client to capture them already.
591class CaptureDroppedDiagnostics {
David Blaikie9c902b52011-09-25 23:23:43 +0000592 DiagnosticsEngine &Diags;
David Blaikief18d91a2011-09-26 00:01:39 +0000593 StoredDiagnosticConsumer Client;
David Blaikiee2eefae2011-09-25 23:39:51 +0000594 DiagnosticConsumer *PreviousClient;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000595
596public:
David Blaikie9c902b52011-09-25 23:23:43 +0000597 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000598 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Craig Topper49a27902014-05-22 04:46:25 +0000599 : Diags(Diags), Client(StoredDiags), PreviousClient(nullptr)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000600 {
Craig Topper49a27902014-05-22 04:46:25 +0000601 if (RequestCapture || Diags.getClient() == nullptr) {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000602 PreviousClient = Diags.takeClient();
Douglas Gregor33cdd812010-02-18 18:08:43 +0000603 Diags.setClient(&Client);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000604 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000605 }
606
607 ~CaptureDroppedDiagnostics() {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000608 if (Diags.getClient() == &Client) {
609 Diags.takeClient();
610 Diags.setClient(PreviousClient);
611 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000612 }
613};
614
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000615} // anonymous namespace
616
David Blaikief18d91a2011-09-26 00:01:39 +0000617void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +0000618 const Diagnostic &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000619 // Default implementation (Warnings/errors count).
David Blaikiee2eefae2011-09-25 23:39:51 +0000620 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000621
Douglas Gregor6b930962013-05-03 22:58:43 +0000622 // Only record the diagnostic if it's part of the source manager we know
623 // about. This effectively drops diagnostics from modules we're building.
624 // FIXME: In the long run, ee don't want to drop source managers from modules.
625 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
626 StoredDiags.push_back(StoredDiagnostic(Level, Info));
Douglas Gregor33cdd812010-02-18 18:08:43 +0000627}
628
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000629ASTMutationListener *ASTUnit::getASTMutationListener() {
630 if (WriterData)
631 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000632 return nullptr;
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000633}
634
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000635ASTDeserializationListener *ASTUnit::getDeserializationListener() {
636 if (WriterData)
637 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000638 return nullptr;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000639}
640
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000641llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner26b5c192010-11-23 09:19:42 +0000642 std::string *ErrorStr) {
Chris Lattner5159f612010-11-23 08:35:12 +0000643 assert(FileMgr);
Chris Lattner26b5c192010-11-23 09:19:42 +0000644 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000645}
646
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000647/// \brief Configure the diagnostics object for use with ASTUnit.
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000648void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000649 const char **ArgBegin, const char **ArgEnd,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000650 ASTUnit &AST, bool CaptureDiagnostics) {
Alp Tokerf994cef2014-07-05 03:08:06 +0000651 if (!Diags.get()) {
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000652 // No diagnostics engine was provided, so create our own diagnostics object
653 // with the default options.
Craig Topper49a27902014-05-22 04:46:25 +0000654 DiagnosticConsumer *Client = nullptr;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000655 if (CaptureDiagnostics)
David Blaikief18d91a2011-09-26 00:01:39 +0000656 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Douglas Gregor811db4e2012-10-23 22:26:28 +0000657 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions(),
Sean Silvaf1b49e22013-01-20 01:58:28 +0000658 Client,
Douglas Gregor30071cea2013-05-03 23:07:45 +0000659 /*ShouldOwnClient=*/true);
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000660 } else if (CaptureDiagnostics) {
David Blaikief18d91a2011-09-26 00:01:39 +0000661 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000662 }
663}
664
David Blaikie6f7382d2014-08-10 19:08:04 +0000665std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
666 const std::string &Filename, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
667 const FileSystemOptions &FileSystemOpts, bool OnlyLocalDecls,
668 ArrayRef<RemappedFile> RemappedFiles, bool CaptureDiagnostics,
669 bool AllowPCHWithCompilerErrors, bool UserFilesAreVolatile) {
Ahmed Charlesb8984322014-03-07 20:03:18 +0000670 std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000671
672 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +0000673 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
674 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +0000675 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
676 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +0000677 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000678
Craig Topper49a27902014-05-22 04:46:25 +0000679 ConfigureDiags(Diags, nullptr, nullptr, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000680
Douglas Gregor16bef852009-10-16 20:01:17 +0000681 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000682 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000683 AST->Diagnostics = Diags;
Ben Langmuir8832c062014-04-15 18:16:25 +0000684 IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
685 AST->FileMgr = new FileManager(FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000686 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000687 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000688 AST->getFileManager(),
689 UserFilesAreVolatile);
Douglas Gregorb85b9cc2012-10-24 16:19:39 +0000690 AST->HSOpts = new HeaderSearchOptions();
Craig Topper49a27902014-05-22 04:46:25 +0000691
Douglas Gregorb85b9cc2012-10-24 16:19:39 +0000692 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
Manuel Klimek1f76c4e2013-10-24 07:51:24 +0000693 AST->getSourceManager(),
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000694 AST->getDiagnostics(),
Douglas Gregor89929282012-01-30 06:01:29 +0000695 AST->ASTFileLangOpts,
Craig Topper49a27902014-05-22 04:46:25 +0000696 /*Target=*/nullptr));
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000697
Dmitri Gribenkob41e7e22014-02-10 12:31:34 +0000698 PreprocessorOptions *PPOpts = new PreprocessorOptions();
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000699
Dmitri Gribenkob41e7e22014-02-10 12:31:34 +0000700 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I)
701 PPOpts->addRemappedFile(RemappedFiles[I].first, RemappedFiles[I].second);
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000702
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000703 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000704
David Blaikie6f7382d2014-08-10 19:08:04 +0000705 HeaderSearch &HeaderInfo = *AST->HeaderInfo;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000706 unsigned Counter;
707
Alp Toker96637802014-05-02 03:43:38 +0000708 AST->PP =
709 new Preprocessor(PPOpts, AST->getDiagnostics(), AST->ASTFileLangOpts,
710 AST->getSourceManager(), HeaderInfo, *AST,
Craig Topper49a27902014-05-22 04:46:25 +0000711 /*IILookup=*/nullptr,
Alp Toker96637802014-05-02 03:43:38 +0000712 /*OwnsHeaderSearch=*/false);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000713 Preprocessor &PP = *AST->PP;
714
Alp Toker08043432014-05-03 03:46:04 +0000715 AST->Ctx = new ASTContext(AST->ASTFileLangOpts, AST->getSourceManager(),
716 PP.getIdentifierTable(), PP.getSelectorTable(),
717 PP.getBuiltinInfo());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000718 ASTContext &Context = *AST->Ctx;
Douglas Gregor83297df2011-09-01 23:39:15 +0000719
Argyrios Kyrtzidis945a8192012-09-15 01:10:20 +0000720 bool disableValid = false;
721 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
722 disableValid = true;
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000723 AST->Reader = new ASTReader(PP, Context,
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +0000724 /*isysroot=*/"",
Argyrios Kyrtzidis945a8192012-09-15 01:10:20 +0000725 /*DisableValidation=*/disableValid,
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000726 AllowPCHWithCompilerErrors);
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000727
David Blaikie2721c322014-08-10 16:54:39 +0000728 AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>(
729 *AST->PP, Context, AST->ASTFileLangOpts, AST->TargetOpts, AST->Target,
730 Counter));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000731
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000732 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis2ec29362012-11-15 18:57:22 +0000733 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000734 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000735 break;
Mike Stump11289f42009-09-09 15:08:12 +0000736
Sebastian Redl2c499f62010-08-18 23:56:43 +0000737 case ASTReader::Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +0000738 case ASTReader::Missing:
Douglas Gregorc9ad5fb2012-10-22 22:50:17 +0000739 case ASTReader::OutOfDate:
740 case ASTReader::VersionMismatch:
741 case ASTReader::ConfigurationMismatch:
742 case ASTReader::HadErrors:
Douglas Gregord03e8232010-04-05 21:10:19 +0000743 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Craig Topper49a27902014-05-22 04:46:25 +0000744 return nullptr;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000745 }
Mike Stump11289f42009-09-09 15:08:12 +0000746
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000747 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
Daniel Dunbara8a50932009-12-02 08:44:16 +0000748
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000749 PP.setCounterValue(Counter);
Mike Stump11289f42009-09-09 15:08:12 +0000750
Sebastian Redl2c499f62010-08-18 23:56:43 +0000751 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000752 // source, so that declarations will be deserialized from the
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000753 // AST file as needed.
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000754 Context.setExternalSource(AST->Reader);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000755
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000756 // Create an AST consumer, even though it isn't used.
757 AST->Consumer.reset(new ASTConsumer);
758
Sebastian Redl2c499f62010-08-18 23:56:43 +0000759 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000760 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
761 AST->TheSema->Initialize();
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000762 AST->Reader->InitializeSema(*AST->TheSema);
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000763
Douglas Gregor6b930962013-05-03 22:58:43 +0000764 // Tell the diagnostic client that we have started a source file.
765 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
766
David Blaikie6f7382d2014-08-10 19:08:04 +0000767 return AST;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000768}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000769
770namespace {
771
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000772/// \brief Preprocessor callback class that updates a hash value with the names
773/// of all macros that have been defined by the translation unit.
774class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
775 unsigned &Hash;
776
777public:
778 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
Craig Topperafa7cb32014-03-13 06:07:04 +0000779
780 void MacroDefined(const Token &MacroNameTok,
781 const MacroDirective *MD) override {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000782 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
783 }
784};
785
786/// \brief Add the given declaration to the hash of all top-level entities.
787void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
788 if (!D)
789 return;
790
791 DeclContext *DC = D->getDeclContext();
792 if (!DC)
793 return;
794
795 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
796 return;
797
798 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000799 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
800 // For an unscoped enum include the enumerators in the hash since they
801 // enter the top-level namespace.
802 if (!EnumD->isScoped()) {
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000803 for (const auto *EI : EnumD->enumerators()) {
804 if (EI->getIdentifier())
805 Hash = llvm::HashString(EI->getIdentifier()->getName(), Hash);
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000806 }
807 }
808 }
809
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000810 if (ND->getIdentifier())
811 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
812 else if (DeclarationName Name = ND->getDeclName()) {
813 std::string NameStr = Name.getAsString();
814 Hash = llvm::HashString(NameStr, Hash);
815 }
816 return;
Argyrios Kyrtzidis48d88de2013-06-24 21:19:12 +0000817 }
818
819 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
820 if (Module *Mod = ImportD->getImportedModule()) {
821 std::string ModName = Mod->getFullModuleName();
822 Hash = llvm::HashString(ModName, Hash);
823 }
824 return;
825 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000826}
827
Daniel Dunbar644dca02009-12-04 08:17:33 +0000828class TopLevelDeclTrackerConsumer : public ASTConsumer {
829 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000830 unsigned &Hash;
831
Daniel Dunbar644dca02009-12-04 08:17:33 +0000832public:
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000833 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
834 : Unit(_Unit), Hash(Hash) {
835 Hash = 0;
836 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000837
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000838 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis516eec22011-11-16 02:35:10 +0000839 if (!D)
840 return;
841
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000842 // FIXME: Currently ObjC method declarations are incorrectly being
843 // reported as top-level declarations, even though their DeclContext
844 // is the containing ObjC @interface/@implementation. This is a
845 // fundamental problem in the parser right now.
846 if (isa<ObjCMethodDecl>(D))
847 return;
848
849 AddTopLevelDeclarationToHash(D, Hash);
850 Unit.addTopLevelDecl(D);
851
852 handleFileLevelDecl(D);
853 }
854
855 void handleFileLevelDecl(Decl *D) {
856 Unit.addFileLevelDecl(D);
857 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
Aaron Ballman629afae2014-03-07 19:56:05 +0000858 for (auto *I : NSD->decls())
859 handleFileLevelDecl(I);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000860 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000861 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000862
Craig Topperafa7cb32014-03-13 06:07:04 +0000863 bool HandleTopLevelDecl(DeclGroupRef D) override {
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000864 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
865 handleTopLevelDecl(*it);
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000866 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000867 }
868
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000869 // We're not interested in "interesting" decls.
Craig Topperafa7cb32014-03-13 06:07:04 +0000870 void HandleInterestingDecl(DeclGroupRef) override {}
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000871
Craig Topperafa7cb32014-03-13 06:07:04 +0000872 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000873 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
874 handleTopLevelDecl(*it);
875 }
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000876
Craig Topperafa7cb32014-03-13 06:07:04 +0000877 ASTMutationListener *GetASTMutationListener() override {
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000878 return Unit.getASTMutationListener();
879 }
880
Craig Topperafa7cb32014-03-13 06:07:04 +0000881 ASTDeserializationListener *GetASTDeserializationListener() override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000882 return Unit.getDeserializationListener();
883 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000884};
885
886class TopLevelDeclTrackerAction : public ASTFrontendAction {
887public:
888 ASTUnit &Unit;
889
David Blaikie6beb6aa2014-08-10 19:56:51 +0000890 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
891 StringRef InFile) override {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000892 CI.getPreprocessor().addPPCallbacks(
893 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000894 return llvm::make_unique<TopLevelDeclTrackerConsumer>(
895 Unit, Unit.getCurrentTopLevelHashValue());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000896 }
897
898public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000899 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
900
Craig Topperafa7cb32014-03-13 06:07:04 +0000901 bool hasCodeCompletionSupport() const override { return false; }
902 TranslationUnitKind getTranslationUnitKind() override {
Douglas Gregor69f74f82011-08-25 22:30:56 +0000903 return Unit.getTranslationUnitKind();
Douglas Gregor028d3e42010-08-09 20:45:32 +0000904 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000905};
906
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000907class PrecompilePreambleAction : public ASTFrontendAction {
908 ASTUnit &Unit;
909 bool HasEmittedPreamblePCH;
910
911public:
912 explicit PrecompilePreambleAction(ASTUnit &Unit)
913 : Unit(Unit), HasEmittedPreamblePCH(false) {}
914
David Blaikie6beb6aa2014-08-10 19:56:51 +0000915 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
916 StringRef InFile) override;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000917 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
918 void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH = true; }
Craig Topperafa7cb32014-03-13 06:07:04 +0000919 bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000920
Craig Topperafa7cb32014-03-13 06:07:04 +0000921 bool hasCodeCompletionSupport() const override { return false; }
922 bool hasASTFileSupport() const override { return false; }
923 TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000924};
925
Argyrios Kyrtzidis57332712011-09-19 20:40:48 +0000926class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000927 ASTUnit &Unit;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000928 unsigned &Hash;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000929 std::vector<Decl *> TopLevelDecls;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000930 PrecompilePreambleAction *Action;
931
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000932public:
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000933 PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action,
934 const Preprocessor &PP, StringRef isysroot,
935 raw_ostream *Out)
Craig Topper49a27902014-05-22 04:46:25 +0000936 : PCHGenerator(PP, "", nullptr, isysroot, Out, /*AllowASTWithErrors=*/true),
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000937 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000938 Hash = 0;
939 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000940
Craig Topperafa7cb32014-03-13 06:07:04 +0000941 bool HandleTopLevelDecl(DeclGroupRef D) override {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000942 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
943 Decl *D = *it;
944 // FIXME: Currently ObjC method declarations are incorrectly being
945 // reported as top-level declarations, even though their DeclContext
946 // is the containing ObjC @interface/@implementation. This is a
947 // fundamental problem in the parser right now.
948 if (isa<ObjCMethodDecl>(D))
949 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000950 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000951 TopLevelDecls.push_back(D);
952 }
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000953 return true;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000954 }
955
Craig Topperafa7cb32014-03-13 06:07:04 +0000956 void HandleTranslationUnit(ASTContext &Ctx) override {
Douglas Gregore9db88f2010-08-03 19:06:41 +0000957 PCHGenerator::HandleTranslationUnit(Ctx);
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +0000958 if (hasEmittedPCH()) {
Douglas Gregore9db88f2010-08-03 19:06:41 +0000959 // Translate the top-level declarations we captured during
960 // parsing into declaration IDs in the precompiled
961 // preamble. This will allow us to deserialize those top-level
962 // declarations when requested.
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +0000963 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I) {
964 Decl *D = TopLevelDecls[I];
965 // Invalid top-level decls may not have been serialized.
966 if (D->isInvalidDecl())
967 continue;
968 Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
969 }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000970
971 Action->setHasEmittedPreamblePCH();
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000972 }
973 }
974};
975
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000976}
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000977
David Blaikie6beb6aa2014-08-10 19:56:51 +0000978std::unique_ptr<ASTConsumer>
979PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
980 StringRef InFile) {
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000981 std::string Sysroot;
982 std::string OutputFile;
Craig Topper49a27902014-05-22 04:46:25 +0000983 raw_ostream *OS = nullptr;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000984 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
985 OutputFile, OS))
Craig Topper49a27902014-05-22 04:46:25 +0000986 return nullptr;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000987
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000988 if (!CI.getFrontendOpts().RelocatablePCH)
989 Sysroot.clear();
Douglas Gregorc567ba22011-07-22 16:35:34 +0000990
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000991 CI.getPreprocessor().addPPCallbacks(new MacroDefinitionTrackerPPCallbacks(
992 Unit.getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000993 return llvm::make_unique<PrecompilePreambleConsumer>(
994 Unit, this, CI.getPreprocessor(), Sysroot, OS);
Daniel Dunbar764c0822009-12-01 09:51:01 +0000995}
996
Benjamin Kramer1ce5d802013-05-05 12:39:28 +0000997static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
998 return StoredDiag.getLocation().isValid();
999}
1000
1001static void
1002checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001003 // Get rid of stored diagnostics except the ones from the driver which do not
1004 // have a source location.
Benjamin Kramer1ce5d802013-05-05 12:39:28 +00001005 StoredDiags.erase(
1006 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1007 StoredDiags.end());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001008}
1009
1010static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1011 StoredDiagnostics,
1012 SourceManager &SM) {
1013 // The stored diagnostic has the old source manager in it; update
1014 // the locations to refer into the new source manager. Since we've
1015 // been careful to make sure that the source manager's state
1016 // before and after are identical, so that we can reuse the source
1017 // location itself.
1018 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1019 if (StoredDiagnostics[I].getLocation().isValid()) {
1020 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1021 StoredDiagnostics[I].setLocation(Loc);
1022 }
1023 }
1024}
1025
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001026/// Parse the source file into a translation unit using the given compiler
1027/// invocation, replacing the current translation unit.
1028///
1029/// \returns True if a failure occurred that causes the ASTUnit not to
1030/// contain any translation-unit information, false otherwise.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001031bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor96c04262010-07-27 14:52:07 +00001032 delete SavedMainFileBuffer;
Craig Topper49a27902014-05-22 04:46:25 +00001033 SavedMainFileBuffer = nullptr;
1034
Ted Kremenek5e14d392011-03-21 18:40:17 +00001035 if (!Invocation) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001036 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001037 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001038 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001039
Daniel Dunbar764c0822009-12-01 09:51:01 +00001040 // Create the compiler instance to use for building the AST.
Ahmed Charlesb8984322014-03-07 20:03:18 +00001041 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001042
1043 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001044 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1045 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001046
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001047 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis14c32e82011-09-12 18:09:38 +00001048 CCInvocation(new CompilerInvocation(*Invocation));
1049
Alp Tokerf994cef2014-07-05 03:08:06 +00001050 Clang->setInvocation(CCInvocation.get());
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001051 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001052
Douglas Gregor8e984da2010-08-04 16:47:14 +00001053 // Set up diagnostics, capturing any diagnostics that would
1054 // otherwise be dropped.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001055 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +00001056
Daniel Dunbar764c0822009-12-01 09:51:01 +00001057 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001058 Clang->setTarget(TargetInfo::CreateTargetInfo(
1059 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001060 if (!Clang->hasTarget()) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001061 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001062 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001063 }
1064
Daniel Dunbar764c0822009-12-01 09:51:01 +00001065 // Inform the target of the language options.
1066 //
1067 // FIXME: We shouldn't need to do this, the target should be immutable once
1068 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001069 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001070
Ted Kremenek84de4a12011-03-21 18:40:07 +00001071 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001072 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001073 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001074 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001075 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Daniel Dunbar9507f9c2010-06-07 23:26:47 +00001076 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +00001077
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001078 // Configure the various subsystems.
Alp Toker269d8402014-07-06 05:26:07 +00001079 LangOpts = Clang->getInvocation().LangOpts;
Ted Kremenek84de4a12011-03-21 18:40:07 +00001080 FileSystemOpts = Clang->getFileSystemOpts();
Ben Langmuir2cc485b2014-06-23 16:36:40 +00001081 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1082 createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
1083 if (!VFS) {
1084 delete OverrideMainBuffer;
1085 return true;
1086 }
1087 FileMgr = new FileManager(FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001088 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1089 UserFilesAreVolatile);
Douglas Gregor6fd55e02010-08-13 03:15:25 +00001090 TheSema.reset();
Craig Topper49a27902014-05-22 04:46:25 +00001091 Ctx = nullptr;
1092 PP = nullptr;
1093 Reader = nullptr;
1094
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001095 // Clear out old caches and data.
1096 TopLevelDecls.clear();
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001097 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001098 CleanTemporaryFiles();
Douglas Gregord9a30af2010-08-02 20:51:39 +00001099
Douglas Gregor7b02b582010-08-20 00:02:33 +00001100 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001101 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001102 TopLevelDeclsInPreamble.clear();
1103 }
1104
Daniel Dunbar764c0822009-12-01 09:51:01 +00001105 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001106 Clang->setFileManager(&getFileManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001107
Daniel Dunbar764c0822009-12-01 09:51:01 +00001108 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001109 Clang->setSourceManager(&getSourceManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001110
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001111 // If the main file has been overridden due to the use of a preamble,
1112 // make that override happen and introduce the preamble.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001113 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001114 if (OverrideMainBuffer) {
1115 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1116 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1117 PreprocessorOpts.PrecompiledPreambleBytes.second
1118 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00001119 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorce3a8292010-07-27 00:27:13 +00001120 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +00001121
Douglas Gregord9a30af2010-08-02 20:51:39 +00001122 // The stored diagnostic has the old source manager in it; update
1123 // the locations to refer into the new source manager. Since we've
1124 // been careful to make sure that the source manager's state
1125 // before and after are identical, so that we can reuse the source
1126 // location itself.
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001127 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001128
1129 // Keep track of the override buffer;
1130 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001131 }
Ahmed Charlesb8984322014-03-07 20:03:18 +00001132
1133 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1134 new TopLevelDeclTrackerAction(*this));
1135
Ted Kremenek022a4902011-03-22 01:15:24 +00001136 // Recover resources if we crash before exiting this method.
1137 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1138 ActCleanup(Act.get());
1139
Douglas Gregor32fbe312012-01-20 16:28:04 +00001140 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar764c0822009-12-01 09:51:01 +00001141 goto error;
Douglas Gregor925296b2011-07-19 16:10:42 +00001142
1143 if (OverrideMainBuffer) {
Ted Kremenek06b4f912011-10-27 17:55:18 +00001144 std::string ModName = getPreambleFile(this);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001145 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1146 PreambleDiagnostics, StoredDiagnostics);
Douglas Gregor925296b2011-07-19 16:10:42 +00001147 }
1148
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001149 if (!Act->Execute())
1150 goto error;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001151
1152 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001153
Daniel Dunbar644dca02009-12-04 08:17:33 +00001154 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001155
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001156 FailedParseDiagnostics.clear();
1157
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001158 return false;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001159
Daniel Dunbar764c0822009-12-01 09:51:01 +00001160error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001161 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +00001162 if (OverrideMainBuffer) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001163 delete OverrideMainBuffer;
Craig Topper49a27902014-05-22 04:46:25 +00001164 SavedMainFileBuffer = nullptr;
Douglas Gregorce3a8292010-07-27 00:27:13 +00001165 }
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001166
1167 // Keep the ownership of the data in the ASTUnit because the client may
1168 // want to see the diagnostics.
1169 transferASTDataFromCompilerInstance(*Clang);
1170 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregorefc46952010-10-12 16:25:54 +00001171 StoredDiagnostics.clear();
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001172 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001173 return true;
1174}
1175
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001176/// \brief Simple function to retrieve a path for a preamble precompiled header.
1177static std::string GetPreamblePCHPath() {
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001178 // FIXME: This is a hack so that we can override the preamble file during
1179 // crash-recovery testing, which is the only case where the preamble files
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001180 // are not necessarily cleaned up.
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001181 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1182 if (TmpFile)
1183 return TmpFile;
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001184
1185 SmallString<128> Path;
Rafael Espindolaa36e78e2013-07-05 20:00:06 +00001186 llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001187
1188 return Path.str();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001189}
1190
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001191/// \brief Compute the preamble for the main file, providing the source buffer
1192/// that corresponds to the main file along with a pair (bytes, start-of-line)
1193/// that describes the preamble.
1194std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor028d3e42010-08-09 20:45:32 +00001195ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1196 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001197 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner5159f612010-11-23 08:35:12 +00001198 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001199 CreatedBuffer = false;
1200
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001201 // Try to determine if the main file has been remapped, either from the
1202 // command line (to another file) or directly through the compiler invocation
1203 // (to a memory buffer).
Craig Topper49a27902014-05-22 04:46:25 +00001204 llvm::MemoryBuffer *Buffer = nullptr;
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001205 std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
Rafael Espindola073ff102013-07-29 21:26:52 +00001206 llvm::sys::fs::UniqueID MainFileID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001207 if (!llvm::sys::fs::getUniqueID(MainFilePath, MainFileID)) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001208 // Check whether there is a file-file remapping of the main file
Alp Toker1b070d22014-07-07 07:47:20 +00001209 for (const auto &RF : PreprocessorOpts.RemappedFiles) {
1210 std::string MPath(RF.first);
Rafael Espindola073ff102013-07-29 21:26:52 +00001211 llvm::sys::fs::UniqueID MID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001212 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001213 if (MainFileID == MID) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001214 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001215 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001216 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001217 CreatedBuffer = false;
1218 }
Alp Toker1b070d22014-07-07 07:47:20 +00001219
1220 Buffer = getBufferForFile(RF.second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001221 if (!Buffer)
Craig Topper49a27902014-05-22 04:46:25 +00001222 return std::make_pair(nullptr, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001223 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001224 }
1225 }
1226 }
1227
1228 // Check whether there is a file-buffer remapping. It supercedes the
1229 // file-file remapping.
Alp Toker1b070d22014-07-07 07:47:20 +00001230 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1231 std::string MPath(RB.first);
Rafael Espindola073ff102013-07-29 21:26:52 +00001232 llvm::sys::fs::UniqueID MID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001233 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001234 if (MainFileID == MID) {
1235 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001236 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001237 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001238 CreatedBuffer = false;
1239 }
Alp Toker1b070d22014-07-07 07:47:20 +00001240
1241 Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001242 }
1243 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001244 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001245 }
1246
1247 // If the main source file was not remapped, load it now.
1248 if (!Buffer) {
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001249 Buffer = getBufferForFile(FrontendOpts.Inputs[0].getFile());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001250 if (!Buffer)
Craig Topper49a27902014-05-22 04:46:25 +00001251 return std::make_pair(nullptr, std::make_pair(0, true));
1252
Douglas Gregor4dde7492010-07-23 23:58:40 +00001253 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001254 }
1255
Argyrios Kyrtzidis7aecbc72011-08-25 20:39:19 +00001256 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenek8cf47df2011-11-17 23:01:24 +00001257 *Invocation.getLangOpts(),
Argyrios Kyrtzidis7aecbc72011-08-25 20:39:19 +00001258 MaxLines));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001259}
1260
Dmitri Gribenko47652522013-12-20 00:16:25 +00001261ASTUnit::PreambleFileHash
1262ASTUnit::PreambleFileHash::createForFile(off_t Size, time_t ModTime) {
1263 PreambleFileHash Result;
1264 Result.Size = Size;
1265 Result.ModTime = ModTime;
Dmitri Gribenko3ec8ee72013-12-20 01:07:30 +00001266 memset(Result.MD5, 0, sizeof(Result.MD5));
Dmitri Gribenko47652522013-12-20 00:16:25 +00001267 return Result;
1268}
1269
1270ASTUnit::PreambleFileHash ASTUnit::PreambleFileHash::createForMemoryBuffer(
1271 const llvm::MemoryBuffer *Buffer) {
1272 PreambleFileHash Result;
1273 Result.Size = Buffer->getBufferSize();
1274 Result.ModTime = 0;
1275
1276 llvm::MD5 MD5Ctx;
1277 MD5Ctx.update(Buffer->getBuffer().data());
1278 MD5Ctx.final(Result.MD5);
1279
1280 return Result;
1281}
1282
1283namespace clang {
1284bool operator==(const ASTUnit::PreambleFileHash &LHS,
1285 const ASTUnit::PreambleFileHash &RHS) {
1286 return LHS.Size == RHS.Size && LHS.ModTime == RHS.ModTime &&
Dmitri Gribenko3ec8ee72013-12-20 01:07:30 +00001287 memcmp(LHS.MD5, RHS.MD5, sizeof(LHS.MD5)) == 0;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001288}
1289} // namespace clang
1290
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001291static std::pair<unsigned, unsigned>
1292makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1293 const LangOptions &LangOpts) {
1294 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1295 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1296 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1297 return std::make_pair(Offset, EndOffset);
1298}
1299
1300static void makeStandaloneFixIt(const SourceManager &SM,
1301 const LangOptions &LangOpts,
1302 const FixItHint &InFix,
1303 ASTUnit::StandaloneFixIt &OutFix) {
1304 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1305 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1306 LangOpts);
1307 OutFix.CodeToInsert = InFix.CodeToInsert;
1308 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
1309}
1310
1311static void makeStandaloneDiagnostic(const LangOptions &LangOpts,
1312 const StoredDiagnostic &InDiag,
1313 ASTUnit::StandaloneDiagnostic &OutDiag) {
1314 OutDiag.ID = InDiag.getID();
1315 OutDiag.Level = InDiag.getLevel();
1316 OutDiag.Message = InDiag.getMessage();
1317 OutDiag.LocOffset = 0;
1318 if (InDiag.getLocation().isInvalid())
1319 return;
1320 const SourceManager &SM = InDiag.getLocation().getManager();
1321 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1322 OutDiag.Filename = SM.getFilename(FileLoc);
1323 if (OutDiag.Filename.empty())
1324 return;
1325 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
1326 for (StoredDiagnostic::range_iterator
1327 I = InDiag.range_begin(), E = InDiag.range_end(); I != E; ++I) {
1328 OutDiag.Ranges.push_back(makeStandaloneRange(*I, SM, LangOpts));
1329 }
1330 for (StoredDiagnostic::fixit_iterator
1331 I = InDiag.fixit_begin(), E = InDiag.fixit_end(); I != E; ++I) {
1332 ASTUnit::StandaloneFixIt Fix;
1333 makeStandaloneFixIt(SM, LangOpts, *I, Fix);
1334 OutDiag.FixIts.push_back(Fix);
1335 }
1336}
1337
Douglas Gregor4dde7492010-07-23 23:58:40 +00001338/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1339/// the source file.
1340///
1341/// This routine will compute the preamble of the main source file. If a
1342/// non-trivial preamble is found, it will precompile that preamble into a
1343/// precompiled header so that the precompiled preamble can be used to reduce
1344/// reparsing time. If a precompiled preamble has already been constructed,
1345/// this routine will determine if it is still valid and, if so, avoid
1346/// rebuilding the precompiled preamble.
1347///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001348/// \param AllowRebuild When true (the default), this routine is
1349/// allowed to rebuild the precompiled preamble if it is found to be
1350/// out-of-date.
1351///
1352/// \param MaxLines When non-zero, the maximum number of lines that
1353/// can occur within the preamble.
1354///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001355/// \returns If the precompiled preamble can be used, returns a newly-allocated
1356/// buffer that should be used in place of the main file when doing so.
1357/// Otherwise, returns a NULL pointer.
Douglas Gregor028d3e42010-08-09 20:45:32 +00001358llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor3cc15812011-07-01 18:22:13 +00001359 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001360 bool AllowRebuild,
1361 unsigned MaxLines) {
Douglas Gregor3cc15812011-07-01 18:22:13 +00001362
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001363 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor3cc15812011-07-01 18:22:13 +00001364 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1365 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001366 PreprocessorOptions &PreprocessorOpts
Douglas Gregor3cc15812011-07-01 18:22:13 +00001367 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001368
1369 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001370 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor3cc15812011-07-01 18:22:13 +00001371 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001372
Douglas Gregor925296b2011-07-19 16:10:42 +00001373 // If ComputePreamble() Take ownership of the preamble buffer.
Ahmed Charlesb8984322014-03-07 20:03:18 +00001374 std::unique_ptr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor3edb1672010-11-16 20:45:51 +00001375 if (CreatedPreambleBuffer)
1376 OwnedPreambleBuffer.reset(NewPreamble.first);
1377
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001378 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001379 // We couldn't find a preamble in the main source. Clear out the current
1380 // preamble, if we have one. It's obviously no good any more.
1381 Preamble.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001382 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001383
1384 // The next time we actually see a preamble, precompile it.
1385 PreambleRebuildCounter = 1;
Craig Topper49a27902014-05-22 04:46:25 +00001386 return nullptr;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001387 }
1388
1389 if (!Preamble.empty()) {
1390 // We've previously computed a preamble. Check whether we have the same
1391 // preamble now that we did before, and that there's enough space in
1392 // the main-file buffer within the precompiled preamble to fit the
1393 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001394 if (Preamble.size() == NewPreamble.second.first &&
1395 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001396 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001397 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001398 // The preamble has not changed. We may be able to re-use the precompiled
1399 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001400
Douglas Gregor0e119552010-07-31 00:40:00 +00001401 // Check that none of the files used by the preamble have changed.
1402 bool AnyFileChanged = false;
1403
1404 // First, make a record of those files that have been overridden via
1405 // remapping or unsaved_files.
Dmitri Gribenko47652522013-12-20 00:16:25 +00001406 llvm::StringMap<PreambleFileHash> OverriddenFiles;
Alp Toker1b070d22014-07-07 07:47:20 +00001407 for (const auto &R : PreprocessorOpts.RemappedFiles) {
1408 if (AnyFileChanged)
1409 break;
1410
Ben Langmuirc8130a72014-02-20 21:59:23 +00001411 vfs::Status Status;
Alp Toker1b070d22014-07-07 07:47:20 +00001412 if (FileMgr->getNoncachedStatValue(R.second, Status)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001413 // If we can't stat the file we're remapping to, assume that something
1414 // horrible happened.
1415 AnyFileChanged = true;
1416 break;
1417 }
Rafael Espindolae4777f42013-07-29 18:22:23 +00001418
Alp Toker1b070d22014-07-07 07:47:20 +00001419 OverriddenFiles[R.first] = PreambleFileHash::createForFile(
Rafael Espindolae4777f42013-07-29 18:22:23 +00001420 Status.getSize(), Status.getLastModificationTime().toEpochTime());
Douglas Gregor0e119552010-07-31 00:40:00 +00001421 }
Alp Toker1b070d22014-07-07 07:47:20 +00001422
1423 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1424 if (AnyFileChanged)
1425 break;
1426 OverriddenFiles[RB.first] =
1427 PreambleFileHash::createForMemoryBuffer(RB.second);
Douglas Gregor0e119552010-07-31 00:40:00 +00001428 }
1429
1430 // Check whether anything has changed.
Dmitri Gribenko47652522013-12-20 00:16:25 +00001431 for (llvm::StringMap<PreambleFileHash>::iterator
Douglas Gregor0e119552010-07-31 00:40:00 +00001432 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1433 !AnyFileChanged && F != FEnd;
1434 ++F) {
Dmitri Gribenko47652522013-12-20 00:16:25 +00001435 llvm::StringMap<PreambleFileHash>::iterator Overridden
Douglas Gregor0e119552010-07-31 00:40:00 +00001436 = OverriddenFiles.find(F->first());
1437 if (Overridden != OverriddenFiles.end()) {
1438 // This file was remapped; check whether the newly-mapped file
1439 // matches up with the previous mapping.
1440 if (Overridden->second != F->second)
1441 AnyFileChanged = true;
1442 continue;
1443 }
1444
1445 // The file was not remapped; check whether it has changed on disk.
Ben Langmuirc8130a72014-02-20 21:59:23 +00001446 vfs::Status Status;
Rafael Espindolae4777f42013-07-29 18:22:23 +00001447 if (FileMgr->getNoncachedStatValue(F->first(), Status)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001448 // If we can't stat the file, assume that something horrible happened.
1449 AnyFileChanged = true;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001450 } else if (Status.getSize() != uint64_t(F->second.Size) ||
Rafael Espindolae4777f42013-07-29 18:22:23 +00001451 Status.getLastModificationTime().toEpochTime() !=
Dmitri Gribenko47652522013-12-20 00:16:25 +00001452 uint64_t(F->second.ModTime))
Douglas Gregor0e119552010-07-31 00:40:00 +00001453 AnyFileChanged = true;
1454 }
1455
1456 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001457 // Okay! We can re-use the precompiled preamble.
1458
1459 // Set the state of the diagnostic object to mimic its state
1460 // after parsing the preamble.
1461 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001462 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor3cc15812011-07-01 18:22:13 +00001463 PreambleInvocation->getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001464 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001465
Argyrios Kyrtzidisb255ee92014-03-09 04:24:57 +00001466 return llvm::MemoryBuffer::getMemBufferCopy(
1467 NewPreamble.first->getBuffer(), FrontendOpts.Inputs[0].getFile());
Douglas Gregor0e119552010-07-31 00:40:00 +00001468 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001469 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001470
1471 // If we aren't allowed to rebuild the precompiled preamble, just
1472 // return now.
1473 if (!AllowRebuild)
Craig Topper49a27902014-05-22 04:46:25 +00001474 return nullptr;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001475
Douglas Gregor4dde7492010-07-23 23:58:40 +00001476 // We can't reuse the previously-computed preamble. Build a new one.
1477 Preamble.clear();
Douglas Gregor925296b2011-07-19 16:10:42 +00001478 PreambleDiagnostics.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001479 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001480 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001481 } else if (!AllowRebuild) {
1482 // We aren't allowed to rebuild the precompiled preamble; just
1483 // return now.
Craig Topper49a27902014-05-22 04:46:25 +00001484 return nullptr;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001485 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001486
1487 // If the preamble rebuild counter > 1, it's because we previously
1488 // failed to build a preamble and we're not yet ready to try
1489 // again. Decrement the counter and return a failure.
1490 if (PreambleRebuildCounter > 1) {
1491 --PreambleRebuildCounter;
Craig Topper49a27902014-05-22 04:46:25 +00001492 return nullptr;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001493 }
1494
Douglas Gregore10f0e52010-09-11 17:56:52 +00001495 // Create a temporary file for the precompiled preamble. In rare
1496 // circumstances, this can fail.
1497 std::string PreamblePCHPath = GetPreamblePCHPath();
1498 if (PreamblePCHPath.empty()) {
1499 // Try again next time.
1500 PreambleRebuildCounter = 1;
Craig Topper49a27902014-05-22 04:46:25 +00001501 return nullptr;
Douglas Gregore10f0e52010-09-11 17:56:52 +00001502 }
1503
Douglas Gregor4dde7492010-07-23 23:58:40 +00001504 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001505 SimpleTimer PreambleTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001506 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor4dde7492010-07-23 23:58:40 +00001507
Douglas Gregord9a30af2010-08-02 20:51:39 +00001508 // Save the preamble text for later; we'll need to compare against it for
1509 // subsequent reparses.
Dmitri Gribenko40798d32013-12-19 23:25:59 +00001510 StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001511 Preamble.assign(FileMgr->getFile(MainFilename),
1512 NewPreamble.first->getBufferStart(),
Douglas Gregord9a30af2010-08-02 20:51:39 +00001513 NewPreamble.first->getBufferStart()
1514 + NewPreamble.second.first);
1515 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1516
Douglas Gregora0734c52010-08-19 01:33:06 +00001517 delete PreambleBuffer;
1518 PreambleBuffer
Argyrios Kyrtzidisb255ee92014-03-09 04:24:57 +00001519 = llvm::MemoryBuffer::getMemBufferCopy(
1520 NewPreamble.first->getBuffer().slice(0, Preamble.size()), MainFilename);
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001521
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001522 // Remap the main source file to the preamble buffer.
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001523 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
1524 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer);
1525
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001526 // Tell the compiler invocation to generate a temporary precompiled header.
1527 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001528 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001529 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001530 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1531 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001532
1533 // Create the compiler instance to use for building the precompiled preamble.
Ahmed Charlesb8984322014-03-07 20:03:18 +00001534 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001535
1536 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001537 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1538 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001539
Douglas Gregor3cc15812011-07-01 18:22:13 +00001540 Clang->setInvocation(&*PreambleInvocation);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001541 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001542
Douglas Gregor8e984da2010-08-04 16:47:14 +00001543 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001544 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001545
1546 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001547 Clang->setTarget(TargetInfo::CreateTargetInfo(
1548 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001549 if (!Clang->hasTarget()) {
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001550 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001551 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001552 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Alp Toker1b070d22014-07-07 07:47:20 +00001553 PreprocessorOpts.RemappedFileBuffers.pop_back();
Craig Topper49a27902014-05-22 04:46:25 +00001554 return nullptr;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001555 }
1556
1557 // Inform the target of the language options.
1558 //
1559 // FIXME: We shouldn't need to do this, the target should be immutable once
1560 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001561 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001562
Ted Kremenek84de4a12011-03-21 18:40:07 +00001563 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001564 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001565 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001566 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001567 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001568 "IR inputs not support here!");
1569
1570 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001571 getDiagnostics().Reset();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001572 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001573 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregore9db88f2010-08-03 19:06:41 +00001574 TopLevelDecls.clear();
1575 TopLevelDeclsInPreamble.clear();
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001576 PreambleDiagnostics.clear();
Ben Langmuir8832c062014-04-15 18:16:25 +00001577
1578 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1579 createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
1580 if (!VFS)
1581 return nullptr;
1582
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001583 // Create a file manager object to provide access to and cache the filesystem.
Ben Langmuir8832c062014-04-15 18:16:25 +00001584 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001585
1586 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001587 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek5e14d392011-03-21 18:40:17 +00001588 Clang->getFileManager()));
Ahmed Charlesb8984322014-03-07 20:03:18 +00001589
Ben Langmuir33c80902014-06-30 20:04:14 +00001590 auto PreambleDepCollector = std::make_shared<DependencyCollector>();
1591 Clang->addDependencyCollector(PreambleDepCollector);
1592
Ahmed Charlesb8984322014-03-07 20:03:18 +00001593 std::unique_ptr<PrecompilePreambleAction> Act;
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001594 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor32fbe312012-01-20 16:28:04 +00001595 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001596 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001597 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001598 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Alp Toker1b070d22014-07-07 07:47:20 +00001599 PreprocessorOpts.RemappedFileBuffers.pop_back();
Craig Topper49a27902014-05-22 04:46:25 +00001600 return nullptr;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001601 }
1602
1603 Act->Execute();
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001604
1605 // Transfer any diagnostics generated when parsing the preamble into the set
1606 // of preamble diagnostics.
1607 for (stored_diag_iterator
1608 I = stored_diag_afterDriver_begin(),
1609 E = stored_diag_end(); I != E; ++I) {
1610 StandaloneDiagnostic Diag;
1611 makeStandaloneDiagnostic(Clang->getLangOpts(), *I, Diag);
1612 PreambleDiagnostics.push_back(Diag);
1613 }
1614
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001615 Act->EndSourceFile();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001616
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001617 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1618
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +00001619 if (!Act->hasEmittedPreamblePCH()) {
Argyrios Kyrtzidisd6f57222013-06-11 16:42:34 +00001620 // The preamble PCH failed (e.g. there was a module loading fatal error),
1621 // so no precompiled header was generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001622 // FIXME: Should we leave a note for ourselves to try again?
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001623 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001624 Preamble.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001625 TopLevelDeclsInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001626 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Alp Toker1b070d22014-07-07 07:47:20 +00001627 PreprocessorOpts.RemappedFileBuffers.pop_back();
Craig Topper49a27902014-05-22 04:46:25 +00001628 return nullptr;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001629 }
1630
1631 // Keep track of the preamble we precompiled.
Ted Kremenek06b4f912011-10-27 17:55:18 +00001632 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001633 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001634
1635 // Keep track of all of the files that the source manager knows about,
1636 // so we can verify whether they have changed or not.
1637 FilesInPreamble.clear();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001638 SourceManager &SourceMgr = Clang->getSourceManager();
Ben Langmuir33c80902014-06-30 20:04:14 +00001639 for (auto &Filename : PreambleDepCollector->getDependencies()) {
1640 const FileEntry *File = Clang->getFileManager().getFile(Filename);
1641 if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
Douglas Gregor0e119552010-07-31 00:40:00 +00001642 continue;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001643 if (time_t ModTime = File->getModificationTime()) {
1644 FilesInPreamble[File->getName()] = PreambleFileHash::createForFile(
Ben Langmuir33c80902014-06-30 20:04:14 +00001645 File->getSize(), ModTime);
Dmitri Gribenko47652522013-12-20 00:16:25 +00001646 } else {
Ben Langmuir33c80902014-06-30 20:04:14 +00001647 llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
Dmitri Gribenko47652522013-12-20 00:16:25 +00001648 FilesInPreamble[File->getName()] =
1649 PreambleFileHash::createForMemoryBuffer(Buffer);
1650 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001651 }
Ben Langmuir33c80902014-06-30 20:04:14 +00001652
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001653 PreambleRebuildCounter = 1;
Alp Toker1b070d22014-07-07 07:47:20 +00001654 PreprocessorOpts.RemappedFileBuffers.pop_back();
1655
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001656 // If the hash of top-level entities differs from the hash of the top-level
1657 // entities the last time we rebuilt the preamble, clear out the completion
1658 // cache.
1659 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1660 CompletionCacheTopLevelHashValue = 0;
1661 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1662 }
1663
Argyrios Kyrtzidisb255ee92014-03-09 04:24:57 +00001664 return llvm::MemoryBuffer::getMemBufferCopy(NewPreamble.first->getBuffer(),
1665 MainFilename);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001666}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001667
Douglas Gregore9db88f2010-08-03 19:06:41 +00001668void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1669 std::vector<Decl *> Resolved;
1670 Resolved.reserve(TopLevelDeclsInPreamble.size());
1671 ExternalASTSource &Source = *getASTContext().getExternalSource();
1672 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1673 // Resolve the declaration ID to an actual declaration, possibly
1674 // deserializing the declaration in the process.
1675 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1676 if (D)
1677 Resolved.push_back(D);
1678 }
1679 TopLevelDeclsInPreamble.clear();
1680 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1681}
1682
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001683void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
Ben Langmuir749323f2014-04-22 17:40:12 +00001684 // Steal the created target, context, and preprocessor if they have been
1685 // created.
1686 assert(CI.hasInvocation() && "missing invocation");
Alp Toker269d8402014-07-06 05:26:07 +00001687 LangOpts = CI.getInvocation().LangOpts;
David Blaikieec99b5e2014-08-10 19:14:48 +00001688 TheSema = CI.takeSema();
David Blaikie6beb6aa2014-08-10 19:56:51 +00001689 Consumer = CI.takeASTConsumer();
Ben Langmuir532fdc02014-04-18 20:39:48 +00001690 if (CI.hasASTContext())
1691 Ctx = &CI.getASTContext();
1692 if (CI.hasPreprocessor())
1693 PP = &CI.getPreprocessor();
Craig Topper49a27902014-05-22 04:46:25 +00001694 CI.setSourceManager(nullptr);
1695 CI.setFileManager(nullptr);
Ben Langmuir532fdc02014-04-18 20:39:48 +00001696 if (CI.hasTarget())
1697 Target = &CI.getTarget();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001698 Reader = CI.getModuleManager();
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001699 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001700}
1701
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001702StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis928e1fd2013-01-11 22:11:14 +00001703 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1704 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1705 if (Input.isFile())
1706 return Input.getFile();
1707 else
1708 return Input.getBuffer()->getBufferIdentifier();
1709 }
1710
1711 if (SourceMgr) {
1712 if (const FileEntry *
1713 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1714 return FE->getName();
1715 }
1716
1717 return StringRef();
Douglas Gregor16896c42010-10-28 15:44:59 +00001718}
1719
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00001720StringRef ASTUnit::getASTFileName() const {
1721 if (!isMainFileAST())
1722 return StringRef();
1723
1724 serialization::ModuleFile &
1725 Mod = Reader->getModuleManager().getPrimaryModule();
1726 return Mod.FileName;
1727}
1728
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001729ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001730 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001731 bool CaptureDiagnostics,
1732 bool UserFilesAreVolatile) {
Ahmed Charlesb8984322014-03-07 20:03:18 +00001733 std::unique_ptr<ASTUnit> AST;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001734 AST.reset(new ASTUnit(false));
Craig Topper49a27902014-05-22 04:46:25 +00001735 ConfigureDiags(Diags, nullptr, nullptr, *AST, CaptureDiagnostics);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001736 AST->Diagnostics = Diags;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001737 AST->Invocation = CI;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001738 AST->FileSystemOpts = CI->getFileSystemOpts();
Ben Langmuir8832c062014-04-15 18:16:25 +00001739 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1740 createVFSFromCompilerInvocation(*CI, *Diags);
1741 if (!VFS)
1742 return nullptr;
1743 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001744 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1745 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1746 UserFilesAreVolatile);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001747
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001748 return AST.release();
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001749}
1750
Ahmed Charlesb8984322014-03-07 20:03:18 +00001751ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
1752 CompilerInvocation *CI, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1753 ASTFrontendAction *Action, ASTUnit *Unit, bool Persistent,
1754 StringRef ResourceFilesPath, bool OnlyLocalDecls, bool CaptureDiagnostics,
1755 bool PrecompilePreamble, bool CacheCodeCompletionResults,
1756 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1757 std::unique_ptr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001758 assert(CI && "A CompilerInvocation is required");
1759
Ahmed Charlesb8984322014-03-07 20:03:18 +00001760 std::unique_ptr<ASTUnit> OwnAST;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001761 ASTUnit *AST = Unit;
1762 if (!AST) {
1763 // Create the AST unit.
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001764 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001765 AST = OwnAST.get();
Ben Langmuir8832c062014-04-15 18:16:25 +00001766 if (!AST)
1767 return nullptr;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001768 }
1769
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001770 if (!ResourceFilesPath.empty()) {
1771 // Override the resources path.
1772 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1773 }
1774 AST->OnlyLocalDecls = OnlyLocalDecls;
1775 AST->CaptureDiagnostics = CaptureDiagnostics;
1776 if (PrecompilePreamble)
1777 AST->PreambleRebuildCounter = 2;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001778 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001779 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001780 AST->IncludeBriefCommentsInCodeCompletion
1781 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001782
1783 // Recover resources if we crash before exiting this method.
1784 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001785 ASTUnitCleanup(OwnAST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001786 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1787 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00001788 DiagCleanup(Diags.get());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001789
1790 // We'll manage file buffers ourselves.
1791 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1792 CI->getFrontendOpts().DisableFree = false;
1793 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1794
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001795 // Create the compiler instance to use for building the AST.
Ahmed Charlesb8984322014-03-07 20:03:18 +00001796 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001797
1798 // Recover resources if we crash before exiting this method.
1799 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1800 CICleanup(Clang.get());
1801
1802 Clang->setInvocation(CI);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001803 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001804
1805 // Set up diagnostics, capturing any diagnostics that would
1806 // otherwise be dropped.
1807 Clang->setDiagnostics(&AST->getDiagnostics());
1808
1809 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001810 Clang->setTarget(TargetInfo::CreateTargetInfo(
1811 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001812 if (!Clang->hasTarget())
Craig Topper49a27902014-05-22 04:46:25 +00001813 return nullptr;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001814
1815 // Inform the target of the language options.
1816 //
1817 // FIXME: We shouldn't need to do this, the target should be immutable once
1818 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001819 Clang->getTarget().adjust(Clang->getLangOpts());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001820
1821 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1822 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001823 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001824 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001825 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001826 "IR inputs not supported here!");
1827
1828 // Configure the various subsystems.
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001829 AST->TheSema.reset();
Craig Topper49a27902014-05-22 04:46:25 +00001830 AST->Ctx = nullptr;
1831 AST->PP = nullptr;
1832 AST->Reader = nullptr;
1833
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001834 // Create a file manager object to provide access to and cache the filesystem.
1835 Clang->setFileManager(&AST->getFileManager());
1836
1837 // Create the source manager.
1838 Clang->setSourceManager(&AST->getSourceManager());
1839
1840 ASTFrontendAction *Act = Action;
1841
Ahmed Charlesb8984322014-03-07 20:03:18 +00001842 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001843 if (!Act) {
1844 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1845 Act = TrackerAct.get();
1846 }
1847
1848 // Recover resources if we crash before exiting this method.
1849 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1850 ActCleanup(TrackerAct.get());
1851
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001852 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1853 AST->transferASTDataFromCompilerInstance(*Clang);
1854 if (OwnAST && ErrAST)
1855 ErrAST->swap(OwnAST);
1856
Craig Topper49a27902014-05-22 04:46:25 +00001857 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001858 }
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001859
1860 if (Persistent && !TrackerAct) {
1861 Clang->getPreprocessor().addPPCallbacks(
1862 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +00001863 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001864 if (Clang->hasASTConsumer())
1865 Consumers.push_back(Clang->takeASTConsumer());
David Blaikie6beb6aa2014-08-10 19:56:51 +00001866 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1867 *AST, AST->getCurrentTopLevelHashValue()));
1868 Clang->setASTConsumer(
1869 llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001870 }
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001871 if (!Act->Execute()) {
1872 AST->transferASTDataFromCompilerInstance(*Clang);
1873 if (OwnAST && ErrAST)
1874 ErrAST->swap(OwnAST);
1875
Craig Topper49a27902014-05-22 04:46:25 +00001876 return nullptr;
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001877 }
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001878
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001879 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001880 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001881
1882 Act->EndSourceFile();
1883
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001884 if (OwnAST)
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001885 return OwnAST.release();
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001886 else
1887 return AST;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001888}
1889
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001890bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1891 if (!Invocation)
1892 return true;
1893
1894 // We'll manage file buffers ourselves.
1895 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1896 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001897 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001898
Craig Topper49a27902014-05-22 04:46:25 +00001899 llvm::MemoryBuffer *OverrideMainBuffer = nullptr;
Douglas Gregorf5a18542010-10-27 17:24:53 +00001900 if (PrecompilePreamble) {
Douglas Gregorc6592922010-11-15 23:00:34 +00001901 PreambleRebuildCounter = 2;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001902 OverrideMainBuffer
1903 = getMainBufferWithPrecompiledPreamble(*Invocation);
1904 }
1905
Douglas Gregor16896c42010-10-28 15:44:59 +00001906 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001907 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001908
Ted Kremenek022a4902011-03-22 01:15:24 +00001909 // Recover resources if we crash before exiting this method.
1910 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1911 MemBufferCleanup(OverrideMainBuffer);
1912
Douglas Gregor16896c42010-10-28 15:44:59 +00001913 return Parse(OverrideMainBuffer);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001914}
1915
David Blaikie103a2de2014-04-25 17:01:33 +00001916std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1917 CompilerInvocation *CI, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1918 bool OnlyLocalDecls, bool CaptureDiagnostics, bool PrecompilePreamble,
1919 TranslationUnitKind TUKind, bool CacheCodeCompletionResults,
1920 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001921 // Create the AST unit.
David Blaikie103a2de2014-04-25 17:01:33 +00001922 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
Craig Topper49a27902014-05-22 04:46:25 +00001923 ConfigureDiags(Diags, nullptr, nullptr, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001924 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001925 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001926 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001927 AST->TUKind = TUKind;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001928 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001929 AST->IncludeBriefCommentsInCodeCompletion
1930 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001931 AST->Invocation = CI;
Argyrios Kyrtzidis3ad52ed2013-01-21 18:45:42 +00001932 AST->FileSystemOpts = CI->getFileSystemOpts();
Ben Langmuir8832c062014-04-15 18:16:25 +00001933 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1934 createVFSFromCompilerInvocation(*CI, *Diags);
1935 if (!VFS)
1936 return nullptr;
1937 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001938 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001939
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001940 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001941 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1942 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001943 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1944 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00001945 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001946
David Blaikie103a2de2014-04-25 17:01:33 +00001947 if (AST->LoadFromCompilerInvocation(PrecompilePreamble))
1948 return nullptr;
1949 return AST;
Daniel Dunbar764c0822009-12-01 09:51:01 +00001950}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001951
Ahmed Charlesb8984322014-03-07 20:03:18 +00001952ASTUnit *ASTUnit::LoadFromCommandLine(
1953 const char **ArgBegin, const char **ArgEnd,
1954 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1955 bool OnlyLocalDecls, bool CaptureDiagnostics,
1956 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
1957 bool PrecompilePreamble, TranslationUnitKind TUKind,
1958 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1959 bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
1960 bool UserFilesAreVolatile, bool ForSerialization,
1961 std::unique_ptr<ASTUnit> *ErrAST) {
Alp Tokerf994cef2014-07-05 03:08:06 +00001962 if (!Diags.get()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00001963 // No diagnostics engine was provided, so create our own diagnostics object
1964 // with the default options.
Sean Silvaf1b49e22013-01-20 01:58:28 +00001965 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions());
Douglas Gregord03e8232010-04-05 21:10:19 +00001966 }
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001967
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001968 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001969
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001970 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001971
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001972 {
Douglas Gregor925296b2011-07-19 16:10:42 +00001973
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001974 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001975 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001976
Argyrios Kyrtzidis5cf423e2011-04-04 23:11:45 +00001977 CI = clang::createInvocationFromCommandLine(
Frits van Bommel717d7ed2011-07-18 12:00:32 +00001978 llvm::makeArrayRef(ArgBegin, ArgEnd),
1979 Diags);
Argyrios Kyrtzidisf606b822011-04-04 21:38:51 +00001980 if (!CI)
Craig Topper49a27902014-05-22 04:46:25 +00001981 return nullptr;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001982 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001983
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001984 // Override any files that need remapping
Dmitri Gribenko2febd212014-02-07 15:00:22 +00001985 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00001986 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1987 RemappedFiles[I].second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001988 }
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00001989 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1990 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1991 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001992
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001993 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001994 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001995
Erik Verbruggen6e922512012-04-12 10:11:59 +00001996 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1997
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001998 // Create the AST unit.
Ahmed Charlesb8984322014-03-07 20:03:18 +00001999 std::unique_ptr<ASTUnit> AST;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002000 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00002001 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002002 AST->Diagnostics = Diags;
Craig Topper49a27902014-05-22 04:46:25 +00002003 Diags = nullptr; // Zero out now to ease cleanup during crash recovery.
Anders Carlssonc30dcec2011-03-18 18:22:40 +00002004 AST->FileSystemOpts = CI->getFileSystemOpts();
Ben Langmuir8832c062014-04-15 18:16:25 +00002005 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
2006 createVFSFromCompilerInvocation(*CI, *Diags);
2007 if (!VFS)
2008 return nullptr;
2009 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002010 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00002011 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00002012 AST->TUKind = TUKind;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002013 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002014 AST->IncludeBriefCommentsInCodeCompletion
2015 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00002016 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002017 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002018 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek5e14d392011-03-21 18:40:17 +00002019 AST->Invocation = CI;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002020 if (ForSerialization)
2021 AST->WriterData.reset(new ASTWriterData());
Craig Topper49a27902014-05-22 04:46:25 +00002022 CI = nullptr; // Zero out now to ease cleanup during crash recovery.
2023
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002024 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002025 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2026 ASTUnitCleanup(AST.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002027
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00002028 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
2029 // Some error occurred, if caller wants to examine diagnostics, pass it the
2030 // ASTUnit.
2031 if (ErrAST) {
2032 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2033 ErrAST->swap(AST);
2034 }
Craig Topper49a27902014-05-22 04:46:25 +00002035 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00002036 }
2037
Ahmed Charles9a16beb2014-03-07 19:33:25 +00002038 return AST.release();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002039}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002040
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002041bool ASTUnit::Reparse(ArrayRef<RemappedFile> RemappedFiles) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002042 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002043 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002044
2045 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002046
Douglas Gregor16896c42010-10-28 15:44:59 +00002047 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002048 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00002049
Douglas Gregor0e119552010-07-31 00:40:00 +00002050 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00002051 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Alp Toker1b070d22014-07-07 07:47:20 +00002052 for (const auto &RB : PPOpts.RemappedFileBuffers)
2053 delete RB.second;
2054
Douglas Gregor0e119552010-07-31 00:40:00 +00002055 Invocation->getPreprocessorOpts().clearRemappedFiles();
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002056 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002057 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2058 RemappedFiles[I].second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002059 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002060
Douglas Gregorbb420ab2010-08-04 05:53:38 +00002061 // If we have a preamble file lying around, or if we might try to
2062 // build a precompiled preamble, do so now.
Craig Topper49a27902014-05-22 04:46:25 +00002063 llvm::MemoryBuffer *OverrideMainBuffer = nullptr;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002064 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregorb97b6662010-08-20 00:59:43 +00002065 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor4dde7492010-07-23 23:58:40 +00002066
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002067 // Clear out the diagnostics state.
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002068 getDiagnostics().Reset();
2069 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis462ff352011-11-03 20:57:33 +00002070 if (OverrideMainBuffer)
2071 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002072
Douglas Gregor4dde7492010-07-23 23:58:40 +00002073 // Parse the sources
Douglas Gregordf7a79a2011-02-16 18:16:54 +00002074 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis36893372011-10-31 21:25:31 +00002075
2076 // If we're caching global code-completion results, and the top-level
2077 // declarations have changed, clear out the code-completion cache.
2078 if (!Result && ShouldCacheCodeCompletionResults &&
2079 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2080 CacheCodeCompletionResults();
Douglas Gregordf7a79a2011-02-16 18:16:54 +00002081
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002082 // We now need to clear out the completion info related to this translation
2083 // unit; it'll be recreated if necessary.
2084 CCTUInfo.reset();
Douglas Gregor3f35bb22011-08-04 20:04:59 +00002085
Douglas Gregor4dde7492010-07-23 23:58:40 +00002086 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002087}
Douglas Gregor8e984da2010-08-04 16:47:14 +00002088
Douglas Gregorb14904c2010-08-13 22:48:40 +00002089//----------------------------------------------------------------------------//
2090// Code completion
2091//----------------------------------------------------------------------------//
2092
2093namespace {
2094 /// \brief Code completion consumer that combines the cached code-completion
2095 /// results from an ASTUnit with the code-completion results provided to it,
2096 /// then passes the result on to
2097 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith697cc9e2012-08-14 03:13:00 +00002098 uint64_t NormalContexts;
Douglas Gregorb14904c2010-08-13 22:48:40 +00002099 ASTUnit &AST;
2100 CodeCompleteConsumer &Next;
2101
2102 public:
2103 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002104 const CodeCompleteOptions &CodeCompleteOpts)
2105 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2106 AST(AST), Next(Next)
Douglas Gregorb14904c2010-08-13 22:48:40 +00002107 {
2108 // Compute the set of contexts in which we will look when we don't have
2109 // any information about the specific context.
2110 NormalContexts
Richard Smith697cc9e2012-08-14 03:13:00 +00002111 = (1LL << CodeCompletionContext::CCC_TopLevel)
2112 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2113 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2114 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2115 | (1LL << CodeCompletionContext::CCC_Statement)
2116 | (1LL << CodeCompletionContext::CCC_Expression)
2117 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2118 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2119 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2120 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2121 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2122 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2123 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor5e35d592010-09-14 23:59:36 +00002124
David Blaikiebbafb8a2012-03-11 07:00:24 +00002125 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +00002126 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2127 | (1LL << CodeCompletionContext::CCC_UnionTag)
2128 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregorb14904c2010-08-13 22:48:40 +00002129 }
Craig Topperafa7cb32014-03-13 06:07:04 +00002130
2131 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
2132 CodeCompletionResult *Results,
2133 unsigned NumResults) override;
2134
2135 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2136 OverloadCandidate *Candidates,
2137 unsigned NumCandidates) override {
Douglas Gregorb14904c2010-08-13 22:48:40 +00002138 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2139 }
Craig Topperafa7cb32014-03-13 06:07:04 +00002140
2141 CodeCompletionAllocator &getAllocator() override {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002142 return Next.getAllocator();
2143 }
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002144
Craig Topperafa7cb32014-03-13 06:07:04 +00002145 CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002146 return Next.getCodeCompletionTUInfo();
2147 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00002148 };
2149}
Douglas Gregord46cf182010-08-16 20:01:48 +00002150
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002151/// \brief Helper function that computes which global names are hidden by the
2152/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002153static void CalculateHiddenNames(const CodeCompletionContext &Context,
2154 CodeCompletionResult *Results,
2155 unsigned NumResults,
2156 ASTContext &Ctx,
2157 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002158 bool OnlyTagNames = false;
2159 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00002160 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002161 case CodeCompletionContext::CCC_TopLevel:
2162 case CodeCompletionContext::CCC_ObjCInterface:
2163 case CodeCompletionContext::CCC_ObjCImplementation:
2164 case CodeCompletionContext::CCC_ObjCIvarList:
2165 case CodeCompletionContext::CCC_ClassStructUnion:
2166 case CodeCompletionContext::CCC_Statement:
2167 case CodeCompletionContext::CCC_Expression:
2168 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor21325842011-07-07 16:03:39 +00002169 case CodeCompletionContext::CCC_DotMemberAccess:
2170 case CodeCompletionContext::CCC_ArrowMemberAccess:
2171 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002172 case CodeCompletionContext::CCC_Namespace:
2173 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00002174 case CodeCompletionContext::CCC_Name:
2175 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00002176 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor2c595ad2011-07-30 06:55:39 +00002177 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002178 break;
2179
2180 case CodeCompletionContext::CCC_EnumTag:
2181 case CodeCompletionContext::CCC_UnionTag:
2182 case CodeCompletionContext::CCC_ClassOrStructTag:
2183 OnlyTagNames = true;
2184 break;
2185
2186 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00002187 case CodeCompletionContext::CCC_MacroName:
2188 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00002189 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002190 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00002191 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00002192 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00002193 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00002194 case CodeCompletionContext::CCC_Other:
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00002195 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor21325842011-07-07 16:03:39 +00002196 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2197 case CodeCompletionContext::CCC_ObjCClassMessage:
2198 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002199 // We're looking for nothing, or we're looking for names that cannot
2200 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002201 return;
2202 }
2203
John McCall276321a2010-08-25 06:19:51 +00002204 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002205 for (unsigned I = 0; I != NumResults; ++I) {
2206 if (Results[I].Kind != Result::RK_Declaration)
2207 continue;
2208
2209 unsigned IDNS
2210 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2211
2212 bool Hiding = false;
2213 if (OnlyTagNames)
2214 Hiding = (IDNS & Decl::IDNS_Tag);
2215 else {
2216 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00002217 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2218 Decl::IDNS_NonMemberOperator);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002219 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002220 HiddenIDNS |= Decl::IDNS_Tag;
2221 Hiding = (IDNS & HiddenIDNS);
2222 }
2223
2224 if (!Hiding)
2225 continue;
2226
2227 DeclarationName Name = Results[I].Declaration->getDeclName();
2228 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2229 HiddenNames.insert(Identifier->getName());
2230 else
2231 HiddenNames.insert(Name.getAsString());
2232 }
2233}
2234
2235
Douglas Gregord46cf182010-08-16 20:01:48 +00002236void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2237 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002238 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00002239 unsigned NumResults) {
2240 // Merge the results we were given with the results we cached.
2241 bool AddedResult = false;
Richard Smith697cc9e2012-08-14 03:13:00 +00002242 uint64_t InContexts =
2243 Context.getKind() == CodeCompletionContext::CCC_Recovery
2244 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002245 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002246 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall276321a2010-08-25 06:19:51 +00002247 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002248 SmallVector<Result, 8> AllResults;
Douglas Gregord46cf182010-08-16 20:01:48 +00002249 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00002250 C = AST.cached_completion_begin(),
2251 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00002252 C != CEnd; ++C) {
2253 // If the context we are in matches any of the contexts we are
2254 // interested in, we'll add this result.
2255 if ((C->ShowInContexts & InContexts) == 0)
2256 continue;
2257
2258 // If we haven't added any results previously, do so now.
2259 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002260 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2261 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00002262 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2263 AddedResult = true;
2264 }
2265
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002266 // Determine whether this global completion result is hidden by a local
2267 // completion result. If so, skip it.
2268 if (C->Kind != CXCursor_MacroDefinition &&
2269 HiddenNames.count(C->Completion->getTypedText()))
2270 continue;
2271
Douglas Gregord46cf182010-08-16 20:01:48 +00002272 // Adjust priority based on similar type classes.
2273 unsigned Priority = C->Priority;
Douglas Gregor12785102010-08-24 20:21:13 +00002274 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00002275 if (!Context.getPreferredType().isNull()) {
2276 if (C->Kind == CXCursor_MacroDefinition) {
2277 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002278 S.getLangOpts(),
Douglas Gregor12785102010-08-24 20:21:13 +00002279 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00002280 } else if (C->Type) {
2281 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00002282 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00002283 Context.getPreferredType().getUnqualifiedType());
2284 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2285 if (ExpectedSTC == C->TypeClass) {
2286 // We know this type is similar; check for an exact match.
2287 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00002288 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00002289 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00002290 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00002291 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2292 Priority /= CCF_ExactTypeMatch;
2293 else
2294 Priority /= CCF_SimilarTypeMatch;
2295 }
2296 }
2297 }
2298
Douglas Gregor12785102010-08-24 20:21:13 +00002299 // Adjust the completion string, if required.
2300 if (C->Kind == CXCursor_MacroDefinition &&
2301 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2302 // Create a new code-completion string that just contains the
2303 // macro name, without its arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002304 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2305 CCP_CodePattern, C->Availability);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002306 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00002307 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002308 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00002309 }
2310
Argyrios Kyrtzidis5c8b1cd2012-09-27 00:24:09 +00002311 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregorf757a122010-08-23 23:00:57 +00002312 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00002313 }
2314
2315 // If we did not add any cached completion results, just forward the
2316 // results we were given to the next consumer.
2317 if (!AddedResult) {
2318 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2319 return;
2320 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002321
Douglas Gregord46cf182010-08-16 20:01:48 +00002322 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2323 AllResults.size());
2324}
2325
2326
2327
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002328void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002329 ArrayRef<RemappedFile> RemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00002330 bool IncludeMacros,
2331 bool IncludeCodePatterns,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002332 bool IncludeBriefComments,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002333 CodeCompleteConsumer &Consumer,
David Blaikie9c902b52011-09-25 23:23:43 +00002334 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002335 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002336 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2337 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002338 if (!Invocation)
Douglas Gregor8e984da2010-08-04 16:47:14 +00002339 return;
2340
Douglas Gregor16896c42010-10-28 15:44:59 +00002341 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002342 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002343 Twine(Line) + ":" + Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00002344
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00002345 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek5e14d392011-03-21 18:40:17 +00002346 CCInvocation(new CompilerInvocation(*Invocation));
2347
2348 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002349 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek5e14d392011-03-21 18:40:17 +00002350 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002351
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002352 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2353 CachedCompletionResults.empty();
2354 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2355 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2356 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2357
2358 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2359
Douglas Gregor8e984da2010-08-04 16:47:14 +00002360 FrontendOpts.CodeCompletionAt.FileName = File;
2361 FrontendOpts.CodeCompletionAt.Line = Line;
2362 FrontendOpts.CodeCompletionAt.Column = Column;
2363
2364 // Set the language options appropriately.
Ted Kremenek8cf47df2011-11-17 23:01:24 +00002365 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002366
Ahmed Charlesb8984322014-03-07 20:03:18 +00002367 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002368
2369 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002370 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2371 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002372
Ted Kremenek5e14d392011-03-21 18:40:17 +00002373 Clang->setInvocation(&*CCInvocation);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002374 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002375
2376 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002377 Clang->setDiagnostics(&Diag);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002378 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek84de4a12011-03-21 18:40:07 +00002379 Clang->getDiagnostics(),
Douglas Gregor8e984da2010-08-04 16:47:14 +00002380 StoredDiagnostics);
Manuel Klimekbe0474c2013-07-18 14:23:12 +00002381 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002382
2383 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00002384 Clang->setTarget(TargetInfo::CreateTargetInfo(
2385 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002386 if (!Clang->hasTarget()) {
Craig Topper49a27902014-05-22 04:46:25 +00002387 Clang->setInvocation(nullptr);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002388 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002389 }
2390
2391 // Inform the target of the language options.
2392 //
2393 // FIXME: We shouldn't need to do this, the target should be immutable once
2394 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00002395 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002396
Ted Kremenek84de4a12011-03-21 18:40:07 +00002397 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002398 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002399 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002400 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002401 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002402 "IR inputs not support here!");
2403
2404
2405 // Use the source and file managers that we were given.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002406 Clang->setFileManager(&FileMgr);
2407 Clang->setSourceManager(&SourceMgr);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002408
2409 // Remap files.
2410 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00002411 PreprocessorOpts.RetainRemappedFileBuffers = true;
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002412 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002413 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
2414 RemappedFiles[I].second);
Daniel Jasperd90ec572014-02-12 08:45:05 +00002415 OwnedBuffers.push_back(RemappedFiles[I].second);
Douglas Gregorb97b6662010-08-20 00:59:43 +00002416 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002417
Douglas Gregorb14904c2010-08-13 22:48:40 +00002418 // Use the code completion consumer we were given, but adding any cached
2419 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00002420 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002421 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002422 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002423
Douglas Gregor028d3e42010-08-09 20:45:32 +00002424 // If we have a precompiled preamble, try to use it. We only allow
2425 // the use of the precompiled preamble if we're if the completion
2426 // point is within the main file, after the end of the precompiled
2427 // preamble.
Craig Topper49a27902014-05-22 04:46:25 +00002428 llvm::MemoryBuffer *OverrideMainBuffer = nullptr;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002429 if (!getPreambleFile(this).empty()) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002430 std::string CompleteFilePath(File);
Rafael Espindola073ff102013-07-29 21:26:52 +00002431 llvm::sys::fs::UniqueID CompleteFileID;
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002432
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00002433 if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002434 std::string MainPath(OriginalSourceFile);
Rafael Espindola073ff102013-07-29 21:26:52 +00002435 llvm::sys::fs::UniqueID MainID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00002436 if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002437 if (CompleteFileID == MainID && Line > 1)
Douglas Gregorb97b6662010-08-20 00:59:43 +00002438 OverrideMainBuffer
Ted Kremenek5e14d392011-03-21 18:40:17 +00002439 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregor8e817b62010-08-25 18:04:15 +00002440 Line - 1);
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002441 }
2442 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002443 }
2444
2445 // If the main file has been overridden due to the use of a preamble,
2446 // make that override happen and introduce the preamble.
2447 if (OverrideMainBuffer) {
2448 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2449 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2450 PreprocessorOpts.PrecompiledPreambleBytes.second
2451 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002452 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002453 PreprocessorOpts.DisablePCHValidation = true;
2454
Douglas Gregorb97b6662010-08-20 00:59:43 +00002455 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregor7b02b582010-08-20 00:02:33 +00002456 } else {
2457 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2458 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002459 }
2460
Argyrios Kyrtzidis870704f2012-11-02 22:18:44 +00002461 // Disable the preprocessing record if modules are not enabled.
2462 if (!Clang->getLangOpts().Modules)
2463 PreprocessorOpts.DetailedRecord = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00002464
2465 std::unique_ptr<SyntaxOnlyAction> Act;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002466 Act.reset(new SyntaxOnlyAction);
Douglas Gregor32fbe312012-01-20 16:28:04 +00002467 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00002468 Act->Execute();
2469 Act->EndSourceFile();
2470 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002471}
Douglas Gregore9386682010-08-13 05:36:37 +00002472
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002473bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00002474 if (HadModuleLoaderFatalFailure)
2475 return true;
2476
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002477 // Write to a temporary file and later rename it to the actual file, to avoid
2478 // possible race conditions.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002479 SmallString<128> TempPath;
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002480 TempPath = File;
2481 TempPath += "-%%%%%%%%";
2482 int fd;
Rafael Espindola18627112013-07-05 21:13:58 +00002483 if (llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath))
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002484 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002485
Douglas Gregore9386682010-08-13 05:36:37 +00002486 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2487 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002488 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002489
2490 serialize(Out);
2491 Out.close();
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002492 if (Out.has_error()) {
2493 Out.clear_error();
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002494 return true;
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002495 }
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002496
Rafael Espindola65e025c2011-12-25 01:18:52 +00002497 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Rafael Espindola2a008782014-01-10 21:32:14 +00002498 llvm::sys::fs::remove(TempPath.str());
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002499 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002500 }
2501
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002502 return false;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002503}
2504
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002505static bool serializeUnit(ASTWriter &Writer,
2506 SmallVectorImpl<char> &Buffer,
2507 Sema &S,
2508 bool hasErrors,
2509 raw_ostream &OS) {
Craig Topper49a27902014-05-22 04:46:25 +00002510 Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002511
2512 // Write the generated bitstream to "Out".
2513 if (!Buffer.empty())
2514 OS.write(Buffer.data(), Buffer.size());
2515
2516 return false;
2517}
2518
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002519bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00002520 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002521
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002522 if (WriterData)
2523 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2524 getSema(), hasErrors, OS);
2525
Daniel Dunbar9a963862012-02-29 20:31:23 +00002526 SmallString<128> Buffer;
Douglas Gregore9386682010-08-13 05:36:37 +00002527 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002528 ASTWriter Writer(Stream);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002529 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregore9386682010-08-13 05:36:37 +00002530}
Douglas Gregor925296b2011-07-19 16:10:42 +00002531
2532typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2533
Douglas Gregor925296b2011-07-19 16:10:42 +00002534void ASTUnit::TranslateStoredDiagnostics(
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002535 FileManager &FileMgr,
Douglas Gregor925296b2011-07-19 16:10:42 +00002536 SourceManager &SrcMgr,
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002537 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002538 SmallVectorImpl<StoredDiagnostic> &Out) {
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002539 // Map the standalone diagnostic into the new source manager. We also need to
2540 // remap all the locations to the new view. This includes the diag location,
2541 // any associated source ranges, and the source ranges of associated fix-its.
Douglas Gregor925296b2011-07-19 16:10:42 +00002542 // FIXME: There should be a cleaner way to do this.
2543
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002544 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregor925296b2011-07-19 16:10:42 +00002545 Result.reserve(Diags.size());
Douglas Gregor925296b2011-07-19 16:10:42 +00002546 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2547 // Rebuild the StoredDiagnostic.
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002548 const StandaloneDiagnostic &SD = Diags[I];
2549 if (SD.Filename.empty())
2550 continue;
2551 const FileEntry *FE = FileMgr.getFile(SD.Filename);
2552 if (!FE)
2553 continue;
2554 FileID FID = SrcMgr.translateFile(FE);
2555 SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
2556 if (FileLoc.isInvalid())
2557 continue;
2558 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
Douglas Gregor925296b2011-07-19 16:10:42 +00002559 FullSourceLoc Loc(L, SrcMgr);
2560
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002561 SmallVector<CharSourceRange, 4> Ranges;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002562 Ranges.reserve(SD.Ranges.size());
2563 for (std::vector<std::pair<unsigned, unsigned> >::const_iterator
2564 I = SD.Ranges.begin(), E = SD.Ranges.end(); I != E; ++I) {
2565 SourceLocation BL = FileLoc.getLocWithOffset((*I).first);
2566 SourceLocation EL = FileLoc.getLocWithOffset((*I).second);
2567 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
Douglas Gregor925296b2011-07-19 16:10:42 +00002568 }
2569
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002570 SmallVector<FixItHint, 2> FixIts;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002571 FixIts.reserve(SD.FixIts.size());
2572 for (std::vector<StandaloneFixIt>::const_iterator
2573 I = SD.FixIts.begin(), E = SD.FixIts.end();
Douglas Gregor925296b2011-07-19 16:10:42 +00002574 I != E; ++I) {
2575 FixIts.push_back(FixItHint());
2576 FixItHint &FH = FixIts.back();
2577 FH.CodeToInsert = I->CodeToInsert;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002578 SourceLocation BL = FileLoc.getLocWithOffset(I->RemoveRange.first);
2579 SourceLocation EL = FileLoc.getLocWithOffset(I->RemoveRange.second);
2580 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
Douglas Gregor925296b2011-07-19 16:10:42 +00002581 }
2582
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002583 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2584 SD.Message, Loc, Ranges, FixIts));
Douglas Gregor925296b2011-07-19 16:10:42 +00002585 }
2586 Result.swap(Out);
2587}
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002588
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002589void ASTUnit::addFileLevelDecl(Decl *D) {
2590 assert(D);
Douglas Gregor61d63d02011-11-07 18:53:57 +00002591
2592 // We only care about local declarations.
2593 if (D->isFromASTFile())
2594 return;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002595
2596 SourceManager &SM = *SourceMgr;
2597 SourceLocation Loc = D->getLocation();
2598 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2599 return;
2600
2601 // We only keep track of the file-level declarations of each file.
2602 if (!D->getLexicalDeclContext()->isFileContext())
2603 return;
2604
2605 SourceLocation FileLoc = SM.getFileLoc(Loc);
2606 assert(SM.isLocalSourceLocation(FileLoc));
2607 FileID FID;
2608 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002609 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002610 if (FID.isInvalid())
2611 return;
2612
2613 LocDeclsTy *&Decls = FileDecls[FID];
2614 if (!Decls)
2615 Decls = new LocDeclsTy();
2616
2617 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2618
2619 if (Decls->empty() || Decls->back().first <= Offset) {
2620 Decls->push_back(LocDecl);
2621 return;
2622 }
2623
Benjamin Kramer45025c02013-08-24 13:22:59 +00002624 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2625 LocDecl, llvm::less_first());
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002626
2627 Decls->insert(I, LocDecl);
2628}
2629
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002630void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2631 SmallVectorImpl<Decl *> &Decls) {
2632 if (File.isInvalid())
2633 return;
2634
2635 if (SourceMgr->isLoadedFileID(File)) {
2636 assert(Ctx->getExternalSource() && "No external source!");
2637 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2638 Decls);
2639 }
2640
2641 FileDeclsTy::iterator I = FileDecls.find(File);
2642 if (I == FileDecls.end())
2643 return;
2644
2645 LocDeclsTy &LocDecls = *I->second;
2646 if (LocDecls.empty())
2647 return;
2648
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002649 LocDeclsTy::iterator BeginIt =
2650 std::lower_bound(LocDecls.begin(), LocDecls.end(),
Craig Topper49a27902014-05-22 04:46:25 +00002651 std::make_pair(Offset, (Decl *)nullptr),
2652 llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002653 if (BeginIt != LocDecls.begin())
2654 --BeginIt;
2655
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00002656 // If we are pointing at a top-level decl inside an objc container, we need
2657 // to backtrack until we find it otherwise we will fail to report that the
2658 // region overlaps with an objc container.
2659 while (BeginIt != LocDecls.begin() &&
2660 BeginIt->second->isTopLevelDeclInObjCContainer())
2661 --BeginIt;
2662
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002663 LocDeclsTy::iterator EndIt = std::upper_bound(
2664 LocDecls.begin(), LocDecls.end(),
Craig Topper49a27902014-05-22 04:46:25 +00002665 std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002666 if (EndIt != LocDecls.end())
2667 ++EndIt;
2668
2669 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2670 Decls.push_back(DIt->second);
2671}
2672
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002673SourceLocation ASTUnit::getLocation(const FileEntry *File,
2674 unsigned Line, unsigned Col) const {
2675 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002676 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002677 return SM.getMacroArgExpandedLocation(Loc);
2678}
2679
2680SourceLocation ASTUnit::getLocation(const FileEntry *File,
2681 unsigned Offset) const {
2682 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002683 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002684 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2685}
2686
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002687/// \brief If \arg Loc is a loaded location from the preamble, returns
2688/// the corresponding local location of the main file, otherwise it returns
2689/// \arg Loc.
2690SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2691 FileID PreambleID;
2692 if (SourceMgr)
2693 PreambleID = SourceMgr->getPreambleFileID();
2694
2695 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2696 return Loc;
2697
2698 unsigned Offs;
2699 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2700 SourceLocation FileLoc
2701 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2702 return FileLoc.getLocWithOffset(Offs);
2703 }
2704
2705 return Loc;
2706}
2707
2708/// \brief If \arg Loc is a local location of the main file but inside the
2709/// preamble chunk, returns the corresponding loaded location from the
2710/// preamble, otherwise it returns \arg Loc.
2711SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2712 FileID PreambleID;
2713 if (SourceMgr)
2714 PreambleID = SourceMgr->getPreambleFileID();
2715
2716 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2717 return Loc;
2718
2719 unsigned Offs;
2720 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2721 Offs < Preamble.size()) {
2722 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2723 return FileLoc.getLocWithOffset(Offs);
2724 }
2725
2726 return Loc;
2727}
2728
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002729bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2730 FileID FID;
2731 if (SourceMgr)
2732 FID = SourceMgr->getPreambleFileID();
2733
2734 if (Loc.isInvalid() || FID.isInvalid())
2735 return false;
2736
2737 return SourceMgr->isInFileID(Loc, FID);
2738}
2739
2740bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2741 FileID FID;
2742 if (SourceMgr)
2743 FID = SourceMgr->getMainFileID();
2744
2745 if (Loc.isInvalid() || FID.isInvalid())
2746 return false;
2747
2748 return SourceMgr->isInFileID(Loc, FID);
2749}
2750
2751SourceLocation ASTUnit::getEndOfPreambleFileID() {
2752 FileID FID;
2753 if (SourceMgr)
2754 FID = SourceMgr->getPreambleFileID();
2755
2756 if (FID.isInvalid())
2757 return SourceLocation();
2758
2759 return SourceMgr->getLocForEndOfFile(FID);
2760}
2761
2762SourceLocation ASTUnit::getStartOfMainFileID() {
2763 FileID FID;
2764 if (SourceMgr)
2765 FID = SourceMgr->getMainFileID();
2766
2767 if (FID.isInvalid())
2768 return SourceLocation();
2769
2770 return SourceMgr->getLocForStartOfFile(FID);
2771}
2772
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002773std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
2774ASTUnit::getLocalPreprocessingEntities() const {
2775 if (isMainFileAST()) {
2776 serialization::ModuleFile &
2777 Mod = Reader->getModuleManager().getPrimaryModule();
2778 return Reader->getModulePreprocessedEntities(Mod);
2779 }
2780
2781 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2782 return std::make_pair(PPRec->local_begin(), PPRec->local_end());
2783
2784 return std::make_pair(PreprocessingRecord::iterator(),
2785 PreprocessingRecord::iterator());
2786}
2787
Argyrios Kyrtzidise514b202012-10-03 01:58:28 +00002788bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002789 if (isMainFileAST()) {
2790 serialization::ModuleFile &
2791 Mod = Reader->getModuleManager().getPrimaryModule();
2792 ASTReader::ModuleDeclIterator MDI, MDE;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002793 std::tie(MDI, MDE) = Reader->getModuleFileLevelDecls(Mod);
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002794 for (; MDI != MDE; ++MDI) {
2795 if (!Fn(context, *MDI))
2796 return false;
2797 }
2798
2799 return true;
2800 }
2801
2802 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2803 TLEnd = top_level_end();
2804 TL != TLEnd; ++TL) {
2805 if (!Fn(context, *TL))
2806 return false;
2807 }
2808
2809 return true;
2810}
2811
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002812namespace {
2813struct PCHLocatorInfo {
2814 serialization::ModuleFile *Mod;
Craig Topper49a27902014-05-22 04:46:25 +00002815 PCHLocatorInfo() : Mod(nullptr) {}
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002816};
2817}
2818
2819static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
2820 PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
2821 switch (M.Kind) {
2822 case serialization::MK_Module:
2823 return true; // skip dependencies.
2824 case serialization::MK_PCH:
2825 Info.Mod = &M;
2826 return true; // found it.
2827 case serialization::MK_Preamble:
2828 return false; // look in dependencies.
2829 case serialization::MK_MainFile:
2830 return false; // look in dependencies.
2831 }
2832
2833 return true;
2834}
2835
2836const FileEntry *ASTUnit::getPCHFile() {
2837 if (!Reader)
Craig Topper49a27902014-05-22 04:46:25 +00002838 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002839
2840 PCHLocatorInfo Info;
2841 Reader->getModuleManager().visit(PCHLocator, &Info);
2842 if (Info.Mod)
2843 return Info.Mod->File;
2844
Craig Topper49a27902014-05-22 04:46:25 +00002845 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002846}
2847
Argyrios Kyrtzidise445c722012-10-10 02:12:47 +00002848bool ASTUnit::isModuleFile() {
2849 return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2850}
2851
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002852void ASTUnit::PreambleData::countLines() const {
2853 NumLines = 0;
2854 if (empty())
2855 return;
2856
2857 for (std::vector<char>::const_iterator
2858 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2859 if (*I == '\n')
2860 ++NumLines;
2861 }
2862 if (Buffer.back() != '\n')
2863 ++NumLines;
2864}
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002865
2866#ifndef NDEBUG
2867ASTUnit::ConcurrencyState::ConcurrencyState() {
2868 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2869}
2870
2871ASTUnit::ConcurrencyState::~ConcurrencyState() {
2872 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2873}
2874
2875void ASTUnit::ConcurrencyState::start() {
2876 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2877 assert(acquired && "Concurrent access to ASTUnit!");
2878}
2879
2880void ASTUnit::ConcurrencyState::finish() {
2881 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2882}
2883
2884#else // NDEBUG
2885
Alp Tokerb159c132013-11-22 07:49:39 +00002886ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = 0; }
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002887ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2888void ASTUnit::ConcurrencyState::start() {}
2889void ASTUnit::ConcurrencyState::finish() {}
2890
2891#endif