blob: 055537b46fd1c9504306b2929d0b321048250d0e [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>
Douglas Gregor0e119552010-07-31 00:40:00 +000050#include <sys/stat.h>
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000051using namespace clang;
52
Douglas Gregor16896c42010-10-28 15:44:59 +000053using llvm::TimeRecord;
54
55namespace {
56 class SimpleTimer {
57 bool WantTiming;
58 TimeRecord Start;
59 std::string Output;
60
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000061 public:
Douglas Gregor1cbdd952010-11-01 13:48:43 +000062 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor16896c42010-10-28 15:44:59 +000063 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000064 Start = TimeRecord::getCurrentTime();
Douglas Gregor16896c42010-10-28 15:44:59 +000065 }
66
Chris Lattner0e62c1c2011-07-23 10:55:15 +000067 void setOutput(const Twine &Output) {
Douglas Gregor16896c42010-10-28 15:44:59 +000068 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000069 this->Output = Output.str();
Douglas Gregor16896c42010-10-28 15:44:59 +000070 }
71
Douglas Gregor16896c42010-10-28 15:44:59 +000072 ~SimpleTimer() {
73 if (WantTiming) {
74 TimeRecord Elapsed = TimeRecord::getCurrentTime();
75 Elapsed -= Start;
76 llvm::errs() << Output << ':';
77 Elapsed.print(Elapsed, llvm::errs());
78 llvm::errs() << '\n';
79 }
80 }
81 };
Ted Kremenek06b4f912011-10-27 17:55:18 +000082
83 struct OnDiskData {
84 /// \brief The file in which the precompiled preamble is stored.
85 std::string PreambleFile;
86
Rafael Espindolabc7d9492013-06-26 03:52:38 +000087 /// \brief Temporary files that should be removed when the ASTUnit is
Ted Kremenek06b4f912011-10-27 17:55:18 +000088 /// destroyed.
Rafael Espindolabc7d9492013-06-26 03:52:38 +000089 SmallVector<std::string, 4> TemporaryFiles;
90
Ted Kremenek06b4f912011-10-27 17:55:18 +000091 /// \brief Erase temporary files.
92 void CleanTemporaryFiles();
93
94 /// \brief Erase the preamble file.
95 void CleanPreambleFile();
96
97 /// \brief Erase temporary files and the preamble file.
98 void Cleanup();
99 };
100}
101
Ted Kremenekbd307a52011-10-27 19:44:25 +0000102static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
103 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
104 return M;
105}
106
Dmitri Gribenkob2aa9232012-11-15 14:28:07 +0000107static void cleanupOnDiskMapAtExit();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000108
109typedef llvm::DenseMap<const ASTUnit *, OnDiskData *> OnDiskDataMap;
110static 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();
136 OnDiskData *&D = M[AU];
137 if (!D)
138 D = new OnDiskData();
139 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();
154 delete I->second;
155 M.erase(AU);
156 }
157}
158
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000159static void setPreambleFile(const ASTUnit *AU, StringRef preambleFile) {
Ted Kremenek06b4f912011-10-27 17:55:18 +0000160 getOnDiskData(AU).PreambleFile = preambleFile;
161}
162
163static const std::string &getPreambleFile(const ASTUnit *AU) {
164 return getOnDiskData(AU).PreambleFile;
165}
166
167void OnDiskData::CleanTemporaryFiles() {
168 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
Rafael Espindolabc7d9492013-06-26 03:52:38 +0000169 llvm::sys::fs::remove(TemporaryFiles[I]);
170 TemporaryFiles.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +0000171}
172
173void OnDiskData::CleanPreambleFile() {
174 if (!PreambleFile.empty()) {
Rafael Espindolabc4aa552013-06-26 04:02:37 +0000175 llvm::sys::fs::remove(PreambleFile);
Ted Kremenek06b4f912011-10-27 17:55:18 +0000176 PreambleFile.clear();
177 }
178}
179
180void OnDiskData::Cleanup() {
181 CleanTemporaryFiles();
182 CleanPreambleFile();
183}
184
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000185struct ASTUnit::ASTWriterData {
186 SmallString<128> Buffer;
187 llvm::BitstreamWriter Stream;
188 ASTWriter Writer;
189
190 ASTWriterData() : Stream(Buffer), Writer(Stream) { }
191};
192
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000193void ASTUnit::clearFileLevelDecls() {
Reid Kleckner588c9372014-02-19 23:44:52 +0000194 llvm::DeleteContainerSeconds(FileDecls);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000195}
196
Ted Kremenek06b4f912011-10-27 17:55:18 +0000197void ASTUnit::CleanTemporaryFiles() {
198 getOnDiskData(this).CleanTemporaryFiles();
199}
200
Rafael Espindolabc7d9492013-06-26 03:52:38 +0000201void ASTUnit::addTemporaryFile(StringRef TempFile) {
Ted Kremenek06b4f912011-10-27 17:55:18 +0000202 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
Douglas Gregor16896c42010-10-28 15:44:59 +0000203}
204
Douglas Gregorbb420ab2010-08-04 05:53:38 +0000205/// \brief After failing to build a precompiled preamble (due to
206/// errors in the source that occurs in the preamble), the number of
207/// reparses during which we'll skip even trying to precompile the
208/// preamble.
209const unsigned DefaultPreambleRebuildInterval = 5;
210
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000211/// \brief Tracks the number of ASTUnit objects that are currently active.
212///
213/// Used for debugging purposes only.
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000214static std::atomic<unsigned> ActiveASTUnitObjects;
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000215
Douglas Gregord03e8232010-04-05 21:10:19 +0000216ASTUnit::ASTUnit(bool _MainFileIsAST)
Craig Topper49a27902014-05-22 04:46:25 +0000217 : Reader(nullptr), HadModuleLoaderFatalFailure(false),
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +0000218 OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000219 MainFileIsAST(_MainFileIsAST),
Douglas Gregor69f74f82011-08-25 22:30:56 +0000220 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis4954bc12011-03-05 01:03:48 +0000221 OwnsRemappedFileBuffers(true),
Douglas Gregor16896c42010-10-28 15:44:59 +0000222 NumStoredDiagnosticsFromDriver(0),
Craig Topper49a27902014-05-22 04:46:25 +0000223 PreambleRebuildCounter(0), SavedMainFileBuffer(nullptr),
224 PreambleBuffer(nullptr), NumWarningsInPreamble(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +0000225 ShouldCacheCodeCompletionResults(false),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000226 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000227 CompletionCacheTopLevelHashValue(0),
228 PreambleTopLevelHashValue(0),
229 CurrentTopLevelHashValue(0),
Douglas Gregor4740c452010-08-19 00:45:44 +0000230 UnsafeToFree(false) {
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000231 if (getenv("LIBCLANG_OBJTRACKING"))
232 fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000233}
Douglas Gregord03e8232010-04-05 21:10:19 +0000234
Daniel Dunbar764c0822009-12-01 09:51:01 +0000235ASTUnit::~ASTUnit() {
Douglas Gregor6b930962013-05-03 22:58:43 +0000236 // If we loaded from an AST file, balance out the BeginSourceFile call.
237 if (MainFileIsAST && getDiagnostics().getClient()) {
238 getDiagnostics().getClient()->EndSourceFile();
239 }
240
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000241 clearFileLevelDecls();
242
Ted Kremenek06b4f912011-10-27 17:55:18 +0000243 // Clean up the temporary files and the preamble file.
244 removeOnDiskEntry(this);
245
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000246 // Free the buffers associated with remapped files. We are required to
247 // perform this operation here because we explicitly request that the
248 // compiler instance *not* free these buffers for each invocation of the
249 // parser.
Alp Tokerf994cef2014-07-05 03:08:06 +0000250 if (Invocation.get() && OwnsRemappedFileBuffers) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000251 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
252 for (PreprocessorOptions::remapped_file_buffer_iterator
253 FB = PPOpts.remapped_file_buffer_begin(),
254 FBEnd = PPOpts.remapped_file_buffer_end();
255 FB != FBEnd;
256 ++FB)
257 delete FB->second;
258 }
Douglas Gregor96c04262010-07-27 14:52:07 +0000259
260 delete SavedMainFileBuffer;
Douglas Gregora0734c52010-08-19 01:33:06 +0000261 delete PreambleBuffer;
262
Douglas Gregor16896c42010-10-28 15:44:59 +0000263 ClearCachedCompletionResults();
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000264
Benjamin Kramer4527fb22014-03-02 17:08:31 +0000265 if (getenv("LIBCLANG_OBJTRACKING"))
266 fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000267}
268
Argyrios Kyrtzidisda6e0542012-01-17 18:48:07 +0000269void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
270
Douglas Gregor39982192010-08-15 06:18:01 +0000271/// \brief Determine the set of code-completion contexts in which this
272/// declaration should be shown.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000273static unsigned getDeclShowContexts(const NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000274 const LangOptions &LangOpts,
275 bool &IsNestedNameSpecifier) {
276 IsNestedNameSpecifier = false;
277
Douglas Gregor39982192010-08-15 06:18:01 +0000278 if (isa<UsingShadowDecl>(ND))
279 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
280 if (!ND)
281 return 0;
282
Richard Smith697cc9e2012-08-14 03:13:00 +0000283 uint64_t Contexts = 0;
Douglas Gregor39982192010-08-15 06:18:01 +0000284 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
285 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
286 // Types can appear in these contexts.
287 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000288 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
289 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
290 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
291 | (1LL << CodeCompletionContext::CCC_Statement)
292 | (1LL << CodeCompletionContext::CCC_Type)
293 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor39982192010-08-15 06:18:01 +0000294
295 // In C++, types can appear in expressions contexts (for functional casts).
296 if (LangOpts.CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +0000297 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor39982192010-08-15 06:18:01 +0000298
299 // In Objective-C, message sends can send interfaces. In Objective-C++,
300 // all types are available due to functional casts.
301 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000302 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor21325842011-07-07 16:03:39 +0000303
304 // In Objective-C, you can only be a subclass of another Objective-C class
305 if (isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000306 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor39982192010-08-15 06:18:01 +0000307
308 // Deal with tag names.
309 if (isa<EnumDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000310 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000311
Douglas Gregor59cab552010-08-16 23:05:20 +0000312 // Part of the nested-name-specifier in C++0x.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000313 if (LangOpts.CPlusPlus11)
Douglas Gregor59cab552010-08-16 23:05:20 +0000314 IsNestedNameSpecifier = true;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000315 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
Douglas Gregor39982192010-08-15 06:18:01 +0000316 if (Record->isUnion())
Richard Smith697cc9e2012-08-14 03:13:00 +0000317 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000318 else
Richard Smith697cc9e2012-08-14 03:13:00 +0000319 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000320
Douglas Gregor39982192010-08-15 06:18:01 +0000321 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000322 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000323 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000324 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000325 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
326 // Values can appear in these contexts.
Richard Smith697cc9e2012-08-14 03:13:00 +0000327 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
328 | (1LL << CodeCompletionContext::CCC_Expression)
329 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
330 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor39982192010-08-15 06:18:01 +0000331 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000332 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor21325842011-07-07 16:03:39 +0000333 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000334 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor39982192010-08-15 06:18:01 +0000335 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000336 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor39982192010-08-15 06:18:01 +0000337
338 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000339 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000340 }
341
342 return Contexts;
343}
344
Douglas Gregorb14904c2010-08-13 22:48:40 +0000345void ASTUnit::CacheCodeCompletionResults() {
346 if (!TheSema)
347 return;
348
Douglas Gregor16896c42010-10-28 15:44:59 +0000349 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000350 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000351
352 // Clear out the previous results.
353 ClearCachedCompletionResults();
354
355 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000356 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000357 SmallVector<Result, 8> Results;
Douglas Gregor162b7122011-02-16 19:08:06 +0000358 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000359 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000360 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000361 CCTUInfo, Results);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000362
363 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000364 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
365
Douglas Gregorb14904c2010-08-13 22:48:40 +0000366 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
367 switch (Results[I].Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000368 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000369 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000370 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000371 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000372 *CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000373 CCTUInfo,
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000374 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor39982192010-08-15 06:18:01 +0000375 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000376 Ctx->getLangOpts(),
Douglas Gregor59cab552010-08-16 23:05:20 +0000377 IsNestedNameSpecifier);
Douglas Gregor39982192010-08-15 06:18:01 +0000378 CachedResult.Priority = Results[I].Priority;
379 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000380 CachedResult.Availability = Results[I].Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000381
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000382 // Keep track of the type of this completion in an ASTContext-agnostic
383 // way.
Douglas Gregor24747402010-08-16 16:46:30 +0000384 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000385 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000386 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000387 CachedResult.Type = 0;
388 } else {
389 CanQualType CanUsageType
390 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
391 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
392
393 // Determine whether we have already seen this type. If so, we save
394 // ourselves the work of formatting the type string by using the
395 // temporary, CanQualType-based hash table to find the associated value.
396 unsigned &TypeValue = CompletionTypes[CanUsageType];
397 if (TypeValue == 0) {
398 TypeValue = CompletionTypes.size();
399 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
400 = TypeValue;
401 }
402
403 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000404 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000405
Douglas Gregor39982192010-08-15 06:18:01 +0000406 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000407
408 /// Handle nested-name-specifiers in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000409 if (TheSema->Context.getLangOpts().CPlusPlus &&
Douglas Gregor59cab552010-08-16 23:05:20 +0000410 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
411 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith697cc9e2012-08-14 03:13:00 +0000412 uint64_t NNSContexts
413 = (1LL << CodeCompletionContext::CCC_TopLevel)
414 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
415 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
416 | (1LL << CodeCompletionContext::CCC_Statement)
417 | (1LL << CodeCompletionContext::CCC_Expression)
418 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
419 | (1LL << CodeCompletionContext::CCC_EnumTag)
420 | (1LL << CodeCompletionContext::CCC_UnionTag)
421 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
422 | (1LL << CodeCompletionContext::CCC_Type)
423 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
424 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor59cab552010-08-16 23:05:20 +0000425
426 if (isa<NamespaceDecl>(Results[I].Declaration) ||
427 isa<NamespaceAliasDecl>(Results[I].Declaration))
Richard Smith697cc9e2012-08-14 03:13:00 +0000428 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor59cab552010-08-16 23:05:20 +0000429
430 if (unsigned RemainingContexts
431 = NNSContexts & ~CachedResult.ShowInContexts) {
432 // If there any contexts where this completion can be a
433 // nested-name-specifier but isn't already an option, create a
434 // nested-name-specifier completion.
435 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000436 CachedResult.Completion
437 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000438 *CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000439 CCTUInfo,
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000440 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor59cab552010-08-16 23:05:20 +0000441 CachedResult.ShowInContexts = RemainingContexts;
442 CachedResult.Priority = CCP_NestedNameSpecifier;
443 CachedResult.TypeClass = STC_Void;
444 CachedResult.Type = 0;
445 CachedCompletionResults.push_back(CachedResult);
446 }
447 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000448 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000449 }
450
Douglas Gregorb14904c2010-08-13 22:48:40 +0000451 case Result::RK_Keyword:
452 case Result::RK_Pattern:
453 // Ignore keywords and patterns; we don't care, since they are so
454 // easily regenerated.
455 break;
456
457 case Result::RK_Macro: {
458 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000459 CachedResult.Completion
460 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000461 *CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000462 CCTUInfo,
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000463 IncludeBriefCommentsInCodeCompletion);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000464 CachedResult.ShowInContexts
Richard Smith697cc9e2012-08-14 03:13:00 +0000465 = (1LL << CodeCompletionContext::CCC_TopLevel)
466 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
467 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
468 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
469 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
470 | (1LL << CodeCompletionContext::CCC_Statement)
471 | (1LL << CodeCompletionContext::CCC_Expression)
472 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
473 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
474 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
475 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
476 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000477
Douglas Gregorb14904c2010-08-13 22:48:40 +0000478 CachedResult.Priority = Results[I].Priority;
479 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000480 CachedResult.Availability = Results[I].Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000481 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000482 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000483 CachedCompletionResults.push_back(CachedResult);
484 break;
485 }
486 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000487 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000488
489 // Save the current top-level hash value.
490 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000491}
492
493void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregorb14904c2010-08-13 22:48:40 +0000494 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000495 CachedCompletionTypes.clear();
Craig Topper49a27902014-05-22 04:46:25 +0000496 CachedCompletionAllocator = nullptr;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000497}
498
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000499namespace {
500
Sebastian Redl2c499f62010-08-18 23:56:43 +0000501/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000502/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000503class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor83297df2011-09-01 23:39:15 +0000504 Preprocessor &PP;
Douglas Gregore8bbc122011-09-02 00:18:52 +0000505 ASTContext &Context;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000506 LangOptions &LangOpt;
Douglas Gregorcb177f12012-10-16 23:40:58 +0000507 IntrusiveRefCntPtr<TargetOptions> &TargetOpts;
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000508 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000509 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000510
Douglas Gregore8bbc122011-09-02 00:18:52 +0000511 bool InitializedLanguage;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000512public:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000513 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
Douglas Gregorcb177f12012-10-16 23:40:58 +0000514 IntrusiveRefCntPtr<TargetOptions> &TargetOpts,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000515 IntrusiveRefCntPtr<TargetInfo> &Target,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000516 unsigned &Counter)
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +0000517 : PP(PP), Context(Context), LangOpt(LangOpt),
Douglas Gregorbc10b9f2012-10-15 16:45:32 +0000518 TargetOpts(TargetOpts), Target(Target),
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +0000519 Counter(Counter),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000520 InitializedLanguage(false) {}
Mike Stump11289f42009-09-09 15:08:12 +0000521
Craig Topperafa7cb32014-03-13 06:07:04 +0000522 bool ReadLanguageOptions(const LangOptions &LangOpts,
523 bool Complain) override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000524 if (InitializedLanguage)
Douglas Gregor83297df2011-09-01 23:39:15 +0000525 return false;
526
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000527 LangOpt = LangOpts;
528 InitializedLanguage = true;
529
530 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000531 return false;
532 }
Mike Stump11289f42009-09-09 15:08:12 +0000533
Craig Topperafa7cb32014-03-13 06:07:04 +0000534 bool ReadTargetOptions(const TargetOptions &TargetOpts,
535 bool Complain) override {
Douglas Gregor83297df2011-09-01 23:39:15 +0000536 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000537 if (Target)
Douglas Gregor83297df2011-09-01 23:39:15 +0000538 return false;
539
Douglas Gregorcb177f12012-10-16 23:40:58 +0000540 this->TargetOpts = new TargetOptions(TargetOpts);
Douglas Gregorf8715de2012-11-16 04:24:59 +0000541 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(),
542 &*this->TargetOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000543
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000544 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000545 return false;
546 }
Mike Stump11289f42009-09-09 15:08:12 +0000547
Craig Topperafa7cb32014-03-13 06:07:04 +0000548 void ReadCounter(const serialization::ModuleFile &M,
549 unsigned Value) override {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000550 Counter = Value;
551 }
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000552
553private:
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000554 void updated() {
555 if (!Target || !InitializedLanguage)
556 return;
557
558 // Inform the target of the language options.
559 //
560 // FIXME: We shouldn't need to do this, the target should be immutable once
561 // created. This complexity should be lifted elsewhere.
562 Target->setForcedLangOptions(LangOpt);
563
564 // Initialize the preprocessor.
565 PP.Initialize(*Target);
566
567 // Initialize the ASTContext
568 Context.InitBuiltinTypes(*Target);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000569
570 // We didn't have access to the comment options when the ASTContext was
571 // constructed, so register them now.
572 Context.getCommentCommandTraits().registerCommentOptions(
573 LangOpt.CommentOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000574 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000575};
576
Douglas Gregor6b930962013-05-03 22:58:43 +0000577 /// \brief Diagnostic consumer that saves each diagnostic it is given.
David Blaikief18d91a2011-09-26 00:01:39 +0000578class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000579 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregor6b930962013-05-03 22:58:43 +0000580 SourceManager *SourceMgr;
581
Douglas Gregor33cdd812010-02-18 18:08:43 +0000582public:
David Blaikief18d91a2011-09-26 00:01:39 +0000583 explicit StoredDiagnosticConsumer(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000584 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Craig Topper49a27902014-05-22 04:46:25 +0000585 : StoredDiags(StoredDiags), SourceMgr(nullptr) {}
Douglas Gregor6b930962013-05-03 22:58:43 +0000586
Craig Topperafa7cb32014-03-13 06:07:04 +0000587 void BeginSourceFile(const LangOptions &LangOpts,
Craig Topper49a27902014-05-22 04:46:25 +0000588 const Preprocessor *PP = nullptr) override {
Douglas Gregor6b930962013-05-03 22:58:43 +0000589 if (PP)
590 SourceMgr = &PP->getSourceManager();
591 }
592
Craig Topperafa7cb32014-03-13 06:07:04 +0000593 void HandleDiagnostic(DiagnosticsEngine::Level Level,
594 const Diagnostic &Info) override;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000595};
596
597/// \brief RAII object that optionally captures diagnostics, if
598/// there is no diagnostic client to capture them already.
599class CaptureDroppedDiagnostics {
David Blaikie9c902b52011-09-25 23:23:43 +0000600 DiagnosticsEngine &Diags;
David Blaikief18d91a2011-09-26 00:01:39 +0000601 StoredDiagnosticConsumer Client;
David Blaikiee2eefae2011-09-25 23:39:51 +0000602 DiagnosticConsumer *PreviousClient;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000603
604public:
David Blaikie9c902b52011-09-25 23:23:43 +0000605 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000606 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Craig Topper49a27902014-05-22 04:46:25 +0000607 : Diags(Diags), Client(StoredDiags), PreviousClient(nullptr)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000608 {
Craig Topper49a27902014-05-22 04:46:25 +0000609 if (RequestCapture || Diags.getClient() == nullptr) {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000610 PreviousClient = Diags.takeClient();
Douglas Gregor33cdd812010-02-18 18:08:43 +0000611 Diags.setClient(&Client);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000612 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000613 }
614
615 ~CaptureDroppedDiagnostics() {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000616 if (Diags.getClient() == &Client) {
617 Diags.takeClient();
618 Diags.setClient(PreviousClient);
619 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000620 }
621};
622
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000623} // anonymous namespace
624
David Blaikief18d91a2011-09-26 00:01:39 +0000625void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +0000626 const Diagnostic &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000627 // Default implementation (Warnings/errors count).
David Blaikiee2eefae2011-09-25 23:39:51 +0000628 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000629
Douglas Gregor6b930962013-05-03 22:58:43 +0000630 // Only record the diagnostic if it's part of the source manager we know
631 // about. This effectively drops diagnostics from modules we're building.
632 // FIXME: In the long run, ee don't want to drop source managers from modules.
633 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
634 StoredDiags.push_back(StoredDiagnostic(Level, Info));
Douglas Gregor33cdd812010-02-18 18:08:43 +0000635}
636
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000637ASTMutationListener *ASTUnit::getASTMutationListener() {
638 if (WriterData)
639 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000640 return nullptr;
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000641}
642
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000643ASTDeserializationListener *ASTUnit::getDeserializationListener() {
644 if (WriterData)
645 return &WriterData->Writer;
Craig Topper49a27902014-05-22 04:46:25 +0000646 return nullptr;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000647}
648
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000649llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner26b5c192010-11-23 09:19:42 +0000650 std::string *ErrorStr) {
Chris Lattner5159f612010-11-23 08:35:12 +0000651 assert(FileMgr);
Chris Lattner26b5c192010-11-23 09:19:42 +0000652 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000653}
654
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000655/// \brief Configure the diagnostics object for use with ASTUnit.
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000656void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000657 const char **ArgBegin, const char **ArgEnd,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000658 ASTUnit &AST, bool CaptureDiagnostics) {
Alp Tokerf994cef2014-07-05 03:08:06 +0000659 if (!Diags.get()) {
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000660 // No diagnostics engine was provided, so create our own diagnostics object
661 // with the default options.
Craig Topper49a27902014-05-22 04:46:25 +0000662 DiagnosticConsumer *Client = nullptr;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000663 if (CaptureDiagnostics)
David Blaikief18d91a2011-09-26 00:01:39 +0000664 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Douglas Gregor811db4e2012-10-23 22:26:28 +0000665 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions(),
Sean Silvaf1b49e22013-01-20 01:58:28 +0000666 Client,
Douglas Gregor30071cea2013-05-03 23:07:45 +0000667 /*ShouldOwnClient=*/true);
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000668 } else if (CaptureDiagnostics) {
David Blaikief18d91a2011-09-26 00:01:39 +0000669 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000670 }
671}
672
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000673ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000674 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000675 const FileSystemOptions &FileSystemOpts,
Ted Kremenek8bcb1c62009-10-17 00:34:24 +0000676 bool OnlyLocalDecls,
Dmitri Gribenko2febd212014-02-07 15:00:22 +0000677 ArrayRef<RemappedFile> RemappedFiles,
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +0000678 bool CaptureDiagnostics,
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000679 bool AllowPCHWithCompilerErrors,
680 bool UserFilesAreVolatile) {
Ahmed Charlesb8984322014-03-07 20:03:18 +0000681 std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000682
683 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +0000684 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
685 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +0000686 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
687 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +0000688 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000689
Craig Topper49a27902014-05-22 04:46:25 +0000690 ConfigureDiags(Diags, nullptr, nullptr, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000691
Douglas Gregor16bef852009-10-16 20:01:17 +0000692 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000693 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000694 AST->Diagnostics = Diags;
Ben Langmuir8832c062014-04-15 18:16:25 +0000695 IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
696 AST->FileMgr = new FileManager(FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000697 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000698 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000699 AST->getFileManager(),
700 UserFilesAreVolatile);
Douglas Gregorb85b9cc2012-10-24 16:19:39 +0000701 AST->HSOpts = new HeaderSearchOptions();
Craig Topper49a27902014-05-22 04:46:25 +0000702
Douglas Gregorb85b9cc2012-10-24 16:19:39 +0000703 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
Manuel Klimek1f76c4e2013-10-24 07:51:24 +0000704 AST->getSourceManager(),
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000705 AST->getDiagnostics(),
Douglas Gregor89929282012-01-30 06:01:29 +0000706 AST->ASTFileLangOpts,
Craig Topper49a27902014-05-22 04:46:25 +0000707 /*Target=*/nullptr));
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000708
Dmitri Gribenkob41e7e22014-02-10 12:31:34 +0000709 PreprocessorOptions *PPOpts = new PreprocessorOptions();
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000710
Dmitri Gribenkob41e7e22014-02-10 12:31:34 +0000711 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I)
712 PPOpts->addRemappedFile(RemappedFiles[I].first, RemappedFiles[I].second);
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000713
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000714 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000715
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000716 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000717 unsigned Counter;
718
Alp Toker96637802014-05-02 03:43:38 +0000719 AST->PP =
720 new Preprocessor(PPOpts, AST->getDiagnostics(), AST->ASTFileLangOpts,
721 AST->getSourceManager(), HeaderInfo, *AST,
Craig Topper49a27902014-05-22 04:46:25 +0000722 /*IILookup=*/nullptr,
Alp Toker96637802014-05-02 03:43:38 +0000723 /*OwnsHeaderSearch=*/false);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000724 Preprocessor &PP = *AST->PP;
725
Alp Toker08043432014-05-03 03:46:04 +0000726 AST->Ctx = new ASTContext(AST->ASTFileLangOpts, AST->getSourceManager(),
727 PP.getIdentifierTable(), PP.getSelectorTable(),
728 PP.getBuiltinInfo());
Douglas Gregore8bbc122011-09-02 00:18:52 +0000729 ASTContext &Context = *AST->Ctx;
Douglas Gregor83297df2011-09-01 23:39:15 +0000730
Argyrios Kyrtzidis945a8192012-09-15 01:10:20 +0000731 bool disableValid = false;
732 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
733 disableValid = true;
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000734 AST->Reader = new ASTReader(PP, Context,
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +0000735 /*isysroot=*/"",
Argyrios Kyrtzidis945a8192012-09-15 01:10:20 +0000736 /*DisableValidation=*/disableValid,
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000737 AllowPCHWithCompilerErrors);
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000738
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000739 AST->Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +0000740 AST->ASTFileLangOpts,
Douglas Gregorbc10b9f2012-10-15 16:45:32 +0000741 AST->TargetOpts, AST->Target,
Douglas Gregord02437c2012-10-25 00:09:28 +0000742 Counter));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000743
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000744 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis2ec29362012-11-15 18:57:22 +0000745 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000746 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000747 break;
Mike Stump11289f42009-09-09 15:08:12 +0000748
Sebastian Redl2c499f62010-08-18 23:56:43 +0000749 case ASTReader::Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +0000750 case ASTReader::Missing:
Douglas Gregorc9ad5fb2012-10-22 22:50:17 +0000751 case ASTReader::OutOfDate:
752 case ASTReader::VersionMismatch:
753 case ASTReader::ConfigurationMismatch:
754 case ASTReader::HadErrors:
Douglas Gregord03e8232010-04-05 21:10:19 +0000755 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Craig Topper49a27902014-05-22 04:46:25 +0000756 return nullptr;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000757 }
Mike Stump11289f42009-09-09 15:08:12 +0000758
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000759 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
Daniel Dunbara8a50932009-12-02 08:44:16 +0000760
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000761 PP.setCounterValue(Counter);
Mike Stump11289f42009-09-09 15:08:12 +0000762
Sebastian Redl2c499f62010-08-18 23:56:43 +0000763 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000764 // source, so that declarations will be deserialized from the
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000765 // AST file as needed.
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000766 Context.setExternalSource(AST->Reader);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000767
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000768 // Create an AST consumer, even though it isn't used.
769 AST->Consumer.reset(new ASTConsumer);
770
Sebastian Redl2c499f62010-08-18 23:56:43 +0000771 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000772 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
773 AST->TheSema->Initialize();
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000774 AST->Reader->InitializeSema(*AST->TheSema);
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000775
Douglas Gregor6b930962013-05-03 22:58:43 +0000776 // Tell the diagnostic client that we have started a source file.
777 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
778
Ahmed Charles9a16beb2014-03-07 19:33:25 +0000779 return AST.release();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000780}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000781
782namespace {
783
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000784/// \brief Preprocessor callback class that updates a hash value with the names
785/// of all macros that have been defined by the translation unit.
786class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
787 unsigned &Hash;
788
789public:
790 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
Craig Topperafa7cb32014-03-13 06:07:04 +0000791
792 void MacroDefined(const Token &MacroNameTok,
793 const MacroDirective *MD) override {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000794 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
795 }
796};
797
798/// \brief Add the given declaration to the hash of all top-level entities.
799void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
800 if (!D)
801 return;
802
803 DeclContext *DC = D->getDeclContext();
804 if (!DC)
805 return;
806
807 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
808 return;
809
810 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000811 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
812 // For an unscoped enum include the enumerators in the hash since they
813 // enter the top-level namespace.
814 if (!EnumD->isScoped()) {
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000815 for (const auto *EI : EnumD->enumerators()) {
816 if (EI->getIdentifier())
817 Hash = llvm::HashString(EI->getIdentifier()->getName(), Hash);
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000818 }
819 }
820 }
821
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000822 if (ND->getIdentifier())
823 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
824 else if (DeclarationName Name = ND->getDeclName()) {
825 std::string NameStr = Name.getAsString();
826 Hash = llvm::HashString(NameStr, Hash);
827 }
828 return;
Argyrios Kyrtzidis48d88de2013-06-24 21:19:12 +0000829 }
830
831 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
832 if (Module *Mod = ImportD->getImportedModule()) {
833 std::string ModName = Mod->getFullModuleName();
834 Hash = llvm::HashString(ModName, Hash);
835 }
836 return;
837 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000838}
839
Daniel Dunbar644dca02009-12-04 08:17:33 +0000840class TopLevelDeclTrackerConsumer : public ASTConsumer {
841 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000842 unsigned &Hash;
843
Daniel Dunbar644dca02009-12-04 08:17:33 +0000844public:
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000845 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
846 : Unit(_Unit), Hash(Hash) {
847 Hash = 0;
848 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000849
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000850 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis516eec22011-11-16 02:35:10 +0000851 if (!D)
852 return;
853
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000854 // FIXME: Currently ObjC method declarations are incorrectly being
855 // reported as top-level declarations, even though their DeclContext
856 // is the containing ObjC @interface/@implementation. This is a
857 // fundamental problem in the parser right now.
858 if (isa<ObjCMethodDecl>(D))
859 return;
860
861 AddTopLevelDeclarationToHash(D, Hash);
862 Unit.addTopLevelDecl(D);
863
864 handleFileLevelDecl(D);
865 }
866
867 void handleFileLevelDecl(Decl *D) {
868 Unit.addFileLevelDecl(D);
869 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
Aaron Ballman629afae2014-03-07 19:56:05 +0000870 for (auto *I : NSD->decls())
871 handleFileLevelDecl(I);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000872 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000873 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000874
Craig Topperafa7cb32014-03-13 06:07:04 +0000875 bool HandleTopLevelDecl(DeclGroupRef D) override {
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000876 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
877 handleTopLevelDecl(*it);
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000878 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000879 }
880
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000881 // We're not interested in "interesting" decls.
Craig Topperafa7cb32014-03-13 06:07:04 +0000882 void HandleInterestingDecl(DeclGroupRef) override {}
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000883
Craig Topperafa7cb32014-03-13 06:07:04 +0000884 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000885 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
886 handleTopLevelDecl(*it);
887 }
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000888
Craig Topperafa7cb32014-03-13 06:07:04 +0000889 ASTMutationListener *GetASTMutationListener() override {
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000890 return Unit.getASTMutationListener();
891 }
892
Craig Topperafa7cb32014-03-13 06:07:04 +0000893 ASTDeserializationListener *GetASTDeserializationListener() override {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000894 return Unit.getDeserializationListener();
895 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000896};
897
898class TopLevelDeclTrackerAction : public ASTFrontendAction {
899public:
900 ASTUnit &Unit;
901
Craig Topperafa7cb32014-03-13 06:07:04 +0000902 ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
903 StringRef InFile) override {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000904 CI.getPreprocessor().addPPCallbacks(
905 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
906 return new TopLevelDeclTrackerConsumer(Unit,
907 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000908 }
909
910public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000911 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
912
Craig Topperafa7cb32014-03-13 06:07:04 +0000913 bool hasCodeCompletionSupport() const override { return false; }
914 TranslationUnitKind getTranslationUnitKind() override {
Douglas Gregor69f74f82011-08-25 22:30:56 +0000915 return Unit.getTranslationUnitKind();
Douglas Gregor028d3e42010-08-09 20:45:32 +0000916 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000917};
918
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000919class PrecompilePreambleAction : public ASTFrontendAction {
920 ASTUnit &Unit;
921 bool HasEmittedPreamblePCH;
922
923public:
924 explicit PrecompilePreambleAction(ASTUnit &Unit)
925 : Unit(Unit), HasEmittedPreamblePCH(false) {}
926
Craig Topperafa7cb32014-03-13 06:07:04 +0000927 ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
928 StringRef InFile) override;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000929 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
930 void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH = true; }
Craig Topperafa7cb32014-03-13 06:07:04 +0000931 bool shouldEraseOutputFiles() override { return !hasEmittedPreamblePCH(); }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000932
Craig Topperafa7cb32014-03-13 06:07:04 +0000933 bool hasCodeCompletionSupport() const override { return false; }
934 bool hasASTFileSupport() const override { return false; }
935 TranslationUnitKind getTranslationUnitKind() override { return TU_Prefix; }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000936};
937
Argyrios Kyrtzidis57332712011-09-19 20:40:48 +0000938class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000939 ASTUnit &Unit;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000940 unsigned &Hash;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000941 std::vector<Decl *> TopLevelDecls;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000942 PrecompilePreambleAction *Action;
943
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000944public:
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000945 PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action,
946 const Preprocessor &PP, StringRef isysroot,
947 raw_ostream *Out)
Craig Topper49a27902014-05-22 04:46:25 +0000948 : PCHGenerator(PP, "", nullptr, isysroot, Out, /*AllowASTWithErrors=*/true),
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000949 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000950 Hash = 0;
951 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000952
Craig Topperafa7cb32014-03-13 06:07:04 +0000953 bool HandleTopLevelDecl(DeclGroupRef D) override {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000954 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
955 Decl *D = *it;
956 // FIXME: Currently ObjC method declarations are incorrectly being
957 // reported as top-level declarations, even though their DeclContext
958 // is the containing ObjC @interface/@implementation. This is a
959 // fundamental problem in the parser right now.
960 if (isa<ObjCMethodDecl>(D))
961 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000962 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000963 TopLevelDecls.push_back(D);
964 }
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000965 return true;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000966 }
967
Craig Topperafa7cb32014-03-13 06:07:04 +0000968 void HandleTranslationUnit(ASTContext &Ctx) override {
Douglas Gregore9db88f2010-08-03 19:06:41 +0000969 PCHGenerator::HandleTranslationUnit(Ctx);
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +0000970 if (hasEmittedPCH()) {
Douglas Gregore9db88f2010-08-03 19:06:41 +0000971 // Translate the top-level declarations we captured during
972 // parsing into declaration IDs in the precompiled
973 // preamble. This will allow us to deserialize those top-level
974 // declarations when requested.
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +0000975 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I) {
976 Decl *D = TopLevelDecls[I];
977 // Invalid top-level decls may not have been serialized.
978 if (D->isInvalidDecl())
979 continue;
980 Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
981 }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000982
983 Action->setHasEmittedPreamblePCH();
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000984 }
985 }
986};
987
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000988}
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000989
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000990ASTConsumer *PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
991 StringRef InFile) {
992 std::string Sysroot;
993 std::string OutputFile;
Craig Topper49a27902014-05-22 04:46:25 +0000994 raw_ostream *OS = nullptr;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000995 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
996 OutputFile, OS))
Craig Topper49a27902014-05-22 04:46:25 +0000997 return nullptr;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000998
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000999 if (!CI.getFrontendOpts().RelocatablePCH)
1000 Sysroot.clear();
Douglas Gregorc567ba22011-07-22 16:35:34 +00001001
Benjamin Kramer65745dc2013-06-11 13:07:19 +00001002 CI.getPreprocessor().addPPCallbacks(new MacroDefinitionTrackerPPCallbacks(
1003 Unit.getCurrentTopLevelHashValue()));
1004 return new PrecompilePreambleConsumer(Unit, this, CI.getPreprocessor(),
1005 Sysroot, OS);
Daniel Dunbar764c0822009-12-01 09:51:01 +00001006}
1007
Benjamin Kramer1ce5d802013-05-05 12:39:28 +00001008static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
1009 return StoredDiag.getLocation().isValid();
1010}
1011
1012static void
1013checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001014 // Get rid of stored diagnostics except the ones from the driver which do not
1015 // have a source location.
Benjamin Kramer1ce5d802013-05-05 12:39:28 +00001016 StoredDiags.erase(
1017 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1018 StoredDiags.end());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001019}
1020
1021static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1022 StoredDiagnostics,
1023 SourceManager &SM) {
1024 // The stored diagnostic has the old source manager in it; update
1025 // the locations to refer into the new source manager. Since we've
1026 // been careful to make sure that the source manager's state
1027 // before and after are identical, so that we can reuse the source
1028 // location itself.
1029 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1030 if (StoredDiagnostics[I].getLocation().isValid()) {
1031 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1032 StoredDiagnostics[I].setLocation(Loc);
1033 }
1034 }
1035}
1036
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001037/// Parse the source file into a translation unit using the given compiler
1038/// invocation, replacing the current translation unit.
1039///
1040/// \returns True if a failure occurred that causes the ASTUnit not to
1041/// contain any translation-unit information, false otherwise.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001042bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor96c04262010-07-27 14:52:07 +00001043 delete SavedMainFileBuffer;
Craig Topper49a27902014-05-22 04:46:25 +00001044 SavedMainFileBuffer = nullptr;
1045
Ted Kremenek5e14d392011-03-21 18:40:17 +00001046 if (!Invocation) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001047 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001048 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001049 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001050
Daniel Dunbar764c0822009-12-01 09:51:01 +00001051 // Create the compiler instance to use for building the AST.
Ahmed Charlesb8984322014-03-07 20:03:18 +00001052 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001053
1054 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001055 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1056 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001057
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001058 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis14c32e82011-09-12 18:09:38 +00001059 CCInvocation(new CompilerInvocation(*Invocation));
1060
Alp Tokerf994cef2014-07-05 03:08:06 +00001061 Clang->setInvocation(CCInvocation.get());
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001062 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001063
Douglas Gregor8e984da2010-08-04 16:47:14 +00001064 // Set up diagnostics, capturing any diagnostics that would
1065 // otherwise be dropped.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001066 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +00001067
Daniel Dunbar764c0822009-12-01 09:51:01 +00001068 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001069 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregorf8715de2012-11-16 04:24:59 +00001070 &Clang->getTargetOpts()));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001071 if (!Clang->hasTarget()) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001072 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001073 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001074 }
1075
Daniel Dunbar764c0822009-12-01 09:51:01 +00001076 // Inform the target of the language options.
1077 //
1078 // FIXME: We shouldn't need to do this, the target should be immutable once
1079 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001080 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001081
Ted Kremenek84de4a12011-03-21 18:40:07 +00001082 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001083 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001084 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001085 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001086 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Daniel Dunbar9507f9c2010-06-07 23:26:47 +00001087 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +00001088
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001089 // Configure the various subsystems.
Ted Kremenek8cf47df2011-11-17 23:01:24 +00001090 LangOpts = &Clang->getLangOpts();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001091 FileSystemOpts = Clang->getFileSystemOpts();
Ben Langmuir2cc485b2014-06-23 16:36:40 +00001092 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1093 createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
1094 if (!VFS) {
1095 delete OverrideMainBuffer;
1096 return true;
1097 }
1098 FileMgr = new FileManager(FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001099 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1100 UserFilesAreVolatile);
Douglas Gregor6fd55e02010-08-13 03:15:25 +00001101 TheSema.reset();
Craig Topper49a27902014-05-22 04:46:25 +00001102 Ctx = nullptr;
1103 PP = nullptr;
1104 Reader = nullptr;
1105
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001106 // Clear out old caches and data.
1107 TopLevelDecls.clear();
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001108 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001109 CleanTemporaryFiles();
Douglas Gregord9a30af2010-08-02 20:51:39 +00001110
Douglas Gregor7b02b582010-08-20 00:02:33 +00001111 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001112 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001113 TopLevelDeclsInPreamble.clear();
1114 }
1115
Daniel Dunbar764c0822009-12-01 09:51:01 +00001116 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001117 Clang->setFileManager(&getFileManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001118
Daniel Dunbar764c0822009-12-01 09:51:01 +00001119 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001120 Clang->setSourceManager(&getSourceManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001121
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001122 // If the main file has been overridden due to the use of a preamble,
1123 // make that override happen and introduce the preamble.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001124 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001125 if (OverrideMainBuffer) {
1126 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1127 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1128 PreprocessorOpts.PrecompiledPreambleBytes.second
1129 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00001130 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorce3a8292010-07-27 00:27:13 +00001131 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +00001132
Douglas Gregord9a30af2010-08-02 20:51:39 +00001133 // The stored diagnostic has the old source manager in it; update
1134 // the locations to refer into the new source manager. Since we've
1135 // been careful to make sure that the source manager's state
1136 // before and after are identical, so that we can reuse the source
1137 // location itself.
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001138 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001139
1140 // Keep track of the override buffer;
1141 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001142 }
Ahmed Charlesb8984322014-03-07 20:03:18 +00001143
1144 std::unique_ptr<TopLevelDeclTrackerAction> Act(
1145 new TopLevelDeclTrackerAction(*this));
1146
Ted Kremenek022a4902011-03-22 01:15:24 +00001147 // Recover resources if we crash before exiting this method.
1148 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1149 ActCleanup(Act.get());
1150
Douglas Gregor32fbe312012-01-20 16:28:04 +00001151 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar764c0822009-12-01 09:51:01 +00001152 goto error;
Douglas Gregor925296b2011-07-19 16:10:42 +00001153
1154 if (OverrideMainBuffer) {
Ted Kremenek06b4f912011-10-27 17:55:18 +00001155 std::string ModName = getPreambleFile(this);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001156 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1157 PreambleDiagnostics, StoredDiagnostics);
Douglas Gregor925296b2011-07-19 16:10:42 +00001158 }
1159
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001160 if (!Act->Execute())
1161 goto error;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001162
1163 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001164
Daniel Dunbar644dca02009-12-04 08:17:33 +00001165 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001166
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001167 FailedParseDiagnostics.clear();
1168
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001169 return false;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001170
Daniel Dunbar764c0822009-12-01 09:51:01 +00001171error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001172 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +00001173 if (OverrideMainBuffer) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001174 delete OverrideMainBuffer;
Craig Topper49a27902014-05-22 04:46:25 +00001175 SavedMainFileBuffer = nullptr;
Douglas Gregorce3a8292010-07-27 00:27:13 +00001176 }
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001177
1178 // Keep the ownership of the data in the ASTUnit because the client may
1179 // want to see the diagnostics.
1180 transferASTDataFromCompilerInstance(*Clang);
1181 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregorefc46952010-10-12 16:25:54 +00001182 StoredDiagnostics.clear();
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001183 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001184 return true;
1185}
1186
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001187/// \brief Simple function to retrieve a path for a preamble precompiled header.
1188static std::string GetPreamblePCHPath() {
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001189 // FIXME: This is a hack so that we can override the preamble file during
1190 // crash-recovery testing, which is the only case where the preamble files
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001191 // are not necessarily cleaned up.
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001192 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1193 if (TmpFile)
1194 return TmpFile;
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001195
1196 SmallString<128> Path;
Rafael Espindolaa36e78e2013-07-05 20:00:06 +00001197 llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001198
1199 return Path.str();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001200}
1201
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001202/// \brief Compute the preamble for the main file, providing the source buffer
1203/// that corresponds to the main file along with a pair (bytes, start-of-line)
1204/// that describes the preamble.
1205std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor028d3e42010-08-09 20:45:32 +00001206ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1207 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001208 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner5159f612010-11-23 08:35:12 +00001209 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001210 CreatedBuffer = false;
1211
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001212 // Try to determine if the main file has been remapped, either from the
1213 // command line (to another file) or directly through the compiler invocation
1214 // (to a memory buffer).
Craig Topper49a27902014-05-22 04:46:25 +00001215 llvm::MemoryBuffer *Buffer = nullptr;
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001216 std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
Rafael Espindola073ff102013-07-29 21:26:52 +00001217 llvm::sys::fs::UniqueID MainFileID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001218 if (!llvm::sys::fs::getUniqueID(MainFilePath, MainFileID)) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001219 // Check whether there is a file-file remapping of the main file
1220 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor4dde7492010-07-23 23:58:40 +00001221 M = PreprocessorOpts.remapped_file_begin(),
1222 E = PreprocessorOpts.remapped_file_end();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001223 M != E;
1224 ++M) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001225 std::string MPath(M->first);
Rafael Espindola073ff102013-07-29 21:26:52 +00001226 llvm::sys::fs::UniqueID MID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001227 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001228 if (MainFileID == MID) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001229 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001230 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001231 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001232 CreatedBuffer = false;
1233 }
1234
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001235 Buffer = getBufferForFile(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001236 if (!Buffer)
Craig Topper49a27902014-05-22 04:46:25 +00001237 return std::make_pair(nullptr, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001238 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001239 }
1240 }
1241 }
1242
1243 // Check whether there is a file-buffer remapping. It supercedes the
1244 // file-file remapping.
1245 for (PreprocessorOptions::remapped_file_buffer_iterator
1246 M = PreprocessorOpts.remapped_file_buffer_begin(),
1247 E = PreprocessorOpts.remapped_file_buffer_end();
1248 M != E;
1249 ++M) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001250 std::string MPath(M->first);
Rafael Espindola073ff102013-07-29 21:26:52 +00001251 llvm::sys::fs::UniqueID MID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001252 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001253 if (MainFileID == MID) {
1254 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001255 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001256 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001257 CreatedBuffer = false;
1258 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001259
Douglas Gregor4dde7492010-07-23 23:58:40 +00001260 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001261 }
1262 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001263 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001264 }
1265
1266 // If the main source file was not remapped, load it now.
1267 if (!Buffer) {
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001268 Buffer = getBufferForFile(FrontendOpts.Inputs[0].getFile());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001269 if (!Buffer)
Craig Topper49a27902014-05-22 04:46:25 +00001270 return std::make_pair(nullptr, std::make_pair(0, true));
1271
Douglas Gregor4dde7492010-07-23 23:58:40 +00001272 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001273 }
1274
Argyrios Kyrtzidis7aecbc72011-08-25 20:39:19 +00001275 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenek8cf47df2011-11-17 23:01:24 +00001276 *Invocation.getLangOpts(),
Argyrios Kyrtzidis7aecbc72011-08-25 20:39:19 +00001277 MaxLines));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001278}
1279
Dmitri Gribenko47652522013-12-20 00:16:25 +00001280ASTUnit::PreambleFileHash
1281ASTUnit::PreambleFileHash::createForFile(off_t Size, time_t ModTime) {
1282 PreambleFileHash Result;
1283 Result.Size = Size;
1284 Result.ModTime = ModTime;
Dmitri Gribenko3ec8ee72013-12-20 01:07:30 +00001285 memset(Result.MD5, 0, sizeof(Result.MD5));
Dmitri Gribenko47652522013-12-20 00:16:25 +00001286 return Result;
1287}
1288
1289ASTUnit::PreambleFileHash ASTUnit::PreambleFileHash::createForMemoryBuffer(
1290 const llvm::MemoryBuffer *Buffer) {
1291 PreambleFileHash Result;
1292 Result.Size = Buffer->getBufferSize();
1293 Result.ModTime = 0;
1294
1295 llvm::MD5 MD5Ctx;
1296 MD5Ctx.update(Buffer->getBuffer().data());
1297 MD5Ctx.final(Result.MD5);
1298
1299 return Result;
1300}
1301
1302namespace clang {
1303bool operator==(const ASTUnit::PreambleFileHash &LHS,
1304 const ASTUnit::PreambleFileHash &RHS) {
1305 return LHS.Size == RHS.Size && LHS.ModTime == RHS.ModTime &&
Dmitri Gribenko3ec8ee72013-12-20 01:07:30 +00001306 memcmp(LHS.MD5, RHS.MD5, sizeof(LHS.MD5)) == 0;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001307}
1308} // namespace clang
1309
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001310static std::pair<unsigned, unsigned>
1311makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1312 const LangOptions &LangOpts) {
1313 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1314 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1315 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1316 return std::make_pair(Offset, EndOffset);
1317}
1318
1319static void makeStandaloneFixIt(const SourceManager &SM,
1320 const LangOptions &LangOpts,
1321 const FixItHint &InFix,
1322 ASTUnit::StandaloneFixIt &OutFix) {
1323 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1324 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1325 LangOpts);
1326 OutFix.CodeToInsert = InFix.CodeToInsert;
1327 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
1328}
1329
1330static void makeStandaloneDiagnostic(const LangOptions &LangOpts,
1331 const StoredDiagnostic &InDiag,
1332 ASTUnit::StandaloneDiagnostic &OutDiag) {
1333 OutDiag.ID = InDiag.getID();
1334 OutDiag.Level = InDiag.getLevel();
1335 OutDiag.Message = InDiag.getMessage();
1336 OutDiag.LocOffset = 0;
1337 if (InDiag.getLocation().isInvalid())
1338 return;
1339 const SourceManager &SM = InDiag.getLocation().getManager();
1340 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1341 OutDiag.Filename = SM.getFilename(FileLoc);
1342 if (OutDiag.Filename.empty())
1343 return;
1344 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
1345 for (StoredDiagnostic::range_iterator
1346 I = InDiag.range_begin(), E = InDiag.range_end(); I != E; ++I) {
1347 OutDiag.Ranges.push_back(makeStandaloneRange(*I, SM, LangOpts));
1348 }
1349 for (StoredDiagnostic::fixit_iterator
1350 I = InDiag.fixit_begin(), E = InDiag.fixit_end(); I != E; ++I) {
1351 ASTUnit::StandaloneFixIt Fix;
1352 makeStandaloneFixIt(SM, LangOpts, *I, Fix);
1353 OutDiag.FixIts.push_back(Fix);
1354 }
1355}
1356
Douglas Gregor4dde7492010-07-23 23:58:40 +00001357/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1358/// the source file.
1359///
1360/// This routine will compute the preamble of the main source file. If a
1361/// non-trivial preamble is found, it will precompile that preamble into a
1362/// precompiled header so that the precompiled preamble can be used to reduce
1363/// reparsing time. If a precompiled preamble has already been constructed,
1364/// this routine will determine if it is still valid and, if so, avoid
1365/// rebuilding the precompiled preamble.
1366///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001367/// \param AllowRebuild When true (the default), this routine is
1368/// allowed to rebuild the precompiled preamble if it is found to be
1369/// out-of-date.
1370///
1371/// \param MaxLines When non-zero, the maximum number of lines that
1372/// can occur within the preamble.
1373///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001374/// \returns If the precompiled preamble can be used, returns a newly-allocated
1375/// buffer that should be used in place of the main file when doing so.
1376/// Otherwise, returns a NULL pointer.
Douglas Gregor028d3e42010-08-09 20:45:32 +00001377llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor3cc15812011-07-01 18:22:13 +00001378 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001379 bool AllowRebuild,
1380 unsigned MaxLines) {
Douglas Gregor3cc15812011-07-01 18:22:13 +00001381
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001382 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor3cc15812011-07-01 18:22:13 +00001383 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1384 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001385 PreprocessorOptions &PreprocessorOpts
Douglas Gregor3cc15812011-07-01 18:22:13 +00001386 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001387
1388 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001389 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor3cc15812011-07-01 18:22:13 +00001390 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001391
Douglas Gregor925296b2011-07-19 16:10:42 +00001392 // If ComputePreamble() Take ownership of the preamble buffer.
Ahmed Charlesb8984322014-03-07 20:03:18 +00001393 std::unique_ptr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor3edb1672010-11-16 20:45:51 +00001394 if (CreatedPreambleBuffer)
1395 OwnedPreambleBuffer.reset(NewPreamble.first);
1396
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001397 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001398 // We couldn't find a preamble in the main source. Clear out the current
1399 // preamble, if we have one. It's obviously no good any more.
1400 Preamble.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001401 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001402
1403 // The next time we actually see a preamble, precompile it.
1404 PreambleRebuildCounter = 1;
Craig Topper49a27902014-05-22 04:46:25 +00001405 return nullptr;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001406 }
1407
1408 if (!Preamble.empty()) {
1409 // We've previously computed a preamble. Check whether we have the same
1410 // preamble now that we did before, and that there's enough space in
1411 // the main-file buffer within the precompiled preamble to fit the
1412 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001413 if (Preamble.size() == NewPreamble.second.first &&
1414 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001415 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001416 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001417 // The preamble has not changed. We may be able to re-use the precompiled
1418 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001419
Douglas Gregor0e119552010-07-31 00:40:00 +00001420 // Check that none of the files used by the preamble have changed.
1421 bool AnyFileChanged = false;
1422
1423 // First, make a record of those files that have been overridden via
1424 // remapping or unsaved_files.
Dmitri Gribenko47652522013-12-20 00:16:25 +00001425 llvm::StringMap<PreambleFileHash> OverriddenFiles;
Douglas Gregor0e119552010-07-31 00:40:00 +00001426 for (PreprocessorOptions::remapped_file_iterator
1427 R = PreprocessorOpts.remapped_file_begin(),
1428 REnd = PreprocessorOpts.remapped_file_end();
1429 !AnyFileChanged && R != REnd;
1430 ++R) {
Ben Langmuirc8130a72014-02-20 21:59:23 +00001431 vfs::Status Status;
Rafael Espindolae4777f42013-07-29 18:22:23 +00001432 if (FileMgr->getNoncachedStatValue(R->second, Status)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001433 // If we can't stat the file we're remapping to, assume that something
1434 // horrible happened.
1435 AnyFileChanged = true;
1436 break;
1437 }
Rafael Espindolae4777f42013-07-29 18:22:23 +00001438
Dmitri Gribenko47652522013-12-20 00:16:25 +00001439 OverriddenFiles[R->first] = PreambleFileHash::createForFile(
Rafael Espindolae4777f42013-07-29 18:22:23 +00001440 Status.getSize(), Status.getLastModificationTime().toEpochTime());
Douglas Gregor0e119552010-07-31 00:40:00 +00001441 }
1442 for (PreprocessorOptions::remapped_file_buffer_iterator
1443 R = PreprocessorOpts.remapped_file_buffer_begin(),
1444 REnd = PreprocessorOpts.remapped_file_buffer_end();
1445 !AnyFileChanged && R != REnd;
1446 ++R) {
Dmitri Gribenko47652522013-12-20 00:16:25 +00001447 OverriddenFiles[R->first] =
1448 PreambleFileHash::createForMemoryBuffer(R->second);
Douglas Gregor0e119552010-07-31 00:40:00 +00001449 }
1450
1451 // Check whether anything has changed.
Dmitri Gribenko47652522013-12-20 00:16:25 +00001452 for (llvm::StringMap<PreambleFileHash>::iterator
Douglas Gregor0e119552010-07-31 00:40:00 +00001453 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1454 !AnyFileChanged && F != FEnd;
1455 ++F) {
Dmitri Gribenko47652522013-12-20 00:16:25 +00001456 llvm::StringMap<PreambleFileHash>::iterator Overridden
Douglas Gregor0e119552010-07-31 00:40:00 +00001457 = OverriddenFiles.find(F->first());
1458 if (Overridden != OverriddenFiles.end()) {
1459 // This file was remapped; check whether the newly-mapped file
1460 // matches up with the previous mapping.
1461 if (Overridden->second != F->second)
1462 AnyFileChanged = true;
1463 continue;
1464 }
1465
1466 // The file was not remapped; check whether it has changed on disk.
Ben Langmuirc8130a72014-02-20 21:59:23 +00001467 vfs::Status Status;
Rafael Espindolae4777f42013-07-29 18:22:23 +00001468 if (FileMgr->getNoncachedStatValue(F->first(), Status)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001469 // If we can't stat the file, assume that something horrible happened.
1470 AnyFileChanged = true;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001471 } else if (Status.getSize() != uint64_t(F->second.Size) ||
Rafael Espindolae4777f42013-07-29 18:22:23 +00001472 Status.getLastModificationTime().toEpochTime() !=
Dmitri Gribenko47652522013-12-20 00:16:25 +00001473 uint64_t(F->second.ModTime))
Douglas Gregor0e119552010-07-31 00:40:00 +00001474 AnyFileChanged = true;
1475 }
1476
1477 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001478 // Okay! We can re-use the precompiled preamble.
1479
1480 // Set the state of the diagnostic object to mimic its state
1481 // after parsing the preamble.
1482 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001483 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor3cc15812011-07-01 18:22:13 +00001484 PreambleInvocation->getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001485 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001486
Argyrios Kyrtzidisb255ee92014-03-09 04:24:57 +00001487 return llvm::MemoryBuffer::getMemBufferCopy(
1488 NewPreamble.first->getBuffer(), FrontendOpts.Inputs[0].getFile());
Douglas Gregor0e119552010-07-31 00:40:00 +00001489 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001490 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001491
1492 // If we aren't allowed to rebuild the precompiled preamble, just
1493 // return now.
1494 if (!AllowRebuild)
Craig Topper49a27902014-05-22 04:46:25 +00001495 return nullptr;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001496
Douglas Gregor4dde7492010-07-23 23:58:40 +00001497 // We can't reuse the previously-computed preamble. Build a new one.
1498 Preamble.clear();
Douglas Gregor925296b2011-07-19 16:10:42 +00001499 PreambleDiagnostics.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001500 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001501 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001502 } else if (!AllowRebuild) {
1503 // We aren't allowed to rebuild the precompiled preamble; just
1504 // return now.
Craig Topper49a27902014-05-22 04:46:25 +00001505 return nullptr;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001506 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001507
1508 // If the preamble rebuild counter > 1, it's because we previously
1509 // failed to build a preamble and we're not yet ready to try
1510 // again. Decrement the counter and return a failure.
1511 if (PreambleRebuildCounter > 1) {
1512 --PreambleRebuildCounter;
Craig Topper49a27902014-05-22 04:46:25 +00001513 return nullptr;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001514 }
1515
Douglas Gregore10f0e52010-09-11 17:56:52 +00001516 // Create a temporary file for the precompiled preamble. In rare
1517 // circumstances, this can fail.
1518 std::string PreamblePCHPath = GetPreamblePCHPath();
1519 if (PreamblePCHPath.empty()) {
1520 // Try again next time.
1521 PreambleRebuildCounter = 1;
Craig Topper49a27902014-05-22 04:46:25 +00001522 return nullptr;
Douglas Gregore10f0e52010-09-11 17:56:52 +00001523 }
1524
Douglas Gregor4dde7492010-07-23 23:58:40 +00001525 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001526 SimpleTimer PreambleTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001527 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor4dde7492010-07-23 23:58:40 +00001528
Douglas Gregord9a30af2010-08-02 20:51:39 +00001529 // Save the preamble text for later; we'll need to compare against it for
1530 // subsequent reparses.
Dmitri Gribenko40798d32013-12-19 23:25:59 +00001531 StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001532 Preamble.assign(FileMgr->getFile(MainFilename),
1533 NewPreamble.first->getBufferStart(),
Douglas Gregord9a30af2010-08-02 20:51:39 +00001534 NewPreamble.first->getBufferStart()
1535 + NewPreamble.second.first);
1536 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1537
Douglas Gregora0734c52010-08-19 01:33:06 +00001538 delete PreambleBuffer;
1539 PreambleBuffer
Argyrios Kyrtzidisb255ee92014-03-09 04:24:57 +00001540 = llvm::MemoryBuffer::getMemBufferCopy(
1541 NewPreamble.first->getBuffer().slice(0, Preamble.size()), MainFilename);
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001542
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001543 // Remap the main source file to the preamble buffer.
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001544 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
1545 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer);
1546
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001547 // Tell the compiler invocation to generate a temporary precompiled header.
1548 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001549 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001550 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001551 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1552 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001553
1554 // Create the compiler instance to use for building the precompiled preamble.
Ahmed Charlesb8984322014-03-07 20:03:18 +00001555 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001556
1557 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001558 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1559 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001560
Douglas Gregor3cc15812011-07-01 18:22:13 +00001561 Clang->setInvocation(&*PreambleInvocation);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001562 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001563
Douglas Gregor8e984da2010-08-04 16:47:14 +00001564 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001565 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001566
1567 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001568 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregorf8715de2012-11-16 04:24:59 +00001569 &Clang->getTargetOpts()));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001570 if (!Clang->hasTarget()) {
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001571 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001572 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001573 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001574 PreprocessorOpts.eraseRemappedFile(
1575 PreprocessorOpts.remapped_file_buffer_end() - 1);
Craig Topper49a27902014-05-22 04:46:25 +00001576 return nullptr;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001577 }
1578
1579 // Inform the target of the language options.
1580 //
1581 // FIXME: We shouldn't need to do this, the target should be immutable once
1582 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001583 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001584
Ted Kremenek84de4a12011-03-21 18:40:07 +00001585 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001586 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001587 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001588 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001589 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001590 "IR inputs not support here!");
1591
1592 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001593 getDiagnostics().Reset();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001594 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001595 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregore9db88f2010-08-03 19:06:41 +00001596 TopLevelDecls.clear();
1597 TopLevelDeclsInPreamble.clear();
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001598 PreambleDiagnostics.clear();
Ben Langmuir8832c062014-04-15 18:16:25 +00001599
1600 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1601 createVFSFromCompilerInvocation(Clang->getInvocation(), getDiagnostics());
1602 if (!VFS)
1603 return nullptr;
1604
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001605 // Create a file manager object to provide access to and cache the filesystem.
Ben Langmuir8832c062014-04-15 18:16:25 +00001606 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts(), VFS));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001607
1608 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001609 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek5e14d392011-03-21 18:40:17 +00001610 Clang->getFileManager()));
Ahmed Charlesb8984322014-03-07 20:03:18 +00001611
Ben Langmuir33c80902014-06-30 20:04:14 +00001612 auto PreambleDepCollector = std::make_shared<DependencyCollector>();
1613 Clang->addDependencyCollector(PreambleDepCollector);
1614
Ahmed Charlesb8984322014-03-07 20:03:18 +00001615 std::unique_ptr<PrecompilePreambleAction> Act;
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001616 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor32fbe312012-01-20 16:28:04 +00001617 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001618 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001619 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001620 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001621 PreprocessorOpts.eraseRemappedFile(
1622 PreprocessorOpts.remapped_file_buffer_end() - 1);
Craig Topper49a27902014-05-22 04:46:25 +00001623 return nullptr;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001624 }
1625
1626 Act->Execute();
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001627
1628 // Transfer any diagnostics generated when parsing the preamble into the set
1629 // of preamble diagnostics.
1630 for (stored_diag_iterator
1631 I = stored_diag_afterDriver_begin(),
1632 E = stored_diag_end(); I != E; ++I) {
1633 StandaloneDiagnostic Diag;
1634 makeStandaloneDiagnostic(Clang->getLangOpts(), *I, Diag);
1635 PreambleDiagnostics.push_back(Diag);
1636 }
1637
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001638 Act->EndSourceFile();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001639
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001640 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1641
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +00001642 if (!Act->hasEmittedPreamblePCH()) {
Argyrios Kyrtzidisd6f57222013-06-11 16:42:34 +00001643 // The preamble PCH failed (e.g. there was a module loading fatal error),
1644 // so no precompiled header was generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001645 // FIXME: Should we leave a note for ourselves to try again?
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001646 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001647 Preamble.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001648 TopLevelDeclsInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001649 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001650 PreprocessorOpts.eraseRemappedFile(
1651 PreprocessorOpts.remapped_file_buffer_end() - 1);
Craig Topper49a27902014-05-22 04:46:25 +00001652 return nullptr;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001653 }
1654
1655 // Keep track of the preamble we precompiled.
Ted Kremenek06b4f912011-10-27 17:55:18 +00001656 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001657 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001658
1659 // Keep track of all of the files that the source manager knows about,
1660 // so we can verify whether they have changed or not.
1661 FilesInPreamble.clear();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001662 SourceManager &SourceMgr = Clang->getSourceManager();
Ben Langmuir33c80902014-06-30 20:04:14 +00001663 for (auto &Filename : PreambleDepCollector->getDependencies()) {
1664 const FileEntry *File = Clang->getFileManager().getFile(Filename);
1665 if (!File || File == SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))
Douglas Gregor0e119552010-07-31 00:40:00 +00001666 continue;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001667 if (time_t ModTime = File->getModificationTime()) {
1668 FilesInPreamble[File->getName()] = PreambleFileHash::createForFile(
Ben Langmuir33c80902014-06-30 20:04:14 +00001669 File->getSize(), ModTime);
Dmitri Gribenko47652522013-12-20 00:16:25 +00001670 } else {
Ben Langmuir33c80902014-06-30 20:04:14 +00001671 llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
Dmitri Gribenko47652522013-12-20 00:16:25 +00001672 FilesInPreamble[File->getName()] =
1673 PreambleFileHash::createForMemoryBuffer(Buffer);
1674 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001675 }
Ben Langmuir33c80902014-06-30 20:04:14 +00001676
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001677 PreambleRebuildCounter = 1;
Douglas Gregora0734c52010-08-19 01:33:06 +00001678 PreprocessorOpts.eraseRemappedFile(
1679 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001680
1681 // If the hash of top-level entities differs from the hash of the top-level
1682 // entities the last time we rebuilt the preamble, clear out the completion
1683 // cache.
1684 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1685 CompletionCacheTopLevelHashValue = 0;
1686 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1687 }
1688
Argyrios Kyrtzidisb255ee92014-03-09 04:24:57 +00001689 return llvm::MemoryBuffer::getMemBufferCopy(NewPreamble.first->getBuffer(),
1690 MainFilename);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001691}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001692
Douglas Gregore9db88f2010-08-03 19:06:41 +00001693void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1694 std::vector<Decl *> Resolved;
1695 Resolved.reserve(TopLevelDeclsInPreamble.size());
1696 ExternalASTSource &Source = *getASTContext().getExternalSource();
1697 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1698 // Resolve the declaration ID to an actual declaration, possibly
1699 // deserializing the declaration in the process.
1700 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1701 if (D)
1702 Resolved.push_back(D);
1703 }
1704 TopLevelDeclsInPreamble.clear();
1705 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1706}
1707
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001708void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
Ben Langmuir749323f2014-04-22 17:40:12 +00001709 // Steal the created target, context, and preprocessor if they have been
1710 // created.
1711 assert(CI.hasInvocation() && "missing invocation");
1712 LangOpts = CI.getInvocation().getLangOpts();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001713 TheSema.reset(CI.takeSema());
1714 Consumer.reset(CI.takeASTConsumer());
Ben Langmuir532fdc02014-04-18 20:39:48 +00001715 if (CI.hasASTContext())
1716 Ctx = &CI.getASTContext();
1717 if (CI.hasPreprocessor())
1718 PP = &CI.getPreprocessor();
Craig Topper49a27902014-05-22 04:46:25 +00001719 CI.setSourceManager(nullptr);
1720 CI.setFileManager(nullptr);
Ben Langmuir532fdc02014-04-18 20:39:48 +00001721 if (CI.hasTarget())
1722 Target = &CI.getTarget();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001723 Reader = CI.getModuleManager();
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001724 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001725}
1726
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001727StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis928e1fd2013-01-11 22:11:14 +00001728 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1729 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1730 if (Input.isFile())
1731 return Input.getFile();
1732 else
1733 return Input.getBuffer()->getBufferIdentifier();
1734 }
1735
1736 if (SourceMgr) {
1737 if (const FileEntry *
1738 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1739 return FE->getName();
1740 }
1741
1742 return StringRef();
Douglas Gregor16896c42010-10-28 15:44:59 +00001743}
1744
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00001745StringRef ASTUnit::getASTFileName() const {
1746 if (!isMainFileAST())
1747 return StringRef();
1748
1749 serialization::ModuleFile &
1750 Mod = Reader->getModuleManager().getPrimaryModule();
1751 return Mod.FileName;
1752}
1753
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001754ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001755 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001756 bool CaptureDiagnostics,
1757 bool UserFilesAreVolatile) {
Ahmed Charlesb8984322014-03-07 20:03:18 +00001758 std::unique_ptr<ASTUnit> AST;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001759 AST.reset(new ASTUnit(false));
Craig Topper49a27902014-05-22 04:46:25 +00001760 ConfigureDiags(Diags, nullptr, nullptr, *AST, CaptureDiagnostics);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001761 AST->Diagnostics = Diags;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001762 AST->Invocation = CI;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001763 AST->FileSystemOpts = CI->getFileSystemOpts();
Ben Langmuir8832c062014-04-15 18:16:25 +00001764 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1765 createVFSFromCompilerInvocation(*CI, *Diags);
1766 if (!VFS)
1767 return nullptr;
1768 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001769 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1770 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1771 UserFilesAreVolatile);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001772
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001773 return AST.release();
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001774}
1775
Ahmed Charlesb8984322014-03-07 20:03:18 +00001776ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
1777 CompilerInvocation *CI, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1778 ASTFrontendAction *Action, ASTUnit *Unit, bool Persistent,
1779 StringRef ResourceFilesPath, bool OnlyLocalDecls, bool CaptureDiagnostics,
1780 bool PrecompilePreamble, bool CacheCodeCompletionResults,
1781 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile,
1782 std::unique_ptr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001783 assert(CI && "A CompilerInvocation is required");
1784
Ahmed Charlesb8984322014-03-07 20:03:18 +00001785 std::unique_ptr<ASTUnit> OwnAST;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001786 ASTUnit *AST = Unit;
1787 if (!AST) {
1788 // Create the AST unit.
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001789 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001790 AST = OwnAST.get();
Ben Langmuir8832c062014-04-15 18:16:25 +00001791 if (!AST)
1792 return nullptr;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001793 }
1794
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001795 if (!ResourceFilesPath.empty()) {
1796 // Override the resources path.
1797 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1798 }
1799 AST->OnlyLocalDecls = OnlyLocalDecls;
1800 AST->CaptureDiagnostics = CaptureDiagnostics;
1801 if (PrecompilePreamble)
1802 AST->PreambleRebuildCounter = 2;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001803 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001804 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001805 AST->IncludeBriefCommentsInCodeCompletion
1806 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001807
1808 // Recover resources if we crash before exiting this method.
1809 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001810 ASTUnitCleanup(OwnAST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001811 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1812 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00001813 DiagCleanup(Diags.get());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001814
1815 // We'll manage file buffers ourselves.
1816 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1817 CI->getFrontendOpts().DisableFree = false;
1818 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1819
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001820 // Create the compiler instance to use for building the AST.
Ahmed Charlesb8984322014-03-07 20:03:18 +00001821 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001822
1823 // Recover resources if we crash before exiting this method.
1824 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1825 CICleanup(Clang.get());
1826
1827 Clang->setInvocation(CI);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001828 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001829
1830 // Set up diagnostics, capturing any diagnostics that would
1831 // otherwise be dropped.
1832 Clang->setDiagnostics(&AST->getDiagnostics());
1833
1834 // Create the target instance.
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001835 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregorf8715de2012-11-16 04:24:59 +00001836 &Clang->getTargetOpts()));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001837 if (!Clang->hasTarget())
Craig Topper49a27902014-05-22 04:46:25 +00001838 return nullptr;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001839
1840 // Inform the target of the language options.
1841 //
1842 // FIXME: We shouldn't need to do this, the target should be immutable once
1843 // created. This complexity should be lifted elsewhere.
1844 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1845
1846 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1847 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001848 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001849 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001850 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001851 "IR inputs not supported here!");
1852
1853 // Configure the various subsystems.
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001854 AST->TheSema.reset();
Craig Topper49a27902014-05-22 04:46:25 +00001855 AST->Ctx = nullptr;
1856 AST->PP = nullptr;
1857 AST->Reader = nullptr;
1858
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001859 // Create a file manager object to provide access to and cache the filesystem.
1860 Clang->setFileManager(&AST->getFileManager());
1861
1862 // Create the source manager.
1863 Clang->setSourceManager(&AST->getSourceManager());
1864
1865 ASTFrontendAction *Act = Action;
1866
Ahmed Charlesb8984322014-03-07 20:03:18 +00001867 std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001868 if (!Act) {
1869 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1870 Act = TrackerAct.get();
1871 }
1872
1873 // Recover resources if we crash before exiting this method.
1874 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1875 ActCleanup(TrackerAct.get());
1876
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001877 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1878 AST->transferASTDataFromCompilerInstance(*Clang);
1879 if (OwnAST && ErrAST)
1880 ErrAST->swap(OwnAST);
1881
Craig Topper49a27902014-05-22 04:46:25 +00001882 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001883 }
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001884
1885 if (Persistent && !TrackerAct) {
1886 Clang->getPreprocessor().addPPCallbacks(
1887 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1888 std::vector<ASTConsumer*> Consumers;
1889 if (Clang->hasASTConsumer())
1890 Consumers.push_back(Clang->takeASTConsumer());
1891 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1892 AST->getCurrentTopLevelHashValue()));
1893 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1894 }
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001895 if (!Act->Execute()) {
1896 AST->transferASTDataFromCompilerInstance(*Clang);
1897 if (OwnAST && ErrAST)
1898 ErrAST->swap(OwnAST);
1899
Craig Topper49a27902014-05-22 04:46:25 +00001900 return nullptr;
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001901 }
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001902
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001903 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001904 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001905
1906 Act->EndSourceFile();
1907
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001908 if (OwnAST)
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001909 return OwnAST.release();
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001910 else
1911 return AST;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001912}
1913
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001914bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1915 if (!Invocation)
1916 return true;
1917
1918 // We'll manage file buffers ourselves.
1919 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1920 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001921 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001922
Craig Topper49a27902014-05-22 04:46:25 +00001923 llvm::MemoryBuffer *OverrideMainBuffer = nullptr;
Douglas Gregorf5a18542010-10-27 17:24:53 +00001924 if (PrecompilePreamble) {
Douglas Gregorc6592922010-11-15 23:00:34 +00001925 PreambleRebuildCounter = 2;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001926 OverrideMainBuffer
1927 = getMainBufferWithPrecompiledPreamble(*Invocation);
1928 }
1929
Douglas Gregor16896c42010-10-28 15:44:59 +00001930 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001931 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001932
Ted Kremenek022a4902011-03-22 01:15:24 +00001933 // Recover resources if we crash before exiting this method.
1934 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1935 MemBufferCleanup(OverrideMainBuffer);
1936
Douglas Gregor16896c42010-10-28 15:44:59 +00001937 return Parse(OverrideMainBuffer);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001938}
1939
David Blaikie103a2de2014-04-25 17:01:33 +00001940std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1941 CompilerInvocation *CI, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1942 bool OnlyLocalDecls, bool CaptureDiagnostics, bool PrecompilePreamble,
1943 TranslationUnitKind TUKind, bool CacheCodeCompletionResults,
1944 bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001945 // Create the AST unit.
David Blaikie103a2de2014-04-25 17:01:33 +00001946 std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
Craig Topper49a27902014-05-22 04:46:25 +00001947 ConfigureDiags(Diags, nullptr, nullptr, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001948 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001949 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001950 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001951 AST->TUKind = TUKind;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001952 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001953 AST->IncludeBriefCommentsInCodeCompletion
1954 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001955 AST->Invocation = CI;
Argyrios Kyrtzidis3ad52ed2013-01-21 18:45:42 +00001956 AST->FileSystemOpts = CI->getFileSystemOpts();
Ben Langmuir8832c062014-04-15 18:16:25 +00001957 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
1958 createVFSFromCompilerInvocation(*CI, *Diags);
1959 if (!VFS)
1960 return nullptr;
1961 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001962 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001963
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001964 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001965 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1966 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001967 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1968 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Alp Tokerf994cef2014-07-05 03:08:06 +00001969 DiagCleanup(Diags.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00001970
David Blaikie103a2de2014-04-25 17:01:33 +00001971 if (AST->LoadFromCompilerInvocation(PrecompilePreamble))
1972 return nullptr;
1973 return AST;
Daniel Dunbar764c0822009-12-01 09:51:01 +00001974}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001975
Ahmed Charlesb8984322014-03-07 20:03:18 +00001976ASTUnit *ASTUnit::LoadFromCommandLine(
1977 const char **ArgBegin, const char **ArgEnd,
1978 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1979 bool OnlyLocalDecls, bool CaptureDiagnostics,
1980 ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
1981 bool PrecompilePreamble, TranslationUnitKind TUKind,
1982 bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1983 bool AllowPCHWithCompilerErrors, bool SkipFunctionBodies,
1984 bool UserFilesAreVolatile, bool ForSerialization,
1985 std::unique_ptr<ASTUnit> *ErrAST) {
Alp Tokerf994cef2014-07-05 03:08:06 +00001986 if (!Diags.get()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00001987 // No diagnostics engine was provided, so create our own diagnostics object
1988 // with the default options.
Sean Silvaf1b49e22013-01-20 01:58:28 +00001989 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions());
Douglas Gregord03e8232010-04-05 21:10:19 +00001990 }
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001991
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001992 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001993
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001994 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001995
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001996 {
Douglas Gregor925296b2011-07-19 16:10:42 +00001997
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001998 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001999 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00002000
Argyrios Kyrtzidis5cf423e2011-04-04 23:11:45 +00002001 CI = clang::createInvocationFromCommandLine(
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002002 llvm::makeArrayRef(ArgBegin, ArgEnd),
2003 Diags);
Argyrios Kyrtzidisf606b822011-04-04 21:38:51 +00002004 if (!CI)
Craig Topper49a27902014-05-22 04:46:25 +00002005 return nullptr;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002006 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00002007
Douglas Gregoraa98ed92010-01-23 00:14:00 +00002008 // Override any files that need remapping
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002009 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002010 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2011 RemappedFiles[I].second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002012 }
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00002013 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
2014 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
2015 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00002016
Daniel Dunbara5a166d2009-12-15 00:06:45 +00002017 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00002018 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002019
Erik Verbruggen6e922512012-04-12 10:11:59 +00002020 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
2021
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002022 // Create the AST unit.
Ahmed Charlesb8984322014-03-07 20:03:18 +00002023 std::unique_ptr<ASTUnit> AST;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002024 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00002025 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002026 AST->Diagnostics = Diags;
Craig Topper49a27902014-05-22 04:46:25 +00002027 Diags = nullptr; // Zero out now to ease cleanup during crash recovery.
Anders Carlssonc30dcec2011-03-18 18:22:40 +00002028 AST->FileSystemOpts = CI->getFileSystemOpts();
Ben Langmuir8832c062014-04-15 18:16:25 +00002029 IntrusiveRefCntPtr<vfs::FileSystem> VFS =
2030 createVFSFromCompilerInvocation(*CI, *Diags);
2031 if (!VFS)
2032 return nullptr;
2033 AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002034 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00002035 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00002036 AST->TUKind = TUKind;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002037 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002038 AST->IncludeBriefCommentsInCodeCompletion
2039 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00002040 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002041 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002042 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek5e14d392011-03-21 18:40:17 +00002043 AST->Invocation = CI;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002044 if (ForSerialization)
2045 AST->WriterData.reset(new ASTWriterData());
Craig Topper49a27902014-05-22 04:46:25 +00002046 CI = nullptr; // Zero out now to ease cleanup during crash recovery.
2047
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002048 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002049 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2050 ASTUnitCleanup(AST.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002051
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00002052 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
2053 // Some error occurred, if caller wants to examine diagnostics, pass it the
2054 // ASTUnit.
2055 if (ErrAST) {
2056 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2057 ErrAST->swap(AST);
2058 }
Craig Topper49a27902014-05-22 04:46:25 +00002059 return nullptr;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00002060 }
2061
Ahmed Charles9a16beb2014-03-07 19:33:25 +00002062 return AST.release();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002063}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002064
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002065bool ASTUnit::Reparse(ArrayRef<RemappedFile> RemappedFiles) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002066 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002067 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002068
2069 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002070
Douglas Gregor16896c42010-10-28 15:44:59 +00002071 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002072 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00002073
Douglas Gregor0e119552010-07-31 00:40:00 +00002074 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00002075 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
2076 for (PreprocessorOptions::remapped_file_buffer_iterator
2077 R = PPOpts.remapped_file_buffer_begin(),
2078 REnd = PPOpts.remapped_file_buffer_end();
2079 R != REnd;
2080 ++R) {
2081 delete R->second;
2082 }
Douglas Gregor0e119552010-07-31 00:40:00 +00002083 Invocation->getPreprocessorOpts().clearRemappedFiles();
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002084 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002085 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2086 RemappedFiles[I].second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002087 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002088
Douglas Gregorbb420ab2010-08-04 05:53:38 +00002089 // If we have a preamble file lying around, or if we might try to
2090 // build a precompiled preamble, do so now.
Craig Topper49a27902014-05-22 04:46:25 +00002091 llvm::MemoryBuffer *OverrideMainBuffer = nullptr;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002092 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregorb97b6662010-08-20 00:59:43 +00002093 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor4dde7492010-07-23 23:58:40 +00002094
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002095 // Clear out the diagnostics state.
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002096 getDiagnostics().Reset();
2097 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis462ff352011-11-03 20:57:33 +00002098 if (OverrideMainBuffer)
2099 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002100
Douglas Gregor4dde7492010-07-23 23:58:40 +00002101 // Parse the sources
Douglas Gregordf7a79a2011-02-16 18:16:54 +00002102 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis36893372011-10-31 21:25:31 +00002103
2104 // If we're caching global code-completion results, and the top-level
2105 // declarations have changed, clear out the code-completion cache.
2106 if (!Result && ShouldCacheCodeCompletionResults &&
2107 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2108 CacheCodeCompletionResults();
Douglas Gregordf7a79a2011-02-16 18:16:54 +00002109
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002110 // We now need to clear out the completion info related to this translation
2111 // unit; it'll be recreated if necessary.
2112 CCTUInfo.reset();
Douglas Gregor3f35bb22011-08-04 20:04:59 +00002113
Douglas Gregor4dde7492010-07-23 23:58:40 +00002114 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002115}
Douglas Gregor8e984da2010-08-04 16:47:14 +00002116
Douglas Gregorb14904c2010-08-13 22:48:40 +00002117//----------------------------------------------------------------------------//
2118// Code completion
2119//----------------------------------------------------------------------------//
2120
2121namespace {
2122 /// \brief Code completion consumer that combines the cached code-completion
2123 /// results from an ASTUnit with the code-completion results provided to it,
2124 /// then passes the result on to
2125 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith697cc9e2012-08-14 03:13:00 +00002126 uint64_t NormalContexts;
Douglas Gregorb14904c2010-08-13 22:48:40 +00002127 ASTUnit &AST;
2128 CodeCompleteConsumer &Next;
2129
2130 public:
2131 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002132 const CodeCompleteOptions &CodeCompleteOpts)
2133 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2134 AST(AST), Next(Next)
Douglas Gregorb14904c2010-08-13 22:48:40 +00002135 {
2136 // Compute the set of contexts in which we will look when we don't have
2137 // any information about the specific context.
2138 NormalContexts
Richard Smith697cc9e2012-08-14 03:13:00 +00002139 = (1LL << CodeCompletionContext::CCC_TopLevel)
2140 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2141 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2142 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2143 | (1LL << CodeCompletionContext::CCC_Statement)
2144 | (1LL << CodeCompletionContext::CCC_Expression)
2145 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2146 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2147 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2148 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2149 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2150 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2151 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor5e35d592010-09-14 23:59:36 +00002152
David Blaikiebbafb8a2012-03-11 07:00:24 +00002153 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +00002154 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2155 | (1LL << CodeCompletionContext::CCC_UnionTag)
2156 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregorb14904c2010-08-13 22:48:40 +00002157 }
Craig Topperafa7cb32014-03-13 06:07:04 +00002158
2159 void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
2160 CodeCompletionResult *Results,
2161 unsigned NumResults) override;
2162
2163 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2164 OverloadCandidate *Candidates,
2165 unsigned NumCandidates) override {
Douglas Gregorb14904c2010-08-13 22:48:40 +00002166 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2167 }
Craig Topperafa7cb32014-03-13 06:07:04 +00002168
2169 CodeCompletionAllocator &getAllocator() override {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002170 return Next.getAllocator();
2171 }
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002172
Craig Topperafa7cb32014-03-13 06:07:04 +00002173 CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002174 return Next.getCodeCompletionTUInfo();
2175 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00002176 };
2177}
Douglas Gregord46cf182010-08-16 20:01:48 +00002178
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002179/// \brief Helper function that computes which global names are hidden by the
2180/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002181static void CalculateHiddenNames(const CodeCompletionContext &Context,
2182 CodeCompletionResult *Results,
2183 unsigned NumResults,
2184 ASTContext &Ctx,
2185 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002186 bool OnlyTagNames = false;
2187 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00002188 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002189 case CodeCompletionContext::CCC_TopLevel:
2190 case CodeCompletionContext::CCC_ObjCInterface:
2191 case CodeCompletionContext::CCC_ObjCImplementation:
2192 case CodeCompletionContext::CCC_ObjCIvarList:
2193 case CodeCompletionContext::CCC_ClassStructUnion:
2194 case CodeCompletionContext::CCC_Statement:
2195 case CodeCompletionContext::CCC_Expression:
2196 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor21325842011-07-07 16:03:39 +00002197 case CodeCompletionContext::CCC_DotMemberAccess:
2198 case CodeCompletionContext::CCC_ArrowMemberAccess:
2199 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002200 case CodeCompletionContext::CCC_Namespace:
2201 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00002202 case CodeCompletionContext::CCC_Name:
2203 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00002204 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor2c595ad2011-07-30 06:55:39 +00002205 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002206 break;
2207
2208 case CodeCompletionContext::CCC_EnumTag:
2209 case CodeCompletionContext::CCC_UnionTag:
2210 case CodeCompletionContext::CCC_ClassOrStructTag:
2211 OnlyTagNames = true;
2212 break;
2213
2214 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00002215 case CodeCompletionContext::CCC_MacroName:
2216 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00002217 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002218 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00002219 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00002220 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00002221 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00002222 case CodeCompletionContext::CCC_Other:
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00002223 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor21325842011-07-07 16:03:39 +00002224 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2225 case CodeCompletionContext::CCC_ObjCClassMessage:
2226 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002227 // We're looking for nothing, or we're looking for names that cannot
2228 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002229 return;
2230 }
2231
John McCall276321a2010-08-25 06:19:51 +00002232 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002233 for (unsigned I = 0; I != NumResults; ++I) {
2234 if (Results[I].Kind != Result::RK_Declaration)
2235 continue;
2236
2237 unsigned IDNS
2238 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2239
2240 bool Hiding = false;
2241 if (OnlyTagNames)
2242 Hiding = (IDNS & Decl::IDNS_Tag);
2243 else {
2244 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00002245 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2246 Decl::IDNS_NonMemberOperator);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002247 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002248 HiddenIDNS |= Decl::IDNS_Tag;
2249 Hiding = (IDNS & HiddenIDNS);
2250 }
2251
2252 if (!Hiding)
2253 continue;
2254
2255 DeclarationName Name = Results[I].Declaration->getDeclName();
2256 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2257 HiddenNames.insert(Identifier->getName());
2258 else
2259 HiddenNames.insert(Name.getAsString());
2260 }
2261}
2262
2263
Douglas Gregord46cf182010-08-16 20:01:48 +00002264void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2265 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002266 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00002267 unsigned NumResults) {
2268 // Merge the results we were given with the results we cached.
2269 bool AddedResult = false;
Richard Smith697cc9e2012-08-14 03:13:00 +00002270 uint64_t InContexts =
2271 Context.getKind() == CodeCompletionContext::CCC_Recovery
2272 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002273 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002274 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall276321a2010-08-25 06:19:51 +00002275 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002276 SmallVector<Result, 8> AllResults;
Douglas Gregord46cf182010-08-16 20:01:48 +00002277 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00002278 C = AST.cached_completion_begin(),
2279 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00002280 C != CEnd; ++C) {
2281 // If the context we are in matches any of the contexts we are
2282 // interested in, we'll add this result.
2283 if ((C->ShowInContexts & InContexts) == 0)
2284 continue;
2285
2286 // If we haven't added any results previously, do so now.
2287 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002288 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2289 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00002290 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2291 AddedResult = true;
2292 }
2293
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002294 // Determine whether this global completion result is hidden by a local
2295 // completion result. If so, skip it.
2296 if (C->Kind != CXCursor_MacroDefinition &&
2297 HiddenNames.count(C->Completion->getTypedText()))
2298 continue;
2299
Douglas Gregord46cf182010-08-16 20:01:48 +00002300 // Adjust priority based on similar type classes.
2301 unsigned Priority = C->Priority;
Douglas Gregor12785102010-08-24 20:21:13 +00002302 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00002303 if (!Context.getPreferredType().isNull()) {
2304 if (C->Kind == CXCursor_MacroDefinition) {
2305 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002306 S.getLangOpts(),
Douglas Gregor12785102010-08-24 20:21:13 +00002307 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00002308 } else if (C->Type) {
2309 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00002310 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00002311 Context.getPreferredType().getUnqualifiedType());
2312 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2313 if (ExpectedSTC == C->TypeClass) {
2314 // We know this type is similar; check for an exact match.
2315 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00002316 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00002317 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00002318 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00002319 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2320 Priority /= CCF_ExactTypeMatch;
2321 else
2322 Priority /= CCF_SimilarTypeMatch;
2323 }
2324 }
2325 }
2326
Douglas Gregor12785102010-08-24 20:21:13 +00002327 // Adjust the completion string, if required.
2328 if (C->Kind == CXCursor_MacroDefinition &&
2329 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2330 // Create a new code-completion string that just contains the
2331 // macro name, without its arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002332 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2333 CCP_CodePattern, C->Availability);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002334 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00002335 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002336 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00002337 }
2338
Argyrios Kyrtzidis5c8b1cd2012-09-27 00:24:09 +00002339 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregorf757a122010-08-23 23:00:57 +00002340 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00002341 }
2342
2343 // If we did not add any cached completion results, just forward the
2344 // results we were given to the next consumer.
2345 if (!AddedResult) {
2346 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2347 return;
2348 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002349
Douglas Gregord46cf182010-08-16 20:01:48 +00002350 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2351 AllResults.size());
2352}
2353
2354
2355
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002356void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002357 ArrayRef<RemappedFile> RemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00002358 bool IncludeMacros,
2359 bool IncludeCodePatterns,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002360 bool IncludeBriefComments,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002361 CodeCompleteConsumer &Consumer,
David Blaikie9c902b52011-09-25 23:23:43 +00002362 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002363 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002364 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2365 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002366 if (!Invocation)
Douglas Gregor8e984da2010-08-04 16:47:14 +00002367 return;
2368
Douglas Gregor16896c42010-10-28 15:44:59 +00002369 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002370 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002371 Twine(Line) + ":" + Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00002372
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00002373 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek5e14d392011-03-21 18:40:17 +00002374 CCInvocation(new CompilerInvocation(*Invocation));
2375
2376 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002377 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek5e14d392011-03-21 18:40:17 +00002378 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002379
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002380 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2381 CachedCompletionResults.empty();
2382 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2383 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2384 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2385
2386 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2387
Douglas Gregor8e984da2010-08-04 16:47:14 +00002388 FrontendOpts.CodeCompletionAt.FileName = File;
2389 FrontendOpts.CodeCompletionAt.Line = Line;
2390 FrontendOpts.CodeCompletionAt.Column = Column;
2391
2392 // Set the language options appropriately.
Ted Kremenek8cf47df2011-11-17 23:01:24 +00002393 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002394
Ahmed Charlesb8984322014-03-07 20:03:18 +00002395 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002396
2397 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002398 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2399 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002400
Ted Kremenek5e14d392011-03-21 18:40:17 +00002401 Clang->setInvocation(&*CCInvocation);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002402 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002403
2404 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002405 Clang->setDiagnostics(&Diag);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002406 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek84de4a12011-03-21 18:40:07 +00002407 Clang->getDiagnostics(),
Douglas Gregor8e984da2010-08-04 16:47:14 +00002408 StoredDiagnostics);
Manuel Klimekbe0474c2013-07-18 14:23:12 +00002409 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002410
2411 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002412 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregorf8715de2012-11-16 04:24:59 +00002413 &Clang->getTargetOpts()));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002414 if (!Clang->hasTarget()) {
Craig Topper49a27902014-05-22 04:46:25 +00002415 Clang->setInvocation(nullptr);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002416 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002417 }
2418
2419 // Inform the target of the language options.
2420 //
2421 // FIXME: We shouldn't need to do this, the target should be immutable once
2422 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002423 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002424
Ted Kremenek84de4a12011-03-21 18:40:07 +00002425 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002426 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002427 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002428 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002429 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002430 "IR inputs not support here!");
2431
2432
2433 // Use the source and file managers that we were given.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002434 Clang->setFileManager(&FileMgr);
2435 Clang->setSourceManager(&SourceMgr);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002436
2437 // Remap files.
2438 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00002439 PreprocessorOpts.RetainRemappedFileBuffers = true;
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002440 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002441 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
2442 RemappedFiles[I].second);
Daniel Jasperd90ec572014-02-12 08:45:05 +00002443 OwnedBuffers.push_back(RemappedFiles[I].second);
Douglas Gregorb97b6662010-08-20 00:59:43 +00002444 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002445
Douglas Gregorb14904c2010-08-13 22:48:40 +00002446 // Use the code completion consumer we were given, but adding any cached
2447 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00002448 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002449 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002450 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002451
Douglas Gregor028d3e42010-08-09 20:45:32 +00002452 // If we have a precompiled preamble, try to use it. We only allow
2453 // the use of the precompiled preamble if we're if the completion
2454 // point is within the main file, after the end of the precompiled
2455 // preamble.
Craig Topper49a27902014-05-22 04:46:25 +00002456 llvm::MemoryBuffer *OverrideMainBuffer = nullptr;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002457 if (!getPreambleFile(this).empty()) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002458 std::string CompleteFilePath(File);
Rafael Espindola073ff102013-07-29 21:26:52 +00002459 llvm::sys::fs::UniqueID CompleteFileID;
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002460
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00002461 if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002462 std::string MainPath(OriginalSourceFile);
Rafael Espindola073ff102013-07-29 21:26:52 +00002463 llvm::sys::fs::UniqueID MainID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00002464 if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002465 if (CompleteFileID == MainID && Line > 1)
Douglas Gregorb97b6662010-08-20 00:59:43 +00002466 OverrideMainBuffer
Ted Kremenek5e14d392011-03-21 18:40:17 +00002467 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregor8e817b62010-08-25 18:04:15 +00002468 Line - 1);
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002469 }
2470 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002471 }
2472
2473 // If the main file has been overridden due to the use of a preamble,
2474 // make that override happen and introduce the preamble.
2475 if (OverrideMainBuffer) {
2476 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2477 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2478 PreprocessorOpts.PrecompiledPreambleBytes.second
2479 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002480 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002481 PreprocessorOpts.DisablePCHValidation = true;
2482
Douglas Gregorb97b6662010-08-20 00:59:43 +00002483 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregor7b02b582010-08-20 00:02:33 +00002484 } else {
2485 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2486 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002487 }
2488
Argyrios Kyrtzidis870704f2012-11-02 22:18:44 +00002489 // Disable the preprocessing record if modules are not enabled.
2490 if (!Clang->getLangOpts().Modules)
2491 PreprocessorOpts.DetailedRecord = false;
Ahmed Charlesb8984322014-03-07 20:03:18 +00002492
2493 std::unique_ptr<SyntaxOnlyAction> Act;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002494 Act.reset(new SyntaxOnlyAction);
Douglas Gregor32fbe312012-01-20 16:28:04 +00002495 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00002496 Act->Execute();
2497 Act->EndSourceFile();
2498 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002499}
Douglas Gregore9386682010-08-13 05:36:37 +00002500
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002501bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00002502 if (HadModuleLoaderFatalFailure)
2503 return true;
2504
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002505 // Write to a temporary file and later rename it to the actual file, to avoid
2506 // possible race conditions.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002507 SmallString<128> TempPath;
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002508 TempPath = File;
2509 TempPath += "-%%%%%%%%";
2510 int fd;
Rafael Espindola18627112013-07-05 21:13:58 +00002511 if (llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath))
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002512 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002513
Douglas Gregore9386682010-08-13 05:36:37 +00002514 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2515 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002516 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002517
2518 serialize(Out);
2519 Out.close();
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002520 if (Out.has_error()) {
2521 Out.clear_error();
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002522 return true;
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002523 }
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002524
Rafael Espindola65e025c2011-12-25 01:18:52 +00002525 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Rafael Espindola2a008782014-01-10 21:32:14 +00002526 llvm::sys::fs::remove(TempPath.str());
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002527 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002528 }
2529
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002530 return false;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002531}
2532
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002533static bool serializeUnit(ASTWriter &Writer,
2534 SmallVectorImpl<char> &Buffer,
2535 Sema &S,
2536 bool hasErrors,
2537 raw_ostream &OS) {
Craig Topper49a27902014-05-22 04:46:25 +00002538 Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002539
2540 // Write the generated bitstream to "Out".
2541 if (!Buffer.empty())
2542 OS.write(Buffer.data(), Buffer.size());
2543
2544 return false;
2545}
2546
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002547bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00002548 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002549
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002550 if (WriterData)
2551 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2552 getSema(), hasErrors, OS);
2553
Daniel Dunbar9a963862012-02-29 20:31:23 +00002554 SmallString<128> Buffer;
Douglas Gregore9386682010-08-13 05:36:37 +00002555 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002556 ASTWriter Writer(Stream);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002557 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregore9386682010-08-13 05:36:37 +00002558}
Douglas Gregor925296b2011-07-19 16:10:42 +00002559
2560typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2561
Douglas Gregor925296b2011-07-19 16:10:42 +00002562void ASTUnit::TranslateStoredDiagnostics(
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002563 FileManager &FileMgr,
Douglas Gregor925296b2011-07-19 16:10:42 +00002564 SourceManager &SrcMgr,
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002565 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002566 SmallVectorImpl<StoredDiagnostic> &Out) {
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002567 // Map the standalone diagnostic into the new source manager. We also need to
2568 // remap all the locations to the new view. This includes the diag location,
2569 // any associated source ranges, and the source ranges of associated fix-its.
Douglas Gregor925296b2011-07-19 16:10:42 +00002570 // FIXME: There should be a cleaner way to do this.
2571
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002572 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregor925296b2011-07-19 16:10:42 +00002573 Result.reserve(Diags.size());
Douglas Gregor925296b2011-07-19 16:10:42 +00002574 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2575 // Rebuild the StoredDiagnostic.
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002576 const StandaloneDiagnostic &SD = Diags[I];
2577 if (SD.Filename.empty())
2578 continue;
2579 const FileEntry *FE = FileMgr.getFile(SD.Filename);
2580 if (!FE)
2581 continue;
2582 FileID FID = SrcMgr.translateFile(FE);
2583 SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
2584 if (FileLoc.isInvalid())
2585 continue;
2586 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
Douglas Gregor925296b2011-07-19 16:10:42 +00002587 FullSourceLoc Loc(L, SrcMgr);
2588
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002589 SmallVector<CharSourceRange, 4> Ranges;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002590 Ranges.reserve(SD.Ranges.size());
2591 for (std::vector<std::pair<unsigned, unsigned> >::const_iterator
2592 I = SD.Ranges.begin(), E = SD.Ranges.end(); I != E; ++I) {
2593 SourceLocation BL = FileLoc.getLocWithOffset((*I).first);
2594 SourceLocation EL = FileLoc.getLocWithOffset((*I).second);
2595 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
Douglas Gregor925296b2011-07-19 16:10:42 +00002596 }
2597
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002598 SmallVector<FixItHint, 2> FixIts;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002599 FixIts.reserve(SD.FixIts.size());
2600 for (std::vector<StandaloneFixIt>::const_iterator
2601 I = SD.FixIts.begin(), E = SD.FixIts.end();
Douglas Gregor925296b2011-07-19 16:10:42 +00002602 I != E; ++I) {
2603 FixIts.push_back(FixItHint());
2604 FixItHint &FH = FixIts.back();
2605 FH.CodeToInsert = I->CodeToInsert;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002606 SourceLocation BL = FileLoc.getLocWithOffset(I->RemoveRange.first);
2607 SourceLocation EL = FileLoc.getLocWithOffset(I->RemoveRange.second);
2608 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
Douglas Gregor925296b2011-07-19 16:10:42 +00002609 }
2610
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002611 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2612 SD.Message, Loc, Ranges, FixIts));
Douglas Gregor925296b2011-07-19 16:10:42 +00002613 }
2614 Result.swap(Out);
2615}
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002616
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002617void ASTUnit::addFileLevelDecl(Decl *D) {
2618 assert(D);
Douglas Gregor61d63d02011-11-07 18:53:57 +00002619
2620 // We only care about local declarations.
2621 if (D->isFromASTFile())
2622 return;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002623
2624 SourceManager &SM = *SourceMgr;
2625 SourceLocation Loc = D->getLocation();
2626 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2627 return;
2628
2629 // We only keep track of the file-level declarations of each file.
2630 if (!D->getLexicalDeclContext()->isFileContext())
2631 return;
2632
2633 SourceLocation FileLoc = SM.getFileLoc(Loc);
2634 assert(SM.isLocalSourceLocation(FileLoc));
2635 FileID FID;
2636 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002637 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002638 if (FID.isInvalid())
2639 return;
2640
2641 LocDeclsTy *&Decls = FileDecls[FID];
2642 if (!Decls)
2643 Decls = new LocDeclsTy();
2644
2645 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2646
2647 if (Decls->empty() || Decls->back().first <= Offset) {
2648 Decls->push_back(LocDecl);
2649 return;
2650 }
2651
Benjamin Kramer45025c02013-08-24 13:22:59 +00002652 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2653 LocDecl, llvm::less_first());
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002654
2655 Decls->insert(I, LocDecl);
2656}
2657
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002658void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2659 SmallVectorImpl<Decl *> &Decls) {
2660 if (File.isInvalid())
2661 return;
2662
2663 if (SourceMgr->isLoadedFileID(File)) {
2664 assert(Ctx->getExternalSource() && "No external source!");
2665 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2666 Decls);
2667 }
2668
2669 FileDeclsTy::iterator I = FileDecls.find(File);
2670 if (I == FileDecls.end())
2671 return;
2672
2673 LocDeclsTy &LocDecls = *I->second;
2674 if (LocDecls.empty())
2675 return;
2676
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002677 LocDeclsTy::iterator BeginIt =
2678 std::lower_bound(LocDecls.begin(), LocDecls.end(),
Craig Topper49a27902014-05-22 04:46:25 +00002679 std::make_pair(Offset, (Decl *)nullptr),
2680 llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002681 if (BeginIt != LocDecls.begin())
2682 --BeginIt;
2683
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00002684 // If we are pointing at a top-level decl inside an objc container, we need
2685 // to backtrack until we find it otherwise we will fail to report that the
2686 // region overlaps with an objc container.
2687 while (BeginIt != LocDecls.begin() &&
2688 BeginIt->second->isTopLevelDeclInObjCContainer())
2689 --BeginIt;
2690
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002691 LocDeclsTy::iterator EndIt = std::upper_bound(
2692 LocDecls.begin(), LocDecls.end(),
Craig Topper49a27902014-05-22 04:46:25 +00002693 std::make_pair(Offset + Length, (Decl *)nullptr), llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002694 if (EndIt != LocDecls.end())
2695 ++EndIt;
2696
2697 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2698 Decls.push_back(DIt->second);
2699}
2700
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002701SourceLocation ASTUnit::getLocation(const FileEntry *File,
2702 unsigned Line, unsigned Col) const {
2703 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002704 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002705 return SM.getMacroArgExpandedLocation(Loc);
2706}
2707
2708SourceLocation ASTUnit::getLocation(const FileEntry *File,
2709 unsigned Offset) const {
2710 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002711 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002712 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2713}
2714
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002715/// \brief If \arg Loc is a loaded location from the preamble, returns
2716/// the corresponding local location of the main file, otherwise it returns
2717/// \arg Loc.
2718SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2719 FileID PreambleID;
2720 if (SourceMgr)
2721 PreambleID = SourceMgr->getPreambleFileID();
2722
2723 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2724 return Loc;
2725
2726 unsigned Offs;
2727 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2728 SourceLocation FileLoc
2729 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2730 return FileLoc.getLocWithOffset(Offs);
2731 }
2732
2733 return Loc;
2734}
2735
2736/// \brief If \arg Loc is a local location of the main file but inside the
2737/// preamble chunk, returns the corresponding loaded location from the
2738/// preamble, otherwise it returns \arg Loc.
2739SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2740 FileID PreambleID;
2741 if (SourceMgr)
2742 PreambleID = SourceMgr->getPreambleFileID();
2743
2744 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2745 return Loc;
2746
2747 unsigned Offs;
2748 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2749 Offs < Preamble.size()) {
2750 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2751 return FileLoc.getLocWithOffset(Offs);
2752 }
2753
2754 return Loc;
2755}
2756
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002757bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2758 FileID FID;
2759 if (SourceMgr)
2760 FID = SourceMgr->getPreambleFileID();
2761
2762 if (Loc.isInvalid() || FID.isInvalid())
2763 return false;
2764
2765 return SourceMgr->isInFileID(Loc, FID);
2766}
2767
2768bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2769 FileID FID;
2770 if (SourceMgr)
2771 FID = SourceMgr->getMainFileID();
2772
2773 if (Loc.isInvalid() || FID.isInvalid())
2774 return false;
2775
2776 return SourceMgr->isInFileID(Loc, FID);
2777}
2778
2779SourceLocation ASTUnit::getEndOfPreambleFileID() {
2780 FileID FID;
2781 if (SourceMgr)
2782 FID = SourceMgr->getPreambleFileID();
2783
2784 if (FID.isInvalid())
2785 return SourceLocation();
2786
2787 return SourceMgr->getLocForEndOfFile(FID);
2788}
2789
2790SourceLocation ASTUnit::getStartOfMainFileID() {
2791 FileID FID;
2792 if (SourceMgr)
2793 FID = SourceMgr->getMainFileID();
2794
2795 if (FID.isInvalid())
2796 return SourceLocation();
2797
2798 return SourceMgr->getLocForStartOfFile(FID);
2799}
2800
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002801std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
2802ASTUnit::getLocalPreprocessingEntities() const {
2803 if (isMainFileAST()) {
2804 serialization::ModuleFile &
2805 Mod = Reader->getModuleManager().getPrimaryModule();
2806 return Reader->getModulePreprocessedEntities(Mod);
2807 }
2808
2809 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2810 return std::make_pair(PPRec->local_begin(), PPRec->local_end());
2811
2812 return std::make_pair(PreprocessingRecord::iterator(),
2813 PreprocessingRecord::iterator());
2814}
2815
Argyrios Kyrtzidise514b202012-10-03 01:58:28 +00002816bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002817 if (isMainFileAST()) {
2818 serialization::ModuleFile &
2819 Mod = Reader->getModuleManager().getPrimaryModule();
2820 ASTReader::ModuleDeclIterator MDI, MDE;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002821 std::tie(MDI, MDE) = Reader->getModuleFileLevelDecls(Mod);
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002822 for (; MDI != MDE; ++MDI) {
2823 if (!Fn(context, *MDI))
2824 return false;
2825 }
2826
2827 return true;
2828 }
2829
2830 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2831 TLEnd = top_level_end();
2832 TL != TLEnd; ++TL) {
2833 if (!Fn(context, *TL))
2834 return false;
2835 }
2836
2837 return true;
2838}
2839
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002840namespace {
2841struct PCHLocatorInfo {
2842 serialization::ModuleFile *Mod;
Craig Topper49a27902014-05-22 04:46:25 +00002843 PCHLocatorInfo() : Mod(nullptr) {}
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002844};
2845}
2846
2847static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
2848 PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
2849 switch (M.Kind) {
2850 case serialization::MK_Module:
2851 return true; // skip dependencies.
2852 case serialization::MK_PCH:
2853 Info.Mod = &M;
2854 return true; // found it.
2855 case serialization::MK_Preamble:
2856 return false; // look in dependencies.
2857 case serialization::MK_MainFile:
2858 return false; // look in dependencies.
2859 }
2860
2861 return true;
2862}
2863
2864const FileEntry *ASTUnit::getPCHFile() {
2865 if (!Reader)
Craig Topper49a27902014-05-22 04:46:25 +00002866 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002867
2868 PCHLocatorInfo Info;
2869 Reader->getModuleManager().visit(PCHLocator, &Info);
2870 if (Info.Mod)
2871 return Info.Mod->File;
2872
Craig Topper49a27902014-05-22 04:46:25 +00002873 return nullptr;
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002874}
2875
Argyrios Kyrtzidise445c722012-10-10 02:12:47 +00002876bool ASTUnit::isModuleFile() {
2877 return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2878}
2879
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002880void ASTUnit::PreambleData::countLines() const {
2881 NumLines = 0;
2882 if (empty())
2883 return;
2884
2885 for (std::vector<char>::const_iterator
2886 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2887 if (*I == '\n')
2888 ++NumLines;
2889 }
2890 if (Buffer.back() != '\n')
2891 ++NumLines;
2892}
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002893
2894#ifndef NDEBUG
2895ASTUnit::ConcurrencyState::ConcurrencyState() {
2896 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2897}
2898
2899ASTUnit::ConcurrencyState::~ConcurrencyState() {
2900 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2901}
2902
2903void ASTUnit::ConcurrencyState::start() {
2904 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2905 assert(acquired && "Concurrent access to ASTUnit!");
2906}
2907
2908void ASTUnit::ConcurrencyState::finish() {
2909 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2910}
2911
2912#else // NDEBUG
2913
Alp Tokerb159c132013-11-22 07:49:39 +00002914ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = 0; }
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002915ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2916void ASTUnit::ConcurrencyState::start() {}
2917void ASTUnit::ConcurrencyState::finish() {}
2918
2919#endif