blob: 913bbc77dd3c409b1806cb46bf1acdf2c96e0a52 [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"
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +000039#include "llvm/Support/Atomic.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000040#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000041#include "llvm/Support/Host.h"
42#include "llvm/Support/MemoryBuffer.h"
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +000043#include "llvm/Support/Mutex.h"
Ted Kremenekbd307a52011-10-27 19:44:25 +000044#include "llvm/Support/MutexGuard.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000045#include "llvm/Support/Path.h"
46#include "llvm/Support/Timer.h"
47#include "llvm/Support/raw_ostream.h"
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.
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +0000214static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000215
Douglas Gregord03e8232010-04-05 21:10:19 +0000216ASTUnit::ASTUnit(bool _MainFileIsAST)
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +0000217 : Reader(0), HadModuleLoaderFatalFailure(false),
218 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),
Douglas Gregora0734c52010-08-19 01:33:06 +0000223 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Argyrios Kyrtzidis85b4a372011-11-29 18:18:33 +0000224 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) {
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000231 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +0000232 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Reid Klecknerc50b4bf2014-02-03 22:20:24 +0000233 fprintf(stderr, "+++ %d translation units\n", (int)ActiveASTUnitObjects);
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000234 }
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000235}
Douglas Gregord03e8232010-04-05 21:10:19 +0000236
Daniel Dunbar764c0822009-12-01 09:51:01 +0000237ASTUnit::~ASTUnit() {
Douglas Gregor6b930962013-05-03 22:58:43 +0000238 // If we loaded from an AST file, balance out the BeginSourceFile call.
239 if (MainFileIsAST && getDiagnostics().getClient()) {
240 getDiagnostics().getClient()->EndSourceFile();
241 }
242
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000243 clearFileLevelDecls();
244
Ted Kremenek06b4f912011-10-27 17:55:18 +0000245 // Clean up the temporary files and the preamble file.
246 removeOnDiskEntry(this);
247
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000248 // Free the buffers associated with remapped files. We are required to
249 // perform this operation here because we explicitly request that the
250 // compiler instance *not* free these buffers for each invocation of the
251 // parser.
Ted Kremenek5e14d392011-03-21 18:40:17 +0000252 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000253 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
254 for (PreprocessorOptions::remapped_file_buffer_iterator
255 FB = PPOpts.remapped_file_buffer_begin(),
256 FBEnd = PPOpts.remapped_file_buffer_end();
257 FB != FBEnd;
258 ++FB)
259 delete FB->second;
260 }
Douglas Gregor96c04262010-07-27 14:52:07 +0000261
262 delete SavedMainFileBuffer;
Douglas Gregora0734c52010-08-19 01:33:06 +0000263 delete PreambleBuffer;
264
Douglas Gregor16896c42010-10-28 15:44:59 +0000265 ClearCachedCompletionResults();
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000266
267 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +0000268 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Reid Klecknerc50b4bf2014-02-03 22:20:24 +0000269 fprintf(stderr, "--- %d translation units\n", (int)ActiveASTUnitObjects);
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000270 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000271}
272
Argyrios Kyrtzidisda6e0542012-01-17 18:48:07 +0000273void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
274
Douglas Gregor39982192010-08-15 06:18:01 +0000275/// \brief Determine the set of code-completion contexts in which this
276/// declaration should be shown.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000277static unsigned getDeclShowContexts(const NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000278 const LangOptions &LangOpts,
279 bool &IsNestedNameSpecifier) {
280 IsNestedNameSpecifier = false;
281
Douglas Gregor39982192010-08-15 06:18:01 +0000282 if (isa<UsingShadowDecl>(ND))
283 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
284 if (!ND)
285 return 0;
286
Richard Smith697cc9e2012-08-14 03:13:00 +0000287 uint64_t Contexts = 0;
Douglas Gregor39982192010-08-15 06:18:01 +0000288 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
289 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
290 // Types can appear in these contexts.
291 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000292 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
293 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
294 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
295 | (1LL << CodeCompletionContext::CCC_Statement)
296 | (1LL << CodeCompletionContext::CCC_Type)
297 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor39982192010-08-15 06:18:01 +0000298
299 // In C++, types can appear in expressions contexts (for functional casts).
300 if (LangOpts.CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +0000301 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor39982192010-08-15 06:18:01 +0000302
303 // In Objective-C, message sends can send interfaces. In Objective-C++,
304 // all types are available due to functional casts.
305 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000306 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor21325842011-07-07 16:03:39 +0000307
308 // In Objective-C, you can only be a subclass of another Objective-C class
309 if (isa<ObjCInterfaceDecl>(ND))
Richard Smith697cc9e2012-08-14 03:13:00 +0000310 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor39982192010-08-15 06:18:01 +0000311
312 // Deal with tag names.
313 if (isa<EnumDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000314 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000315
Douglas Gregor59cab552010-08-16 23:05:20 +0000316 // Part of the nested-name-specifier in C++0x.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000317 if (LangOpts.CPlusPlus11)
Douglas Gregor59cab552010-08-16 23:05:20 +0000318 IsNestedNameSpecifier = true;
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000319 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
Douglas Gregor39982192010-08-15 06:18:01 +0000320 if (Record->isUnion())
Richard Smith697cc9e2012-08-14 03:13:00 +0000321 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000322 else
Richard Smith697cc9e2012-08-14 03:13:00 +0000323 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor39982192010-08-15 06:18:01 +0000324
Douglas Gregor39982192010-08-15 06:18:01 +0000325 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000326 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000327 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000328 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000329 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
330 // Values can appear in these contexts.
Richard Smith697cc9e2012-08-14 03:13:00 +0000331 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
332 | (1LL << CodeCompletionContext::CCC_Expression)
333 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
334 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor39982192010-08-15 06:18:01 +0000335 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000336 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor21325842011-07-07 16:03:39 +0000337 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000338 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor39982192010-08-15 06:18:01 +0000339 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith697cc9e2012-08-14 03:13:00 +0000340 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor39982192010-08-15 06:18:01 +0000341
342 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000343 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000344 }
345
346 return Contexts;
347}
348
Douglas Gregorb14904c2010-08-13 22:48:40 +0000349void ASTUnit::CacheCodeCompletionResults() {
350 if (!TheSema)
351 return;
352
Douglas Gregor16896c42010-10-28 15:44:59 +0000353 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000354 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000355
356 // Clear out the previous results.
357 ClearCachedCompletionResults();
358
359 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000360 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000361 SmallVector<Result, 8> Results;
Douglas Gregor162b7122011-02-16 19:08:06 +0000362 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000363 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000364 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000365 CCTUInfo, Results);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000366
367 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000368 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
369
Douglas Gregorb14904c2010-08-13 22:48:40 +0000370 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
371 switch (Results[I].Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000372 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000373 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000374 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000375 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000376 *CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000377 CCTUInfo,
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000378 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor39982192010-08-15 06:18:01 +0000379 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000380 Ctx->getLangOpts(),
Douglas Gregor59cab552010-08-16 23:05:20 +0000381 IsNestedNameSpecifier);
Douglas Gregor39982192010-08-15 06:18:01 +0000382 CachedResult.Priority = Results[I].Priority;
383 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000384 CachedResult.Availability = Results[I].Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000385
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000386 // Keep track of the type of this completion in an ASTContext-agnostic
387 // way.
Douglas Gregor24747402010-08-16 16:46:30 +0000388 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000389 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000390 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000391 CachedResult.Type = 0;
392 } else {
393 CanQualType CanUsageType
394 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
395 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
396
397 // Determine whether we have already seen this type. If so, we save
398 // ourselves the work of formatting the type string by using the
399 // temporary, CanQualType-based hash table to find the associated value.
400 unsigned &TypeValue = CompletionTypes[CanUsageType];
401 if (TypeValue == 0) {
402 TypeValue = CompletionTypes.size();
403 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
404 = TypeValue;
405 }
406
407 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000408 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000409
Douglas Gregor39982192010-08-15 06:18:01 +0000410 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000411
412 /// Handle nested-name-specifiers in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000413 if (TheSema->Context.getLangOpts().CPlusPlus &&
Douglas Gregor59cab552010-08-16 23:05:20 +0000414 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
415 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith697cc9e2012-08-14 03:13:00 +0000416 uint64_t NNSContexts
417 = (1LL << CodeCompletionContext::CCC_TopLevel)
418 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
419 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
420 | (1LL << CodeCompletionContext::CCC_Statement)
421 | (1LL << CodeCompletionContext::CCC_Expression)
422 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
423 | (1LL << CodeCompletionContext::CCC_EnumTag)
424 | (1LL << CodeCompletionContext::CCC_UnionTag)
425 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
426 | (1LL << CodeCompletionContext::CCC_Type)
427 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
428 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor59cab552010-08-16 23:05:20 +0000429
430 if (isa<NamespaceDecl>(Results[I].Declaration) ||
431 isa<NamespaceAliasDecl>(Results[I].Declaration))
Richard Smith697cc9e2012-08-14 03:13:00 +0000432 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor59cab552010-08-16 23:05:20 +0000433
434 if (unsigned RemainingContexts
435 = NNSContexts & ~CachedResult.ShowInContexts) {
436 // If there any contexts where this completion can be a
437 // nested-name-specifier but isn't already an option, create a
438 // nested-name-specifier completion.
439 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000440 CachedResult.Completion
441 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000442 *CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000443 CCTUInfo,
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000444 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor59cab552010-08-16 23:05:20 +0000445 CachedResult.ShowInContexts = RemainingContexts;
446 CachedResult.Priority = CCP_NestedNameSpecifier;
447 CachedResult.TypeClass = STC_Void;
448 CachedResult.Type = 0;
449 CachedCompletionResults.push_back(CachedResult);
450 }
451 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000452 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000453 }
454
Douglas Gregorb14904c2010-08-13 22:48:40 +0000455 case Result::RK_Keyword:
456 case Result::RK_Pattern:
457 // Ignore keywords and patterns; we don't care, since they are so
458 // easily regenerated.
459 break;
460
461 case Result::RK_Macro: {
462 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000463 CachedResult.Completion
464 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000465 *CachedCompletionAllocator,
Argyrios Kyrtzidis2bafa002012-11-16 03:34:57 +0000466 CCTUInfo,
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000467 IncludeBriefCommentsInCodeCompletion);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000468 CachedResult.ShowInContexts
Richard Smith697cc9e2012-08-14 03:13:00 +0000469 = (1LL << CodeCompletionContext::CCC_TopLevel)
470 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
471 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
472 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
473 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
474 | (1LL << CodeCompletionContext::CCC_Statement)
475 | (1LL << CodeCompletionContext::CCC_Expression)
476 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
477 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
478 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
479 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
480 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000481
Douglas Gregorb14904c2010-08-13 22:48:40 +0000482 CachedResult.Priority = Results[I].Priority;
483 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000484 CachedResult.Availability = Results[I].Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000485 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000486 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000487 CachedCompletionResults.push_back(CachedResult);
488 break;
489 }
490 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000491 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000492
493 // Save the current top-level hash value.
494 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000495}
496
497void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregorb14904c2010-08-13 22:48:40 +0000498 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000499 CachedCompletionTypes.clear();
Douglas Gregor162b7122011-02-16 19:08:06 +0000500 CachedCompletionAllocator = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000501}
502
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000503namespace {
504
Sebastian Redl2c499f62010-08-18 23:56:43 +0000505/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000506/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000507class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor83297df2011-09-01 23:39:15 +0000508 Preprocessor &PP;
Douglas Gregore8bbc122011-09-02 00:18:52 +0000509 ASTContext &Context;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000510 LangOptions &LangOpt;
Douglas Gregorcb177f12012-10-16 23:40:58 +0000511 IntrusiveRefCntPtr<TargetOptions> &TargetOpts;
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000512 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000513 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000514
Douglas Gregore8bbc122011-09-02 00:18:52 +0000515 bool InitializedLanguage;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000516public:
Douglas Gregore8bbc122011-09-02 00:18:52 +0000517 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
Douglas Gregorcb177f12012-10-16 23:40:58 +0000518 IntrusiveRefCntPtr<TargetOptions> &TargetOpts,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000519 IntrusiveRefCntPtr<TargetInfo> &Target,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000520 unsigned &Counter)
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +0000521 : PP(PP), Context(Context), LangOpt(LangOpt),
Douglas Gregorbc10b9f2012-10-15 16:45:32 +0000522 TargetOpts(TargetOpts), Target(Target),
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +0000523 Counter(Counter),
Douglas Gregore8bbc122011-09-02 00:18:52 +0000524 InitializedLanguage(false) {}
Mike Stump11289f42009-09-09 15:08:12 +0000525
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000526 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
Douglas Gregor4b29c162012-10-22 23:51:00 +0000527 bool Complain) {
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000528 if (InitializedLanguage)
Douglas Gregor83297df2011-09-01 23:39:15 +0000529 return false;
530
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000531 LangOpt = LangOpts;
532 InitializedLanguage = true;
533
534 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000535 return false;
536 }
Mike Stump11289f42009-09-09 15:08:12 +0000537
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000538 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
Douglas Gregor4b29c162012-10-22 23:51:00 +0000539 bool Complain) {
Douglas Gregor83297df2011-09-01 23:39:15 +0000540 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000541 if (Target)
Douglas Gregor83297df2011-09-01 23:39:15 +0000542 return false;
543
Douglas Gregorcb177f12012-10-16 23:40:58 +0000544 this->TargetOpts = new TargetOptions(TargetOpts);
Douglas Gregorf8715de2012-11-16 04:24:59 +0000545 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(),
546 &*this->TargetOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000547
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000548 updated();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000549 return false;
550 }
Mike Stump11289f42009-09-09 15:08:12 +0000551
Argyrios Kyrtzidise445c722012-10-10 02:12:47 +0000552 virtual void ReadCounter(const serialization::ModuleFile &M, unsigned Value) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000553 Counter = Value;
554 }
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000555
556private:
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000557 void updated() {
558 if (!Target || !InitializedLanguage)
559 return;
560
561 // Inform the target of the language options.
562 //
563 // FIXME: We shouldn't need to do this, the target should be immutable once
564 // created. This complexity should be lifted elsewhere.
565 Target->setForcedLangOptions(LangOpt);
566
567 // Initialize the preprocessor.
568 PP.Initialize(*Target);
569
570 // Initialize the ASTContext
571 Context.InitBuiltinTypes(*Target);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000572
573 // We didn't have access to the comment options when the ASTContext was
574 // constructed, so register them now.
575 Context.getCommentCommandTraits().registerCommentOptions(
576 LangOpt.CommentOpts);
Argyrios Kyrtzidis9e1fb562012-09-14 20:24:53 +0000577 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000578};
579
Douglas Gregor6b930962013-05-03 22:58:43 +0000580 /// \brief Diagnostic consumer that saves each diagnostic it is given.
David Blaikief18d91a2011-09-26 00:01:39 +0000581class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000582 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregor6b930962013-05-03 22:58:43 +0000583 SourceManager *SourceMgr;
584
Douglas Gregor33cdd812010-02-18 18:08:43 +0000585public:
David Blaikief18d91a2011-09-26 00:01:39 +0000586 explicit StoredDiagnosticConsumer(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000587 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregor6b930962013-05-03 22:58:43 +0000588 : StoredDiags(StoredDiags), SourceMgr(0) { }
589
590 virtual void BeginSourceFile(const LangOptions &LangOpts,
591 const Preprocessor *PP = 0) {
592 if (PP)
593 SourceMgr = &PP->getSourceManager();
594 }
595
David Blaikie9c902b52011-09-25 23:23:43 +0000596 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +0000597 const Diagnostic &Info);
Douglas Gregor33cdd812010-02-18 18:08:43 +0000598};
599
600/// \brief RAII object that optionally captures diagnostics, if
601/// there is no diagnostic client to capture them already.
602class CaptureDroppedDiagnostics {
David Blaikie9c902b52011-09-25 23:23:43 +0000603 DiagnosticsEngine &Diags;
David Blaikief18d91a2011-09-26 00:01:39 +0000604 StoredDiagnosticConsumer Client;
David Blaikiee2eefae2011-09-25 23:39:51 +0000605 DiagnosticConsumer *PreviousClient;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000606
607public:
David Blaikie9c902b52011-09-25 23:23:43 +0000608 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000609 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000610 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000611 {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000612 if (RequestCapture || Diags.getClient() == 0) {
613 PreviousClient = Diags.takeClient();
Douglas Gregor33cdd812010-02-18 18:08:43 +0000614 Diags.setClient(&Client);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000615 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000616 }
617
618 ~CaptureDroppedDiagnostics() {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000619 if (Diags.getClient() == &Client) {
620 Diags.takeClient();
621 Diags.setClient(PreviousClient);
622 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000623 }
624};
625
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000626} // anonymous namespace
627
David Blaikief18d91a2011-09-26 00:01:39 +0000628void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +0000629 const Diagnostic &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000630 // Default implementation (Warnings/errors count).
David Blaikiee2eefae2011-09-25 23:39:51 +0000631 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000632
Douglas Gregor6b930962013-05-03 22:58:43 +0000633 // Only record the diagnostic if it's part of the source manager we know
634 // about. This effectively drops diagnostics from modules we're building.
635 // FIXME: In the long run, ee don't want to drop source managers from modules.
636 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
637 StoredDiags.push_back(StoredDiagnostic(Level, Info));
Douglas Gregor33cdd812010-02-18 18:08:43 +0000638}
639
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000640ASTMutationListener *ASTUnit::getASTMutationListener() {
641 if (WriterData)
642 return &WriterData->Writer;
643 return 0;
644}
645
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000646ASTDeserializationListener *ASTUnit::getDeserializationListener() {
647 if (WriterData)
648 return &WriterData->Writer;
649 return 0;
650}
651
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000652llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner26b5c192010-11-23 09:19:42 +0000653 std::string *ErrorStr) {
Chris Lattner5159f612010-11-23 08:35:12 +0000654 assert(FileMgr);
Chris Lattner26b5c192010-11-23 09:19:42 +0000655 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000656}
657
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000658/// \brief Configure the diagnostics object for use with ASTUnit.
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000659void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000660 const char **ArgBegin, const char **ArgEnd,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000661 ASTUnit &AST, bool CaptureDiagnostics) {
662 if (!Diags.getPtr()) {
663 // No diagnostics engine was provided, so create our own diagnostics object
664 // with the default options.
David Blaikiee2eefae2011-09-25 23:39:51 +0000665 DiagnosticConsumer *Client = 0;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000666 if (CaptureDiagnostics)
David Blaikief18d91a2011-09-26 00:01:39 +0000667 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Douglas Gregor811db4e2012-10-23 22:26:28 +0000668 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions(),
Sean Silvaf1b49e22013-01-20 01:58:28 +0000669 Client,
Douglas Gregor30071cea2013-05-03 23:07:45 +0000670 /*ShouldOwnClient=*/true);
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000671 } else if (CaptureDiagnostics) {
David Blaikief18d91a2011-09-26 00:01:39 +0000672 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000673 }
674}
675
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000676ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000677 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000678 const FileSystemOptions &FileSystemOpts,
Ted Kremenek8bcb1c62009-10-17 00:34:24 +0000679 bool OnlyLocalDecls,
Dmitri Gribenko2febd212014-02-07 15:00:22 +0000680 ArrayRef<RemappedFile> RemappedFiles,
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +0000681 bool CaptureDiagnostics,
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000682 bool AllowPCHWithCompilerErrors,
683 bool UserFilesAreVolatile) {
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000684 OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000685
686 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +0000687 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
688 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +0000689 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
690 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek022a4902011-03-22 01:15:24 +0000691 DiagCleanup(Diags.getPtr());
Ted Kremenek4422bfe2011-03-18 02:06:56 +0000692
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000693 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000694
Douglas Gregor16bef852009-10-16 20:01:17 +0000695 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000696 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000697 AST->Diagnostics = Diags;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000698 AST->FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000699 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek5e14d392011-03-21 18:40:17 +0000700 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +0000701 AST->getFileManager(),
702 UserFilesAreVolatile);
Douglas Gregorb85b9cc2012-10-24 16:19:39 +0000703 AST->HSOpts = new HeaderSearchOptions();
704
705 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
Manuel Klimek1f76c4e2013-10-24 07:51:24 +0000706 AST->getSourceManager(),
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000707 AST->getDiagnostics(),
Douglas Gregor89929282012-01-30 06:01:29 +0000708 AST->ASTFileLangOpts,
709 /*Target=*/0));
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000710
Dmitri Gribenkob41e7e22014-02-10 12:31:34 +0000711 PreprocessorOptions *PPOpts = new PreprocessorOptions();
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000712
Dmitri Gribenkob41e7e22014-02-10 12:31:34 +0000713 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I)
714 PPOpts->addRemappedFile(RemappedFiles[I].first, RemappedFiles[I].second);
Dmitri Gribenkoc444b572014-02-08 00:38:15 +0000715
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000716 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000717
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000718 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000719 unsigned Counter;
720
Dmitri Gribenkob41e7e22014-02-10 12:31:34 +0000721 AST->PP = new Preprocessor(PPOpts,
Douglas Gregor1452ff12012-10-24 17:46:57 +0000722 AST->getDiagnostics(), AST->ASTFileLangOpts,
Douglas Gregor83297df2011-09-01 23:39:15 +0000723 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
724 *AST,
725 /*IILookup=*/0,
726 /*OwnsHeaderSearch=*/false,
727 /*DelayInitialization=*/true);
Douglas Gregore8bbc122011-09-02 00:18:52 +0000728 Preprocessor &PP = *AST->PP;
729
730 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
731 AST->getSourceManager(),
732 /*Target=*/0,
733 PP.getIdentifierTable(),
734 PP.getSelectorTable(),
735 PP.getBuiltinInfo(),
736 /* size_reserve = */0,
737 /*DelayInitialization=*/true);
738 ASTContext &Context = *AST->Ctx;
Douglas Gregor83297df2011-09-01 23:39:15 +0000739
Argyrios Kyrtzidis945a8192012-09-15 01:10:20 +0000740 bool disableValid = false;
741 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
742 disableValid = true;
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000743 AST->Reader = new ASTReader(PP, Context,
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +0000744 /*isysroot=*/"",
Argyrios Kyrtzidis945a8192012-09-15 01:10:20 +0000745 /*DisableValidation=*/disableValid,
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000746 AllowPCHWithCompilerErrors);
Ted Kremenek2159b8d2011-05-04 23:27:12 +0000747
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000748 AST->Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +0000749 AST->ASTFileLangOpts,
Douglas Gregorbc10b9f2012-10-15 16:45:32 +0000750 AST->TargetOpts, AST->Target,
Douglas Gregord02437c2012-10-25 00:09:28 +0000751 Counter));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000752
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000753 switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis2ec29362012-11-15 18:57:22 +0000754 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000755 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000756 break;
Mike Stump11289f42009-09-09 15:08:12 +0000757
Sebastian Redl2c499f62010-08-18 23:56:43 +0000758 case ASTReader::Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +0000759 case ASTReader::Missing:
Douglas Gregorc9ad5fb2012-10-22 22:50:17 +0000760 case ASTReader::OutOfDate:
761 case ASTReader::VersionMismatch:
762 case ASTReader::ConfigurationMismatch:
763 case ASTReader::HadErrors:
Douglas Gregord03e8232010-04-05 21:10:19 +0000764 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000765 return NULL;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000766 }
Mike Stump11289f42009-09-09 15:08:12 +0000767
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000768 AST->OriginalSourceFile = AST->Reader->getOriginalSourceFile();
Daniel Dunbara8a50932009-12-02 08:44:16 +0000769
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000770 PP.setCounterValue(Counter);
Mike Stump11289f42009-09-09 15:08:12 +0000771
Sebastian Redl2c499f62010-08-18 23:56:43 +0000772 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000773 // source, so that declarations will be deserialized from the
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000774 // AST file as needed.
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000775 Context.setExternalSource(AST->Reader);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000776
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000777 // Create an AST consumer, even though it isn't used.
778 AST->Consumer.reset(new ASTConsumer);
779
Sebastian Redl2c499f62010-08-18 23:56:43 +0000780 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000781 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
782 AST->TheSema->Initialize();
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000783 AST->Reader->InitializeSema(*AST->TheSema);
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000784
Douglas Gregor6b930962013-05-03 22:58:43 +0000785 // Tell the diagnostic client that we have started a source file.
786 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
787
Mike Stump11289f42009-09-09 15:08:12 +0000788 return AST.take();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000789}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000790
791namespace {
792
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000793/// \brief Preprocessor callback class that updates a hash value with the names
794/// of all macros that have been defined by the translation unit.
795class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
796 unsigned &Hash;
797
798public:
799 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
800
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000801 virtual void MacroDefined(const Token &MacroNameTok,
802 const MacroDirective *MD) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000803 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
804 }
805};
806
807/// \brief Add the given declaration to the hash of all top-level entities.
808void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
809 if (!D)
810 return;
811
812 DeclContext *DC = D->getDeclContext();
813 if (!DC)
814 return;
815
816 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
817 return;
818
819 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
Argyrios Kyrtzidisca5c7be2013-10-15 17:37:55 +0000820 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
821 // For an unscoped enum include the enumerators in the hash since they
822 // enter the top-level namespace.
823 if (!EnumD->isScoped()) {
824 for (EnumDecl::enumerator_iterator EI = EnumD->enumerator_begin(),
825 EE = EnumD->enumerator_end(); EI != EE; ++EI) {
826 if ((*EI)->getIdentifier())
827 Hash = llvm::HashString((*EI)->getIdentifier()->getName(), Hash);
828 }
829 }
830 }
831
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000832 if (ND->getIdentifier())
833 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
834 else if (DeclarationName Name = ND->getDeclName()) {
835 std::string NameStr = Name.getAsString();
836 Hash = llvm::HashString(NameStr, Hash);
837 }
838 return;
Argyrios Kyrtzidis48d88de2013-06-24 21:19:12 +0000839 }
840
841 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
842 if (Module *Mod = ImportD->getImportedModule()) {
843 std::string ModName = Mod->getFullModuleName();
844 Hash = llvm::HashString(ModName, Hash);
845 }
846 return;
847 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000848}
849
Daniel Dunbar644dca02009-12-04 08:17:33 +0000850class TopLevelDeclTrackerConsumer : public ASTConsumer {
851 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000852 unsigned &Hash;
853
Daniel Dunbar644dca02009-12-04 08:17:33 +0000854public:
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000855 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
856 : Unit(_Unit), Hash(Hash) {
857 Hash = 0;
858 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000859
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000860 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis516eec22011-11-16 02:35:10 +0000861 if (!D)
862 return;
863
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000864 // FIXME: Currently ObjC method declarations are incorrectly being
865 // reported as top-level declarations, even though their DeclContext
866 // is the containing ObjC @interface/@implementation. This is a
867 // fundamental problem in the parser right now.
868 if (isa<ObjCMethodDecl>(D))
869 return;
870
871 AddTopLevelDeclarationToHash(D, Hash);
872 Unit.addTopLevelDecl(D);
873
874 handleFileLevelDecl(D);
875 }
876
877 void handleFileLevelDecl(Decl *D) {
878 Unit.addFileLevelDecl(D);
879 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
880 for (NamespaceDecl::decl_iterator
881 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
882 handleFileLevelDecl(*I);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000883 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000884 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000885
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000886 bool HandleTopLevelDecl(DeclGroupRef D) {
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000887 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
888 handleTopLevelDecl(*it);
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000889 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000890 }
891
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000892 // We're not interested in "interesting" decls.
893 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +0000894
895 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
896 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
897 handleTopLevelDecl(*it);
898 }
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000899
Argyrios Kyrtzidis1c7455f2013-05-10 01:28:51 +0000900 virtual ASTMutationListener *GetASTMutationListener() {
901 return Unit.getASTMutationListener();
902 }
903
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +0000904 virtual ASTDeserializationListener *GetASTDeserializationListener() {
905 return Unit.getDeserializationListener();
906 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000907};
908
909class TopLevelDeclTrackerAction : public ASTFrontendAction {
910public:
911 ASTUnit &Unit;
912
Daniel Dunbar764c0822009-12-01 09:51:01 +0000913 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000914 StringRef InFile) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000915 CI.getPreprocessor().addPPCallbacks(
916 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
917 return new TopLevelDeclTrackerConsumer(Unit,
918 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000919 }
920
921public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000922 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
923
Daniel Dunbar764c0822009-12-01 09:51:01 +0000924 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor69f74f82011-08-25 22:30:56 +0000925 virtual TranslationUnitKind getTranslationUnitKind() {
926 return Unit.getTranslationUnitKind();
Douglas Gregor028d3e42010-08-09 20:45:32 +0000927 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000928};
929
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000930class PrecompilePreambleAction : public ASTFrontendAction {
931 ASTUnit &Unit;
932 bool HasEmittedPreamblePCH;
933
934public:
935 explicit PrecompilePreambleAction(ASTUnit &Unit)
936 : Unit(Unit), HasEmittedPreamblePCH(false) {}
937
938 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
939 StringRef InFile);
940 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
941 void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH = true; }
942 virtual bool shouldEraseOutputFiles() { return !hasEmittedPreamblePCH(); }
943
944 virtual bool hasCodeCompletionSupport() const { return false; }
945 virtual bool hasASTFileSupport() const { return false; }
946 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
947};
948
Argyrios Kyrtzidis57332712011-09-19 20:40:48 +0000949class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000950 ASTUnit &Unit;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000951 unsigned &Hash;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000952 std::vector<Decl *> TopLevelDecls;
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000953 PrecompilePreambleAction *Action;
954
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000955public:
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000956 PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action,
957 const Preprocessor &PP, StringRef isysroot,
958 raw_ostream *Out)
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +0000959 : PCHGenerator(PP, "", 0, isysroot, Out, /*AllowASTWithErrors=*/true),
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000960 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000961 Hash = 0;
962 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000963
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000964 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000965 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
966 Decl *D = *it;
967 // FIXME: Currently ObjC method declarations are incorrectly being
968 // reported as top-level declarations, even though their DeclContext
969 // is the containing ObjC @interface/@implementation. This is a
970 // fundamental problem in the parser right now.
971 if (isa<ObjCMethodDecl>(D))
972 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000973 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000974 TopLevelDecls.push_back(D);
975 }
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000976 return true;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000977 }
978
979 virtual void HandleTranslationUnit(ASTContext &Ctx) {
980 PCHGenerator::HandleTranslationUnit(Ctx);
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +0000981 if (hasEmittedPCH()) {
Douglas Gregore9db88f2010-08-03 19:06:41 +0000982 // Translate the top-level declarations we captured during
983 // parsing into declaration IDs in the precompiled
984 // preamble. This will allow us to deserialize those top-level
985 // declarations when requested.
Argyrios Kyrtzidisacfbbd72013-08-07 21:17:33 +0000986 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I) {
987 Decl *D = TopLevelDecls[I];
988 // Invalid top-level decls may not have been serialized.
989 if (D->isInvalidDecl())
990 continue;
991 Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
992 }
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000993
994 Action->setHasEmittedPreamblePCH();
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000995 }
996 }
997};
998
Benjamin Kramer65745dc2013-06-11 13:07:19 +0000999}
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001000
Benjamin Kramer65745dc2013-06-11 13:07:19 +00001001ASTConsumer *PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
1002 StringRef InFile) {
1003 std::string Sysroot;
1004 std::string OutputFile;
1005 raw_ostream *OS = 0;
1006 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
1007 OutputFile, OS))
1008 return 0;
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001009
Benjamin Kramer65745dc2013-06-11 13:07:19 +00001010 if (!CI.getFrontendOpts().RelocatablePCH)
1011 Sysroot.clear();
Douglas Gregorc567ba22011-07-22 16:35:34 +00001012
Benjamin Kramer65745dc2013-06-11 13:07:19 +00001013 CI.getPreprocessor().addPPCallbacks(new MacroDefinitionTrackerPPCallbacks(
1014 Unit.getCurrentTopLevelHashValue()));
1015 return new PrecompilePreambleConsumer(Unit, this, CI.getPreprocessor(),
1016 Sysroot, OS);
Daniel Dunbar764c0822009-12-01 09:51:01 +00001017}
1018
Benjamin Kramer1ce5d802013-05-05 12:39:28 +00001019static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
1020 return StoredDiag.getLocation().isValid();
1021}
1022
1023static void
1024checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001025 // Get rid of stored diagnostics except the ones from the driver which do not
1026 // have a source location.
Benjamin Kramer1ce5d802013-05-05 12:39:28 +00001027 StoredDiags.erase(
1028 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1029 StoredDiags.end());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001030}
1031
1032static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1033 StoredDiagnostics,
1034 SourceManager &SM) {
1035 // The stored diagnostic has the old source manager in it; update
1036 // the locations to refer into the new source manager. Since we've
1037 // been careful to make sure that the source manager's state
1038 // before and after are identical, so that we can reuse the source
1039 // location itself.
1040 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1041 if (StoredDiagnostics[I].getLocation().isValid()) {
1042 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1043 StoredDiagnostics[I].setLocation(Loc);
1044 }
1045 }
1046}
1047
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001048/// Parse the source file into a translation unit using the given compiler
1049/// invocation, replacing the current translation unit.
1050///
1051/// \returns True if a failure occurred that causes the ASTUnit not to
1052/// contain any translation-unit information, false otherwise.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001053bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor96c04262010-07-27 14:52:07 +00001054 delete SavedMainFileBuffer;
1055 SavedMainFileBuffer = 0;
1056
Ted Kremenek5e14d392011-03-21 18:40:17 +00001057 if (!Invocation) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001058 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001059 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001060 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001061
Daniel Dunbar764c0822009-12-01 09:51:01 +00001062 // Create the compiler instance to use for building the AST.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001063 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001064
1065 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001066 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1067 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001068
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001069 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis14c32e82011-09-12 18:09:38 +00001070 CCInvocation(new CompilerInvocation(*Invocation));
1071
1072 Clang->setInvocation(CCInvocation.getPtr());
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001073 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001074
Douglas Gregor8e984da2010-08-04 16:47:14 +00001075 // Set up diagnostics, capturing any diagnostics that would
1076 // otherwise be dropped.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001077 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +00001078
Daniel Dunbar764c0822009-12-01 09:51:01 +00001079 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001080 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregorf8715de2012-11-16 04:24:59 +00001081 &Clang->getTargetOpts()));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001082 if (!Clang->hasTarget()) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001083 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001084 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +00001085 }
1086
Daniel Dunbar764c0822009-12-01 09:51:01 +00001087 // Inform the target of the language options.
1088 //
1089 // FIXME: We shouldn't need to do this, the target should be immutable once
1090 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001091 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001092
Ted Kremenek84de4a12011-03-21 18:40:07 +00001093 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001094 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001095 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +00001096 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001097 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Daniel Dunbar9507f9c2010-06-07 23:26:47 +00001098 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +00001099
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001100 // Configure the various subsystems.
1101 // FIXME: Should we retain the previous file manager?
Ted Kremenek8cf47df2011-11-17 23:01:24 +00001102 LangOpts = &Clang->getLangOpts();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001103 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001104 FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001105 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1106 UserFilesAreVolatile);
Douglas Gregor6fd55e02010-08-13 03:15:25 +00001107 TheSema.reset();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001108 Ctx = 0;
1109 PP = 0;
Argyrios Kyrtzidis244ce8b2011-11-01 17:14:15 +00001110 Reader = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001111
1112 // Clear out old caches and data.
1113 TopLevelDecls.clear();
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00001114 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001115 CleanTemporaryFiles();
Douglas Gregord9a30af2010-08-02 20:51:39 +00001116
Douglas Gregor7b02b582010-08-20 00:02:33 +00001117 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001118 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001119 TopLevelDeclsInPreamble.clear();
1120 }
1121
Daniel Dunbar764c0822009-12-01 09:51:01 +00001122 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001123 Clang->setFileManager(&getFileManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001124
Daniel Dunbar764c0822009-12-01 09:51:01 +00001125 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001126 Clang->setSourceManager(&getSourceManager());
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001127
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001128 // If the main file has been overridden due to the use of a preamble,
1129 // make that override happen and introduce the preamble.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001130 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001131 if (OverrideMainBuffer) {
1132 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1133 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1134 PreprocessorOpts.PrecompiledPreambleBytes.second
1135 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00001136 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorce3a8292010-07-27 00:27:13 +00001137 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +00001138
Douglas Gregord9a30af2010-08-02 20:51:39 +00001139 // The stored diagnostic has the old source manager in it; update
1140 // the locations to refer into the new source manager. Since we've
1141 // been careful to make sure that the source manager's state
1142 // before and after are identical, so that we can reuse the source
1143 // location itself.
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001144 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001145
1146 // Keep track of the override buffer;
1147 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001148 }
1149
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001150 OwningPtr<TopLevelDeclTrackerAction> Act(
Ted Kremenek022a4902011-03-22 01:15:24 +00001151 new TopLevelDeclTrackerAction(*this));
1152
1153 // Recover resources if we crash before exiting this method.
1154 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1155 ActCleanup(Act.get());
1156
Douglas Gregor32fbe312012-01-20 16:28:04 +00001157 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar764c0822009-12-01 09:51:01 +00001158 goto error;
Douglas Gregor925296b2011-07-19 16:10:42 +00001159
1160 if (OverrideMainBuffer) {
Ted Kremenek06b4f912011-10-27 17:55:18 +00001161 std::string ModName = getPreambleFile(this);
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001162 TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1163 PreambleDiagnostics, StoredDiagnostics);
Douglas Gregor925296b2011-07-19 16:10:42 +00001164 }
1165
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001166 if (!Act->Execute())
1167 goto error;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001168
1169 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001170
Daniel Dunbar644dca02009-12-04 08:17:33 +00001171 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001172
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001173 FailedParseDiagnostics.clear();
1174
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001175 return false;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001176
Daniel Dunbar764c0822009-12-01 09:51:01 +00001177error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001178 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +00001179 if (OverrideMainBuffer) {
Douglas Gregora0734c52010-08-19 01:33:06 +00001180 delete OverrideMainBuffer;
Douglas Gregora3d3ba12010-10-06 21:11:08 +00001181 SavedMainFileBuffer = 0;
Douglas Gregorce3a8292010-07-27 00:27:13 +00001182 }
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001183
1184 // Keep the ownership of the data in the ASTUnit because the client may
1185 // want to see the diagnostics.
1186 transferASTDataFromCompilerInstance(*Clang);
1187 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregorefc46952010-10-12 16:25:54 +00001188 StoredDiagnostics.clear();
Argyrios Kyrtzidis067cbfa2011-10-24 17:25:20 +00001189 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001190 return true;
1191}
1192
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001193/// \brief Simple function to retrieve a path for a preamble precompiled header.
1194static std::string GetPreamblePCHPath() {
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001195 // FIXME: This is a hack so that we can override the preamble file during
1196 // crash-recovery testing, which is the only case where the preamble files
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001197 // are not necessarily cleaned up.
Douglas Gregor250ab1d2010-09-11 18:05:19 +00001198 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1199 if (TmpFile)
1200 return TmpFile;
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001201
1202 SmallString<128> Path;
Rafael Espindolaa36e78e2013-07-05 20:00:06 +00001203 llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
Rafael Espindolabc4aa552013-06-26 04:02:37 +00001204
1205 return Path.str();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001206}
1207
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001208/// \brief Compute the preamble for the main file, providing the source buffer
1209/// that corresponds to the main file along with a pair (bytes, start-of-line)
1210/// that describes the preamble.
1211std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor028d3e42010-08-09 20:45:32 +00001212ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1213 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001214 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner5159f612010-11-23 08:35:12 +00001215 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001216 CreatedBuffer = false;
1217
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001218 // Try to determine if the main file has been remapped, either from the
1219 // command line (to another file) or directly through the compiler invocation
1220 // (to a memory buffer).
Douglas Gregor4dde7492010-07-23 23:58:40 +00001221 llvm::MemoryBuffer *Buffer = 0;
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001222 std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
Rafael Espindola073ff102013-07-29 21:26:52 +00001223 llvm::sys::fs::UniqueID MainFileID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001224 if (!llvm::sys::fs::getUniqueID(MainFilePath, MainFileID)) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001225 // Check whether there is a file-file remapping of the main file
1226 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor4dde7492010-07-23 23:58:40 +00001227 M = PreprocessorOpts.remapped_file_begin(),
1228 E = PreprocessorOpts.remapped_file_end();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001229 M != E;
1230 ++M) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001231 std::string MPath(M->first);
Rafael Espindola073ff102013-07-29 21:26:52 +00001232 llvm::sys::fs::UniqueID MID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001233 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001234 if (MainFileID == MID) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001235 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001236 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001237 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001238 CreatedBuffer = false;
1239 }
1240
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001241 Buffer = getBufferForFile(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001242 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001243 return std::make_pair((llvm::MemoryBuffer*)0,
1244 std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001245 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001246 }
1247 }
1248 }
1249
1250 // Check whether there is a file-buffer remapping. It supercedes the
1251 // file-file remapping.
1252 for (PreprocessorOptions::remapped_file_buffer_iterator
1253 M = PreprocessorOpts.remapped_file_buffer_begin(),
1254 E = PreprocessorOpts.remapped_file_buffer_end();
1255 M != E;
1256 ++M) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001257 std::string MPath(M->first);
Rafael Espindola073ff102013-07-29 21:26:52 +00001258 llvm::sys::fs::UniqueID MID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00001259 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00001260 if (MainFileID == MID) {
1261 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001262 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001263 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001264 CreatedBuffer = false;
1265 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001266
Douglas Gregor4dde7492010-07-23 23:58:40 +00001267 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001268 }
1269 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001270 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001271 }
1272
1273 // If the main source file was not remapped, load it now.
1274 if (!Buffer) {
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001275 Buffer = getBufferForFile(FrontendOpts.Inputs[0].getFile());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001276 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001277 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001278
1279 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001280 }
1281
Argyrios Kyrtzidis7aecbc72011-08-25 20:39:19 +00001282 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenek8cf47df2011-11-17 23:01:24 +00001283 *Invocation.getLangOpts(),
Argyrios Kyrtzidis7aecbc72011-08-25 20:39:19 +00001284 MaxLines));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001285}
1286
Douglas Gregor6481ef12010-07-24 00:38:13 +00001287static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001288 unsigned NewSize,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001289 StringRef NewName) {
Douglas Gregor6481ef12010-07-24 00:38:13 +00001290 llvm::MemoryBuffer *Result
1291 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1292 memcpy(const_cast<char*>(Result->getBufferStart()),
1293 Old->getBufferStart(), Old->getBufferSize());
1294 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001295 ' ', NewSize - Old->getBufferSize() - 1);
1296 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor6481ef12010-07-24 00:38:13 +00001297
Douglas Gregor6481ef12010-07-24 00:38:13 +00001298 return Result;
1299}
1300
Dmitri Gribenko47652522013-12-20 00:16:25 +00001301ASTUnit::PreambleFileHash
1302ASTUnit::PreambleFileHash::createForFile(off_t Size, time_t ModTime) {
1303 PreambleFileHash Result;
1304 Result.Size = Size;
1305 Result.ModTime = ModTime;
Dmitri Gribenko3ec8ee72013-12-20 01:07:30 +00001306 memset(Result.MD5, 0, sizeof(Result.MD5));
Dmitri Gribenko47652522013-12-20 00:16:25 +00001307 return Result;
1308}
1309
1310ASTUnit::PreambleFileHash ASTUnit::PreambleFileHash::createForMemoryBuffer(
1311 const llvm::MemoryBuffer *Buffer) {
1312 PreambleFileHash Result;
1313 Result.Size = Buffer->getBufferSize();
1314 Result.ModTime = 0;
1315
1316 llvm::MD5 MD5Ctx;
1317 MD5Ctx.update(Buffer->getBuffer().data());
1318 MD5Ctx.final(Result.MD5);
1319
1320 return Result;
1321}
1322
1323namespace clang {
1324bool operator==(const ASTUnit::PreambleFileHash &LHS,
1325 const ASTUnit::PreambleFileHash &RHS) {
1326 return LHS.Size == RHS.Size && LHS.ModTime == RHS.ModTime &&
Dmitri Gribenko3ec8ee72013-12-20 01:07:30 +00001327 memcmp(LHS.MD5, RHS.MD5, sizeof(LHS.MD5)) == 0;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001328}
1329} // namespace clang
1330
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001331static std::pair<unsigned, unsigned>
1332makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1333 const LangOptions &LangOpts) {
1334 CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1335 unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1336 unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1337 return std::make_pair(Offset, EndOffset);
1338}
1339
1340static void makeStandaloneFixIt(const SourceManager &SM,
1341 const LangOptions &LangOpts,
1342 const FixItHint &InFix,
1343 ASTUnit::StandaloneFixIt &OutFix) {
1344 OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1345 OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1346 LangOpts);
1347 OutFix.CodeToInsert = InFix.CodeToInsert;
1348 OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
1349}
1350
1351static void makeStandaloneDiagnostic(const LangOptions &LangOpts,
1352 const StoredDiagnostic &InDiag,
1353 ASTUnit::StandaloneDiagnostic &OutDiag) {
1354 OutDiag.ID = InDiag.getID();
1355 OutDiag.Level = InDiag.getLevel();
1356 OutDiag.Message = InDiag.getMessage();
1357 OutDiag.LocOffset = 0;
1358 if (InDiag.getLocation().isInvalid())
1359 return;
1360 const SourceManager &SM = InDiag.getLocation().getManager();
1361 SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1362 OutDiag.Filename = SM.getFilename(FileLoc);
1363 if (OutDiag.Filename.empty())
1364 return;
1365 OutDiag.LocOffset = SM.getFileOffset(FileLoc);
1366 for (StoredDiagnostic::range_iterator
1367 I = InDiag.range_begin(), E = InDiag.range_end(); I != E; ++I) {
1368 OutDiag.Ranges.push_back(makeStandaloneRange(*I, SM, LangOpts));
1369 }
1370 for (StoredDiagnostic::fixit_iterator
1371 I = InDiag.fixit_begin(), E = InDiag.fixit_end(); I != E; ++I) {
1372 ASTUnit::StandaloneFixIt Fix;
1373 makeStandaloneFixIt(SM, LangOpts, *I, Fix);
1374 OutDiag.FixIts.push_back(Fix);
1375 }
1376}
1377
Douglas Gregor4dde7492010-07-23 23:58:40 +00001378/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1379/// the source file.
1380///
1381/// This routine will compute the preamble of the main source file. If a
1382/// non-trivial preamble is found, it will precompile that preamble into a
1383/// precompiled header so that the precompiled preamble can be used to reduce
1384/// reparsing time. If a precompiled preamble has already been constructed,
1385/// this routine will determine if it is still valid and, if so, avoid
1386/// rebuilding the precompiled preamble.
1387///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001388/// \param AllowRebuild When true (the default), this routine is
1389/// allowed to rebuild the precompiled preamble if it is found to be
1390/// out-of-date.
1391///
1392/// \param MaxLines When non-zero, the maximum number of lines that
1393/// can occur within the preamble.
1394///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001395/// \returns If the precompiled preamble can be used, returns a newly-allocated
1396/// buffer that should be used in place of the main file when doing so.
1397/// Otherwise, returns a NULL pointer.
Douglas Gregor028d3e42010-08-09 20:45:32 +00001398llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor3cc15812011-07-01 18:22:13 +00001399 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001400 bool AllowRebuild,
1401 unsigned MaxLines) {
Douglas Gregor3cc15812011-07-01 18:22:13 +00001402
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001403 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor3cc15812011-07-01 18:22:13 +00001404 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1405 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001406 PreprocessorOptions &PreprocessorOpts
Douglas Gregor3cc15812011-07-01 18:22:13 +00001407 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001408
1409 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001410 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor3cc15812011-07-01 18:22:13 +00001411 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001412
Douglas Gregor925296b2011-07-19 16:10:42 +00001413 // If ComputePreamble() Take ownership of the preamble buffer.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001414 OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor3edb1672010-11-16 20:45:51 +00001415 if (CreatedPreambleBuffer)
1416 OwnedPreambleBuffer.reset(NewPreamble.first);
1417
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001418 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001419 // We couldn't find a preamble in the main source. Clear out the current
1420 // preamble, if we have one. It's obviously no good any more.
1421 Preamble.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001422 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001423
1424 // The next time we actually see a preamble, precompile it.
1425 PreambleRebuildCounter = 1;
Douglas Gregor6481ef12010-07-24 00:38:13 +00001426 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001427 }
1428
1429 if (!Preamble.empty()) {
1430 // We've previously computed a preamble. Check whether we have the same
1431 // preamble now that we did before, and that there's enough space in
1432 // the main-file buffer within the precompiled preamble to fit the
1433 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001434 if (Preamble.size() == NewPreamble.second.first &&
1435 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregorf5275a82010-07-24 00:42:07 +00001436 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001437 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001438 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001439 // The preamble has not changed. We may be able to re-use the precompiled
1440 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001441
Douglas Gregor0e119552010-07-31 00:40:00 +00001442 // Check that none of the files used by the preamble have changed.
1443 bool AnyFileChanged = false;
1444
1445 // First, make a record of those files that have been overridden via
1446 // remapping or unsaved_files.
Dmitri Gribenko47652522013-12-20 00:16:25 +00001447 llvm::StringMap<PreambleFileHash> OverriddenFiles;
Douglas Gregor0e119552010-07-31 00:40:00 +00001448 for (PreprocessorOptions::remapped_file_iterator
1449 R = PreprocessorOpts.remapped_file_begin(),
1450 REnd = PreprocessorOpts.remapped_file_end();
1451 !AnyFileChanged && R != REnd;
1452 ++R) {
Ben Langmuirc8130a72014-02-20 21:59:23 +00001453 vfs::Status Status;
Rafael Espindolae4777f42013-07-29 18:22:23 +00001454 if (FileMgr->getNoncachedStatValue(R->second, Status)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001455 // If we can't stat the file we're remapping to, assume that something
1456 // horrible happened.
1457 AnyFileChanged = true;
1458 break;
1459 }
Rafael Espindolae4777f42013-07-29 18:22:23 +00001460
Dmitri Gribenko47652522013-12-20 00:16:25 +00001461 OverriddenFiles[R->first] = PreambleFileHash::createForFile(
Rafael Espindolae4777f42013-07-29 18:22:23 +00001462 Status.getSize(), Status.getLastModificationTime().toEpochTime());
Douglas Gregor0e119552010-07-31 00:40:00 +00001463 }
1464 for (PreprocessorOptions::remapped_file_buffer_iterator
1465 R = PreprocessorOpts.remapped_file_buffer_begin(),
1466 REnd = PreprocessorOpts.remapped_file_buffer_end();
1467 !AnyFileChanged && R != REnd;
1468 ++R) {
Dmitri Gribenko47652522013-12-20 00:16:25 +00001469 OverriddenFiles[R->first] =
1470 PreambleFileHash::createForMemoryBuffer(R->second);
Douglas Gregor0e119552010-07-31 00:40:00 +00001471 }
1472
1473 // Check whether anything has changed.
Dmitri Gribenko47652522013-12-20 00:16:25 +00001474 for (llvm::StringMap<PreambleFileHash>::iterator
Douglas Gregor0e119552010-07-31 00:40:00 +00001475 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1476 !AnyFileChanged && F != FEnd;
1477 ++F) {
Dmitri Gribenko47652522013-12-20 00:16:25 +00001478 llvm::StringMap<PreambleFileHash>::iterator Overridden
Douglas Gregor0e119552010-07-31 00:40:00 +00001479 = OverriddenFiles.find(F->first());
1480 if (Overridden != OverriddenFiles.end()) {
1481 // This file was remapped; check whether the newly-mapped file
1482 // matches up with the previous mapping.
1483 if (Overridden->second != F->second)
1484 AnyFileChanged = true;
1485 continue;
1486 }
1487
1488 // The file was not remapped; check whether it has changed on disk.
Ben Langmuirc8130a72014-02-20 21:59:23 +00001489 vfs::Status Status;
Rafael Espindolae4777f42013-07-29 18:22:23 +00001490 if (FileMgr->getNoncachedStatValue(F->first(), Status)) {
Douglas Gregor0e119552010-07-31 00:40:00 +00001491 // If we can't stat the file, assume that something horrible happened.
1492 AnyFileChanged = true;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001493 } else if (Status.getSize() != uint64_t(F->second.Size) ||
Rafael Espindolae4777f42013-07-29 18:22:23 +00001494 Status.getLastModificationTime().toEpochTime() !=
Dmitri Gribenko47652522013-12-20 00:16:25 +00001495 uint64_t(F->second.ModTime))
Douglas Gregor0e119552010-07-31 00:40:00 +00001496 AnyFileChanged = true;
1497 }
1498
1499 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001500 // Okay! We can re-use the precompiled preamble.
1501
1502 // Set the state of the diagnostic object to mimic its state
1503 // after parsing the preamble.
1504 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001505 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor3cc15812011-07-01 18:22:13 +00001506 PreambleInvocation->getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001507 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001508
1509 // Create a version of the main file buffer that is padded to
1510 // buffer size we reserved when creating the preamble.
Douglas Gregor0e119552010-07-31 00:40:00 +00001511 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor0e119552010-07-31 00:40:00 +00001512 PreambleReservedSize,
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001513 FrontendOpts.Inputs[0].getFile());
Douglas Gregor0e119552010-07-31 00:40:00 +00001514 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001515 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001516
1517 // If we aren't allowed to rebuild the precompiled preamble, just
1518 // return now.
1519 if (!AllowRebuild)
1520 return 0;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001521
Douglas Gregor4dde7492010-07-23 23:58:40 +00001522 // We can't reuse the previously-computed preamble. Build a new one.
1523 Preamble.clear();
Douglas Gregor925296b2011-07-19 16:10:42 +00001524 PreambleDiagnostics.clear();
Ted Kremenek06b4f912011-10-27 17:55:18 +00001525 erasePreambleFile(this);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001526 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001527 } else if (!AllowRebuild) {
1528 // We aren't allowed to rebuild the precompiled preamble; just
1529 // return now.
1530 return 0;
1531 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001532
1533 // If the preamble rebuild counter > 1, it's because we previously
1534 // failed to build a preamble and we're not yet ready to try
1535 // again. Decrement the counter and return a failure.
1536 if (PreambleRebuildCounter > 1) {
1537 --PreambleRebuildCounter;
1538 return 0;
1539 }
1540
Douglas Gregore10f0e52010-09-11 17:56:52 +00001541 // Create a temporary file for the precompiled preamble. In rare
1542 // circumstances, this can fail.
1543 std::string PreamblePCHPath = GetPreamblePCHPath();
1544 if (PreamblePCHPath.empty()) {
1545 // Try again next time.
1546 PreambleRebuildCounter = 1;
1547 return 0;
1548 }
1549
Douglas Gregor4dde7492010-07-23 23:58:40 +00001550 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001551 SimpleTimer PreambleTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001552 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001553
1554 // Create a new buffer that stores the preamble. The buffer also contains
1555 // extra space for the original contents of the file (which will be present
1556 // when we actually parse the file) along with more room in case the file
Douglas Gregor4dde7492010-07-23 23:58:40 +00001557 // grows.
1558 PreambleReservedSize = NewPreamble.first->getBufferSize();
1559 if (PreambleReservedSize < 4096)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001560 PreambleReservedSize = 8191;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001561 else
Douglas Gregor4dde7492010-07-23 23:58:40 +00001562 PreambleReservedSize *= 2;
1563
Douglas Gregord9a30af2010-08-02 20:51:39 +00001564 // Save the preamble text for later; we'll need to compare against it for
1565 // subsequent reparses.
Dmitri Gribenko40798d32013-12-19 23:25:59 +00001566 StringRef MainFilename = FrontendOpts.Inputs[0].getFile();
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00001567 Preamble.assign(FileMgr->getFile(MainFilename),
1568 NewPreamble.first->getBufferStart(),
Douglas Gregord9a30af2010-08-02 20:51:39 +00001569 NewPreamble.first->getBufferStart()
1570 + NewPreamble.second.first);
1571 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1572
Douglas Gregora0734c52010-08-19 01:33:06 +00001573 delete PreambleBuffer;
1574 PreambleBuffer
Douglas Gregor4dde7492010-07-23 23:58:40 +00001575 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001576 FrontendOpts.Inputs[0].getFile());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001577 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor4dde7492010-07-23 23:58:40 +00001578 NewPreamble.first->getBufferStart(), Preamble.size());
1579 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001580 ' ', PreambleReservedSize - Preamble.size() - 1);
1581 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001582
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001583 // Remap the main source file to the preamble buffer.
Rafael Espindolaa96bd562013-06-26 04:12:57 +00001584 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
1585 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer);
1586
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001587 // Tell the compiler invocation to generate a temporary precompiled header.
1588 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001589 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001590 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001591 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1592 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001593
1594 // Create the compiler instance to use for building the precompiled preamble.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001595 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001596
1597 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00001598 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1599 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00001600
Douglas Gregor3cc15812011-07-01 18:22:13 +00001601 Clang->setInvocation(&*PreambleInvocation);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001602 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001603
Douglas Gregor8e984da2010-08-04 16:47:14 +00001604 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001605 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001606
1607 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001608 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregorf8715de2012-11-16 04:24:59 +00001609 &Clang->getTargetOpts()));
Ted Kremenek84de4a12011-03-21 18:40:07 +00001610 if (!Clang->hasTarget()) {
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001611 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001612 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001613 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001614 PreprocessorOpts.eraseRemappedFile(
1615 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001616 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001617 }
1618
1619 // Inform the target of the language options.
1620 //
1621 // FIXME: We shouldn't need to do this, the target should be immutable once
1622 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001623 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001624
Ted Kremenek84de4a12011-03-21 18:40:07 +00001625 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001626 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001627 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001628 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001629 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001630 "IR inputs not support here!");
1631
1632 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001633 getDiagnostics().Reset();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001634 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis38bacf32012-02-01 19:54:02 +00001635 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregore9db88f2010-08-03 19:06:41 +00001636 TopLevelDecls.clear();
1637 TopLevelDeclsInPreamble.clear();
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001638 PreambleDiagnostics.clear();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001639
1640 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001641 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001642
1643 // Create the source manager.
Ted Kremenek84de4a12011-03-21 18:40:07 +00001644 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek5e14d392011-03-21 18:40:17 +00001645 Clang->getFileManager()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001646
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001647 OwningPtr<PrecompilePreambleAction> Act;
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001648 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor32fbe312012-01-20 16:28:04 +00001649 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001650 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001651 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001652 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001653 PreprocessorOpts.eraseRemappedFile(
1654 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001655 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001656 }
1657
1658 Act->Execute();
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001659
1660 // Transfer any diagnostics generated when parsing the preamble into the set
1661 // of preamble diagnostics.
1662 for (stored_diag_iterator
1663 I = stored_diag_afterDriver_begin(),
1664 E = stored_diag_end(); I != E; ++I) {
1665 StandaloneDiagnostic Diag;
1666 makeStandaloneDiagnostic(Clang->getLangOpts(), *I, Diag);
1667 PreambleDiagnostics.push_back(Diag);
1668 }
1669
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001670 Act->EndSourceFile();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001671
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00001672 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1673
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +00001674 if (!Act->hasEmittedPreamblePCH()) {
Argyrios Kyrtzidisd6f57222013-06-11 16:42:34 +00001675 // The preamble PCH failed (e.g. there was a module loading fatal error),
1676 // so no precompiled header was generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001677 // FIXME: Should we leave a note for ourselves to try again?
Rafael Espindolaf5e5bc42013-06-26 04:26:38 +00001678 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001679 Preamble.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001680 TopLevelDeclsInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001681 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001682 PreprocessorOpts.eraseRemappedFile(
1683 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001684 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001685 }
1686
1687 // Keep track of the preamble we precompiled.
Ted Kremenek06b4f912011-10-27 17:55:18 +00001688 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregord9a30af2010-08-02 20:51:39 +00001689 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001690
1691 // Keep track of all of the files that the source manager knows about,
1692 // so we can verify whether they have changed or not.
1693 FilesInPreamble.clear();
Ted Kremenek84de4a12011-03-21 18:40:07 +00001694 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregor0e119552010-07-31 00:40:00 +00001695 const llvm::MemoryBuffer *MainFileBuffer
1696 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1697 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1698 FEnd = SourceMgr.fileinfo_end();
1699 F != FEnd;
1700 ++F) {
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00001701 const FileEntry *File = F->second->OrigEntry;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001702 if (!File)
Douglas Gregor0e119552010-07-31 00:40:00 +00001703 continue;
Dmitri Gribenko47652522013-12-20 00:16:25 +00001704 const llvm::MemoryBuffer *Buffer = F->second->getRawBuffer();
1705 if (Buffer == MainFileBuffer)
1706 continue;
1707
1708 if (time_t ModTime = File->getModificationTime()) {
1709 FilesInPreamble[File->getName()] = PreambleFileHash::createForFile(
1710 F->second->getSize(), ModTime);
1711 } else {
1712 assert(F->second->getSize() == Buffer->getBufferSize());
1713 FilesInPreamble[File->getName()] =
1714 PreambleFileHash::createForMemoryBuffer(Buffer);
1715 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001716 }
1717
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001718 PreambleRebuildCounter = 1;
Douglas Gregora0734c52010-08-19 01:33:06 +00001719 PreprocessorOpts.eraseRemappedFile(
1720 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001721
1722 // If the hash of top-level entities differs from the hash of the top-level
1723 // entities the last time we rebuilt the preamble, clear out the completion
1724 // cache.
1725 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1726 CompletionCacheTopLevelHashValue = 0;
1727 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1728 }
1729
Douglas Gregor6481ef12010-07-24 00:38:13 +00001730 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001731 PreambleReservedSize,
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001732 FrontendOpts.Inputs[0].getFile());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001733}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001734
Douglas Gregore9db88f2010-08-03 19:06:41 +00001735void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1736 std::vector<Decl *> Resolved;
1737 Resolved.reserve(TopLevelDeclsInPreamble.size());
1738 ExternalASTSource &Source = *getASTContext().getExternalSource();
1739 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1740 // Resolve the declaration ID to an actual declaration, possibly
1741 // deserializing the declaration in the process.
1742 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1743 if (D)
1744 Resolved.push_back(D);
1745 }
1746 TopLevelDeclsInPreamble.clear();
1747 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1748}
1749
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001750void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1751 // Steal the created target, context, and preprocessor.
1752 TheSema.reset(CI.takeSema());
1753 Consumer.reset(CI.takeASTConsumer());
1754 Ctx = &CI.getASTContext();
1755 PP = &CI.getPreprocessor();
1756 CI.setSourceManager(0);
1757 CI.setFileManager(0);
1758 Target = &CI.getTarget();
1759 Reader = CI.getModuleManager();
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00001760 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001761}
1762
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001763StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis928e1fd2013-01-11 22:11:14 +00001764 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1765 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1766 if (Input.isFile())
1767 return Input.getFile();
1768 else
1769 return Input.getBuffer()->getBufferIdentifier();
1770 }
1771
1772 if (SourceMgr) {
1773 if (const FileEntry *
1774 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1775 return FE->getName();
1776 }
1777
1778 return StringRef();
Douglas Gregor16896c42010-10-28 15:44:59 +00001779}
1780
Argyrios Kyrtzidis37f2ab42013-03-05 20:21:14 +00001781StringRef ASTUnit::getASTFileName() const {
1782 if (!isMainFileAST())
1783 return StringRef();
1784
1785 serialization::ModuleFile &
1786 Mod = Reader->getModuleManager().getPrimaryModule();
1787 return Mod.FileName;
1788}
1789
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001790ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001791 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001792 bool CaptureDiagnostics,
1793 bool UserFilesAreVolatile) {
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001794 OwningPtr<ASTUnit> AST;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001795 AST.reset(new ASTUnit(false));
Argyrios Kyrtzidis67aa7db2011-11-28 04:55:55 +00001796 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001797 AST->Diagnostics = Diags;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001798 AST->Invocation = CI;
Anders Carlssonc30dcec2011-03-18 18:22:40 +00001799 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00001800 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001801 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1802 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1803 UserFilesAreVolatile);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00001804
1805 return AST.take();
1806}
1807
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001808ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001809 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001810 ASTFrontendAction *Action,
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001811 ASTUnit *Unit,
1812 bool Persistent,
1813 StringRef ResourceFilesPath,
1814 bool OnlyLocalDecls,
1815 bool CaptureDiagnostics,
1816 bool PrecompilePreamble,
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001817 bool CacheCodeCompletionResults,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001818 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001819 bool UserFilesAreVolatile,
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001820 OwningPtr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001821 assert(CI && "A CompilerInvocation is required");
1822
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001823 OwningPtr<ASTUnit> OwnAST;
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001824 ASTUnit *AST = Unit;
1825 if (!AST) {
1826 // Create the AST unit.
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001827 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001828 AST = OwnAST.get();
1829 }
1830
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001831 if (!ResourceFilesPath.empty()) {
1832 // Override the resources path.
1833 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1834 }
1835 AST->OnlyLocalDecls = OnlyLocalDecls;
1836 AST->CaptureDiagnostics = CaptureDiagnostics;
1837 if (PrecompilePreamble)
1838 AST->PreambleRebuildCounter = 2;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001839 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001840 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001841 AST->IncludeBriefCommentsInCodeCompletion
1842 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001843
1844 // Recover resources if we crash before exiting this method.
1845 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001846 ASTUnitCleanup(OwnAST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00001847 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1848 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001849 DiagCleanup(Diags.getPtr());
1850
1851 // We'll manage file buffers ourselves.
1852 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1853 CI->getFrontendOpts().DisableFree = false;
1854 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1855
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001856 // Create the compiler instance to use for building the AST.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001857 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001858
1859 // Recover resources if we crash before exiting this method.
1860 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1861 CICleanup(Clang.get());
1862
1863 Clang->setInvocation(CI);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001864 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001865
1866 // Set up diagnostics, capturing any diagnostics that would
1867 // otherwise be dropped.
1868 Clang->setDiagnostics(&AST->getDiagnostics());
1869
1870 // Create the target instance.
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001871 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregorf8715de2012-11-16 04:24:59 +00001872 &Clang->getTargetOpts()));
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001873 if (!Clang->hasTarget())
1874 return 0;
1875
1876 // Inform the target of the language options.
1877 //
1878 // FIXME: We shouldn't need to do this, the target should be immutable once
1879 // created. This complexity should be lifted elsewhere.
1880 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1881
1882 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1883 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001884 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001885 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00001886 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001887 "IR inputs not supported here!");
1888
1889 // Configure the various subsystems.
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001890 AST->TheSema.reset();
1891 AST->Ctx = 0;
1892 AST->PP = 0;
Argyrios Kyrtzidis244ce8b2011-11-01 17:14:15 +00001893 AST->Reader = 0;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001894
1895 // Create a file manager object to provide access to and cache the filesystem.
1896 Clang->setFileManager(&AST->getFileManager());
1897
1898 // Create the source manager.
1899 Clang->setSourceManager(&AST->getSourceManager());
1900
1901 ASTFrontendAction *Act = Action;
1902
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001903 OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001904 if (!Act) {
1905 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1906 Act = TrackerAct.get();
1907 }
1908
1909 // Recover resources if we crash before exiting this method.
1910 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1911 ActCleanup(TrackerAct.get());
1912
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001913 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1914 AST->transferASTDataFromCompilerInstance(*Clang);
1915 if (OwnAST && ErrAST)
1916 ErrAST->swap(OwnAST);
1917
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001918 return 0;
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001919 }
Argyrios Kyrtzidisb11f5a42011-11-28 04:56:00 +00001920
1921 if (Persistent && !TrackerAct) {
1922 Clang->getPreprocessor().addPPCallbacks(
1923 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1924 std::vector<ASTConsumer*> Consumers;
1925 if (Clang->hasASTConsumer())
1926 Consumers.push_back(Clang->takeASTConsumer());
1927 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1928 AST->getCurrentTopLevelHashValue()));
1929 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1930 }
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +00001931 if (!Act->Execute()) {
1932 AST->transferASTDataFromCompilerInstance(*Clang);
1933 if (OwnAST && ErrAST)
1934 ErrAST->swap(OwnAST);
1935
1936 return 0;
1937 }
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001938
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001939 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00001940 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001941
1942 Act->EndSourceFile();
1943
Argyrios Kyrtzidis1ac5da12011-10-14 21:22:05 +00001944 if (OwnAST)
1945 return OwnAST.take();
1946 else
1947 return AST;
Argyrios Kyrtzidisf1f67592011-05-03 23:26:34 +00001948}
1949
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001950bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1951 if (!Invocation)
1952 return true;
1953
1954 // We'll manage file buffers ourselves.
1955 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1956 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001957 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001958
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001959 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorf5a18542010-10-27 17:24:53 +00001960 if (PrecompilePreamble) {
Douglas Gregorc6592922010-11-15 23:00:34 +00001961 PreambleRebuildCounter = 2;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001962 OverrideMainBuffer
1963 = getMainBufferWithPrecompiledPreamble(*Invocation);
1964 }
1965
Douglas Gregor16896c42010-10-28 15:44:59 +00001966 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001967 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001968
Ted Kremenek022a4902011-03-22 01:15:24 +00001969 // Recover resources if we crash before exiting this method.
1970 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1971 MemBufferCleanup(OverrideMainBuffer);
1972
Douglas Gregor16896c42010-10-28 15:44:59 +00001973 return Parse(OverrideMainBuffer);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001974}
1975
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001976ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00001977 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001978 bool OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001979 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001980 bool PrecompilePreamble,
Douglas Gregor69f74f82011-08-25 22:30:56 +00001981 TranslationUnitKind TUKind,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001982 bool CacheCodeCompletionResults,
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001983 bool IncludeBriefCommentsInCodeCompletion,
1984 bool UserFilesAreVolatile) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001985 // Create the AST unit.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00001986 OwningPtr<ASTUnit> AST;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001987 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001988 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001989 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001990 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001991 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00001992 AST->TUKind = TUKind;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001993 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00001994 AST->IncludeBriefCommentsInCodeCompletion
1995 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek5e14d392011-03-21 18:40:17 +00001996 AST->Invocation = CI;
Argyrios Kyrtzidis3ad52ed2013-01-21 18:45:42 +00001997 AST->FileSystemOpts = CI->getFileSystemOpts();
1998 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00001999 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002000
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002001 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002002 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2003 ASTUnitCleanup(AST.get());
David Blaikie9c902b52011-09-25 23:23:43 +00002004 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
2005 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek022a4902011-03-22 01:15:24 +00002006 DiagCleanup(Diags.getPtr());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002007
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002008 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar764c0822009-12-01 09:51:01 +00002009}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002010
2011ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
2012 const char **ArgEnd,
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00002013 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002014 StringRef ResourceFilesPath,
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002015 bool OnlyLocalDecls,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00002016 bool CaptureDiagnostics,
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002017 ArrayRef<RemappedFile> RemappedFiles,
Argyrios Kyrtzidis97d3a382011-03-08 23:35:24 +00002018 bool RemappedFilesKeepOriginalName,
Douglas Gregor028d3e42010-08-09 20:45:32 +00002019 bool PrecompilePreamble,
Douglas Gregor69f74f82011-08-25 22:30:56 +00002020 TranslationUnitKind TUKind,
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00002021 bool CacheCodeCompletionResults,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002022 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00002023 bool AllowPCHWithCompilerErrors,
Erik Verbruggen6e922512012-04-12 10:11:59 +00002024 bool SkipFunctionBodies,
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00002025 bool UserFilesAreVolatile,
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002026 bool ForSerialization,
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00002027 OwningPtr<ASTUnit> *ErrAST) {
Douglas Gregor7f95d262010-04-05 23:52:57 +00002028 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00002029 // No diagnostics engine was provided, so create our own diagnostics object
2030 // with the default options.
Sean Silvaf1b49e22013-01-20 01:58:28 +00002031 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions());
Douglas Gregord03e8232010-04-05 21:10:19 +00002032 }
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002033
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002034 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002035
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00002036 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00002037
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002038 {
Douglas Gregor925296b2011-07-19 16:10:42 +00002039
Douglas Gregor44c6ee72010-11-11 00:39:14 +00002040 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002041 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00002042
Argyrios Kyrtzidis5cf423e2011-04-04 23:11:45 +00002043 CI = clang::createInvocationFromCommandLine(
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002044 llvm::makeArrayRef(ArgBegin, ArgEnd),
2045 Diags);
Argyrios Kyrtzidisf606b822011-04-04 21:38:51 +00002046 if (!CI)
Argyrios Kyrtzidisbc1f48f2011-03-07 22:45:01 +00002047 return 0;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002048 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00002049
Douglas Gregoraa98ed92010-01-23 00:14:00 +00002050 // Override any files that need remapping
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002051 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002052 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2053 RemappedFiles[I].second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002054 }
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00002055 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
2056 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
2057 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregoraa98ed92010-01-23 00:14:00 +00002058
Daniel Dunbara5a166d2009-12-15 00:06:45 +00002059 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00002060 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002061
Erik Verbruggen6e922512012-04-12 10:11:59 +00002062 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
2063
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002064 // Create the AST unit.
Dylan Noblesmithe2778992012-02-05 02:12:40 +00002065 OwningPtr<ASTUnit> AST;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002066 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00002067 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002068 AST->Diagnostics = Diags;
Ted Kremenek25047602011-11-17 23:01:17 +00002069 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlssonc30dcec2011-03-18 18:22:40 +00002070 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek5e14d392011-03-21 18:40:17 +00002071 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002072 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00002073 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor69f74f82011-08-25 22:30:56 +00002074 AST->TUKind = TUKind;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002075 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002076 AST->IncludeBriefCommentsInCodeCompletion
2077 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidis6d7833f2012-07-11 20:59:04 +00002078 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002079 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002080 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek5e14d392011-03-21 18:40:17 +00002081 AST->Invocation = CI;
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002082 if (ForSerialization)
2083 AST->WriterData.reset(new ASTWriterData());
Ted Kremenek25047602011-11-17 23:01:17 +00002084 CI = 0; // Zero out now to ease cleanup during crash recovery.
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002085
2086 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002087 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2088 ASTUnitCleanup(AST.get());
Ted Kremenek4422bfe2011-03-18 02:06:56 +00002089
Argyrios Kyrtzidisac1cc932012-04-11 02:11:16 +00002090 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
2091 // Some error occurred, if caller wants to examine diagnostics, pass it the
2092 // ASTUnit.
2093 if (ErrAST) {
2094 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2095 ErrAST->swap(AST);
2096 }
2097 return 0;
2098 }
2099
2100 return AST.take();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00002101}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002102
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002103bool ASTUnit::Reparse(ArrayRef<RemappedFile> RemappedFiles) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002104 if (!Invocation)
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002105 return true;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002106
2107 clearFileLevelDecls();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002108
Douglas Gregor16896c42010-10-28 15:44:59 +00002109 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002110 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00002111
Douglas Gregor0e119552010-07-31 00:40:00 +00002112 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00002113 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
2114 for (PreprocessorOptions::remapped_file_buffer_iterator
2115 R = PPOpts.remapped_file_buffer_begin(),
2116 REnd = PPOpts.remapped_file_buffer_end();
2117 R != REnd;
2118 ++R) {
2119 delete R->second;
2120 }
Douglas Gregor0e119552010-07-31 00:40:00 +00002121 Invocation->getPreprocessorOpts().clearRemappedFiles();
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002122 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002123 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2124 RemappedFiles[I].second);
Argyrios Kyrtzidis11e6f0a2011-03-05 01:03:53 +00002125 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002126
Douglas Gregorbb420ab2010-08-04 05:53:38 +00002127 // If we have a preamble file lying around, or if we might try to
2128 // build a precompiled preamble, do so now.
Douglas Gregor6481ef12010-07-24 00:38:13 +00002129 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002130 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregorb97b6662010-08-20 00:59:43 +00002131 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor4dde7492010-07-23 23:58:40 +00002132
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002133 // Clear out the diagnostics state.
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002134 getDiagnostics().Reset();
2135 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis462ff352011-11-03 20:57:33 +00002136 if (OverrideMainBuffer)
2137 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidisf50f7b22011-11-03 20:28:19 +00002138
Douglas Gregor4dde7492010-07-23 23:58:40 +00002139 // Parse the sources
Douglas Gregordf7a79a2011-02-16 18:16:54 +00002140 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis36893372011-10-31 21:25:31 +00002141
2142 // If we're caching global code-completion results, and the top-level
2143 // declarations have changed, clear out the code-completion cache.
2144 if (!Result && ShouldCacheCodeCompletionResults &&
2145 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2146 CacheCodeCompletionResults();
Douglas Gregordf7a79a2011-02-16 18:16:54 +00002147
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002148 // We now need to clear out the completion info related to this translation
2149 // unit; it'll be recreated if necessary.
2150 CCTUInfo.reset();
Douglas Gregor3f35bb22011-08-04 20:04:59 +00002151
Douglas Gregor4dde7492010-07-23 23:58:40 +00002152 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00002153}
Douglas Gregor8e984da2010-08-04 16:47:14 +00002154
Douglas Gregorb14904c2010-08-13 22:48:40 +00002155//----------------------------------------------------------------------------//
2156// Code completion
2157//----------------------------------------------------------------------------//
2158
2159namespace {
2160 /// \brief Code completion consumer that combines the cached code-completion
2161 /// results from an ASTUnit with the code-completion results provided to it,
2162 /// then passes the result on to
2163 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith697cc9e2012-08-14 03:13:00 +00002164 uint64_t NormalContexts;
Douglas Gregorb14904c2010-08-13 22:48:40 +00002165 ASTUnit &AST;
2166 CodeCompleteConsumer &Next;
2167
2168 public:
2169 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002170 const CodeCompleteOptions &CodeCompleteOpts)
2171 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2172 AST(AST), Next(Next)
Douglas Gregorb14904c2010-08-13 22:48:40 +00002173 {
2174 // Compute the set of contexts in which we will look when we don't have
2175 // any information about the specific context.
2176 NormalContexts
Richard Smith697cc9e2012-08-14 03:13:00 +00002177 = (1LL << CodeCompletionContext::CCC_TopLevel)
2178 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2179 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2180 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2181 | (1LL << CodeCompletionContext::CCC_Statement)
2182 | (1LL << CodeCompletionContext::CCC_Expression)
2183 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2184 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2185 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2186 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2187 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2188 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2189 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor5e35d592010-09-14 23:59:36 +00002190
David Blaikiebbafb8a2012-03-11 07:00:24 +00002191 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith697cc9e2012-08-14 03:13:00 +00002192 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2193 | (1LL << CodeCompletionContext::CCC_UnionTag)
2194 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregorb14904c2010-08-13 22:48:40 +00002195 }
2196
2197 virtual void ProcessCodeCompleteResults(Sema &S,
2198 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002199 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00002200 unsigned NumResults);
Douglas Gregorb14904c2010-08-13 22:48:40 +00002201
2202 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2203 OverloadCandidate *Candidates,
2204 unsigned NumCandidates) {
2205 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2206 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002207
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00002208 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002209 return Next.getAllocator();
2210 }
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002211
2212 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() {
2213 return Next.getCodeCompletionTUInfo();
2214 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00002215 };
2216}
Douglas Gregord46cf182010-08-16 20:01:48 +00002217
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002218/// \brief Helper function that computes which global names are hidden by the
2219/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002220static void CalculateHiddenNames(const CodeCompletionContext &Context,
2221 CodeCompletionResult *Results,
2222 unsigned NumResults,
2223 ASTContext &Ctx,
2224 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002225 bool OnlyTagNames = false;
2226 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00002227 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002228 case CodeCompletionContext::CCC_TopLevel:
2229 case CodeCompletionContext::CCC_ObjCInterface:
2230 case CodeCompletionContext::CCC_ObjCImplementation:
2231 case CodeCompletionContext::CCC_ObjCIvarList:
2232 case CodeCompletionContext::CCC_ClassStructUnion:
2233 case CodeCompletionContext::CCC_Statement:
2234 case CodeCompletionContext::CCC_Expression:
2235 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor21325842011-07-07 16:03:39 +00002236 case CodeCompletionContext::CCC_DotMemberAccess:
2237 case CodeCompletionContext::CCC_ArrowMemberAccess:
2238 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002239 case CodeCompletionContext::CCC_Namespace:
2240 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00002241 case CodeCompletionContext::CCC_Name:
2242 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00002243 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor2c595ad2011-07-30 06:55:39 +00002244 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002245 break;
2246
2247 case CodeCompletionContext::CCC_EnumTag:
2248 case CodeCompletionContext::CCC_UnionTag:
2249 case CodeCompletionContext::CCC_ClassOrStructTag:
2250 OnlyTagNames = true;
2251 break;
2252
2253 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00002254 case CodeCompletionContext::CCC_MacroName:
2255 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00002256 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002257 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00002258 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00002259 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00002260 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00002261 case CodeCompletionContext::CCC_Other:
Douglas Gregor3a69eaf2011-02-18 23:30:37 +00002262 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor21325842011-07-07 16:03:39 +00002263 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2264 case CodeCompletionContext::CCC_ObjCClassMessage:
2265 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00002266 // We're looking for nothing, or we're looking for names that cannot
2267 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002268 return;
2269 }
2270
John McCall276321a2010-08-25 06:19:51 +00002271 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002272 for (unsigned I = 0; I != NumResults; ++I) {
2273 if (Results[I].Kind != Result::RK_Declaration)
2274 continue;
2275
2276 unsigned IDNS
2277 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2278
2279 bool Hiding = false;
2280 if (OnlyTagNames)
2281 Hiding = (IDNS & Decl::IDNS_Tag);
2282 else {
2283 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00002284 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2285 Decl::IDNS_NonMemberOperator);
David Blaikiebbafb8a2012-03-11 07:00:24 +00002286 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002287 HiddenIDNS |= Decl::IDNS_Tag;
2288 Hiding = (IDNS & HiddenIDNS);
2289 }
2290
2291 if (!Hiding)
2292 continue;
2293
2294 DeclarationName Name = Results[I].Declaration->getDeclName();
2295 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2296 HiddenNames.insert(Identifier->getName());
2297 else
2298 HiddenNames.insert(Name.getAsString());
2299 }
2300}
2301
2302
Douglas Gregord46cf182010-08-16 20:01:48 +00002303void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2304 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00002305 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00002306 unsigned NumResults) {
2307 // Merge the results we were given with the results we cached.
2308 bool AddedResult = false;
Richard Smith697cc9e2012-08-14 03:13:00 +00002309 uint64_t InContexts =
2310 Context.getKind() == CodeCompletionContext::CCC_Recovery
2311 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002312 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00002313 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall276321a2010-08-25 06:19:51 +00002314 typedef CodeCompletionResult Result;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002315 SmallVector<Result, 8> AllResults;
Douglas Gregord46cf182010-08-16 20:01:48 +00002316 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00002317 C = AST.cached_completion_begin(),
2318 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00002319 C != CEnd; ++C) {
2320 // If the context we are in matches any of the contexts we are
2321 // interested in, we'll add this result.
2322 if ((C->ShowInContexts & InContexts) == 0)
2323 continue;
2324
2325 // If we haven't added any results previously, do so now.
2326 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002327 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2328 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00002329 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2330 AddedResult = true;
2331 }
2332
Douglas Gregor6199f2d2010-08-16 21:18:39 +00002333 // Determine whether this global completion result is hidden by a local
2334 // completion result. If so, skip it.
2335 if (C->Kind != CXCursor_MacroDefinition &&
2336 HiddenNames.count(C->Completion->getTypedText()))
2337 continue;
2338
Douglas Gregord46cf182010-08-16 20:01:48 +00002339 // Adjust priority based on similar type classes.
2340 unsigned Priority = C->Priority;
Douglas Gregor12785102010-08-24 20:21:13 +00002341 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00002342 if (!Context.getPreferredType().isNull()) {
2343 if (C->Kind == CXCursor_MacroDefinition) {
2344 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002345 S.getLangOpts(),
Douglas Gregor12785102010-08-24 20:21:13 +00002346 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00002347 } else if (C->Type) {
2348 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00002349 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00002350 Context.getPreferredType().getUnqualifiedType());
2351 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2352 if (ExpectedSTC == C->TypeClass) {
2353 // We know this type is similar; check for an exact match.
2354 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00002355 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00002356 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00002357 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00002358 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2359 Priority /= CCF_ExactTypeMatch;
2360 else
2361 Priority /= CCF_SimilarTypeMatch;
2362 }
2363 }
2364 }
2365
Douglas Gregor12785102010-08-24 20:21:13 +00002366 // Adjust the completion string, if required.
2367 if (C->Kind == CXCursor_MacroDefinition &&
2368 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2369 // Create a new code-completion string that just contains the
2370 // macro name, without its arguments.
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +00002371 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2372 CCP_CodePattern, C->Availability);
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002373 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00002374 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00002375 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00002376 }
2377
Argyrios Kyrtzidis5c8b1cd2012-09-27 00:24:09 +00002378 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregorf757a122010-08-23 23:00:57 +00002379 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00002380 }
2381
2382 // If we did not add any cached completion results, just forward the
2383 // results we were given to the next consumer.
2384 if (!AddedResult) {
2385 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2386 return;
2387 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00002388
Douglas Gregord46cf182010-08-16 20:01:48 +00002389 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2390 AllResults.size());
2391}
2392
2393
2394
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002395void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002396 ArrayRef<RemappedFile> RemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00002397 bool IncludeMacros,
2398 bool IncludeCodePatterns,
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002399 bool IncludeBriefComments,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002400 CodeCompleteConsumer &Consumer,
David Blaikie9c902b52011-09-25 23:23:43 +00002401 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor8e984da2010-08-04 16:47:14 +00002402 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002403 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2404 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002405 if (!Invocation)
Douglas Gregor8e984da2010-08-04 16:47:14 +00002406 return;
2407
Douglas Gregor16896c42010-10-28 15:44:59 +00002408 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00002409 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002410 Twine(Line) + ":" + Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00002411
Dylan Noblesmithc95d8192012-02-20 14:00:23 +00002412 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek5e14d392011-03-21 18:40:17 +00002413 CCInvocation(new CompilerInvocation(*Invocation));
2414
2415 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002416 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek5e14d392011-03-21 18:40:17 +00002417 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00002418
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002419 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2420 CachedCompletionResults.empty();
2421 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2422 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2423 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2424
2425 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2426
Douglas Gregor8e984da2010-08-04 16:47:14 +00002427 FrontendOpts.CodeCompletionAt.FileName = File;
2428 FrontendOpts.CodeCompletionAt.Line = Line;
2429 FrontendOpts.CodeCompletionAt.Column = Column;
2430
2431 // Set the language options appropriately.
Ted Kremenek8cf47df2011-11-17 23:01:24 +00002432 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002433
Dylan Noblesmithe2778992012-02-05 02:12:40 +00002434 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002435
2436 // Recover resources if we crash before exiting this method.
Ted Kremenek022a4902011-03-22 01:15:24 +00002437 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2438 CICleanup(Clang.get());
Ted Kremenek84de4a12011-03-21 18:40:07 +00002439
Ted Kremenek5e14d392011-03-21 18:40:17 +00002440 Clang->setInvocation(&*CCInvocation);
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002441 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002442
2443 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002444 Clang->setDiagnostics(&Diag);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002445 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek84de4a12011-03-21 18:40:07 +00002446 Clang->getDiagnostics(),
Douglas Gregor8e984da2010-08-04 16:47:14 +00002447 StoredDiagnostics);
Manuel Klimekbe0474c2013-07-18 14:23:12 +00002448 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002449
2450 // Create the target instance.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002451 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregorf8715de2012-11-16 04:24:59 +00002452 &Clang->getTargetOpts()));
Ted Kremenek84de4a12011-03-21 18:40:07 +00002453 if (!Clang->hasTarget()) {
Ted Kremenek5e14d392011-03-21 18:40:17 +00002454 Clang->setInvocation(0);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002455 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002456 }
2457
2458 // Inform the target of the language options.
2459 //
2460 // FIXME: We shouldn't need to do this, the target should be immutable once
2461 // created. This complexity should be lifted elsewhere.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002462 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00002463
Ted Kremenek84de4a12011-03-21 18:40:07 +00002464 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002465 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002466 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002467 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +00002468 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor8e984da2010-08-04 16:47:14 +00002469 "IR inputs not support here!");
2470
2471
2472 // Use the source and file managers that we were given.
Ted Kremenek84de4a12011-03-21 18:40:07 +00002473 Clang->setFileManager(&FileMgr);
2474 Clang->setSourceManager(&SourceMgr);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002475
2476 // Remap files.
2477 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00002478 PreprocessorOpts.RetainRemappedFileBuffers = true;
Dmitri Gribenko2febd212014-02-07 15:00:22 +00002479 for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) {
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002480 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
2481 RemappedFiles[I].second);
Daniel Jasperd90ec572014-02-12 08:45:05 +00002482 OwnedBuffers.push_back(RemappedFiles[I].second);
Douglas Gregorb97b6662010-08-20 00:59:43 +00002483 }
Dmitri Gribenkoc444b572014-02-08 00:38:15 +00002484
Douglas Gregorb14904c2010-08-13 22:48:40 +00002485 // Use the code completion consumer we were given, but adding any cached
2486 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00002487 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenko3292d062012-07-02 17:35:10 +00002488 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek84de4a12011-03-21 18:40:07 +00002489 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002490
Douglas Gregor028d3e42010-08-09 20:45:32 +00002491 // If we have a precompiled preamble, try to use it. We only allow
2492 // the use of the precompiled preamble if we're if the completion
2493 // point is within the main file, after the end of the precompiled
2494 // preamble.
2495 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002496 if (!getPreambleFile(this).empty()) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002497 std::string CompleteFilePath(File);
Rafael Espindola073ff102013-07-29 21:26:52 +00002498 llvm::sys::fs::UniqueID CompleteFileID;
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002499
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00002500 if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002501 std::string MainPath(OriginalSourceFile);
Rafael Espindola073ff102013-07-29 21:26:52 +00002502 llvm::sys::fs::UniqueID MainID;
Rafael Espindolabe3b12b02013-06-20 15:12:38 +00002503 if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002504 if (CompleteFileID == MainID && Line > 1)
Douglas Gregorb97b6662010-08-20 00:59:43 +00002505 OverrideMainBuffer
Ted Kremenek5e14d392011-03-21 18:40:17 +00002506 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregor8e817b62010-08-25 18:04:15 +00002507 Line - 1);
Rafael Espindolaf9e9bb82013-06-18 19:40:07 +00002508 }
2509 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002510 }
2511
2512 // If the main file has been overridden due to the use of a preamble,
2513 // make that override happen and introduce the preamble.
2514 if (OverrideMainBuffer) {
2515 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2516 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2517 PreprocessorOpts.PrecompiledPreambleBytes.second
2518 = PreambleEndsAtStartOfLine;
Ted Kremenek06b4f912011-10-27 17:55:18 +00002519 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002520 PreprocessorOpts.DisablePCHValidation = true;
2521
Douglas Gregorb97b6662010-08-20 00:59:43 +00002522 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregor7b02b582010-08-20 00:02:33 +00002523 } else {
2524 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2525 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002526 }
2527
Argyrios Kyrtzidis870704f2012-11-02 22:18:44 +00002528 // Disable the preprocessing record if modules are not enabled.
2529 if (!Clang->getLangOpts().Modules)
2530 PreprocessorOpts.DetailedRecord = false;
Douglas Gregor998caea2011-05-06 16:33:08 +00002531
Dylan Noblesmithe2778992012-02-05 02:12:40 +00002532 OwningPtr<SyntaxOnlyAction> Act;
Douglas Gregor8e984da2010-08-04 16:47:14 +00002533 Act.reset(new SyntaxOnlyAction);
Douglas Gregor32fbe312012-01-20 16:28:04 +00002534 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00002535 Act->Execute();
2536 Act->EndSourceFile();
2537 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002538}
Douglas Gregore9386682010-08-13 05:36:37 +00002539
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002540bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00002541 if (HadModuleLoaderFatalFailure)
2542 return true;
2543
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002544 // Write to a temporary file and later rename it to the actual file, to avoid
2545 // possible race conditions.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002546 SmallString<128> TempPath;
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002547 TempPath = File;
2548 TempPath += "-%%%%%%%%";
2549 int fd;
Rafael Espindola18627112013-07-05 21:13:58 +00002550 if (llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath))
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002551 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002552
Douglas Gregore9386682010-08-13 05:36:37 +00002553 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2554 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +00002555 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002556
2557 serialize(Out);
2558 Out.close();
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002559 if (Out.has_error()) {
2560 Out.clear_error();
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002561 return true;
Argyrios Kyrtzidiseeea16a2012-03-13 02:17:06 +00002562 }
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002563
Rafael Espindola65e025c2011-12-25 01:18:52 +00002564 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Rafael Espindola2a008782014-01-10 21:32:14 +00002565 llvm::sys::fs::remove(TempPath.str());
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002566 return true;
Argyrios Kyrtzidis55e75572011-07-21 18:44:49 +00002567 }
2568
Argyrios Kyrtzidis39a76382012-09-26 16:39:46 +00002569 return false;
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002570}
2571
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002572static bool serializeUnit(ASTWriter &Writer,
2573 SmallVectorImpl<char> &Buffer,
2574 Sema &S,
2575 bool hasErrors,
2576 raw_ostream &OS) {
Argyrios Kyrtzidisd7c16b22012-10-31 20:59:50 +00002577 Writer.WriteAST(S, std::string(), 0, "", hasErrors);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002578
2579 // Write the generated bitstream to "Out".
2580 if (!Buffer.empty())
2581 OS.write(Buffer.data(), Buffer.size());
2582
2583 return false;
2584}
2585
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002586bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidis4a280ff2012-03-07 01:51:17 +00002587 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +00002588
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002589 if (WriterData)
2590 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2591 getSema(), hasErrors, OS);
2592
Daniel Dunbar9a963862012-02-29 20:31:23 +00002593 SmallString<128> Buffer;
Douglas Gregore9386682010-08-13 05:36:37 +00002594 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002595 ASTWriter Writer(Stream);
Argyrios Kyrtzidis0db720f2012-10-11 16:05:00 +00002596 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregore9386682010-08-13 05:36:37 +00002597}
Douglas Gregor925296b2011-07-19 16:10:42 +00002598
2599typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2600
Douglas Gregor925296b2011-07-19 16:10:42 +00002601void ASTUnit::TranslateStoredDiagnostics(
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002602 FileManager &FileMgr,
Douglas Gregor925296b2011-07-19 16:10:42 +00002603 SourceManager &SrcMgr,
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002604 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002605 SmallVectorImpl<StoredDiagnostic> &Out) {
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002606 // Map the standalone diagnostic into the new source manager. We also need to
2607 // remap all the locations to the new view. This includes the diag location,
2608 // any associated source ranges, and the source ranges of associated fix-its.
Douglas Gregor925296b2011-07-19 16:10:42 +00002609 // FIXME: There should be a cleaner way to do this.
2610
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002611 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregor925296b2011-07-19 16:10:42 +00002612 Result.reserve(Diags.size());
Douglas Gregor925296b2011-07-19 16:10:42 +00002613 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2614 // Rebuild the StoredDiagnostic.
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002615 const StandaloneDiagnostic &SD = Diags[I];
2616 if (SD.Filename.empty())
2617 continue;
2618 const FileEntry *FE = FileMgr.getFile(SD.Filename);
2619 if (!FE)
2620 continue;
2621 FileID FID = SrcMgr.translateFile(FE);
2622 SourceLocation FileLoc = SrcMgr.getLocForStartOfFile(FID);
2623 if (FileLoc.isInvalid())
2624 continue;
2625 SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
Douglas Gregor925296b2011-07-19 16:10:42 +00002626 FullSourceLoc Loc(L, SrcMgr);
2627
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002628 SmallVector<CharSourceRange, 4> Ranges;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002629 Ranges.reserve(SD.Ranges.size());
2630 for (std::vector<std::pair<unsigned, unsigned> >::const_iterator
2631 I = SD.Ranges.begin(), E = SD.Ranges.end(); I != E; ++I) {
2632 SourceLocation BL = FileLoc.getLocWithOffset((*I).first);
2633 SourceLocation EL = FileLoc.getLocWithOffset((*I).second);
2634 Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
Douglas Gregor925296b2011-07-19 16:10:42 +00002635 }
2636
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002637 SmallVector<FixItHint, 2> FixIts;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002638 FixIts.reserve(SD.FixIts.size());
2639 for (std::vector<StandaloneFixIt>::const_iterator
2640 I = SD.FixIts.begin(), E = SD.FixIts.end();
Douglas Gregor925296b2011-07-19 16:10:42 +00002641 I != E; ++I) {
2642 FixIts.push_back(FixItHint());
2643 FixItHint &FH = FixIts.back();
2644 FH.CodeToInsert = I->CodeToInsert;
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002645 SourceLocation BL = FileLoc.getLocWithOffset(I->RemoveRange.first);
2646 SourceLocation EL = FileLoc.getLocWithOffset(I->RemoveRange.second);
2647 FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
Douglas Gregor925296b2011-07-19 16:10:42 +00002648 }
2649
Argyrios Kyrtzidis24c55222014-02-28 07:11:01 +00002650 Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2651 SD.Message, Loc, Ranges, FixIts));
Douglas Gregor925296b2011-07-19 16:10:42 +00002652 }
2653 Result.swap(Out);
2654}
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002655
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002656void ASTUnit::addFileLevelDecl(Decl *D) {
2657 assert(D);
Douglas Gregor61d63d02011-11-07 18:53:57 +00002658
2659 // We only care about local declarations.
2660 if (D->isFromASTFile())
2661 return;
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002662
2663 SourceManager &SM = *SourceMgr;
2664 SourceLocation Loc = D->getLocation();
2665 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2666 return;
2667
2668 // We only keep track of the file-level declarations of each file.
2669 if (!D->getLexicalDeclContext()->isFileContext())
2670 return;
2671
2672 SourceLocation FileLoc = SM.getFileLoc(Loc);
2673 assert(SM.isLocalSourceLocation(FileLoc));
2674 FileID FID;
2675 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002676 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002677 if (FID.isInvalid())
2678 return;
2679
2680 LocDeclsTy *&Decls = FileDecls[FID];
2681 if (!Decls)
2682 Decls = new LocDeclsTy();
2683
2684 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2685
2686 if (Decls->empty() || Decls->back().first <= Offset) {
2687 Decls->push_back(LocDecl);
2688 return;
2689 }
2690
Benjamin Kramer45025c02013-08-24 13:22:59 +00002691 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2692 LocDecl, llvm::less_first());
Argyrios Kyrtzidise54568d2011-10-31 07:19:59 +00002693
2694 Decls->insert(I, LocDecl);
2695}
2696
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002697void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2698 SmallVectorImpl<Decl *> &Decls) {
2699 if (File.isInvalid())
2700 return;
2701
2702 if (SourceMgr->isLoadedFileID(File)) {
2703 assert(Ctx->getExternalSource() && "No external source!");
2704 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2705 Decls);
2706 }
2707
2708 FileDeclsTy::iterator I = FileDecls.find(File);
2709 if (I == FileDecls.end())
2710 return;
2711
2712 LocDeclsTy &LocDecls = *I->second;
2713 if (LocDecls.empty())
2714 return;
2715
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002716 LocDeclsTy::iterator BeginIt =
2717 std::lower_bound(LocDecls.begin(), LocDecls.end(),
Benjamin Kramer45025c02013-08-24 13:22:59 +00002718 std::make_pair(Offset, (Decl *)0), llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002719 if (BeginIt != LocDecls.begin())
2720 --BeginIt;
2721
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00002722 // If we are pointing at a top-level decl inside an objc container, we need
2723 // to backtrack until we find it otherwise we will fail to report that the
2724 // region overlaps with an objc container.
2725 while (BeginIt != LocDecls.begin() &&
2726 BeginIt->second->isTopLevelDeclInObjCContainer())
2727 --BeginIt;
2728
Benjamin Kramere3e855b2013-08-24 13:12:34 +00002729 LocDeclsTy::iterator EndIt = std::upper_bound(
2730 LocDecls.begin(), LocDecls.end(),
Benjamin Kramer45025c02013-08-24 13:22:59 +00002731 std::make_pair(Offset + Length, (Decl *)0), llvm::less_first());
Argyrios Kyrtzidise9681522011-11-03 02:20:32 +00002732 if (EndIt != LocDecls.end())
2733 ++EndIt;
2734
2735 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2736 Decls.push_back(DIt->second);
2737}
2738
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002739SourceLocation ASTUnit::getLocation(const FileEntry *File,
2740 unsigned Line, unsigned Col) const {
2741 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002742 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002743 return SM.getMacroArgExpandedLocation(Loc);
2744}
2745
2746SourceLocation ASTUnit::getLocation(const FileEntry *File,
2747 unsigned Offset) const {
2748 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002749 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002750 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2751}
2752
Argyrios Kyrtzidis4cdfcae2011-09-26 08:01:41 +00002753/// \brief If \arg Loc is a loaded location from the preamble, returns
2754/// the corresponding local location of the main file, otherwise it returns
2755/// \arg Loc.
2756SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2757 FileID PreambleID;
2758 if (SourceMgr)
2759 PreambleID = SourceMgr->getPreambleFileID();
2760
2761 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2762 return Loc;
2763
2764 unsigned Offs;
2765 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2766 SourceLocation FileLoc
2767 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2768 return FileLoc.getLocWithOffset(Offs);
2769 }
2770
2771 return Loc;
2772}
2773
2774/// \brief If \arg Loc is a local location of the main file but inside the
2775/// preamble chunk, returns the corresponding loaded location from the
2776/// preamble, otherwise it returns \arg Loc.
2777SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2778 FileID PreambleID;
2779 if (SourceMgr)
2780 PreambleID = SourceMgr->getPreambleFileID();
2781
2782 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2783 return Loc;
2784
2785 unsigned Offs;
2786 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2787 Offs < Preamble.size()) {
2788 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2789 return FileLoc.getLocWithOffset(Offs);
2790 }
2791
2792 return Loc;
2793}
2794
Argyrios Kyrtzidis429ec022011-10-25 00:29:50 +00002795bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2796 FileID FID;
2797 if (SourceMgr)
2798 FID = SourceMgr->getPreambleFileID();
2799
2800 if (Loc.isInvalid() || FID.isInvalid())
2801 return false;
2802
2803 return SourceMgr->isInFileID(Loc, FID);
2804}
2805
2806bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2807 FileID FID;
2808 if (SourceMgr)
2809 FID = SourceMgr->getMainFileID();
2810
2811 if (Loc.isInvalid() || FID.isInvalid())
2812 return false;
2813
2814 return SourceMgr->isInFileID(Loc, FID);
2815}
2816
2817SourceLocation ASTUnit::getEndOfPreambleFileID() {
2818 FileID FID;
2819 if (SourceMgr)
2820 FID = SourceMgr->getPreambleFileID();
2821
2822 if (FID.isInvalid())
2823 return SourceLocation();
2824
2825 return SourceMgr->getLocForEndOfFile(FID);
2826}
2827
2828SourceLocation ASTUnit::getStartOfMainFileID() {
2829 FileID FID;
2830 if (SourceMgr)
2831 FID = SourceMgr->getMainFileID();
2832
2833 if (FID.isInvalid())
2834 return SourceLocation();
2835
2836 return SourceMgr->getLocForStartOfFile(FID);
2837}
2838
Argyrios Kyrtzidisd4fcf5802012-10-02 16:10:51 +00002839std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
2840ASTUnit::getLocalPreprocessingEntities() const {
2841 if (isMainFileAST()) {
2842 serialization::ModuleFile &
2843 Mod = Reader->getModuleManager().getPrimaryModule();
2844 return Reader->getModulePreprocessedEntities(Mod);
2845 }
2846
2847 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2848 return std::make_pair(PPRec->local_begin(), PPRec->local_end());
2849
2850 return std::make_pair(PreprocessingRecord::iterator(),
2851 PreprocessingRecord::iterator());
2852}
2853
Argyrios Kyrtzidise514b202012-10-03 01:58:28 +00002854bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002855 if (isMainFileAST()) {
2856 serialization::ModuleFile &
2857 Mod = Reader->getModuleManager().getPrimaryModule();
2858 ASTReader::ModuleDeclIterator MDI, MDE;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002859 std::tie(MDI, MDE) = Reader->getModuleFileLevelDecls(Mod);
Argyrios Kyrtzidis10e78462012-10-02 21:09:13 +00002860 for (; MDI != MDE; ++MDI) {
2861 if (!Fn(context, *MDI))
2862 return false;
2863 }
2864
2865 return true;
2866 }
2867
2868 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2869 TLEnd = top_level_end();
2870 TL != TLEnd; ++TL) {
2871 if (!Fn(context, *TL))
2872 return false;
2873 }
2874
2875 return true;
2876}
2877
Argyrios Kyrtzidisf484b132012-10-03 21:05:51 +00002878namespace {
2879struct PCHLocatorInfo {
2880 serialization::ModuleFile *Mod;
2881 PCHLocatorInfo() : Mod(0) {}
2882};
2883}
2884
2885static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
2886 PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
2887 switch (M.Kind) {
2888 case serialization::MK_Module:
2889 return true; // skip dependencies.
2890 case serialization::MK_PCH:
2891 Info.Mod = &M;
2892 return true; // found it.
2893 case serialization::MK_Preamble:
2894 return false; // look in dependencies.
2895 case serialization::MK_MainFile:
2896 return false; // look in dependencies.
2897 }
2898
2899 return true;
2900}
2901
2902const FileEntry *ASTUnit::getPCHFile() {
2903 if (!Reader)
2904 return 0;
2905
2906 PCHLocatorInfo Info;
2907 Reader->getModuleManager().visit(PCHLocator, &Info);
2908 if (Info.Mod)
2909 return Info.Mod->File;
2910
2911 return 0;
2912}
2913
Argyrios Kyrtzidise445c722012-10-10 02:12:47 +00002914bool ASTUnit::isModuleFile() {
2915 return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2916}
2917
Argyrios Kyrtzidis7c06d862011-09-19 20:40:35 +00002918void ASTUnit::PreambleData::countLines() const {
2919 NumLines = 0;
2920 if (empty())
2921 return;
2922
2923 for (std::vector<char>::const_iterator
2924 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2925 if (*I == '\n')
2926 ++NumLines;
2927 }
2928 if (Buffer.back() != '\n')
2929 ++NumLines;
2930}
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002931
2932#ifndef NDEBUG
2933ASTUnit::ConcurrencyState::ConcurrencyState() {
2934 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2935}
2936
2937ASTUnit::ConcurrencyState::~ConcurrencyState() {
2938 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2939}
2940
2941void ASTUnit::ConcurrencyState::start() {
2942 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2943 assert(acquired && "Concurrent access to ASTUnit!");
2944}
2945
2946void ASTUnit::ConcurrencyState::finish() {
2947 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2948}
2949
2950#else // NDEBUG
2951
Alp Tokerb159c132013-11-22 07:49:39 +00002952ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = 0; }
Argyrios Kyrtzidisebf01362011-10-10 21:57:12 +00002953ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2954void ASTUnit::ConcurrencyState::start() {}
2955void ASTUnit::ConcurrencyState::finish() {}
2956
2957#endif