blob: 31266dca92803aeb2333760824b3bf0c289a27d6 [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
Dylan Noblesmithcdd31512014-08-24 18:59:52 +0000108typedef llvm::DenseMap<const ASTUnit *,
109 std::unique_ptr<OnDiskData>> OnDiskDataMap;
Ted Kremenek06b4f912011-10-27 17:55:18 +0000110static OnDiskDataMap &getOnDiskDataMap() {
111 static OnDiskDataMap M;
112 static bool hasRegisteredAtExit = false;
113 if (!hasRegisteredAtExit) {
114 hasRegisteredAtExit = true;
115 atexit(cleanupOnDiskMapAtExit);
116 }
117 return M;
118}
119
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000120static void cleanupOnDiskMapAtExit() {
Argyrios Kyrtzidis4cf2ffe2012-07-03 16:30:52 +0000121 // Use the mutex because there can be an alive thread destroying an ASTUnit.
122 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek06b4f912011-10-27 17:55:18 +0000123 OnDiskDataMap &M = getOnDiskDataMap();
124 for (OnDiskDataMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
125 // We don't worry about freeing the memory associated with OnDiskDataMap.
126 // All we care about is erasing stale files.
127 I->second->Cleanup();
128 }
129}
130
131static OnDiskData &getOnDiskData(const ASTUnit *AU) {
Ted Kremenekbd307a52011-10-27 19:44:25 +0000132 // We require the mutex since we are modifying the structure of the
133 // DenseMap.
134 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek06b4f912011-10-27 17:55:18 +0000135 OnDiskDataMap &M = getOnDiskDataMap();
Dylan Noblesmithcdd31512014-08-24 18:59:52 +0000136 auto &D = M[AU];
Ted Kremenek06b4f912011-10-27 17:55:18 +0000137 if (!D)
Dylan Noblesmithcdd31512014-08-24 18:59:52 +0000138 D = llvm::make_unique<OnDiskData>();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000139 return *D;
140}
141
142static void erasePreambleFile(const ASTUnit *AU) {
143 getOnDiskData(AU).CleanPreambleFile();
144}
145
146static void removeOnDiskEntry(const ASTUnit *AU) {
Ted Kremenekbd307a52011-10-27 19:44:25 +0000147 // We require the mutex since we are modifying the structure of the
148 // DenseMap.
149 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek06b4f912011-10-27 17:55:18 +0000150 OnDiskDataMap &M = getOnDiskDataMap();
151 OnDiskDataMap::iterator I = M.find(AU);
152 if (I != M.end()) {
153 I->second->Cleanup();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000154 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),
Rafael Espindola4674a872014-08-13 17:08:22 +0000222 PreambleRebuildCounter(0),
Rafael Espindolafa49c0b2014-08-13 16:47:00 +0000223 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 Gregora0734c52010-08-19 01:33:06 +0000254
Douglas Gregor16896c42010-10-28 15:44:59 +0000255 ClearCachedCompletionResults();
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000256
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000257 if (getenv("LIBCLANG_OBJTRACKING"))
258 fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000259}
260
Argyrios Kyrtzidisda6e0542012-01-17 18:48:07 +0000261void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
262
Douglas Gregor39982192010-08-15 06:18:01 +0000263/// \brief Determine the set of code-completion contexts in which this
264/// declaration should be shown.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000265static unsigned getDeclShowContexts(const NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000266 const LangOptions &LangOpts,
267 bool &IsNestedNameSpecifier) {
268 IsNestedNameSpecifier = false;
269
Douglas Gregor39982192010-08-15 06:18:01 +0000270 if (isa<UsingShadowDecl>(ND))
271 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
272 if (!ND)
273 return 0;
274
Richard Smith697cc9e2012-08-14 03:13:00 +0000275 uint64_t Contexts = 0;
Douglas Gregor39982192010-08-15 06:18:01 +0000276 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
277 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
278 // Types can appear in these contexts.
279 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000280 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
281 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
282 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
283 | (1LL << CodeCompletionContext::CCC_Statement)
284 | (1LL << CodeCompletionContext::CCC_Type)
285 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor39982192010-08-15 06:18:01 +0000286
287 // In C++, types can appear in expressions contexts (for functional casts).
288 if (LangOpts.CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +0000289 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor39982192010-08-15 06:18:01 +0000290
291 // In Objective-C, message sends can send interfaces. In Objective-C++,
292 // all types are available due to functional casts.
293 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000294 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor21325842011-07-07 16:03:39 +0000295
296 // In Objective-C, you can only be a subclass of another Objective-C class
297 if (isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000298 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor39982192010-08-15 06:18:01 +0000299
300 // Deal with tag names.
301 if (isa<EnumDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000302 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000303
Douglas Gregor59cab552010-08-16 23:05:20 +0000304 // Part of the nested-name-specifier in C++0x.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000305 if (LangOpts.CPlusPlus11)
Douglas Gregor59cab552010-08-16 23:05:20 +0000306 IsNestedNameSpecifier = true;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000307 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
Douglas Gregor39982192010-08-15 06:18:01 +0000308 if (Record->isUnion())
Richard Smith697cc9e2012-08-14 03:13:00 +0000309 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000310 else
Richard Smith697cc9e2012-08-14 03:13:00 +0000311 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000312
Douglas Gregor39982192010-08-15 06:18:01 +0000313 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000314 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000315 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000316 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000317 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
318 // Values can appear in these contexts.
Richard Smith697cc9e2012-08-14 03:13:00 +0000319 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
320 | (1LL << CodeCompletionContext::CCC_Expression)
321 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
322 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor39982192010-08-15 06:18:01 +0000323 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000324 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor21325842011-07-07 16:03:39 +0000325 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000326 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor39982192010-08-15 06:18:01 +0000327 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000328 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor39982192010-08-15 06:18:01 +0000329
330 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000331 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000332 }
333
334 return Contexts;
335}
336
Douglas Gregorb14904c2010-08-13 22:48:40 +0000337void ASTUnit::CacheCodeCompletionResults() {
338 if (!TheSema)
339 return;
340
Douglas Gregor16896c42010-10-28 15:44:59 +0000341 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000342 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000343
344 // Clear out the previous results.
345 ClearCachedCompletionResults();
346
347 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000348 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000349 SmallVector<Result, 8> Results;
Douglas Gregor162b7122011-02-16 19:08:06 +0000350 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000351 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000352 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000353 CCTUInfo, Results);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000354
355 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000356 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
357
Douglas Gregorb14904c2010-08-13 22:48:40 +0000358 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
359 switch (Results[I].Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000360 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000361 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000362 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000363 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000364 *CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000365 CCTUInfo,
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000366 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor39982192010-08-15 06:18:01 +0000367 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000368 Ctx->getLangOpts(),
Douglas Gregor59cab552010-08-16 23:05:20 +0000369 IsNestedNameSpecifier);
Douglas Gregor39982192010-08-15 06:18:01 +0000370 CachedResult.Priority = Results[I].Priority;
371 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000372 CachedResult.Availability = Results[I].Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000373
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000374 // Keep track of the type of this completion in an ASTContext-agnostic
375 // way.
Douglas Gregor24747402010-08-16 16:46:30 +0000376 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000377 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000378 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000379 CachedResult.Type = 0;
380 } else {
381 CanQualType CanUsageType
382 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
383 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
384
385 // Determine whether we have already seen this type. If so, we save
386 // ourselves the work of formatting the type string by using the
387 // temporary, CanQualType-based hash table to find the associated value.
388 unsigned &TypeValue = CompletionTypes[CanUsageType];
389 if (TypeValue == 0) {
390 TypeValue = CompletionTypes.size();
391 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
392 = TypeValue;
393 }
394
395 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000396 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000397
Douglas Gregor39982192010-08-15 06:18:01 +0000398 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000399
400 /// Handle nested-name-specifiers in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000401 if (TheSema->Context.getLangOpts().CPlusPlus &&
Douglas Gregor59cab552010-08-16 23:05:20 +0000402 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
403 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith697cc9e2012-08-14 03:13:00 +0000404 uint64_t NNSContexts
405 = (1LL << CodeCompletionContext::CCC_TopLevel)
406 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
407 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
408 | (1LL << CodeCompletionContext::CCC_Statement)
409 | (1LL << CodeCompletionContext::CCC_Expression)
410 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
411 | (1LL << CodeCompletionContext::CCC_EnumTag)
412 | (1LL << CodeCompletionContext::CCC_UnionTag)
413 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
414 | (1LL << CodeCompletionContext::CCC_Type)
415 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
416 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor59cab552010-08-16 23:05:20 +0000417
418 if (isa<NamespaceDecl>(Results[I].Declaration) ||
419 isa<NamespaceAliasDecl>(Results[I].Declaration))
Richard Smith697cc9e2012-08-14 03:13:00 +0000420 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor59cab552010-08-16 23:05:20 +0000421
422 if (unsigned RemainingContexts
423 = NNSContexts & ~CachedResult.ShowInContexts) {
424 // If there any contexts where this completion can be a
425 // nested-name-specifier but isn't already an option, create a
426 // nested-name-specifier completion.
427 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000428 CachedResult.Completion
429 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000430 *CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000431 CCTUInfo,
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000432 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor59cab552010-08-16 23:05:20 +0000433 CachedResult.ShowInContexts = RemainingContexts;
434 CachedResult.Priority = CCP_NestedNameSpecifier;
435 CachedResult.TypeClass = STC_Void;
436 CachedResult.Type = 0;
437 CachedCompletionResults.push_back(CachedResult);
438 }
439 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000440 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000441 }
442
Douglas Gregorb14904c2010-08-13 22:48:40 +0000443 case Result::RK_Keyword:
444 case Result::RK_Pattern:
445 // Ignore keywords and patterns; we don't care, since they are so
446 // easily regenerated.
447 break;
448
449 case Result::RK_Macro: {
450 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000451 CachedResult.Completion
452 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000453 *CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000454 CCTUInfo,
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000455 IncludeBriefCommentsInCodeCompletion);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000456 CachedResult.ShowInContexts
Richard Smith697cc9e2012-08-14 03:13:00 +0000457 = (1LL << CodeCompletionContext::CCC_TopLevel)
458 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
459 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
460 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
461 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
462 | (1LL << CodeCompletionContext::CCC_Statement)
463 | (1LL << CodeCompletionContext::CCC_Expression)
464 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
465 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
466 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
467 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
468 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000469
Douglas Gregorb14904c2010-08-13 22:48:40 +0000470 CachedResult.Priority = Results[I].Priority;
471 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000472 CachedResult.Availability = Results[I].Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000473 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000474 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000475 CachedCompletionResults.push_back(CachedResult);
476 break;
477 }
478 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000479 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000480
481 // Save the current top-level hash value.
482 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000483}
484
485void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregorb14904c2010-08-13 22:48:40 +0000486 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000487 CachedCompletionTypes.clear();
Craig Topper49a27902014-05-22 04:46:25 +0000488 CachedCompletionAllocator = nullptr;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000489}
490
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000491namespace {
492
Sebastian Redl2c499f62010-08-18 23:56:43 +0000493/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000494/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000495class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor83297df2011-09-01 23:39:15 +0000496 Preprocessor &PP;
Douglas Gregore8bbc122011-09-02 00:18:52 +0000497 ASTContext &Context;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000498 LangOptions &LangOpt;
Alp Toker80758082014-07-06 05:26:44 +0000499 std::shared_ptr<TargetOptions> &TargetOpts;
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000500 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000501 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000502
Douglas Gregore8bbc122011-09-02 00:18:52 +0000503 bool InitializedLanguage;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000504public:
Alp Toker80758082014-07-06 05:26:44 +0000505 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
506 std::shared_ptr<TargetOptions> &TargetOpts,
507 IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
508 : PP(PP), Context(Context), LangOpt(LangOpt), TargetOpts(TargetOpts),
509 Target(Target), Counter(Counter), InitializedLanguage(false) {}
Mike Stump11289f42009-09-09 15:08:12 +0000510
Craig Topperafa7cb32014-03-13 06:07:04 +0000511 bool ReadLanguageOptions(const LangOptions &LangOpts,
512 bool Complain) override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000513 if (InitializedLanguage)
Douglas Gregor83297df2011-09-01 23:39:15 +0000514 return false;
515
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000516 LangOpt = LangOpts;
517 InitializedLanguage = true;
518
519 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000520 return false;
521 }
Mike Stump11289f42009-09-09 15:08:12 +0000522
Craig Topperafa7cb32014-03-13 06:07:04 +0000523 bool ReadTargetOptions(const TargetOptions &TargetOpts,
524 bool Complain) override {
Douglas Gregor83297df2011-09-01 23:39:15 +0000525 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000526 if (Target)
Douglas Gregor83297df2011-09-01 23:39:15 +0000527 return false;
Alp Toker80758082014-07-06 05:26:44 +0000528
529 this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
530 Target =
531 TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000532
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000533 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000534 return false;
535 }
Mike Stump11289f42009-09-09 15:08:12 +0000536
Craig Topperafa7cb32014-03-13 06:07:04 +0000537 void ReadCounter(const serialization::ModuleFile &M,
538 unsigned Value) override {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000539 Counter = Value;
540 }
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000541
542private:
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000543 void updated() {
544 if (!Target || !InitializedLanguage)
545 return;
546
547 // Inform the target of the language options.
548 //
549 // FIXME: We shouldn't need to do this, the target should be immutable once
550 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +0000551 Target->adjust(LangOpt);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000552
553 // Initialize the preprocessor.
554 PP.Initialize(*Target);
555
556 // Initialize the ASTContext
557 Context.InitBuiltinTypes(*Target);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000558
559 // We didn't have access to the comment options when the ASTContext was
560 // constructed, so register them now.
561 Context.getCommentCommandTraits().registerCommentOptions(
562 LangOpt.CommentOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000563 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000564};
565
Douglas Gregor6b930962013-05-03 22:58:43 +0000566 /// \brief Diagnostic consumer that saves each diagnostic it is given.
David Blaikief18d91a2011-09-26 00:01:39 +0000567class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000568 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregor6b930962013-05-03 22:58:43 +0000569 SourceManager *SourceMgr;
570
Douglas Gregor33cdd812010-02-18 18:08:43 +0000571public:
David Blaikief18d91a2011-09-26 00:01:39 +0000572 explicit StoredDiagnosticConsumer(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000573 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Craig Topper49a27902014-05-22 04:46:25 +0000574 : StoredDiags(StoredDiags), SourceMgr(nullptr) {}
Douglas Gregor6b930962013-05-03 22:58:43 +0000575
Craig Topperafa7cb32014-03-13 06:07:04 +0000576 void BeginSourceFile(const LangOptions &LangOpts,
Craig Topper49a27902014-05-22 04:46:25 +0000577 const Preprocessor *PP = nullptr) override {
Douglas Gregor6b930962013-05-03 22:58:43 +0000578 if (PP)
579 SourceMgr = &PP->getSourceManager();
580 }
581
Craig Topperafa7cb32014-03-13 06:07:04 +0000582 void HandleDiagnostic(DiagnosticsEngine::Level Level,
583 const Diagnostic &Info) override;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000584};
585
586/// \brief RAII object that optionally captures diagnostics, if
587/// there is no diagnostic client to capture them already.
588class CaptureDroppedDiagnostics {
David Blaikie9c902b52011-09-25 23:23:43 +0000589 DiagnosticsEngine &Diags;
David Blaikief18d91a2011-09-26 00:01:39 +0000590 StoredDiagnosticConsumer Client;
David Blaikiee2eefae2011-09-25 23:39:51 +0000591 DiagnosticConsumer *PreviousClient;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000592
593public:
David Blaikie9c902b52011-09-25 23:23:43 +0000594 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000595 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Craig Topper49a27902014-05-22 04:46:25 +0000596 : Diags(Diags), Client(StoredDiags), PreviousClient(nullptr)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000597 {
Craig Topper49a27902014-05-22 04:46:25 +0000598 if (RequestCapture || Diags.getClient() == nullptr) {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000599 PreviousClient = Diags.takeClient();
Douglas Gregor33cdd812010-02-18 18:08:43 +0000600 Diags.setClient(&Client);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000601 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000602 }
603
604 ~CaptureDroppedDiagnostics() {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000605 if (Diags.getClient() == &Client) {
606 Diags.takeClient();
607 Diags.setClient(PreviousClient);
608 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000609 }
610};
611
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000612} // anonymous namespace
613
David Blaikief18d91a2011-09-26 00:01:39 +0000614void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +0000615 const Diagnostic &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000616 // Default implementation (Warnings/errors count).
David Blaikiee2eefae2011-09-25 23:39:51 +0000617 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000618
Douglas Gregor6b930962013-05-03 22:58:43 +0000619 // Only record the diagnostic if it's part of the source manager we know
620 // about. This effectively drops diagnostics from modules we're building.
621 // FIXME: In the long run, ee don't want to drop source managers from modules.
622 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
623 StoredDiags.push_back(StoredDiagnostic(Level, Info));
Douglas Gregor33cdd812010-02-18 18:08:43 +0000624}
625
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000626ASTMutationListener *ASTUnit::getASTMutationListener() {
627 if (WriterData)
628 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000629 return nullptr;
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000630}
631
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000632ASTDeserializationListener *ASTUnit::getDeserializationListener() {
633 if (WriterData)
634 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000635 return nullptr;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000636}
637
Rafael Espindola16e1ba12014-08-26 20:17:44 +0000638std::unique_ptr<llvm::MemoryBuffer>
639ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
Chris Lattner5159f612010-11-23 08:35:12 +0000640 assert(FileMgr);
Rafael Espindola16e1ba12014-08-26 20:17:44 +0000641 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000642}
643
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000644/// \brief Configure the diagnostics object for use with ASTUnit.
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000645void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000646 const char **ArgBegin, const char **ArgEnd,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000647 ASTUnit &AST, bool CaptureDiagnostics) {
Alp Tokerf994cef2014-07-05 03:08:06 +0000648 if (!Diags.get()) {
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000649 // No diagnostics engine was provided, so create our own diagnostics object
650 // with the default options.
Craig Topper49a27902014-05-22 04:46:25 +0000651 DiagnosticConsumer *Client = nullptr;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000652 if (CaptureDiagnostics)
David Blaikief18d91a2011-09-26 00:01:39 +0000653 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Douglas Gregor811db4e2012-10-23 22:26:28 +0000654 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions(),
Sean Silvaf1b49e22013-01-20 01:58:28 +0000655 Client,
Douglas Gregor30071cea2013-05-03 23:07:45 +0000656 /*ShouldOwnClient=*/true);
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000657 } else if (CaptureDiagnostics) {
David Blaikief18d91a2011-09-26 00:01:39 +0000658 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000659 }
660}
661
David Blaikie6f7382d2014-08-10 19:08:04 +0000662std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
663 const std::string &Filename, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
664 const FileSystemOptions &FileSystemOpts, bool OnlyLocalDecls,
665 ArrayRef<RemappedFile> RemappedFiles, bool CaptureDiagnostics,
666 bool AllowPCHWithCompilerErrors, bool UserFilesAreVolatile) {
Ahmed Charlesb8984322014-03-07 20:03:18 +0000667 std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000668
669 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +0000670 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
671 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +0000672 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
673 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +0000674 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000675
Craig Topper49a27902014-05-22 04:46:25 +0000676 ConfigureDiags(Diags, nullptr, nullptr, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000677
Douglas Gregor16bef852009-10-16 20:01:17 +0000678 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000679 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000680 AST->Diagnostics = Diags;
Ben Langmuir8832c062014-04-15 18:16:25 +0000681 IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
682 AST->FileMgr = new FileManager(FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000683 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000684 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000685 AST->getFileManager(),
686 UserFilesAreVolatile);
Douglas Gregorb85b9cc2012-10-24 16:19:39 +0000687 AST->HSOpts = new HeaderSearchOptions();
Craig Topper49a27902014-05-22 04:46:25 +0000688
Douglas Gregorb85b9cc2012-10-24 16:19:39 +0000689 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
Manuel Klimek1f76c4e2013-10-24 07:51:24 +0000690 AST->getSourceManager(),
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000691 AST->getDiagnostics(),
Douglas Gregor89929282012-01-30 06:01:29 +0000692 AST->ASTFileLangOpts,
Craig Topper49a27902014-05-22 04:46:25 +0000693 /*Target=*/nullptr));
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000694
Dmitri Gribenkob41e7e22014-02-10 12:31:34 +0000695 PreprocessorOptions *PPOpts = new PreprocessorOptions();
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000696
Dmitri Gribenkob41e7e22014-02-10 12:31:34 +0000697 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I)
698 PPOpts->addRemappedFile(RemappedFiles[I].first, RemappedFiles[I].second);
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000699
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000700 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000701
David Blaikie6f7382d2014-08-10 19:08:04 +0000702 HeaderSearch &HeaderInfo = *AST->HeaderInfo;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000703 unsigned Counter;
704
Alp Toker96637802014-05-02 03:43:38 +0000705 AST->PP =
706 new Preprocessor(PPOpts, AST->getDiagnostics(), AST->ASTFileLangOpts,
707 AST->getSourceManager(), HeaderInfo, *AST,
Craig Topper49a27902014-05-22 04:46:25 +0000708 /*IILookup=*/nullptr,
Alp Toker96637802014-05-02 03:43:38 +0000709 /*OwnsHeaderSearch=*/false);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000710 Preprocessor &PP = *AST->PP;
711
Alp Toker08043432014-05-03 03:46:04 +0000712 AST->Ctx = new ASTContext(AST->ASTFileLangOpts, AST->getSourceManager(),
713 PP.getIdentifierTable(), PP.getSelectorTable(),
714 PP.getBuiltinInfo());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000715 ASTContext &Context = *AST->Ctx;
Douglas Gregor83297df2011-09-01 23:39:15 +0000716
Argyrios Kyrtzidis945a8192012-09-15 01:10:20 +0000717 bool disableValid = false;
718 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
719 disableValid = true;
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000720 AST->Reader = new ASTReader(PP, Context,
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +0000721 /*isysroot=*/"",
Argyrios Kyrtzidis945a8192012-09-15 01:10:20 +0000722 /*DisableValidation=*/disableValid,
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000723 AllowPCHWithCompilerErrors);
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000724
David Blaikie2721c322014-08-10 16:54:39 +0000725 AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>(
726 *AST->PP, Context, AST->ASTFileLangOpts, AST->TargetOpts, AST->Target,
727 Counter));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000728
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000729 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis2ec29362012-11-15 18:57:22 +0000730 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000731 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000732 break;
Mike Stump11289f42009-09-09 15:08:12 +0000733
Sebastian Redl2c499f62010-08-18 23:56:43 +0000734 case ASTReader::Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +0000735 case ASTReader::Missing:
Douglas Gregorc9ad5fb2012-10-22 22:50:17 +0000736 case ASTReader::OutOfDate:
737 case ASTReader::VersionMismatch:
738 case ASTReader::ConfigurationMismatch:
739 case ASTReader::HadErrors:
Douglas Gregord03e8232010-04-05 21:10:19 +0000740 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Craig Topper49a27902014-05-22 04:46:25 +0000741 return nullptr;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000742 }
Mike Stump11289f42009-09-09 15:08:12 +0000743
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000744 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
Daniel Dunbara8a50932009-12-02 08:44:16 +0000745
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000746 PP.setCounterValue(Counter);
Mike Stump11289f42009-09-09 15:08:12 +0000747
Sebastian Redl2c499f62010-08-18 23:56:43 +0000748 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000749 // source, so that declarations will be deserialized from the
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000750 // AST file as needed.
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000751 Context.setExternalSource(AST->Reader);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000752
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000753 // Create an AST consumer, even though it isn't used.
754 AST->Consumer.reset(new ASTConsumer);
755
Sebastian Redl2c499f62010-08-18 23:56:43 +0000756 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000757 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
758 AST->TheSema->Initialize();
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000759 AST->Reader->InitializeSema(*AST->TheSema);
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000760
Douglas Gregor6b930962013-05-03 22:58:43 +0000761 // Tell the diagnostic client that we have started a source file.
762 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
763
David Blaikie6f7382d2014-08-10 19:08:04 +0000764 return AST;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000765}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000766
767namespace {
768
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000769/// \brief Preprocessor callback class that updates a hash value with the names
770/// of all macros that have been defined by the translation unit.
771class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
772 unsigned &Hash;
773
774public:
775 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
Craig Topperafa7cb32014-03-13 06:07:04 +0000776
777 void MacroDefined(const Token &MacroNameTok,
778 const MacroDirective *MD) override {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000779 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
780 }
781};
782
783/// \brief Add the given declaration to the hash of all top-level entities.
784void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
785 if (!D)
786 return;
787
788 DeclContext *DC = D->getDeclContext();
789 if (!DC)
790 return;
791
792 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
793 return;
794
795 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000796 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
797 // For an unscoped enum include the enumerators in the hash since they
798 // enter the top-level namespace.
799 if (!EnumD->isScoped()) {
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000800 for (const auto *EI : EnumD->enumerators()) {
801 if (EI->getIdentifier())
802 Hash = llvm::HashString(EI->getIdentifier()->getName(), Hash);
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000803 }
804 }
805 }
806
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000807 if (ND->getIdentifier())
808 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
809 else if (DeclarationName Name = ND->getDeclName()) {
810 std::string NameStr = Name.getAsString();
811 Hash = llvm::HashString(NameStr, Hash);
812 }
813 return;
Argyrios Kyrtzidis48d88de2013-06-24 21:19:12 +0000814 }
815
816 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
817 if (Module *Mod = ImportD->getImportedModule()) {
818 std::string ModName = Mod->getFullModuleName();
819 Hash = llvm::HashString(ModName, Hash);
820 }
821 return;
822 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000823}
824
Daniel Dunbar644dca02009-12-04 08:17:33 +0000825class TopLevelDeclTrackerConsumer : public ASTConsumer {
826 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000827 unsigned &Hash;
828
Daniel Dunbar644dca02009-12-04 08:17:33 +0000829public:
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000830 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
831 : Unit(_Unit), Hash(Hash) {
832 Hash = 0;
833 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000834
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000835 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis516eec22011-11-16 02:35:10 +0000836 if (!D)
837 return;
838
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000839 // FIXME: Currently ObjC method declarations are incorrectly being
840 // reported as top-level declarations, even though their DeclContext
841 // is the containing ObjC @interface/@implementation. This is a
842 // fundamental problem in the parser right now.
843 if (isa<ObjCMethodDecl>(D))
844 return;
845
846 AddTopLevelDeclarationToHash(D, Hash);
847 Unit.addTopLevelDecl(D);
848
849 handleFileLevelDecl(D);
850 }
851
852 void handleFileLevelDecl(Decl *D) {
853 Unit.addFileLevelDecl(D);
854 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
Aaron Ballman629afae2014-03-07 19:56:05 +0000855 for (auto *I : NSD->decls())
856 handleFileLevelDecl(I);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000857 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000858 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000859
Craig Topperafa7cb32014-03-13 06:07:04 +0000860 bool HandleTopLevelDecl(DeclGroupRef D) override {
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000861 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
862 handleTopLevelDecl(*it);
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000863 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000864 }
865
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000866 // We're not interested in "interesting" decls.
Craig Topperafa7cb32014-03-13 06:07:04 +0000867 void HandleInterestingDecl(DeclGroupRef) override {}
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000868
Craig Topperafa7cb32014-03-13 06:07:04 +0000869 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000870 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
871 handleTopLevelDecl(*it);
872 }
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000873
Craig Topperafa7cb32014-03-13 06:07:04 +0000874 ASTMutationListener *GetASTMutationListener() override {
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000875 return Unit.getASTMutationListener();
876 }
877
Craig Topperafa7cb32014-03-13 06:07:04 +0000878 ASTDeserializationListener *GetASTDeserializationListener() override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000879 return Unit.getDeserializationListener();
880 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000881};
882
883class TopLevelDeclTrackerAction : public ASTFrontendAction {
884public:
885 ASTUnit &Unit;
886
David Blaikie6beb6aa2014-08-10 19:56:51 +0000887 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
888 StringRef InFile) override {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000889 CI.getPreprocessor().addPPCallbacks(
890 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000891 return llvm::make_unique<TopLevelDeclTrackerConsumer>(
892 Unit, Unit.getCurrentTopLevelHashValue());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000893 }
894
895public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000896 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
897
Craig Topperafa7cb32014-03-13 06:07:04 +0000898 bool hasCodeCompletionSupport() const override { return false; }
899 TranslationUnitKind getTranslationUnitKind() override {
Douglas Gregor69f74f82011-08-25 22:30:56 +0000900 return Unit.getTranslationUnitKind();
Douglas Gregor028d3e42010-08-09 20:45:32 +0000901 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000902};
903
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000904class PrecompilePreambleAction : public ASTFrontendAction {
905 ASTUnit &Unit;
906 bool HasEmittedPreamblePCH;
907
908public:
909 explicit PrecompilePreambleAction(ASTUnit &Unit)
910 : Unit(Unit), HasEmittedPreamblePCH(false) {}
911
David Blaikie6beb6aa2014-08-10 19:56:51 +0000912 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
913 StringRef InFile) override;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000914 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
915 void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH = true; }
Craig Topperafa7cb32014-03-13 06:07:04 +0000916 bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000917
Craig Topperafa7cb32014-03-13 06:07:04 +0000918 bool hasCodeCompletionSupport() const override { return false; }
919 bool hasASTFileSupport() const override { return false; }
920 TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000921};
922
Argyrios Kyrtzidis57332712011-09-19 20:40:48 +0000923class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000924 ASTUnit &Unit;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000925 unsigned &Hash;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000926 std::vector<Decl *> TopLevelDecls;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000927 PrecompilePreambleAction *Action;
928
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000929public:
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000930 PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action,
931 const Preprocessor &PP, StringRef isysroot,
932 raw_ostream *Out)
Craig Topper49a27902014-05-22 04:46:25 +0000933 : PCHGenerator(PP, "", nullptr, isysroot, Out, /*AllowASTWithErrors=*/true),
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000934 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000935 Hash = 0;
936 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000937
Craig Topperafa7cb32014-03-13 06:07:04 +0000938 bool HandleTopLevelDecl(DeclGroupRef D) override {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000939 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
940 Decl *D = *it;
941 // FIXME: Currently ObjC method declarations are incorrectly being
942 // reported as top-level declarations, even though their DeclContext
943 // is the containing ObjC @interface/@implementation. This is a
944 // fundamental problem in the parser right now.
945 if (isa<ObjCMethodDecl>(D))
946 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000947 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000948 TopLevelDecls.push_back(D);
949 }
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000950 return true;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000951 }
952
Craig Topperafa7cb32014-03-13 06:07:04 +0000953 void HandleTranslationUnit(ASTContext &Ctx) override {
Douglas Gregore9db88f2010-08-03 19:06:41 +0000954 PCHGenerator::HandleTranslationUnit(Ctx);
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +0000955 if (hasEmittedPCH()) {
Douglas Gregore9db88f2010-08-03 19:06:41 +0000956 // Translate the top-level declarations we captured during
957 // parsing into declaration IDs in the precompiled
958 // preamble. This will allow us to deserialize those top-level
959 // declarations when requested.
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +0000960 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I) {
961 Decl *D = TopLevelDecls[I];
962 // Invalid top-level decls may not have been serialized.
963 if (D->isInvalidDecl())
964 continue;
965 Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
966 }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000967
968 Action->setHasEmittedPreamblePCH();
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000969 }
970 }
971};
972
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000973}
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000974
David Blaikie6beb6aa2014-08-10 19:56:51 +0000975std::unique_ptr<ASTConsumer>
976PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
977 StringRef InFile) {
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000978 std::string Sysroot;
979 std::string OutputFile;
Craig Topper49a27902014-05-22 04:46:25 +0000980 raw_ostream *OS = nullptr;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000981 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
982 OutputFile, OS))
Craig Topper49a27902014-05-22 04:46:25 +0000983 return nullptr;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000984
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000985 if (!CI.getFrontendOpts().RelocatablePCH)
986 Sysroot.clear();
Douglas Gregorc567ba22011-07-22 16:35:34 +0000987
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000988 CI.getPreprocessor().addPPCallbacks(new MacroDefinitionTrackerPPCallbacks(
989 Unit.getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000990 return llvm::make_unique<PrecompilePreambleConsumer>(
991 Unit, this, CI.getPreprocessor(), Sysroot, OS);
Daniel Dunbar764c0822009-12-01 09:51:01 +0000992}
993
Benjamin Kramer1ce5d802013-05-05 12:39:28 +0000994static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
995 return StoredDiag.getLocation().isValid();
996}
997
998static void
999checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001000 // Get rid of stored diagnostics except the ones from the driver which do not
1001 // have a source location.
Benjamin Kramer1ce5d802013-05-05 12:39:28 +00001002 StoredDiags.erase(
1003 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1004 StoredDiags.end());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001005}
1006
1007static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1008 StoredDiagnostics,
1009 SourceManager &SM) {
1010 // The stored diagnostic has the old source manager in it; update
1011 // the locations to refer into the new source manager. Since we've
1012 // been careful to make sure that the source manager's state
1013 // before and after are identical, so that we can reuse the source
1014 // location itself.
1015 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1016 if (StoredDiagnostics[I].getLocation().isValid()) {
1017 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1018 StoredDiagnostics[I].setLocation(Loc);
1019 }
1020 }
1021}
1022
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001023/// Parse the source file into a translation unit using the given compiler
1024/// invocation, replacing the current translation unit.
1025///
1026/// \returns True if a failure occurred that causes the ASTUnit not to
1027/// contain any translation-unit information, false otherwise.
Rafael Espindola32482082014-08-18 16:23:45 +00001028bool ASTUnit::Parse(std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer) {
Rafael Espindola4674a872014-08-13 17:08:22 +00001029 SavedMainFileBuffer.reset();
Craig Topper49a27902014-05-22 04:46:25 +00001030
Rafael Espindola32482082014-08-18 16:23:45 +00001031 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001032 return true;
Rafael Espindola32482082014-08-18 16:23:45 +00001033
Daniel Dunbar764c0822009-12-01 09:51:01 +00001034 // Create the compiler instance to use for building the AST.
Ahmed Charlesb8984322014-03-07 20:03:18 +00001035 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001036
1037 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001038 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1039 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001040
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001041 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis14c32e82011-09-12 18:09:38 +00001042 CCInvocation(new CompilerInvocation(*Invocation));
1043
Alp Tokerf994cef2014-07-05 03:08:06 +00001044 Clang->setInvocation(CCInvocation.get());
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001045 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001046
Douglas Gregor8e984da2010-08-04 16:47:14 +00001047 // Set up diagnostics, capturing any diagnostics that would
1048 // otherwise be dropped.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001049 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +00001050
Daniel Dunbar764c0822009-12-01 09:51:01 +00001051 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001052 Clang->setTarget(TargetInfo::CreateTargetInfo(
1053 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Rafael Espindola32482082014-08-18 16:23:45 +00001054 if (!Clang->hasTarget())
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001055 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001056
Daniel Dunbar764c0822009-12-01 09:51:01 +00001057 // Inform the target of the language options.
1058 //
1059 // FIXME: We shouldn't need to do this, the target should be immutable once
1060 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001061 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001062
Ted Kremenek84de4a12011-03-21 18:40:07 +00001063 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001064 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001065 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001066 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001067 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Daniel Dunbar9507f9c2010-06-07 23:26:47 +00001068 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +00001069
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001070 // Configure the various subsystems.
Alp Toker269d8402014-07-06 05:26:07 +00001071 LangOpts = Clang->getInvocation().LangOpts;
Ted Kremenek84de4a12011-03-21 18:40:07 +00001072 FileSystemOpts = Clang->getFileSystemOpts();
Ben Langmuir2cc485b2014-06-23 16:36:40 +00001073 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1074 createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
Rafael Espindola32482082014-08-18 16:23:45 +00001075 if (!VFS)
Ben Langmuir2cc485b2014-06-23 16:36:40 +00001076 return true;
Ben Langmuir2cc485b2014-06-23 16:36:40 +00001077 FileMgr = new FileManager(FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001078 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1079 UserFilesAreVolatile);
Douglas Gregor6fd55e02010-08-13 03:15:25 +00001080 TheSema.reset();
Craig Topper49a27902014-05-22 04:46:25 +00001081 Ctx = nullptr;
1082 PP = nullptr;
1083 Reader = nullptr;
1084
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001085 // Clear out old caches and data.
1086 TopLevelDecls.clear();
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001087 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001088 CleanTemporaryFiles();
Douglas Gregord9a30af2010-08-02 20:51:39 +00001089
Douglas Gregor7b02b582010-08-20 00:02:33 +00001090 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001091 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001092 TopLevelDeclsInPreamble.clear();
1093 }
1094
Daniel Dunbar764c0822009-12-01 09:51:01 +00001095 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001096 Clang->setFileManager(&getFileManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001097
Daniel Dunbar764c0822009-12-01 09:51:01 +00001098 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001099 Clang->setSourceManager(&getSourceManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001100
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001101 // If the main file has been overridden due to the use of a preamble,
1102 // make that override happen and introduce the preamble.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001103 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001104 if (OverrideMainBuffer) {
Rafael Espindola32482082014-08-18 16:23:45 +00001105 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
1106 OverrideMainBuffer.get());
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001107 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1108 PreprocessorOpts.PrecompiledPreambleBytes.second
1109 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00001110 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorce3a8292010-07-27 00:27:13 +00001111 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +00001112
Douglas Gregord9a30af2010-08-02 20:51:39 +00001113 // The stored diagnostic has the old source manager in it; update
1114 // the locations to refer into the new source manager. Since we've
1115 // been careful to make sure that the source manager's state
1116 // before and after are identical, so that we can reuse the source
1117 // location itself.
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001118 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001119
1120 // Keep track of the override buffer;
Rafael Espindola32482082014-08-18 16:23:45 +00001121 SavedMainFileBuffer = std::move(OverrideMainBuffer);
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001122 }
Ahmed Charlesb8984322014-03-07 20:03:18 +00001123
1124 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1125 new TopLevelDeclTrackerAction(*this));
1126
Ted Kremenek022a4902011-03-22 01:15:24 +00001127 // Recover resources if we crash before exiting this method.
1128 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1129 ActCleanup(Act.get());
1130
Douglas Gregor32fbe312012-01-20 16:28:04 +00001131 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar764c0822009-12-01 09:51:01 +00001132 goto error;
Douglas Gregor925296b2011-07-19 16:10:42 +00001133
Rafael Espindola32482082014-08-18 16:23:45 +00001134 if (SavedMainFileBuffer) {
Ted Kremenek06b4f912011-10-27 17:55:18 +00001135 std::string ModName = getPreambleFile(this);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001136 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1137 PreambleDiagnostics, StoredDiagnostics);
Douglas Gregor925296b2011-07-19 16:10:42 +00001138 }
1139
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001140 if (!Act->Execute())
1141 goto error;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001142
1143 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001144
Daniel Dunbar644dca02009-12-04 08:17:33 +00001145 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001146
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001147 FailedParseDiagnostics.clear();
1148
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001149 return false;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001150
Daniel Dunbar764c0822009-12-01 09:51:01 +00001151error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001152 // Remove the overridden buffer we used for the preamble.
Rafael Espindola32482082014-08-18 16:23:45 +00001153 SavedMainFileBuffer = nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001154
1155 // Keep the ownership of the data in the ASTUnit because the client may
1156 // want to see the diagnostics.
1157 transferASTDataFromCompilerInstance(*Clang);
1158 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregorefc46952010-10-12 16:25:54 +00001159 StoredDiagnostics.clear();
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001160 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001161 return true;
1162}
1163
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001164/// \brief Simple function to retrieve a path for a preamble precompiled header.
1165static std::string GetPreamblePCHPath() {
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001166 // FIXME: This is a hack so that we can override the preamble file during
1167 // crash-recovery testing, which is the only case where the preamble files
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001168 // are not necessarily cleaned up.
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001169 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1170 if (TmpFile)
1171 return TmpFile;
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001172
1173 SmallString<128> Path;
Rafael Espindolaa36e78e2013-07-05 20:00:06 +00001174 llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001175
1176 return Path.str();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001177}
1178
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001179/// \brief Compute the preamble for the main file, providing the source buffer
1180/// that corresponds to the main file along with a pair (bytes, start-of-line)
1181/// that describes the preamble.
1182std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor028d3e42010-08-09 20:45:32 +00001183ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1184 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001185 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner5159f612010-11-23 08:35:12 +00001186 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001187 CreatedBuffer = false;
1188
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001189 // Try to determine if the main file has been remapped, either from the
1190 // command line (to another file) or directly through the compiler invocation
1191 // (to a memory buffer).
Craig Topper49a27902014-05-22 04:46:25 +00001192 llvm::MemoryBuffer *Buffer = nullptr;
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001193 std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
Rafael Espindola073ff102013-07-29 21:26:52 +00001194 llvm::sys::fs::UniqueID MainFileID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001195 if (!llvm::sys::fs::getUniqueID(MainFilePath, MainFileID)) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001196 // Check whether there is a file-file remapping of the main file
Alp Toker1b070d22014-07-07 07:47:20 +00001197 for (const auto &RF : PreprocessorOpts.RemappedFiles) {
1198 std::string MPath(RF.first);
Rafael Espindola073ff102013-07-29 21:26:52 +00001199 llvm::sys::fs::UniqueID MID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001200 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001201 if (MainFileID == MID) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001202 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001203 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001204 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001205 CreatedBuffer = false;
1206 }
Alp Toker1b070d22014-07-07 07:47:20 +00001207
Rafael Espindola16e1ba12014-08-26 20:17:44 +00001208 Buffer = getBufferForFile(RF.second).release();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001209 if (!Buffer)
Craig Topper49a27902014-05-22 04:46:25 +00001210 return std::make_pair(nullptr, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001211 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001212 }
1213 }
1214 }
1215
1216 // Check whether there is a file-buffer remapping. It supercedes the
1217 // file-file remapping.
Alp Toker1b070d22014-07-07 07:47:20 +00001218 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1219 std::string MPath(RB.first);
Rafael Espindola073ff102013-07-29 21:26:52 +00001220 llvm::sys::fs::UniqueID MID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001221 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001222 if (MainFileID == MID) {
1223 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001224 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001225 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001226 CreatedBuffer = false;
1227 }
Alp Toker1b070d22014-07-07 07:47:20 +00001228
1229 Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001230 }
1231 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001232 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001233 }
1234
1235 // If the main source file was not remapped, load it now.
1236 if (!Buffer) {
Rafael Espindola16e1ba12014-08-26 20:17:44 +00001237 Buffer = getBufferForFile(FrontendOpts.Inputs[0].getFile()).release();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001238 if (!Buffer)
Craig Topper49a27902014-05-22 04:46:25 +00001239 return std::make_pair(nullptr, std::make_pair(0, true));
1240
Douglas Gregor4dde7492010-07-23 23:58:40 +00001241 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001242 }
David Blaikie3d95d852014-08-11 22:08:06 +00001243
1244 return std::make_pair(
Rafael Espindolacd0b3802014-08-12 15:46:24 +00001245 Buffer, Lexer::ComputePreamble(Buffer->getBuffer(),
1246 *Invocation.getLangOpts(), MaxLines));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001247}
1248
Dmitri Gribenko47652522013-12-20 00:16:25 +00001249ASTUnit::PreambleFileHash
1250ASTUnit::PreambleFileHash::createForFile(off_t Size, time_t ModTime) {
1251 PreambleFileHash Result;
1252 Result.Size = Size;
1253 Result.ModTime = ModTime;
Dmitri Gribenko3ec8ee72013-12-20 01:07:30 +00001254 memset(Result.MD5, 0, sizeof(Result.MD5));
Dmitri Gribenko47652522013-12-20 00:16:25 +00001255 return Result;
1256}
1257
1258ASTUnit::PreambleFileHash ASTUnit::PreambleFileHash::createForMemoryBuffer(
1259 const llvm::MemoryBuffer *Buffer) {
1260 PreambleFileHash Result;
1261 Result.Size = Buffer->getBufferSize();
1262 Result.ModTime = 0;
1263
1264 llvm::MD5 MD5Ctx;
1265 MD5Ctx.update(Buffer->getBuffer().data());
1266 MD5Ctx.final(Result.MD5);
1267
1268 return Result;
1269}
1270
1271namespace clang {
1272bool operator==(const ASTUnit::PreambleFileHash &LHS,
1273 const ASTUnit::PreambleFileHash &RHS) {
1274 return LHS.Size == RHS.Size && LHS.ModTime == RHS.ModTime &&
Dmitri Gribenko3ec8ee72013-12-20 01:07:30 +00001275 memcmp(LHS.MD5, RHS.MD5, sizeof(LHS.MD5)) == 0;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001276}
1277} // namespace clang
1278
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001279static std::pair<unsigned, unsigned>
1280makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1281 const LangOptions &LangOpts) {
1282 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1283 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1284 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1285 return std::make_pair(Offset, EndOffset);
1286}
1287
1288static void makeStandaloneFixIt(const SourceManager &SM,
1289 const LangOptions &LangOpts,
1290 const FixItHint &InFix,
1291 ASTUnit::StandaloneFixIt &OutFix) {
1292 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1293 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1294 LangOpts);
1295 OutFix.CodeToInsert = InFix.CodeToInsert;
1296 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
1297}
1298
1299static void makeStandaloneDiagnostic(const LangOptions &LangOpts,
1300 const StoredDiagnostic &InDiag,
1301 ASTUnit::StandaloneDiagnostic &OutDiag) {
1302 OutDiag.ID = InDiag.getID();
1303 OutDiag.Level = InDiag.getLevel();
1304 OutDiag.Message = InDiag.getMessage();
1305 OutDiag.LocOffset = 0;
1306 if (InDiag.getLocation().isInvalid())
1307 return;
1308 const SourceManager &SM = InDiag.getLocation().getManager();
1309 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1310 OutDiag.Filename = SM.getFilename(FileLoc);
1311 if (OutDiag.Filename.empty())
1312 return;
1313 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
1314 for (StoredDiagnostic::range_iterator
1315 I = InDiag.range_begin(), E = InDiag.range_end(); I != E; ++I) {
1316 OutDiag.Ranges.push_back(makeStandaloneRange(*I, SM, LangOpts));
1317 }
1318 for (StoredDiagnostic::fixit_iterator
1319 I = InDiag.fixit_begin(), E = InDiag.fixit_end(); I != E; ++I) {
1320 ASTUnit::StandaloneFixIt Fix;
1321 makeStandaloneFixIt(SM, LangOpts, *I, Fix);
1322 OutDiag.FixIts.push_back(Fix);
1323 }
1324}
1325
Douglas Gregor4dde7492010-07-23 23:58:40 +00001326/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1327/// the source file.
1328///
1329/// This routine will compute the preamble of the main source file. If a
1330/// non-trivial preamble is found, it will precompile that preamble into a
1331/// precompiled header so that the precompiled preamble can be used to reduce
1332/// reparsing time. If a precompiled preamble has already been constructed,
1333/// this routine will determine if it is still valid and, if so, avoid
1334/// rebuilding the precompiled preamble.
1335///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001336/// \param AllowRebuild When true (the default), this routine is
1337/// allowed to rebuild the precompiled preamble if it is found to be
1338/// out-of-date.
1339///
1340/// \param MaxLines When non-zero, the maximum number of lines that
1341/// can occur within the preamble.
1342///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001343/// \returns If the precompiled preamble can be used, returns a newly-allocated
1344/// buffer that should be used in place of the main file when doing so.
1345/// Otherwise, returns a NULL pointer.
Rafael Espindola2346a372014-08-18 18:47:08 +00001346std::unique_ptr<llvm::MemoryBuffer>
1347ASTUnit::getMainBufferWithPrecompiledPreamble(
1348 const CompilerInvocation &PreambleInvocationIn, bool AllowRebuild,
1349 unsigned MaxLines) {
1350
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001351 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor3cc15812011-07-01 18:22:13 +00001352 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1353 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001354 PreprocessorOptions &PreprocessorOpts
Douglas Gregor3cc15812011-07-01 18:22:13 +00001355 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001356
1357 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001358 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor3cc15812011-07-01 18:22:13 +00001359 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001360
Douglas Gregor925296b2011-07-19 16:10:42 +00001361 // If ComputePreamble() Take ownership of the preamble buffer.
Ahmed Charlesb8984322014-03-07 20:03:18 +00001362 std::unique_ptr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor3edb1672010-11-16 20:45:51 +00001363 if (CreatedPreambleBuffer)
1364 OwnedPreambleBuffer.reset(NewPreamble.first);
1365
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001366 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001367 // We couldn't find a preamble in the main source. Clear out the current
1368 // preamble, if we have one. It's obviously no good any more.
1369 Preamble.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001370 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001371
1372 // The next time we actually see a preamble, precompile it.
1373 PreambleRebuildCounter = 1;
Craig Topper49a27902014-05-22 04:46:25 +00001374 return nullptr;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001375 }
1376
1377 if (!Preamble.empty()) {
1378 // We've previously computed a preamble. Check whether we have the same
1379 // preamble now that we did before, and that there's enough space in
1380 // the main-file buffer within the precompiled preamble to fit the
1381 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001382 if (Preamble.size() == NewPreamble.second.first &&
1383 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001384 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001385 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001386 // The preamble has not changed. We may be able to re-use the precompiled
1387 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001388
Douglas Gregor0e119552010-07-31 00:40:00 +00001389 // Check that none of the files used by the preamble have changed.
1390 bool AnyFileChanged = false;
1391
1392 // First, make a record of those files that have been overridden via
1393 // remapping or unsaved_files.
Dmitri Gribenko47652522013-12-20 00:16:25 +00001394 llvm::StringMap<PreambleFileHash> OverriddenFiles;
Alp Toker1b070d22014-07-07 07:47:20 +00001395 for (const auto &R : PreprocessorOpts.RemappedFiles) {
1396 if (AnyFileChanged)
1397 break;
1398
Ben Langmuirc8130a72014-02-20 21:59:23 +00001399 vfs::Status Status;
Alp Toker1b070d22014-07-07 07:47:20 +00001400 if (FileMgr->getNoncachedStatValue(R.second, Status)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001401 // If we can't stat the file we're remapping to, assume that something
1402 // horrible happened.
1403 AnyFileChanged = true;
1404 break;
1405 }
Rafael Espindolae4777f42013-07-29 18:22:23 +00001406
Alp Toker1b070d22014-07-07 07:47:20 +00001407 OverriddenFiles[R.first] = PreambleFileHash::createForFile(
Rafael Espindolae4777f42013-07-29 18:22:23 +00001408 Status.getSize(), Status.getLastModificationTime().toEpochTime());
Douglas Gregor0e119552010-07-31 00:40:00 +00001409 }
Alp Toker1b070d22014-07-07 07:47:20 +00001410
1411 for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
1412 if (AnyFileChanged)
1413 break;
1414 OverriddenFiles[RB.first] =
1415 PreambleFileHash::createForMemoryBuffer(RB.second);
Douglas Gregor0e119552010-07-31 00:40:00 +00001416 }
1417
1418 // Check whether anything has changed.
Dmitri Gribenko47652522013-12-20 00:16:25 +00001419 for (llvm::StringMap<PreambleFileHash>::iterator
Douglas Gregor0e119552010-07-31 00:40:00 +00001420 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1421 !AnyFileChanged && F != FEnd;
1422 ++F) {
Dmitri Gribenko47652522013-12-20 00:16:25 +00001423 llvm::StringMap<PreambleFileHash>::iterator Overridden
Douglas Gregor0e119552010-07-31 00:40:00 +00001424 = OverriddenFiles.find(F->first());
1425 if (Overridden != OverriddenFiles.end()) {
1426 // This file was remapped; check whether the newly-mapped file
1427 // matches up with the previous mapping.
1428 if (Overridden->second != F->second)
1429 AnyFileChanged = true;
1430 continue;
1431 }
1432
1433 // The file was not remapped; check whether it has changed on disk.
Ben Langmuirc8130a72014-02-20 21:59:23 +00001434 vfs::Status Status;
Rafael Espindolae4777f42013-07-29 18:22:23 +00001435 if (FileMgr->getNoncachedStatValue(F->first(), Status)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001436 // If we can't stat the file, assume that something horrible happened.
1437 AnyFileChanged = true;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001438 } else if (Status.getSize() != uint64_t(F->second.Size) ||
Rafael Espindolae4777f42013-07-29 18:22:23 +00001439 Status.getLastModificationTime().toEpochTime() !=
Dmitri Gribenko47652522013-12-20 00:16:25 +00001440 uint64_t(F->second.ModTime))
Douglas Gregor0e119552010-07-31 00:40:00 +00001441 AnyFileChanged = true;
1442 }
1443
1444 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001445 // Okay! We can re-use the precompiled preamble.
1446
1447 // Set the state of the diagnostic object to mimic its state
1448 // after parsing the preamble.
1449 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001450 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor3cc15812011-07-01 18:22:13 +00001451 PreambleInvocation->getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001452 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001453
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001454 return llvm::MemoryBuffer::getMemBufferCopy(
1455 NewPreamble.first->getBuffer(), FrontendOpts.Inputs[0].getFile());
Douglas Gregor0e119552010-07-31 00:40:00 +00001456 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001457 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001458
1459 // If we aren't allowed to rebuild the precompiled preamble, just
1460 // return now.
1461 if (!AllowRebuild)
Craig Topper49a27902014-05-22 04:46:25 +00001462 return nullptr;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001463
Douglas Gregor4dde7492010-07-23 23:58:40 +00001464 // We can't reuse the previously-computed preamble. Build a new one.
1465 Preamble.clear();
Douglas Gregor925296b2011-07-19 16:10:42 +00001466 PreambleDiagnostics.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001467 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001468 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001469 } else if (!AllowRebuild) {
1470 // We aren't allowed to rebuild the precompiled preamble; just
1471 // return now.
Craig Topper49a27902014-05-22 04:46:25 +00001472 return nullptr;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001473 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001474
1475 // If the preamble rebuild counter > 1, it's because we previously
1476 // failed to build a preamble and we're not yet ready to try
1477 // again. Decrement the counter and return a failure.
1478 if (PreambleRebuildCounter > 1) {
1479 --PreambleRebuildCounter;
Craig Topper49a27902014-05-22 04:46:25 +00001480 return nullptr;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001481 }
1482
Douglas Gregore10f0e52010-09-11 17:56:52 +00001483 // Create a temporary file for the precompiled preamble. In rare
1484 // circumstances, this can fail.
1485 std::string PreamblePCHPath = GetPreamblePCHPath();
1486 if (PreamblePCHPath.empty()) {
1487 // Try again next time.
1488 PreambleRebuildCounter = 1;
Craig Topper49a27902014-05-22 04:46:25 +00001489 return nullptr;
Douglas Gregore10f0e52010-09-11 17:56:52 +00001490 }
1491
Douglas Gregor4dde7492010-07-23 23:58:40 +00001492 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001493 SimpleTimer PreambleTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001494 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor4dde7492010-07-23 23:58:40 +00001495
Douglas Gregord9a30af2010-08-02 20:51:39 +00001496 // Save the preamble text for later; we'll need to compare against it for
1497 // subsequent reparses.
Dmitri Gribenko40798d32013-12-19 23:25:59 +00001498 StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001499 Preamble.assign(FileMgr->getFile(MainFilename),
1500 NewPreamble.first->getBufferStart(),
Douglas Gregord9a30af2010-08-02 20:51:39 +00001501 NewPreamble.first->getBufferStart()
1502 + NewPreamble.second.first);
1503 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1504
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001505 PreambleBuffer = llvm::MemoryBuffer::getMemBufferCopy(
1506 NewPreamble.first->getBuffer().slice(0, Preamble.size()), MainFilename);
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001507
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001508 // Remap the main source file to the preamble buffer.
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001509 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
Rafael Espindolafa49c0b2014-08-13 16:47:00 +00001510 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer.get());
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001511
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001512 // Tell the compiler invocation to generate a temporary precompiled header.
1513 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001514 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001515 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001516 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1517 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001518
1519 // Create the compiler instance to use for building the precompiled preamble.
Ahmed Charlesb8984322014-03-07 20:03:18 +00001520 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001521
1522 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001523 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1524 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001525
Douglas Gregor3cc15812011-07-01 18:22:13 +00001526 Clang->setInvocation(&*PreambleInvocation);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001527 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001528
Douglas Gregor8e984da2010-08-04 16:47:14 +00001529 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001530 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001531
1532 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001533 Clang->setTarget(TargetInfo::CreateTargetInfo(
1534 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001535 if (!Clang->hasTarget()) {
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001536 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001537 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001538 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Alp Toker1b070d22014-07-07 07:47:20 +00001539 PreprocessorOpts.RemappedFileBuffers.pop_back();
Craig Topper49a27902014-05-22 04:46:25 +00001540 return nullptr;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001541 }
1542
1543 // Inform the target of the language options.
1544 //
1545 // FIXME: We shouldn't need to do this, the target should be immutable once
1546 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001547 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001548
Ted Kremenek84de4a12011-03-21 18:40:07 +00001549 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001550 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001551 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001552 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001553 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001554 "IR inputs not support here!");
1555
1556 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001557 getDiagnostics().Reset();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001558 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001559 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregore9db88f2010-08-03 19:06:41 +00001560 TopLevelDecls.clear();
1561 TopLevelDeclsInPreamble.clear();
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001562 PreambleDiagnostics.clear();
Ben Langmuir8832c062014-04-15 18:16:25 +00001563
1564 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1565 createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
1566 if (!VFS)
1567 return nullptr;
1568
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001569 // Create a file manager object to provide access to and cache the filesystem.
Ben Langmuir8832c062014-04-15 18:16:25 +00001570 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001571
1572 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001573 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek5e14d392011-03-21 18:40:17 +00001574 Clang->getFileManager()));
Ahmed Charlesb8984322014-03-07 20:03:18 +00001575
Ben Langmuir33c80902014-06-30 20:04:14 +00001576 auto PreambleDepCollector = std::make_shared<DependencyCollector>();
1577 Clang->addDependencyCollector(PreambleDepCollector);
1578
Ahmed Charlesb8984322014-03-07 20:03:18 +00001579 std::unique_ptr<PrecompilePreambleAction> Act;
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001580 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor32fbe312012-01-20 16:28:04 +00001581 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001582 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001583 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001584 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Alp Toker1b070d22014-07-07 07:47:20 +00001585 PreprocessorOpts.RemappedFileBuffers.pop_back();
Craig Topper49a27902014-05-22 04:46:25 +00001586 return nullptr;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001587 }
1588
1589 Act->Execute();
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001590
1591 // Transfer any diagnostics generated when parsing the preamble into the set
1592 // of preamble diagnostics.
1593 for (stored_diag_iterator
1594 I = stored_diag_afterDriver_begin(),
1595 E = stored_diag_end(); I != E; ++I) {
1596 StandaloneDiagnostic Diag;
1597 makeStandaloneDiagnostic(Clang->getLangOpts(), *I, Diag);
1598 PreambleDiagnostics.push_back(Diag);
1599 }
1600
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001601 Act->EndSourceFile();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001602
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001603 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1604
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +00001605 if (!Act->hasEmittedPreamblePCH()) {
Argyrios Kyrtzidisd6f57222013-06-11 16:42:34 +00001606 // The preamble PCH failed (e.g. there was a module loading fatal error),
1607 // so no precompiled header was generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001608 // FIXME: Should we leave a note for ourselves to try again?
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001609 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001610 Preamble.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001611 TopLevelDeclsInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001612 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Alp Toker1b070d22014-07-07 07:47:20 +00001613 PreprocessorOpts.RemappedFileBuffers.pop_back();
Craig Topper49a27902014-05-22 04:46:25 +00001614 return nullptr;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001615 }
1616
1617 // Keep track of the preamble we precompiled.
Ted Kremenek06b4f912011-10-27 17:55:18 +00001618 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001619 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001620
1621 // Keep track of all of the files that the source manager knows about,
1622 // so we can verify whether they have changed or not.
1623 FilesInPreamble.clear();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001624 SourceManager &SourceMgr = Clang->getSourceManager();
Ben Langmuir33c80902014-06-30 20:04:14 +00001625 for (auto &Filename : PreambleDepCollector->getDependencies()) {
1626 const FileEntry *File = Clang->getFileManager().getFile(Filename);
1627 if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
Douglas Gregor0e119552010-07-31 00:40:00 +00001628 continue;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001629 if (time_t ModTime = File->getModificationTime()) {
1630 FilesInPreamble[File->getName()] = PreambleFileHash::createForFile(
Ben Langmuir33c80902014-06-30 20:04:14 +00001631 File->getSize(), ModTime);
Dmitri Gribenko47652522013-12-20 00:16:25 +00001632 } else {
Ben Langmuir33c80902014-06-30 20:04:14 +00001633 llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
Dmitri Gribenko47652522013-12-20 00:16:25 +00001634 FilesInPreamble[File->getName()] =
1635 PreambleFileHash::createForMemoryBuffer(Buffer);
1636 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001637 }
Ben Langmuir33c80902014-06-30 20:04:14 +00001638
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001639 PreambleRebuildCounter = 1;
Alp Toker1b070d22014-07-07 07:47:20 +00001640 PreprocessorOpts.RemappedFileBuffers.pop_back();
1641
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001642 // If the hash of top-level entities differs from the hash of the top-level
1643 // entities the last time we rebuilt the preamble, clear out the completion
1644 // cache.
1645 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1646 CompletionCacheTopLevelHashValue = 0;
1647 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1648 }
Rafael Espindola2346a372014-08-18 18:47:08 +00001649
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001650 return llvm::MemoryBuffer::getMemBufferCopy(NewPreamble.first->getBuffer(),
1651 MainFilename);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001652}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001653
Douglas Gregore9db88f2010-08-03 19:06:41 +00001654void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1655 std::vector<Decl *> Resolved;
1656 Resolved.reserve(TopLevelDeclsInPreamble.size());
1657 ExternalASTSource &Source = *getASTContext().getExternalSource();
1658 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1659 // Resolve the declaration ID to an actual declaration, possibly
1660 // deserializing the declaration in the process.
1661 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1662 if (D)
1663 Resolved.push_back(D);
1664 }
1665 TopLevelDeclsInPreamble.clear();
1666 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1667}
1668
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001669void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
Ben Langmuir749323f2014-04-22 17:40:12 +00001670 // Steal the created target, context, and preprocessor if they have been
1671 // created.
1672 assert(CI.hasInvocation() && "missing invocation");
Alp Toker269d8402014-07-06 05:26:07 +00001673 LangOpts = CI.getInvocation().LangOpts;
David Blaikieec99b5e2014-08-10 19:14:48 +00001674 TheSema = CI.takeSema();
David Blaikie6beb6aa2014-08-10 19:56:51 +00001675 Consumer = CI.takeASTConsumer();
Ben Langmuir532fdc02014-04-18 20:39:48 +00001676 if (CI.hasASTContext())
1677 Ctx = &CI.getASTContext();
1678 if (CI.hasPreprocessor())
1679 PP = &CI.getPreprocessor();
Craig Topper49a27902014-05-22 04:46:25 +00001680 CI.setSourceManager(nullptr);
1681 CI.setFileManager(nullptr);
Ben Langmuir532fdc02014-04-18 20:39:48 +00001682 if (CI.hasTarget())
1683 Target = &CI.getTarget();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001684 Reader = CI.getModuleManager();
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001685 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001686}
1687
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001688StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis928e1fd2013-01-11 22:11:14 +00001689 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1690 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1691 if (Input.isFile())
1692 return Input.getFile();
1693 else
1694 return Input.getBuffer()->getBufferIdentifier();
1695 }
1696
1697 if (SourceMgr) {
1698 if (const FileEntry *
1699 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1700 return FE->getName();
1701 }
1702
1703 return StringRef();
Douglas Gregor16896c42010-10-28 15:44:59 +00001704}
1705
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00001706StringRef ASTUnit::getASTFileName() const {
1707 if (!isMainFileAST())
1708 return StringRef();
1709
1710 serialization::ModuleFile &
1711 Mod = Reader->getModuleManager().getPrimaryModule();
1712 return Mod.FileName;
1713}
1714
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001715ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001716 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001717 bool CaptureDiagnostics,
1718 bool UserFilesAreVolatile) {
Ahmed Charlesb8984322014-03-07 20:03:18 +00001719 std::unique_ptr<ASTUnit> AST;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001720 AST.reset(new ASTUnit(false));
Craig Topper49a27902014-05-22 04:46:25 +00001721 ConfigureDiags(Diags, nullptr, nullptr, *AST, CaptureDiagnostics);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001722 AST->Diagnostics = Diags;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001723 AST->Invocation = CI;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001724 AST->FileSystemOpts = CI->getFileSystemOpts();
Ben Langmuir8832c062014-04-15 18:16:25 +00001725 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1726 createVFSFromCompilerInvocation(*CI, *Diags);
1727 if (!VFS)
1728 return nullptr;
1729 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001730 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1731 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1732 UserFilesAreVolatile);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001733
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001734 return AST.release();
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001735}
1736
Ahmed Charlesb8984322014-03-07 20:03:18 +00001737ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
1738 CompilerInvocation *CI, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1739 ASTFrontendAction *Action, ASTUnit *Unit, bool Persistent,
1740 StringRef ResourceFilesPath, bool OnlyLocalDecls, bool CaptureDiagnostics,
1741 bool PrecompilePreamble, bool CacheCodeCompletionResults,
1742 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1743 std::unique_ptr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001744 assert(CI && "A CompilerInvocation is required");
1745
Ahmed Charlesb8984322014-03-07 20:03:18 +00001746 std::unique_ptr<ASTUnit> OwnAST;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001747 ASTUnit *AST = Unit;
1748 if (!AST) {
1749 // Create the AST unit.
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001750 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001751 AST = OwnAST.get();
Ben Langmuir8832c062014-04-15 18:16:25 +00001752 if (!AST)
1753 return nullptr;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001754 }
1755
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001756 if (!ResourceFilesPath.empty()) {
1757 // Override the resources path.
1758 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1759 }
1760 AST->OnlyLocalDecls = OnlyLocalDecls;
1761 AST->CaptureDiagnostics = CaptureDiagnostics;
1762 if (PrecompilePreamble)
1763 AST->PreambleRebuildCounter = 2;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001764 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001765 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001766 AST->IncludeBriefCommentsInCodeCompletion
1767 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001768
1769 // Recover resources if we crash before exiting this method.
1770 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001771 ASTUnitCleanup(OwnAST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001772 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1773 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00001774 DiagCleanup(Diags.get());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001775
1776 // We'll manage file buffers ourselves.
1777 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1778 CI->getFrontendOpts().DisableFree = false;
1779 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1780
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001781 // Create the compiler instance to use for building the AST.
Ahmed Charlesb8984322014-03-07 20:03:18 +00001782 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001783
1784 // Recover resources if we crash before exiting this method.
1785 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1786 CICleanup(Clang.get());
1787
1788 Clang->setInvocation(CI);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001789 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001790
1791 // Set up diagnostics, capturing any diagnostics that would
1792 // otherwise be dropped.
1793 Clang->setDiagnostics(&AST->getDiagnostics());
1794
1795 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00001796 Clang->setTarget(TargetInfo::CreateTargetInfo(
1797 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001798 if (!Clang->hasTarget())
Craig Topper49a27902014-05-22 04:46:25 +00001799 return nullptr;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001800
1801 // Inform the target of the language options.
1802 //
1803 // FIXME: We shouldn't need to do this, the target should be immutable once
1804 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00001805 Clang->getTarget().adjust(Clang->getLangOpts());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001806
1807 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1808 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001809 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001810 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001811 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001812 "IR inputs not supported here!");
1813
1814 // Configure the various subsystems.
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001815 AST->TheSema.reset();
Craig Topper49a27902014-05-22 04:46:25 +00001816 AST->Ctx = nullptr;
1817 AST->PP = nullptr;
1818 AST->Reader = nullptr;
1819
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001820 // Create a file manager object to provide access to and cache the filesystem.
1821 Clang->setFileManager(&AST->getFileManager());
1822
1823 // Create the source manager.
1824 Clang->setSourceManager(&AST->getSourceManager());
1825
1826 ASTFrontendAction *Act = Action;
1827
Ahmed Charlesb8984322014-03-07 20:03:18 +00001828 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001829 if (!Act) {
1830 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1831 Act = TrackerAct.get();
1832 }
1833
1834 // Recover resources if we crash before exiting this method.
1835 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1836 ActCleanup(TrackerAct.get());
1837
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001838 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1839 AST->transferASTDataFromCompilerInstance(*Clang);
1840 if (OwnAST && ErrAST)
1841 ErrAST->swap(OwnAST);
1842
Craig Topper49a27902014-05-22 04:46:25 +00001843 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001844 }
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001845
1846 if (Persistent && !TrackerAct) {
1847 Clang->getPreprocessor().addPPCallbacks(
1848 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
David Blaikie6beb6aa2014-08-10 19:56:51 +00001849 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001850 if (Clang->hasASTConsumer())
1851 Consumers.push_back(Clang->takeASTConsumer());
David Blaikie6beb6aa2014-08-10 19:56:51 +00001852 Consumers.push_back(llvm::make_unique<TopLevelDeclTrackerConsumer>(
1853 *AST, AST->getCurrentTopLevelHashValue()));
1854 Clang->setASTConsumer(
1855 llvm::make_unique<MultiplexConsumer>(std::move(Consumers)));
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001856 }
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001857 if (!Act->Execute()) {
1858 AST->transferASTDataFromCompilerInstance(*Clang);
1859 if (OwnAST && ErrAST)
1860 ErrAST->swap(OwnAST);
1861
Craig Topper49a27902014-05-22 04:46:25 +00001862 return nullptr;
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001863 }
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001864
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001865 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001866 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001867
1868 Act->EndSourceFile();
1869
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001870 if (OwnAST)
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001871 return OwnAST.release();
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001872 else
1873 return AST;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001874}
1875
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001876bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1877 if (!Invocation)
1878 return true;
1879
1880 // We'll manage file buffers ourselves.
1881 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1882 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001883 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001884
Rafael Espindola32482082014-08-18 16:23:45 +00001885 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Douglas Gregorf5a18542010-10-27 17:24:53 +00001886 if (PrecompilePreamble) {
Douglas Gregorc6592922010-11-15 23:00:34 +00001887 PreambleRebuildCounter = 2;
Rafael Espindola2346a372014-08-18 18:47:08 +00001888 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001889 }
1890
Douglas Gregor16896c42010-10-28 15:44:59 +00001891 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001892 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001893
Ted Kremenek022a4902011-03-22 01:15:24 +00001894 // Recover resources if we crash before exiting this method.
1895 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
Rafael Espindola32482082014-08-18 16:23:45 +00001896 MemBufferCleanup(OverrideMainBuffer.get());
1897
1898 return Parse(std::move(OverrideMainBuffer));
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001899}
1900
David Blaikie103a2de2014-04-25 17:01:33 +00001901std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1902 CompilerInvocation *CI, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1903 bool OnlyLocalDecls, bool CaptureDiagnostics, bool PrecompilePreamble,
1904 TranslationUnitKind TUKind, bool CacheCodeCompletionResults,
1905 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001906 // Create the AST unit.
David Blaikie103a2de2014-04-25 17:01:33 +00001907 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
Craig Topper49a27902014-05-22 04:46:25 +00001908 ConfigureDiags(Diags, nullptr, nullptr, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001909 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001910 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001911 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001912 AST->TUKind = TUKind;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001913 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001914 AST->IncludeBriefCommentsInCodeCompletion
1915 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001916 AST->Invocation = CI;
Argyrios Kyrtzidis3ad52ed2013-01-21 18:45:42 +00001917 AST->FileSystemOpts = CI->getFileSystemOpts();
Ben Langmuir8832c062014-04-15 18:16:25 +00001918 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1919 createVFSFromCompilerInvocation(*CI, *Diags);
1920 if (!VFS)
1921 return nullptr;
1922 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001923 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001924
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001925 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001926 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1927 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001928 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1929 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00001930 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001931
David Blaikie103a2de2014-04-25 17:01:33 +00001932 if (AST->LoadFromCompilerInvocation(PrecompilePreamble))
1933 return nullptr;
1934 return AST;
Daniel Dunbar764c0822009-12-01 09:51:01 +00001935}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001936
Ahmed Charlesb8984322014-03-07 20:03:18 +00001937ASTUnit *ASTUnit::LoadFromCommandLine(
1938 const char **ArgBegin, const char **ArgEnd,
1939 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1940 bool OnlyLocalDecls, bool CaptureDiagnostics,
1941 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
1942 bool PrecompilePreamble, TranslationUnitKind TUKind,
1943 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1944 bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
1945 bool UserFilesAreVolatile, bool ForSerialization,
1946 std::unique_ptr<ASTUnit> *ErrAST) {
Alp Tokerf994cef2014-07-05 03:08:06 +00001947 if (!Diags.get()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00001948 // No diagnostics engine was provided, so create our own diagnostics object
1949 // with the default options.
Sean Silvaf1b49e22013-01-20 01:58:28 +00001950 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions());
Douglas Gregord03e8232010-04-05 21:10:19 +00001951 }
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001952
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001953 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001954
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001955 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001956
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001957 {
Douglas Gregor925296b2011-07-19 16:10:42 +00001958
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001959 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001960 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001961
Argyrios Kyrtzidis5cf423e2011-04-04 23:11:45 +00001962 CI = clang::createInvocationFromCommandLine(
Frits van Bommel717d7ed2011-07-18 12:00:32 +00001963 llvm::makeArrayRef(ArgBegin, ArgEnd),
1964 Diags);
Argyrios Kyrtzidisf606b822011-04-04 21:38:51 +00001965 if (!CI)
Craig Topper49a27902014-05-22 04:46:25 +00001966 return nullptr;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001967 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001968
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001969 // Override any files that need remapping
Dmitri Gribenko2febd212014-02-07 15:00:22 +00001970 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00001971 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1972 RemappedFiles[I].second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001973 }
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00001974 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1975 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1976 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001977
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001978 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001979 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001980
Erik Verbruggen6e922512012-04-12 10:11:59 +00001981 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1982
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001983 // Create the AST unit.
Ahmed Charlesb8984322014-03-07 20:03:18 +00001984 std::unique_ptr<ASTUnit> AST;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001985 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001986 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001987 AST->Diagnostics = Diags;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001988 AST->FileSystemOpts = CI->getFileSystemOpts();
Ben Langmuir8832c062014-04-15 18:16:25 +00001989 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1990 createVFSFromCompilerInvocation(*CI, *Diags);
1991 if (!VFS)
1992 return nullptr;
1993 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001994 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001995 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001996 AST->TUKind = TUKind;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001997 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001998 AST->IncludeBriefCommentsInCodeCompletion
1999 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00002000 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002001 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002002 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek5e14d392011-03-21 18:40:17 +00002003 AST->Invocation = CI;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002004 if (ForSerialization)
2005 AST->WriterData.reset(new ASTWriterData());
Alexey Samsonovb4f99dd2014-08-28 23:51:01 +00002006 // Zero out now to ease cleanup during crash recovery.
2007 CI = nullptr;
2008 Diags = nullptr;
Craig Topper49a27902014-05-22 04:46:25 +00002009
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002010 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002011 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2012 ASTUnitCleanup(AST.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002013
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00002014 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
2015 // Some error occurred, if caller wants to examine diagnostics, pass it the
2016 // ASTUnit.
2017 if (ErrAST) {
2018 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2019 ErrAST->swap(AST);
2020 }
Craig Topper49a27902014-05-22 04:46:25 +00002021 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00002022 }
2023
Ahmed Charles9a16beb2014-03-07 19:33:25 +00002024 return AST.release();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002025}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002026
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002027bool ASTUnit::Reparse(ArrayRef<RemappedFile> RemappedFiles) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002028 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002029 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002030
2031 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002032
Douglas Gregor16896c42010-10-28 15:44:59 +00002033 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002034 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00002035
Douglas Gregor0e119552010-07-31 00:40:00 +00002036 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00002037 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Alp Toker1b070d22014-07-07 07:47:20 +00002038 for (const auto &RB : PPOpts.RemappedFileBuffers)
2039 delete RB.second;
2040
Douglas Gregor0e119552010-07-31 00:40:00 +00002041 Invocation->getPreprocessorOpts().clearRemappedFiles();
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002042 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002043 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2044 RemappedFiles[I].second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002045 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002046
Douglas Gregorbb420ab2010-08-04 05:53:38 +00002047 // If we have a preamble file lying around, or if we might try to
2048 // build a precompiled preamble, do so now.
Rafael Espindola32482082014-08-18 16:23:45 +00002049 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002050 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Rafael Espindola2346a372014-08-18 18:47:08 +00002051 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor4dde7492010-07-23 23:58:40 +00002052
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002053 // Clear out the diagnostics state.
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002054 getDiagnostics().Reset();
2055 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis462ff352011-11-03 20:57:33 +00002056 if (OverrideMainBuffer)
2057 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002058
Douglas Gregor4dde7492010-07-23 23:58:40 +00002059 // Parse the sources
Rafael Espindola32482082014-08-18 16:23:45 +00002060 bool Result = Parse(std::move(OverrideMainBuffer));
2061
Argyrios Kyrtzidis36893372011-10-31 21:25:31 +00002062 // If we're caching global code-completion results, and the top-level
2063 // declarations have changed, clear out the code-completion cache.
2064 if (!Result && ShouldCacheCodeCompletionResults &&
2065 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2066 CacheCodeCompletionResults();
Douglas Gregordf7a79a2011-02-16 18:16:54 +00002067
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002068 // We now need to clear out the completion info related to this translation
2069 // unit; it'll be recreated if necessary.
2070 CCTUInfo.reset();
Douglas Gregor3f35bb22011-08-04 20:04:59 +00002071
Douglas Gregor4dde7492010-07-23 23:58:40 +00002072 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002073}
Douglas Gregor8e984da2010-08-04 16:47:14 +00002074
Douglas Gregorb14904c2010-08-13 22:48:40 +00002075//----------------------------------------------------------------------------//
2076// Code completion
2077//----------------------------------------------------------------------------//
2078
2079namespace {
2080 /// \brief Code completion consumer that combines the cached code-completion
2081 /// results from an ASTUnit with the code-completion results provided to it,
2082 /// then passes the result on to
2083 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith697cc9e2012-08-14 03:13:00 +00002084 uint64_t NormalContexts;
Douglas Gregorb14904c2010-08-13 22:48:40 +00002085 ASTUnit &AST;
2086 CodeCompleteConsumer &Next;
2087
2088 public:
2089 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002090 const CodeCompleteOptions &CodeCompleteOpts)
2091 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2092 AST(AST), Next(Next)
Douglas Gregorb14904c2010-08-13 22:48:40 +00002093 {
2094 // Compute the set of contexts in which we will look when we don't have
2095 // any information about the specific context.
2096 NormalContexts
Richard Smith697cc9e2012-08-14 03:13:00 +00002097 = (1LL << CodeCompletionContext::CCC_TopLevel)
2098 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2099 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2100 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2101 | (1LL << CodeCompletionContext::CCC_Statement)
2102 | (1LL << CodeCompletionContext::CCC_Expression)
2103 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2104 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2105 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2106 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2107 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2108 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2109 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor5e35d592010-09-14 23:59:36 +00002110
David Blaikiebbafb8a2012-03-11 07:00:24 +00002111 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +00002112 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2113 | (1LL << CodeCompletionContext::CCC_UnionTag)
2114 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregorb14904c2010-08-13 22:48:40 +00002115 }
Craig Topperafa7cb32014-03-13 06:07:04 +00002116
2117 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
2118 CodeCompletionResult *Results,
2119 unsigned NumResults) override;
2120
2121 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2122 OverloadCandidate *Candidates,
2123 unsigned NumCandidates) override {
Douglas Gregorb14904c2010-08-13 22:48:40 +00002124 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2125 }
Craig Topperafa7cb32014-03-13 06:07:04 +00002126
2127 CodeCompletionAllocator &getAllocator() override {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002128 return Next.getAllocator();
2129 }
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002130
Craig Topperafa7cb32014-03-13 06:07:04 +00002131 CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002132 return Next.getCodeCompletionTUInfo();
2133 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00002134 };
2135}
Douglas Gregord46cf182010-08-16 20:01:48 +00002136
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002137/// \brief Helper function that computes which global names are hidden by the
2138/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002139static void CalculateHiddenNames(const CodeCompletionContext &Context,
2140 CodeCompletionResult *Results,
2141 unsigned NumResults,
2142 ASTContext &Ctx,
2143 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002144 bool OnlyTagNames = false;
2145 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00002146 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002147 case CodeCompletionContext::CCC_TopLevel:
2148 case CodeCompletionContext::CCC_ObjCInterface:
2149 case CodeCompletionContext::CCC_ObjCImplementation:
2150 case CodeCompletionContext::CCC_ObjCIvarList:
2151 case CodeCompletionContext::CCC_ClassStructUnion:
2152 case CodeCompletionContext::CCC_Statement:
2153 case CodeCompletionContext::CCC_Expression:
2154 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor21325842011-07-07 16:03:39 +00002155 case CodeCompletionContext::CCC_DotMemberAccess:
2156 case CodeCompletionContext::CCC_ArrowMemberAccess:
2157 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002158 case CodeCompletionContext::CCC_Namespace:
2159 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00002160 case CodeCompletionContext::CCC_Name:
2161 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00002162 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor2c595ad2011-07-30 06:55:39 +00002163 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002164 break;
2165
2166 case CodeCompletionContext::CCC_EnumTag:
2167 case CodeCompletionContext::CCC_UnionTag:
2168 case CodeCompletionContext::CCC_ClassOrStructTag:
2169 OnlyTagNames = true;
2170 break;
2171
2172 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00002173 case CodeCompletionContext::CCC_MacroName:
2174 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00002175 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002176 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00002177 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00002178 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00002179 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00002180 case CodeCompletionContext::CCC_Other:
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00002181 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor21325842011-07-07 16:03:39 +00002182 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2183 case CodeCompletionContext::CCC_ObjCClassMessage:
2184 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002185 // We're looking for nothing, or we're looking for names that cannot
2186 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002187 return;
2188 }
2189
John McCall276321a2010-08-25 06:19:51 +00002190 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002191 for (unsigned I = 0; I != NumResults; ++I) {
2192 if (Results[I].Kind != Result::RK_Declaration)
2193 continue;
2194
2195 unsigned IDNS
2196 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2197
2198 bool Hiding = false;
2199 if (OnlyTagNames)
2200 Hiding = (IDNS & Decl::IDNS_Tag);
2201 else {
2202 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00002203 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2204 Decl::IDNS_NonMemberOperator);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002205 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002206 HiddenIDNS |= Decl::IDNS_Tag;
2207 Hiding = (IDNS & HiddenIDNS);
2208 }
2209
2210 if (!Hiding)
2211 continue;
2212
2213 DeclarationName Name = Results[I].Declaration->getDeclName();
2214 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2215 HiddenNames.insert(Identifier->getName());
2216 else
2217 HiddenNames.insert(Name.getAsString());
2218 }
2219}
2220
2221
Douglas Gregord46cf182010-08-16 20:01:48 +00002222void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2223 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002224 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00002225 unsigned NumResults) {
2226 // Merge the results we were given with the results we cached.
2227 bool AddedResult = false;
Richard Smith697cc9e2012-08-14 03:13:00 +00002228 uint64_t InContexts =
2229 Context.getKind() == CodeCompletionContext::CCC_Recovery
2230 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002231 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002232 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall276321a2010-08-25 06:19:51 +00002233 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002234 SmallVector<Result, 8> AllResults;
Douglas Gregord46cf182010-08-16 20:01:48 +00002235 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00002236 C = AST.cached_completion_begin(),
2237 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00002238 C != CEnd; ++C) {
2239 // If the context we are in matches any of the contexts we are
2240 // interested in, we'll add this result.
2241 if ((C->ShowInContexts & InContexts) == 0)
2242 continue;
2243
2244 // If we haven't added any results previously, do so now.
2245 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002246 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2247 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00002248 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2249 AddedResult = true;
2250 }
2251
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002252 // Determine whether this global completion result is hidden by a local
2253 // completion result. If so, skip it.
2254 if (C->Kind != CXCursor_MacroDefinition &&
2255 HiddenNames.count(C->Completion->getTypedText()))
2256 continue;
2257
Douglas Gregord46cf182010-08-16 20:01:48 +00002258 // Adjust priority based on similar type classes.
2259 unsigned Priority = C->Priority;
Douglas Gregor12785102010-08-24 20:21:13 +00002260 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00002261 if (!Context.getPreferredType().isNull()) {
2262 if (C->Kind == CXCursor_MacroDefinition) {
2263 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002264 S.getLangOpts(),
Douglas Gregor12785102010-08-24 20:21:13 +00002265 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00002266 } else if (C->Type) {
2267 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00002268 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00002269 Context.getPreferredType().getUnqualifiedType());
2270 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2271 if (ExpectedSTC == C->TypeClass) {
2272 // We know this type is similar; check for an exact match.
2273 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00002274 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00002275 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00002276 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00002277 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2278 Priority /= CCF_ExactTypeMatch;
2279 else
2280 Priority /= CCF_SimilarTypeMatch;
2281 }
2282 }
2283 }
2284
Douglas Gregor12785102010-08-24 20:21:13 +00002285 // Adjust the completion string, if required.
2286 if (C->Kind == CXCursor_MacroDefinition &&
2287 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2288 // Create a new code-completion string that just contains the
2289 // macro name, without its arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002290 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2291 CCP_CodePattern, C->Availability);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002292 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00002293 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002294 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00002295 }
2296
Argyrios Kyrtzidis5c8b1cd2012-09-27 00:24:09 +00002297 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregorf757a122010-08-23 23:00:57 +00002298 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00002299 }
2300
2301 // If we did not add any cached completion results, just forward the
2302 // results we were given to the next consumer.
2303 if (!AddedResult) {
2304 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2305 return;
2306 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002307
Douglas Gregord46cf182010-08-16 20:01:48 +00002308 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2309 AllResults.size());
2310}
2311
2312
2313
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002314void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002315 ArrayRef<RemappedFile> RemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00002316 bool IncludeMacros,
2317 bool IncludeCodePatterns,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002318 bool IncludeBriefComments,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002319 CodeCompleteConsumer &Consumer,
David Blaikie9c902b52011-09-25 23:23:43 +00002320 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002321 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002322 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2323 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002324 if (!Invocation)
Douglas Gregor8e984da2010-08-04 16:47:14 +00002325 return;
2326
Douglas Gregor16896c42010-10-28 15:44:59 +00002327 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002328 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002329 Twine(Line) + ":" + Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00002330
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00002331 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek5e14d392011-03-21 18:40:17 +00002332 CCInvocation(new CompilerInvocation(*Invocation));
2333
2334 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002335 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek5e14d392011-03-21 18:40:17 +00002336 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002337
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002338 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2339 CachedCompletionResults.empty();
2340 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2341 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2342 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2343
2344 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2345
Douglas Gregor8e984da2010-08-04 16:47:14 +00002346 FrontendOpts.CodeCompletionAt.FileName = File;
2347 FrontendOpts.CodeCompletionAt.Line = Line;
2348 FrontendOpts.CodeCompletionAt.Column = Column;
2349
2350 // Set the language options appropriately.
Ted Kremenek8cf47df2011-11-17 23:01:24 +00002351 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002352
Ahmed Charlesb8984322014-03-07 20:03:18 +00002353 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002354
2355 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002356 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2357 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002358
Ted Kremenek5e14d392011-03-21 18:40:17 +00002359 Clang->setInvocation(&*CCInvocation);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002360 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002361
2362 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002363 Clang->setDiagnostics(&Diag);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002364 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek84de4a12011-03-21 18:40:07 +00002365 Clang->getDiagnostics(),
Douglas Gregor8e984da2010-08-04 16:47:14 +00002366 StoredDiagnostics);
Manuel Klimekbe0474c2013-07-18 14:23:12 +00002367 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002368
2369 // Create the target instance.
Alp Toker80758082014-07-06 05:26:44 +00002370 Clang->setTarget(TargetInfo::CreateTargetInfo(
2371 Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002372 if (!Clang->hasTarget()) {
Craig Topper49a27902014-05-22 04:46:25 +00002373 Clang->setInvocation(nullptr);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002374 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002375 }
2376
2377 // Inform the target of the language options.
2378 //
2379 // FIXME: We shouldn't need to do this, the target should be immutable once
2380 // created. This complexity should be lifted elsewhere.
Alp Toker74437972014-07-06 05:14:24 +00002381 Clang->getTarget().adjust(Clang->getLangOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002382
Ted Kremenek84de4a12011-03-21 18:40:07 +00002383 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002384 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002385 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002386 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002387 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002388 "IR inputs not support here!");
2389
2390
2391 // Use the source and file managers that we were given.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002392 Clang->setFileManager(&FileMgr);
2393 Clang->setSourceManager(&SourceMgr);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002394
2395 // Remap files.
2396 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00002397 PreprocessorOpts.RetainRemappedFileBuffers = true;
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002398 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002399 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
2400 RemappedFiles[I].second);
Daniel Jasperd90ec572014-02-12 08:45:05 +00002401 OwnedBuffers.push_back(RemappedFiles[I].second);
Douglas Gregorb97b6662010-08-20 00:59:43 +00002402 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002403
Douglas Gregorb14904c2010-08-13 22:48:40 +00002404 // Use the code completion consumer we were given, but adding any cached
2405 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00002406 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002407 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002408 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002409
Douglas Gregor028d3e42010-08-09 20:45:32 +00002410 // If we have a precompiled preamble, try to use it. We only allow
2411 // the use of the precompiled preamble if we're if the completion
2412 // point is within the main file, after the end of the precompiled
2413 // preamble.
Rafael Espindola2346a372014-08-18 18:47:08 +00002414 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002415 if (!getPreambleFile(this).empty()) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002416 std::string CompleteFilePath(File);
Rafael Espindola073ff102013-07-29 21:26:52 +00002417 llvm::sys::fs::UniqueID CompleteFileID;
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002418
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00002419 if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002420 std::string MainPath(OriginalSourceFile);
Rafael Espindola073ff102013-07-29 21:26:52 +00002421 llvm::sys::fs::UniqueID MainID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00002422 if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002423 if (CompleteFileID == MainID && Line > 1)
Rafael Espindola2346a372014-08-18 18:47:08 +00002424 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2425 *CCInvocation, false, Line - 1);
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002426 }
2427 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002428 }
2429
2430 // If the main file has been overridden due to the use of a preamble,
2431 // make that override happen and introduce the preamble.
2432 if (OverrideMainBuffer) {
Rafael Espindola2346a372014-08-18 18:47:08 +00002433 PreprocessorOpts.addRemappedFile(OriginalSourceFile,
2434 OverrideMainBuffer.get());
Douglas Gregor028d3e42010-08-09 20:45:32 +00002435 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2436 PreprocessorOpts.PrecompiledPreambleBytes.second
2437 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002438 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002439 PreprocessorOpts.DisablePCHValidation = true;
Rafael Espindola2346a372014-08-18 18:47:08 +00002440
2441 OwnedBuffers.push_back(OverrideMainBuffer.release());
Douglas Gregor7b02b582010-08-20 00:02:33 +00002442 } else {
2443 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2444 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002445 }
2446
Argyrios Kyrtzidis870704f2012-11-02 22:18:44 +00002447 // Disable the preprocessing record if modules are not enabled.
2448 if (!Clang->getLangOpts().Modules)
2449 PreprocessorOpts.DetailedRecord = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00002450
2451 std::unique_ptr<SyntaxOnlyAction> Act;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002452 Act.reset(new SyntaxOnlyAction);
Douglas Gregor32fbe312012-01-20 16:28:04 +00002453 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00002454 Act->Execute();
2455 Act->EndSourceFile();
2456 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002457}
Douglas Gregore9386682010-08-13 05:36:37 +00002458
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002459bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00002460 if (HadModuleLoaderFatalFailure)
2461 return true;
2462
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002463 // Write to a temporary file and later rename it to the actual file, to avoid
2464 // possible race conditions.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002465 SmallString<128> TempPath;
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002466 TempPath = File;
2467 TempPath += "-%%%%%%%%";
2468 int fd;
Rafael Espindola18627112013-07-05 21:13:58 +00002469 if (llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath))
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002470 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002471
Douglas Gregore9386682010-08-13 05:36:37 +00002472 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2473 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002474 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002475
2476 serialize(Out);
2477 Out.close();
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002478 if (Out.has_error()) {
2479 Out.clear_error();
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002480 return true;
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002481 }
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002482
Rafael Espindola65e025c2011-12-25 01:18:52 +00002483 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Rafael Espindola2a008782014-01-10 21:32:14 +00002484 llvm::sys::fs::remove(TempPath.str());
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002485 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002486 }
2487
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002488 return false;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002489}
2490
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002491static bool serializeUnit(ASTWriter &Writer,
2492 SmallVectorImpl<char> &Buffer,
2493 Sema &S,
2494 bool hasErrors,
2495 raw_ostream &OS) {
Craig Topper49a27902014-05-22 04:46:25 +00002496 Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002497
2498 // Write the generated bitstream to "Out".
2499 if (!Buffer.empty())
2500 OS.write(Buffer.data(), Buffer.size());
2501
2502 return false;
2503}
2504
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002505bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00002506 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002507
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002508 if (WriterData)
2509 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2510 getSema(), hasErrors, OS);
2511
Daniel Dunbar9a963862012-02-29 20:31:23 +00002512 SmallString<128> Buffer;
Douglas Gregore9386682010-08-13 05:36:37 +00002513 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002514 ASTWriter Writer(Stream);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002515 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregore9386682010-08-13 05:36:37 +00002516}
Douglas Gregor925296b2011-07-19 16:10:42 +00002517
2518typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2519
Douglas Gregor925296b2011-07-19 16:10:42 +00002520void ASTUnit::TranslateStoredDiagnostics(
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002521 FileManager &FileMgr,
Douglas Gregor925296b2011-07-19 16:10:42 +00002522 SourceManager &SrcMgr,
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002523 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002524 SmallVectorImpl<StoredDiagnostic> &Out) {
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002525 // Map the standalone diagnostic into the new source manager. We also need to
2526 // remap all the locations to the new view. This includes the diag location,
2527 // any associated source ranges, and the source ranges of associated fix-its.
Douglas Gregor925296b2011-07-19 16:10:42 +00002528 // FIXME: There should be a cleaner way to do this.
2529
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002530 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregor925296b2011-07-19 16:10:42 +00002531 Result.reserve(Diags.size());
Douglas Gregor925296b2011-07-19 16:10:42 +00002532 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2533 // Rebuild the StoredDiagnostic.
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002534 const StandaloneDiagnostic &SD = Diags[I];
2535 if (SD.Filename.empty())
2536 continue;
2537 const FileEntry *FE = FileMgr.getFile(SD.Filename);
2538 if (!FE)
2539 continue;
2540 FileID FID = SrcMgr.translateFile(FE);
2541 SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
2542 if (FileLoc.isInvalid())
2543 continue;
2544 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
Douglas Gregor925296b2011-07-19 16:10:42 +00002545 FullSourceLoc Loc(L, SrcMgr);
2546
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002547 SmallVector<CharSourceRange, 4> Ranges;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002548 Ranges.reserve(SD.Ranges.size());
2549 for (std::vector<std::pair<unsigned, unsigned> >::const_iterator
2550 I = SD.Ranges.begin(), E = SD.Ranges.end(); I != E; ++I) {
2551 SourceLocation BL = FileLoc.getLocWithOffset((*I).first);
2552 SourceLocation EL = FileLoc.getLocWithOffset((*I).second);
2553 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
Douglas Gregor925296b2011-07-19 16:10:42 +00002554 }
2555
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002556 SmallVector<FixItHint, 2> FixIts;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002557 FixIts.reserve(SD.FixIts.size());
2558 for (std::vector<StandaloneFixIt>::const_iterator
2559 I = SD.FixIts.begin(), E = SD.FixIts.end();
Douglas Gregor925296b2011-07-19 16:10:42 +00002560 I != E; ++I) {
2561 FixIts.push_back(FixItHint());
2562 FixItHint &FH = FixIts.back();
2563 FH.CodeToInsert = I->CodeToInsert;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002564 SourceLocation BL = FileLoc.getLocWithOffset(I->RemoveRange.first);
2565 SourceLocation EL = FileLoc.getLocWithOffset(I->RemoveRange.second);
2566 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
Douglas Gregor925296b2011-07-19 16:10:42 +00002567 }
2568
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002569 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2570 SD.Message, Loc, Ranges, FixIts));
Douglas Gregor925296b2011-07-19 16:10:42 +00002571 }
2572 Result.swap(Out);
2573}
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002574
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002575void ASTUnit::addFileLevelDecl(Decl *D) {
2576 assert(D);
Douglas Gregor61d63d02011-11-07 18:53:57 +00002577
2578 // We only care about local declarations.
2579 if (D->isFromASTFile())
2580 return;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002581
2582 SourceManager &SM = *SourceMgr;
2583 SourceLocation Loc = D->getLocation();
2584 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2585 return;
2586
2587 // We only keep track of the file-level declarations of each file.
2588 if (!D->getLexicalDeclContext()->isFileContext())
2589 return;
2590
2591 SourceLocation FileLoc = SM.getFileLoc(Loc);
2592 assert(SM.isLocalSourceLocation(FileLoc));
2593 FileID FID;
2594 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002595 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002596 if (FID.isInvalid())
2597 return;
2598
2599 LocDeclsTy *&Decls = FileDecls[FID];
2600 if (!Decls)
2601 Decls = new LocDeclsTy();
2602
2603 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2604
2605 if (Decls->empty() || Decls->back().first <= Offset) {
2606 Decls->push_back(LocDecl);
2607 return;
2608 }
2609
Benjamin Kramer45025c02013-08-24 13:22:59 +00002610 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2611 LocDecl, llvm::less_first());
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002612
2613 Decls->insert(I, LocDecl);
2614}
2615
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002616void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2617 SmallVectorImpl<Decl *> &Decls) {
2618 if (File.isInvalid())
2619 return;
2620
2621 if (SourceMgr->isLoadedFileID(File)) {
2622 assert(Ctx->getExternalSource() && "No external source!");
2623 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2624 Decls);
2625 }
2626
2627 FileDeclsTy::iterator I = FileDecls.find(File);
2628 if (I == FileDecls.end())
2629 return;
2630
2631 LocDeclsTy &LocDecls = *I->second;
2632 if (LocDecls.empty())
2633 return;
2634
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002635 LocDeclsTy::iterator BeginIt =
2636 std::lower_bound(LocDecls.begin(), LocDecls.end(),
Craig Topper49a27902014-05-22 04:46:25 +00002637 std::make_pair(Offset, (Decl *)nullptr),
2638 llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002639 if (BeginIt != LocDecls.begin())
2640 --BeginIt;
2641
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00002642 // If we are pointing at a top-level decl inside an objc container, we need
2643 // to backtrack until we find it otherwise we will fail to report that the
2644 // region overlaps with an objc container.
2645 while (BeginIt != LocDecls.begin() &&
2646 BeginIt->second->isTopLevelDeclInObjCContainer())
2647 --BeginIt;
2648
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002649 LocDeclsTy::iterator EndIt = std::upper_bound(
2650 LocDecls.begin(), LocDecls.end(),
Craig Topper49a27902014-05-22 04:46:25 +00002651 std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002652 if (EndIt != LocDecls.end())
2653 ++EndIt;
2654
2655 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2656 Decls.push_back(DIt->second);
2657}
2658
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002659SourceLocation ASTUnit::getLocation(const FileEntry *File,
2660 unsigned Line, unsigned Col) const {
2661 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002662 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002663 return SM.getMacroArgExpandedLocation(Loc);
2664}
2665
2666SourceLocation ASTUnit::getLocation(const FileEntry *File,
2667 unsigned Offset) const {
2668 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002669 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002670 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2671}
2672
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002673/// \brief If \arg Loc is a loaded location from the preamble, returns
2674/// the corresponding local location of the main file, otherwise it returns
2675/// \arg Loc.
2676SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2677 FileID PreambleID;
2678 if (SourceMgr)
2679 PreambleID = SourceMgr->getPreambleFileID();
2680
2681 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2682 return Loc;
2683
2684 unsigned Offs;
2685 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2686 SourceLocation FileLoc
2687 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2688 return FileLoc.getLocWithOffset(Offs);
2689 }
2690
2691 return Loc;
2692}
2693
2694/// \brief If \arg Loc is a local location of the main file but inside the
2695/// preamble chunk, returns the corresponding loaded location from the
2696/// preamble, otherwise it returns \arg Loc.
2697SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2698 FileID PreambleID;
2699 if (SourceMgr)
2700 PreambleID = SourceMgr->getPreambleFileID();
2701
2702 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2703 return Loc;
2704
2705 unsigned Offs;
2706 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2707 Offs < Preamble.size()) {
2708 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2709 return FileLoc.getLocWithOffset(Offs);
2710 }
2711
2712 return Loc;
2713}
2714
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002715bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2716 FileID FID;
2717 if (SourceMgr)
2718 FID = SourceMgr->getPreambleFileID();
2719
2720 if (Loc.isInvalid() || FID.isInvalid())
2721 return false;
2722
2723 return SourceMgr->isInFileID(Loc, FID);
2724}
2725
2726bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2727 FileID FID;
2728 if (SourceMgr)
2729 FID = SourceMgr->getMainFileID();
2730
2731 if (Loc.isInvalid() || FID.isInvalid())
2732 return false;
2733
2734 return SourceMgr->isInFileID(Loc, FID);
2735}
2736
2737SourceLocation ASTUnit::getEndOfPreambleFileID() {
2738 FileID FID;
2739 if (SourceMgr)
2740 FID = SourceMgr->getPreambleFileID();
2741
2742 if (FID.isInvalid())
2743 return SourceLocation();
2744
2745 return SourceMgr->getLocForEndOfFile(FID);
2746}
2747
2748SourceLocation ASTUnit::getStartOfMainFileID() {
2749 FileID FID;
2750 if (SourceMgr)
2751 FID = SourceMgr->getMainFileID();
2752
2753 if (FID.isInvalid())
2754 return SourceLocation();
2755
2756 return SourceMgr->getLocForStartOfFile(FID);
2757}
2758
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002759std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
2760ASTUnit::getLocalPreprocessingEntities() const {
2761 if (isMainFileAST()) {
2762 serialization::ModuleFile &
2763 Mod = Reader->getModuleManager().getPrimaryModule();
2764 return Reader->getModulePreprocessedEntities(Mod);
2765 }
2766
2767 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2768 return std::make_pair(PPRec->local_begin(), PPRec->local_end());
2769
2770 return std::make_pair(PreprocessingRecord::iterator(),
2771 PreprocessingRecord::iterator());
2772}
2773
Argyrios Kyrtzidise514b202012-10-03 01:58:28 +00002774bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002775 if (isMainFileAST()) {
2776 serialization::ModuleFile &
2777 Mod = Reader->getModuleManager().getPrimaryModule();
2778 ASTReader::ModuleDeclIterator MDI, MDE;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002779 std::tie(MDI, MDE) = Reader->getModuleFileLevelDecls(Mod);
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002780 for (; MDI != MDE; ++MDI) {
2781 if (!Fn(context, *MDI))
2782 return false;
2783 }
2784
2785 return true;
2786 }
2787
2788 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2789 TLEnd = top_level_end();
2790 TL != TLEnd; ++TL) {
2791 if (!Fn(context, *TL))
2792 return false;
2793 }
2794
2795 return true;
2796}
2797
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002798namespace {
2799struct PCHLocatorInfo {
2800 serialization::ModuleFile *Mod;
Craig Topper49a27902014-05-22 04:46:25 +00002801 PCHLocatorInfo() : Mod(nullptr) {}
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002802};
2803}
2804
2805static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
2806 PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
2807 switch (M.Kind) {
2808 case serialization::MK_Module:
2809 return true; // skip dependencies.
2810 case serialization::MK_PCH:
2811 Info.Mod = &M;
2812 return true; // found it.
2813 case serialization::MK_Preamble:
2814 return false; // look in dependencies.
2815 case serialization::MK_MainFile:
2816 return false; // look in dependencies.
2817 }
2818
2819 return true;
2820}
2821
2822const FileEntry *ASTUnit::getPCHFile() {
2823 if (!Reader)
Craig Topper49a27902014-05-22 04:46:25 +00002824 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002825
2826 PCHLocatorInfo Info;
2827 Reader->getModuleManager().visit(PCHLocator, &Info);
2828 if (Info.Mod)
2829 return Info.Mod->File;
2830
Craig Topper49a27902014-05-22 04:46:25 +00002831 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002832}
2833
Argyrios Kyrtzidise445c722012-10-10 02:12:47 +00002834bool ASTUnit::isModuleFile() {
2835 return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2836}
2837
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002838void ASTUnit::PreambleData::countLines() const {
2839 NumLines = 0;
2840 if (empty())
2841 return;
2842
2843 for (std::vector<char>::const_iterator
2844 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2845 if (*I == '\n')
2846 ++NumLines;
2847 }
2848 if (Buffer.back() != '\n')
2849 ++NumLines;
2850}
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002851
2852#ifndef NDEBUG
2853ASTUnit::ConcurrencyState::ConcurrencyState() {
2854 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2855}
2856
2857ASTUnit::ConcurrencyState::~ConcurrencyState() {
2858 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2859}
2860
2861void ASTUnit::ConcurrencyState::start() {
2862 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2863 assert(acquired && "Concurrent access to ASTUnit!");
2864}
2865
2866void ASTUnit::ConcurrencyState::finish() {
2867 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2868}
2869
2870#else // NDEBUG
2871
Alp Tokerb159c132013-11-22 07:49:39 +00002872ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = 0; }
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002873ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2874void ASTUnit::ConcurrencyState::start() {}
2875void ASTUnit::ConcurrencyState::finish() {}
2876
2877#endif