blob: 610c20d9fb14f3c8bef8a568aa3490f545958cc7 [file] [log] [blame]
Argyrios Kyrtzidis4b562cf2009-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 Kyrtzidis0853a022009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000015#include "clang/AST/ASTConsumer.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000016#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
18#include "clang/AST/StmtVisitor.h"
Chandler Carruth55fc8732012-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"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000023#include "clang/Frontend/CompilerInstance.h"
24#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000025#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000026#include "clang/Frontend/FrontendOptions.h"
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +000027#include "clang/Frontend/MultiplexConsumer.h"
Douglas Gregor32be4a52010-10-11 21:37:58 +000028#include "clang/Frontend/Utils.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000029#include "clang/Lex/HeaderSearch.h"
30#include "clang/Lex/Preprocessor.h"
Douglas Gregor36a16492012-10-24 17:46:57 +000031#include "clang/Lex/PreprocessorOptions.h"
David Blaikie0b5ca512013-09-13 18:32:52 +000032#include "clang/Sema/Sema.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000033#include "clang/Serialization/ASTReader.h"
34#include "clang/Serialization/ASTWriter.h"
Chris Lattner7f9fc3f2011-03-23 04:04:01 +000035#include "llvm/ADT/ArrayRef.h"
Douglas Gregor9b7db622011-02-16 18:16:54 +000036#include "llvm/ADT/StringExtras.h"
Douglas Gregor349d38c2010-08-16 23:08:34 +000037#include "llvm/ADT/StringSet.h"
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +000038#include "llvm/Support/Atomic.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000039#include "llvm/Support/CrashRecoveryContext.h"
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +000040#include "llvm/Support/FileSystem.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000041#include "llvm/Support/Host.h"
42#include "llvm/Support/MemoryBuffer.h"
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +000043#include "llvm/Support/Mutex.h"
Ted Kremeneke055f8a2011-10-27 19:44:25 +000044#include "llvm/Support/MutexGuard.h"
Chandler Carruth55fc8732012-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 Xuad23ebe2010-07-23 02:15:08 +000048#include <cstdio>
Chandler Carruth55fc8732012-12-04 09:13:33 +000049#include <cstdlib>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000050#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000051using namespace clang;
52
Douglas Gregor213f18b2010-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 Krameredfb7ec2010-11-09 20:00:56 +000061 public:
Douglas Gregor9dba61a2010-11-01 13:48:43 +000062 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000063 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000064 Start = TimeRecord::getCurrentTime();
Douglas Gregor213f18b2010-10-28 15:44:59 +000065 }
66
Chris Lattner5f9e2722011-07-23 10:55:15 +000067 void setOutput(const Twine &Output) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000068 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000069 this->Output = Output.str();
Douglas Gregor213f18b2010-10-28 15:44:59 +000070 }
71
Douglas Gregor213f18b2010-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 Kremenek1872b312011-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 Espindolab804cb32013-06-26 03:52:38 +000087 /// \brief Temporary files that should be removed when the ASTUnit is
Ted Kremenek1872b312011-10-27 17:55:18 +000088 /// destroyed.
Rafael Espindolab804cb32013-06-26 03:52:38 +000089 SmallVector<std::string, 4> TemporaryFiles;
90
Ted Kremenek1872b312011-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 Kremeneke055f8a2011-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 Gribenkoc4a77902012-11-15 14:28:07 +0000107static void cleanupOnDiskMapAtExit();
Ted Kremenek1872b312011-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 Gribenkoc4a77902012-11-15 14:28:07 +0000120static void cleanupOnDiskMapAtExit() {
Argyrios Kyrtzidis81788132012-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 Kremenek1872b312011-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 Kremeneke055f8a2011-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 Kremenek1872b312011-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 Kremeneke055f8a2011-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 Kremenek1872b312011-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 Gribenkocfa88f82013-01-12 19:30:44 +0000159static void setPreambleFile(const ASTUnit *AU, StringRef preambleFile) {
Ted Kremenek1872b312011-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 Espindolab804cb32013-06-26 03:52:38 +0000169 llvm::sys::fs::remove(TemporaryFiles[I]);
170 TemporaryFiles.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +0000171}
172
173void OnDiskData::CleanPreambleFile() {
174 if (!PreambleFile.empty()) {
Rafael Espindola85d28482013-06-26 04:02:37 +0000175 llvm::sys::fs::remove(PreambleFile);
Ted Kremenek1872b312011-10-27 17:55:18 +0000176 PreambleFile.clear();
177 }
178}
179
180void OnDiskData::Cleanup() {
181 CleanTemporaryFiles();
182 CleanPreambleFile();
183}
184
Argyrios Kyrtzidis900ab952012-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 Kyrtzidis332cb9b2011-10-31 07:19:59 +0000193void ASTUnit::clearFileLevelDecls() {
194 for (FileDeclsTy::iterator
195 I = FileDecls.begin(), E = FileDecls.end(); I != E; ++I)
196 delete I->second;
197 FileDecls.clear();
198}
199
Ted Kremenek1872b312011-10-27 17:55:18 +0000200void ASTUnit::CleanTemporaryFiles() {
201 getOnDiskData(this).CleanTemporaryFiles();
202}
203
Rafael Espindolab804cb32013-06-26 03:52:38 +0000204void ASTUnit::addTemporaryFile(StringRef TempFile) {
Ted Kremenek1872b312011-10-27 17:55:18 +0000205 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
Douglas Gregor213f18b2010-10-28 15:44:59 +0000206}
207
Douglas Gregoreababfb2010-08-04 05:53:38 +0000208/// \brief After failing to build a precompiled preamble (due to
209/// errors in the source that occurs in the preamble), the number of
210/// reparses during which we'll skip even trying to precompile the
211/// preamble.
212const unsigned DefaultPreambleRebuildInterval = 5;
213
Douglas Gregore3c60a72010-11-17 00:13:31 +0000214/// \brief Tracks the number of ASTUnit objects that are currently active.
215///
216/// Used for debugging purposes only.
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000217static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregore3c60a72010-11-17 00:13:31 +0000218
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000219ASTUnit::ASTUnit(bool _MainFileIsAST)
Argyrios Kyrtzidis3b7deda2013-05-24 05:44:08 +0000220 : Reader(0), HadModuleLoaderFatalFailure(false),
221 OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +0000222 MainFileIsAST(_MainFileIsAST),
Douglas Gregor467dc882011-08-25 22:30:56 +0000223 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis15727dd2011-03-05 01:03:48 +0000224 OwnsRemappedFileBuffers(true),
Douglas Gregor213f18b2010-10-28 15:44:59 +0000225 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor671947b2010-08-19 01:33:06 +0000226 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Argyrios Kyrtzidis98704012011-11-29 18:18:33 +0000227 NumWarningsInPreamble(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +0000228 ShouldCacheCodeCompletionResults(false),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000229 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000230 CompletionCacheTopLevelHashValue(0),
231 PreambleTopLevelHashValue(0),
232 CurrentTopLevelHashValue(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +0000233 UnsafeToFree(false) {
Douglas Gregore3c60a72010-11-17 00:13:31 +0000234 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000235 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000236 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
237 }
Douglas Gregor385103b2010-07-30 20:58:08 +0000238}
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000239
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000240ASTUnit::~ASTUnit() {
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000241 // If we loaded from an AST file, balance out the BeginSourceFile call.
242 if (MainFileIsAST && getDiagnostics().getClient()) {
243 getDiagnostics().getClient()->EndSourceFile();
244 }
245
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000246 clearFileLevelDecls();
247
Ted Kremenek1872b312011-10-27 17:55:18 +0000248 // Clean up the temporary files and the preamble file.
249 removeOnDiskEntry(this);
250
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000251 // Free the buffers associated with remapped files. We are required to
252 // perform this operation here because we explicitly request that the
253 // compiler instance *not* free these buffers for each invocation of the
254 // parser.
Ted Kremenek4f327862011-03-21 18:40:17 +0000255 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000256 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
257 for (PreprocessorOptions::remapped_file_buffer_iterator
258 FB = PPOpts.remapped_file_buffer_begin(),
259 FBEnd = PPOpts.remapped_file_buffer_end();
260 FB != FBEnd;
261 ++FB)
262 delete FB->second;
263 }
Douglas Gregor28233422010-07-27 14:52:07 +0000264
265 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +0000266 delete PreambleBuffer;
267
Douglas Gregor213f18b2010-10-28 15:44:59 +0000268 ClearCachedCompletionResults();
Douglas Gregore3c60a72010-11-17 00:13:31 +0000269
270 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000271 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000272 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
273 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000274}
275
Argyrios Kyrtzidis7fe90f32012-01-17 18:48:07 +0000276void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
277
Douglas Gregor8071e422010-08-15 06:18:01 +0000278/// \brief Determine the set of code-completion contexts in which this
279/// declaration should be shown.
Dmitri Gribenko89cf4252013-01-23 17:21:11 +0000280static unsigned getDeclShowContexts(const NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000281 const LangOptions &LangOpts,
282 bool &IsNestedNameSpecifier) {
283 IsNestedNameSpecifier = false;
284
Douglas Gregor8071e422010-08-15 06:18:01 +0000285 if (isa<UsingShadowDecl>(ND))
286 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
287 if (!ND)
288 return 0;
289
Richard Smith026b3582012-08-14 03:13:00 +0000290 uint64_t Contexts = 0;
Douglas Gregor8071e422010-08-15 06:18:01 +0000291 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
292 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
293 // Types can appear in these contexts.
294 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000295 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
296 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
297 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
298 | (1LL << CodeCompletionContext::CCC_Statement)
299 | (1LL << CodeCompletionContext::CCC_Type)
300 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000301
302 // In C++, types can appear in expressions contexts (for functional casts).
303 if (LangOpts.CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +0000304 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
Douglas Gregor8071e422010-08-15 06:18:01 +0000305
306 // In Objective-C, message sends can send interfaces. In Objective-C++,
307 // all types are available due to functional casts.
308 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000309 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000310
311 // In Objective-C, you can only be a subclass of another Objective-C class
312 if (isa<ObjCInterfaceDecl>(ND))
Richard Smith026b3582012-08-14 03:13:00 +0000313 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000314
315 // Deal with tag names.
316 if (isa<EnumDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000317 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000318
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000319 // Part of the nested-name-specifier in C++0x.
Richard Smith80ad52f2013-01-02 11:42:31 +0000320 if (LangOpts.CPlusPlus11)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000321 IsNestedNameSpecifier = true;
Dmitri Gribenko89cf4252013-01-23 17:21:11 +0000322 } else if (const RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000323 if (Record->isUnion())
Richard Smith026b3582012-08-14 03:13:00 +0000324 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000325 else
Richard Smith026b3582012-08-14 03:13:00 +0000326 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor8071e422010-08-15 06:18:01 +0000327
Douglas Gregor8071e422010-08-15 06:18:01 +0000328 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000329 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000330 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000331 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000332 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
333 // Values can appear in these contexts.
Richard Smith026b3582012-08-14 03:13:00 +0000334 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
335 | (1LL << CodeCompletionContext::CCC_Expression)
336 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
337 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
Douglas Gregor8071e422010-08-15 06:18:01 +0000338 } else if (isa<ObjCProtocolDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000339 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
Douglas Gregor3da626b2011-07-07 16:03:39 +0000340 } else if (isa<ObjCCategoryDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000341 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
Douglas Gregor8071e422010-08-15 06:18:01 +0000342 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Richard Smith026b3582012-08-14 03:13:00 +0000343 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregor8071e422010-08-15 06:18:01 +0000344
345 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000346 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000347 }
348
349 return Contexts;
350}
351
Douglas Gregor87c08a52010-08-13 22:48:40 +0000352void ASTUnit::CacheCodeCompletionResults() {
353 if (!TheSema)
354 return;
355
Douglas Gregor213f18b2010-10-28 15:44:59 +0000356 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000357 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000358
359 // Clear out the previous results.
360 ClearCachedCompletionResults();
361
362 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000363 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000364 SmallVector<Result, 8> Results;
Douglas Gregor48601b32011-02-16 19:08:06 +0000365 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000366 CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000367 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000368 CCTUInfo, Results);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000369
370 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000371 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
372
Douglas Gregor87c08a52010-08-13 22:48:40 +0000373 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
374 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000375 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000376 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000377 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000378 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000379 *CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000380 CCTUInfo,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000381 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor8071e422010-08-15 06:18:01 +0000382 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
David Blaikie4e4d0842012-03-11 07:00:24 +0000383 Ctx->getLangOpts(),
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000384 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000385 CachedResult.Priority = Results[I].Priority;
386 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000387 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000388
Douglas Gregorf5586f62010-08-16 18:08:11 +0000389 // Keep track of the type of this completion in an ASTContext-agnostic
390 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000391 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000392 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000393 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000394 CachedResult.Type = 0;
395 } else {
396 CanQualType CanUsageType
397 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
398 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
399
400 // Determine whether we have already seen this type. If so, we save
401 // ourselves the work of formatting the type string by using the
402 // temporary, CanQualType-based hash table to find the associated value.
403 unsigned &TypeValue = CompletionTypes[CanUsageType];
404 if (TypeValue == 0) {
405 TypeValue = CompletionTypes.size();
406 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
407 = TypeValue;
408 }
409
410 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000411 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000412
Douglas Gregor8071e422010-08-15 06:18:01 +0000413 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000414
415 /// Handle nested-name-specifiers in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +0000416 if (TheSema->Context.getLangOpts().CPlusPlus &&
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000417 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
418 // The contexts in which a nested-name-specifier can appear in C++.
Richard Smith026b3582012-08-14 03:13:00 +0000419 uint64_t NNSContexts
420 = (1LL << CodeCompletionContext::CCC_TopLevel)
421 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
422 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
423 | (1LL << CodeCompletionContext::CCC_Statement)
424 | (1LL << CodeCompletionContext::CCC_Expression)
425 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
426 | (1LL << CodeCompletionContext::CCC_EnumTag)
427 | (1LL << CodeCompletionContext::CCC_UnionTag)
428 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
429 | (1LL << CodeCompletionContext::CCC_Type)
430 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
431 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000432
433 if (isa<NamespaceDecl>(Results[I].Declaration) ||
434 isa<NamespaceAliasDecl>(Results[I].Declaration))
Richard Smith026b3582012-08-14 03:13:00 +0000435 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000436
437 if (unsigned RemainingContexts
438 = NNSContexts & ~CachedResult.ShowInContexts) {
439 // If there any contexts where this completion can be a
440 // nested-name-specifier but isn't already an option, create a
441 // nested-name-specifier completion.
442 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregor218937c2011-02-01 19:23:04 +0000443 CachedResult.Completion
444 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000445 *CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000446 CCTUInfo,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000447 IncludeBriefCommentsInCodeCompletion);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000448 CachedResult.ShowInContexts = RemainingContexts;
449 CachedResult.Priority = CCP_NestedNameSpecifier;
450 CachedResult.TypeClass = STC_Void;
451 CachedResult.Type = 0;
452 CachedCompletionResults.push_back(CachedResult);
453 }
454 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000455 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000456 }
457
Douglas Gregor87c08a52010-08-13 22:48:40 +0000458 case Result::RK_Keyword:
459 case Result::RK_Pattern:
460 // Ignore keywords and patterns; we don't care, since they are so
461 // easily regenerated.
462 break;
463
464 case Result::RK_Macro: {
465 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000466 CachedResult.Completion
467 = Results[I].CreateCodeCompletionString(*TheSema,
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +0000468 *CachedCompletionAllocator,
Argyrios Kyrtzidis7fdc8fd2012-11-16 03:34:57 +0000469 CCTUInfo,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +0000470 IncludeBriefCommentsInCodeCompletion);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000471 CachedResult.ShowInContexts
Richard Smith026b3582012-08-14 03:13:00 +0000472 = (1LL << CodeCompletionContext::CCC_TopLevel)
473 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
474 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
475 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
476 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
477 | (1LL << CodeCompletionContext::CCC_Statement)
478 | (1LL << CodeCompletionContext::CCC_Expression)
479 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
480 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
481 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
482 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
483 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000484
Douglas Gregor87c08a52010-08-13 22:48:40 +0000485 CachedResult.Priority = Results[I].Priority;
486 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000487 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000488 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000489 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000490 CachedCompletionResults.push_back(CachedResult);
491 break;
492 }
493 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000494 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000495
496 // Save the current top-level hash value.
497 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000498}
499
500void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregor87c08a52010-08-13 22:48:40 +0000501 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000502 CachedCompletionTypes.clear();
Douglas Gregor48601b32011-02-16 19:08:06 +0000503 CachedCompletionAllocator = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000504}
505
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000506namespace {
507
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000508/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000509/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000510class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000511 Preprocessor &PP;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000512 ASTContext &Context;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000513 LangOptions &LangOpt;
Douglas Gregor57016dd2012-10-16 23:40:58 +0000514 IntrusiveRefCntPtr<TargetOptions> &TargetOpts;
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000515 IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000516 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000517
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000518 bool InitializedLanguage;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000519public:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000520 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
Douglas Gregor57016dd2012-10-16 23:40:58 +0000521 IntrusiveRefCntPtr<TargetOptions> &TargetOpts,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000522 IntrusiveRefCntPtr<TargetInfo> &Target,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000523 unsigned &Counter)
Argyrios Kyrtzidisf9ba8512013-05-08 23:46:55 +0000524 : PP(PP), Context(Context), LangOpt(LangOpt),
Douglas Gregor9a022bb2012-10-15 16:45:32 +0000525 TargetOpts(TargetOpts), Target(Target),
Argyrios Kyrtzidisf9ba8512013-05-08 23:46:55 +0000526 Counter(Counter),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000527 InitializedLanguage(false) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000528
Douglas Gregor27ffa6c2012-10-23 06:18:24 +0000529 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
Douglas Gregor38295be2012-10-22 23:51:00 +0000530 bool Complain) {
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000531 if (InitializedLanguage)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000532 return false;
533
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000534 LangOpt = LangOpts;
535 InitializedLanguage = true;
536
537 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000538 return false;
539 }
Mike Stump1eb44332009-09-09 15:08:12 +0000540
Douglas Gregor27ffa6c2012-10-23 06:18:24 +0000541 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
Douglas Gregor38295be2012-10-22 23:51:00 +0000542 bool Complain) {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000543 // If we've already initialized the target, don't do it again.
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000544 if (Target)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000545 return false;
546
Douglas Gregor57016dd2012-10-16 23:40:58 +0000547 this->TargetOpts = new TargetOptions(TargetOpts);
Douglas Gregor49a87542012-11-16 04:24:59 +0000548 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(),
549 &*this->TargetOpts);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000550
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000551 updated();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000552 return false;
553 }
Mike Stump1eb44332009-09-09 15:08:12 +0000554
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +0000555 virtual void ReadCounter(const serialization::ModuleFile &M, unsigned Value) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000556 Counter = Value;
557 }
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000558
559private:
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000560 void updated() {
561 if (!Target || !InitializedLanguage)
562 return;
563
564 // Inform the target of the language options.
565 //
566 // FIXME: We shouldn't need to do this, the target should be immutable once
567 // created. This complexity should be lifted elsewhere.
568 Target->setForcedLangOptions(LangOpt);
569
570 // Initialize the preprocessor.
571 PP.Initialize(*Target);
572
573 // Initialize the ASTContext
574 Context.InitBuiltinTypes(*Target);
Dmitri Gribenko6ebf0912013-02-22 14:21:27 +0000575
576 // We didn't have access to the comment options when the ASTContext was
577 // constructed, so register them now.
578 Context.getCommentCommandTraits().registerCommentOptions(
579 LangOpt.CommentOpts);
Argyrios Kyrtzidis7f186332012-09-14 20:24:53 +0000580 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000581};
582
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000583 /// \brief Diagnostic consumer that saves each diagnostic it is given.
David Blaikie26e7a902011-09-26 00:01:39 +0000584class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000585 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000586 SourceManager *SourceMgr;
587
Douglas Gregora88084b2010-02-18 18:08:43 +0000588public:
David Blaikie26e7a902011-09-26 00:01:39 +0000589 explicit StoredDiagnosticConsumer(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000590 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000591 : StoredDiags(StoredDiags), SourceMgr(0) { }
592
593 virtual void BeginSourceFile(const LangOptions &LangOpts,
594 const Preprocessor *PP = 0) {
595 if (PP)
596 SourceMgr = &PP->getSourceManager();
597 }
598
David Blaikied6471f72011-09-25 23:23:43 +0000599 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000600 const Diagnostic &Info);
Douglas Gregora88084b2010-02-18 18:08:43 +0000601};
602
603/// \brief RAII object that optionally captures diagnostics, if
604/// there is no diagnostic client to capture them already.
605class CaptureDroppedDiagnostics {
David Blaikied6471f72011-09-25 23:23:43 +0000606 DiagnosticsEngine &Diags;
David Blaikie26e7a902011-09-26 00:01:39 +0000607 StoredDiagnosticConsumer Client;
David Blaikie78ad0b92011-09-25 23:39:51 +0000608 DiagnosticConsumer *PreviousClient;
Douglas Gregora88084b2010-02-18 18:08:43 +0000609
610public:
David Blaikied6471f72011-09-25 23:23:43 +0000611 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000612 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000613 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000614 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000615 if (RequestCapture || Diags.getClient() == 0) {
616 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000617 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000618 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000619 }
620
621 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000622 if (Diags.getClient() == &Client) {
623 Diags.takeClient();
624 Diags.setClient(PreviousClient);
625 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000626 }
627};
628
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000629} // anonymous namespace
630
David Blaikie26e7a902011-09-26 00:01:39 +0000631void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000632 const Diagnostic &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000633 // Default implementation (Warnings/errors count).
David Blaikie78ad0b92011-09-25 23:39:51 +0000634 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000635
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000636 // Only record the diagnostic if it's part of the source manager we know
637 // about. This effectively drops diagnostics from modules we're building.
638 // FIXME: In the long run, ee don't want to drop source managers from modules.
639 if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr)
640 StoredDiags.push_back(StoredDiagnostic(Level, Info));
Douglas Gregora88084b2010-02-18 18:08:43 +0000641}
642
Argyrios Kyrtzidis7eca8d22013-05-10 01:28:51 +0000643ASTMutationListener *ASTUnit::getASTMutationListener() {
644 if (WriterData)
645 return &WriterData->Writer;
646 return 0;
647}
648
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000649ASTDeserializationListener *ASTUnit::getDeserializationListener() {
650 if (WriterData)
651 return &WriterData->Writer;
652 return 0;
653}
654
Chris Lattner5f9e2722011-07-23 10:55:15 +0000655llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner75dfb652010-11-23 09:19:42 +0000656 std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000657 assert(FileMgr);
Chris Lattner75dfb652010-11-23 09:19:42 +0000658 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000659}
660
Douglas Gregore47be3e2010-11-11 00:39:14 +0000661/// \brief Configure the diagnostics object for use with ASTUnit.
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000662void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000663 const char **ArgBegin, const char **ArgEnd,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000664 ASTUnit &AST, bool CaptureDiagnostics) {
665 if (!Diags.getPtr()) {
666 // No diagnostics engine was provided, so create our own diagnostics object
667 // with the default options.
David Blaikie78ad0b92011-09-25 23:39:51 +0000668 DiagnosticConsumer *Client = 0;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000669 if (CaptureDiagnostics)
David Blaikie26e7a902011-09-26 00:01:39 +0000670 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Douglas Gregor02c23eb2012-10-23 22:26:28 +0000671 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions(),
Sean Silvad47afb92013-01-20 01:58:28 +0000672 Client,
Douglas Gregorcc2b6532013-05-03 23:07:45 +0000673 /*ShouldOwnClient=*/true);
Douglas Gregore47be3e2010-11-11 00:39:14 +0000674 } else if (CaptureDiagnostics) {
David Blaikie26e7a902011-09-26 00:01:39 +0000675 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregore47be3e2010-11-11 00:39:14 +0000676 }
677}
678
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000679ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000680 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000681 const FileSystemOptions &FileSystemOpts,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000682 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000683 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000684 unsigned NumRemappedFiles,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000685 bool CaptureDiagnostics,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000686 bool AllowPCHWithCompilerErrors,
687 bool UserFilesAreVolatile) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000688 OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000689
690 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000691 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
692 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +0000693 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
694 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +0000695 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000696
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000697 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000698
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000699 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000700 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000701 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +0000702 AST->FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000703 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Ted Kremenek4f327862011-03-21 18:40:17 +0000704 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +0000705 AST->getFileManager(),
706 UserFilesAreVolatile);
Douglas Gregorc042edd2012-10-24 16:19:39 +0000707 AST->HSOpts = new HeaderSearchOptions();
708
709 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
710 AST->getFileManager(),
Douglas Gregor51f564f2011-12-31 04:05:44 +0000711 AST->getDiagnostics(),
Douglas Gregordc58aa72012-01-30 06:01:29 +0000712 AST->ASTFileLangOpts,
713 /*Target=*/0));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000714
Douglas Gregor4db64a42010-01-23 00:14:00 +0000715 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000716 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
717 if (const llvm::MemoryBuffer *
718 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
719 // Create the file entry for the file that we're mapping from.
720 const FileEntry *FromFile
721 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
722 memBuf->getBufferSize(),
723 0);
724 if (!FromFile) {
725 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
726 << RemappedFiles[I].first;
727 delete memBuf;
728 continue;
729 }
730
731 // Override the contents of the "from" file with the contents of
732 // the "to" file.
733 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
734
735 } else {
736 const char *fname = fileOrBuf.get<const char *>();
737 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
738 if (!ToFile) {
739 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
740 << RemappedFiles[I].first << fname;
741 continue;
742 }
743
744 // Create the file entry for the file that we're mapping from.
745 const FileEntry *FromFile
746 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
747 ToFile->getSize(),
748 0);
749 if (!FromFile) {
750 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
751 << RemappedFiles[I].first;
752 delete memBuf;
753 continue;
754 }
755
756 // Override the contents of the "from" file with the contents of
757 // the "to" file.
758 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000759 }
Douglas Gregor4db64a42010-01-23 00:14:00 +0000760 }
761
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000762 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000763
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000764 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000765 unsigned Counter;
766
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000767 OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000768
Douglas Gregor36a16492012-10-24 17:46:57 +0000769 AST->PP = new Preprocessor(new PreprocessorOptions(),
770 AST->getDiagnostics(), AST->ASTFileLangOpts,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000771 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
772 *AST,
773 /*IILookup=*/0,
774 /*OwnsHeaderSearch=*/false,
775 /*DelayInitialization=*/true);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000776 Preprocessor &PP = *AST->PP;
777
778 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
779 AST->getSourceManager(),
780 /*Target=*/0,
781 PP.getIdentifierTable(),
782 PP.getSelectorTable(),
783 PP.getBuiltinInfo(),
784 /* size_reserve = */0,
785 /*DelayInitialization=*/true);
786 ASTContext &Context = *AST->Ctx;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000787
Argyrios Kyrtzidis98e95bf2012-09-15 01:10:20 +0000788 bool disableValid = false;
789 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
790 disableValid = true;
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000791 Reader.reset(new ASTReader(PP, Context,
792 /*isysroot=*/"",
Argyrios Kyrtzidis98e95bf2012-09-15 01:10:20 +0000793 /*DisableValidation=*/disableValid,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +0000794 AllowPCHWithCompilerErrors));
Ted Kremenek8c647de2011-05-04 23:27:12 +0000795
796 // Recover resources if we crash before exiting this method.
797 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
798 ReaderCleanup(Reader.get());
799
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000800 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Argyrios Kyrtzidisf9ba8512013-05-08 23:46:55 +0000801 AST->ASTFileLangOpts,
Douglas Gregor9a022bb2012-10-15 16:45:32 +0000802 AST->TargetOpts, AST->Target,
Douglas Gregor43998902012-10-25 00:09:28 +0000803 Counter));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000804
Douglas Gregor38295be2012-10-22 23:51:00 +0000805 switch (Reader->ReadAST(Filename, serialization::MK_MainFile,
Argyrios Kyrtzidis958bcaf2012-11-15 18:57:22 +0000806 SourceLocation(), ASTReader::ARR_None)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000807 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000808 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000809
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000810 case ASTReader::Failure:
Douglas Gregor677e15f2013-03-19 00:28:20 +0000811 case ASTReader::Missing:
Douglas Gregor4825fd72012-10-22 22:50:17 +0000812 case ASTReader::OutOfDate:
813 case ASTReader::VersionMismatch:
814 case ASTReader::ConfigurationMismatch:
815 case ASTReader::HadErrors:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000816 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000817 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000818 }
Mike Stump1eb44332009-09-09 15:08:12 +0000819
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000820 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
821
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000822 PP.setCounterValue(Counter);
Mike Stump1eb44332009-09-09 15:08:12 +0000823
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000824 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000825 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000826 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000827 ASTReader *ReaderPtr = Reader.get();
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000828 OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek8c647de2011-05-04 23:27:12 +0000829
830 // Unregister the cleanup for ASTReader. It will get cleaned up
831 // by the ASTUnit cleanup.
832 ReaderCleanup.unregister();
833
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000834 Context.setExternalSource(Source);
835
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000836 // Create an AST consumer, even though it isn't used.
837 AST->Consumer.reset(new ASTConsumer);
838
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000839 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000840 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
841 AST->TheSema->Initialize();
842 ReaderPtr->InitializeSema(*AST->TheSema);
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000843 AST->Reader = ReaderPtr;
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000844
Douglas Gregora4a90ca2013-05-03 22:58:43 +0000845 // Tell the diagnostic client that we have started a source file.
846 AST->getDiagnostics().getClient()->BeginSourceFile(Context.getLangOpts(),&PP);
847
Mike Stump1eb44332009-09-09 15:08:12 +0000848 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000849}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000850
851namespace {
852
Douglas Gregor9b7db622011-02-16 18:16:54 +0000853/// \brief Preprocessor callback class that updates a hash value with the names
854/// of all macros that have been defined by the translation unit.
855class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
856 unsigned &Hash;
857
858public:
859 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
860
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +0000861 virtual void MacroDefined(const Token &MacroNameTok,
862 const MacroDirective *MD) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000863 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
864 }
865};
866
867/// \brief Add the given declaration to the hash of all top-level entities.
868void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
869 if (!D)
870 return;
871
872 DeclContext *DC = D->getDeclContext();
873 if (!DC)
874 return;
875
876 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
877 return;
878
879 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
Argyrios Kyrtzidise96a7b42013-10-15 17:37:55 +0000880 if (EnumDecl *EnumD = dyn_cast<EnumDecl>(D)) {
881 // For an unscoped enum include the enumerators in the hash since they
882 // enter the top-level namespace.
883 if (!EnumD->isScoped()) {
884 for (EnumDecl::enumerator_iterator EI = EnumD->enumerator_begin(),
885 EE = EnumD->enumerator_end(); EI != EE; ++EI) {
886 if ((*EI)->getIdentifier())
887 Hash = llvm::HashString((*EI)->getIdentifier()->getName(), Hash);
888 }
889 }
890 }
891
Douglas Gregor9b7db622011-02-16 18:16:54 +0000892 if (ND->getIdentifier())
893 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
894 else if (DeclarationName Name = ND->getDeclName()) {
895 std::string NameStr = Name.getAsString();
896 Hash = llvm::HashString(NameStr, Hash);
897 }
898 return;
Argyrios Kyrtzidis1f3ff6a2013-06-24 21:19:12 +0000899 }
900
901 if (ImportDecl *ImportD = dyn_cast<ImportDecl>(D)) {
902 if (Module *Mod = ImportD->getImportedModule()) {
903 std::string ModName = Mod->getFullModuleName();
904 Hash = llvm::HashString(ModName, Hash);
905 }
906 return;
907 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000908}
909
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000910class TopLevelDeclTrackerConsumer : public ASTConsumer {
911 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000912 unsigned &Hash;
913
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000914public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000915 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
916 : Unit(_Unit), Hash(Hash) {
917 Hash = 0;
918 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000919
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000920 void handleTopLevelDecl(Decl *D) {
Argyrios Kyrtzidis35593a92011-11-16 02:35:10 +0000921 if (!D)
922 return;
923
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000924 // FIXME: Currently ObjC method declarations are incorrectly being
925 // reported as top-level declarations, even though their DeclContext
926 // is the containing ObjC @interface/@implementation. This is a
927 // fundamental problem in the parser right now.
928 if (isa<ObjCMethodDecl>(D))
929 return;
930
931 AddTopLevelDeclarationToHash(D, Hash);
932 Unit.addTopLevelDecl(D);
933
934 handleFileLevelDecl(D);
935 }
936
937 void handleFileLevelDecl(Decl *D) {
938 Unit.addFileLevelDecl(D);
939 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
940 for (NamespaceDecl::decl_iterator
941 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
942 handleFileLevelDecl(*I);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000943 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000944 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000945
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000946 bool HandleTopLevelDecl(DeclGroupRef D) {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000947 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
948 handleTopLevelDecl(*it);
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000949 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000950 }
951
Sebastian Redl27372b42010-08-11 18:52:41 +0000952 // We're not interested in "interesting" decls.
953 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000954
955 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
956 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
957 handleTopLevelDecl(*it);
958 }
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000959
Argyrios Kyrtzidis7eca8d22013-05-10 01:28:51 +0000960 virtual ASTMutationListener *GetASTMutationListener() {
961 return Unit.getASTMutationListener();
962 }
963
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +0000964 virtual ASTDeserializationListener *GetASTDeserializationListener() {
965 return Unit.getDeserializationListener();
966 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000967};
968
969class TopLevelDeclTrackerAction : public ASTFrontendAction {
970public:
971 ASTUnit &Unit;
972
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000973 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000974 StringRef InFile) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000975 CI.getPreprocessor().addPPCallbacks(
976 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
977 return new TopLevelDeclTrackerConsumer(Unit,
978 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000979 }
980
981public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000982 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
983
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000984 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000985 virtual TranslationUnitKind getTranslationUnitKind() {
986 return Unit.getTranslationUnitKind();
Douglas Gregordf95a132010-08-09 20:45:32 +0000987 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000988};
989
Benjamin Kramerb62b8b92013-06-11 13:07:19 +0000990class PrecompilePreambleAction : public ASTFrontendAction {
991 ASTUnit &Unit;
992 bool HasEmittedPreamblePCH;
993
994public:
995 explicit PrecompilePreambleAction(ASTUnit &Unit)
996 : Unit(Unit), HasEmittedPreamblePCH(false) {}
997
998 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
999 StringRef InFile);
1000 bool hasEmittedPreamblePCH() const { return HasEmittedPreamblePCH; }
1001 void setHasEmittedPreamblePCH() { HasEmittedPreamblePCH = true; }
1002 virtual bool shouldEraseOutputFiles() { return !hasEmittedPreamblePCH(); }
1003
1004 virtual bool hasCodeCompletionSupport() const { return false; }
1005 virtual bool hasASTFileSupport() const { return false; }
1006 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
1007};
1008
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +00001009class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001010 ASTUnit &Unit;
Benjamin Kramerb62b8b92013-06-11 13:07:19 +00001011 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001012 std::vector<Decl *> TopLevelDecls;
Benjamin Kramerb62b8b92013-06-11 13:07:19 +00001013 PrecompilePreambleAction *Action;
1014
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001015public:
Benjamin Kramerb62b8b92013-06-11 13:07:19 +00001016 PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action,
1017 const Preprocessor &PP, StringRef isysroot,
1018 raw_ostream *Out)
Argyrios Kyrtzidis1f01f7c2013-06-11 00:36:55 +00001019 : PCHGenerator(PP, "", 0, isysroot, Out, /*AllowASTWithErrors=*/true),
Benjamin Kramerb62b8b92013-06-11 13:07:19 +00001020 Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action) {
Douglas Gregor9b7db622011-02-16 18:16:54 +00001021 Hash = 0;
1022 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001023
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +00001024 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001025 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
1026 Decl *D = *it;
1027 // FIXME: Currently ObjC method declarations are incorrectly being
1028 // reported as top-level declarations, even though their DeclContext
1029 // is the containing ObjC @interface/@implementation. This is a
1030 // fundamental problem in the parser right now.
1031 if (isa<ObjCMethodDecl>(D))
1032 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +00001033 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001034 TopLevelDecls.push_back(D);
1035 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +00001036 return true;
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001037 }
1038
1039 virtual void HandleTranslationUnit(ASTContext &Ctx) {
1040 PCHGenerator::HandleTranslationUnit(Ctx);
Argyrios Kyrtzidis1f01f7c2013-06-11 00:36:55 +00001041 if (hasEmittedPCH()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001042 // Translate the top-level declarations we captured during
1043 // parsing into declaration IDs in the precompiled
1044 // preamble. This will allow us to deserialize those top-level
1045 // declarations when requested.
Argyrios Kyrtzidis51e75ae2013-08-07 21:17:33 +00001046 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I) {
1047 Decl *D = TopLevelDecls[I];
1048 // Invalid top-level decls may not have been serialized.
1049 if (D->isInvalidDecl())
1050 continue;
1051 Unit.addTopLevelDeclFromPreamble(getWriter().getDeclID(D));
1052 }
Benjamin Kramerb62b8b92013-06-11 13:07:19 +00001053
1054 Action->setHasEmittedPreamblePCH();
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001055 }
1056 }
1057};
1058
Benjamin Kramerb62b8b92013-06-11 13:07:19 +00001059}
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001060
Benjamin Kramerb62b8b92013-06-11 13:07:19 +00001061ASTConsumer *PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI,
1062 StringRef InFile) {
1063 std::string Sysroot;
1064 std::string OutputFile;
1065 raw_ostream *OS = 0;
1066 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
1067 OutputFile, OS))
1068 return 0;
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001069
Benjamin Kramerb62b8b92013-06-11 13:07:19 +00001070 if (!CI.getFrontendOpts().RelocatablePCH)
1071 Sysroot.clear();
Douglas Gregor832d6202011-07-22 16:35:34 +00001072
Benjamin Kramerb62b8b92013-06-11 13:07:19 +00001073 CI.getPreprocessor().addPPCallbacks(new MacroDefinitionTrackerPPCallbacks(
1074 Unit.getCurrentTopLevelHashValue()));
1075 return new PrecompilePreambleConsumer(Unit, this, CI.getPreprocessor(),
1076 Sysroot, OS);
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001077}
1078
Benjamin Kramerfe57db22013-05-05 12:39:28 +00001079static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
1080 return StoredDiag.getLocation().isValid();
1081}
1082
1083static void
1084checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001085 // Get rid of stored diagnostics except the ones from the driver which do not
1086 // have a source location.
Benjamin Kramerfe57db22013-05-05 12:39:28 +00001087 StoredDiags.erase(
1088 std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1089 StoredDiags.end());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001090}
1091
1092static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1093 StoredDiagnostics,
1094 SourceManager &SM) {
1095 // The stored diagnostic has the old source manager in it; update
1096 // the locations to refer into the new source manager. Since we've
1097 // been careful to make sure that the source manager's state
1098 // before and after are identical, so that we can reuse the source
1099 // location itself.
1100 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1101 if (StoredDiagnostics[I].getLocation().isValid()) {
1102 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1103 StoredDiagnostics[I].setLocation(Loc);
1104 }
1105 }
1106}
1107
Douglas Gregorabc563f2010-07-19 21:46:24 +00001108/// Parse the source file into a translation unit using the given compiler
1109/// invocation, replacing the current translation unit.
1110///
1111/// \returns True if a failure occurred that causes the ASTUnit not to
1112/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +00001113bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +00001114 delete SavedMainFileBuffer;
1115 SavedMainFileBuffer = 0;
1116
Ted Kremenek4f327862011-03-21 18:40:17 +00001117 if (!Invocation) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001118 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001119 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001120 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001121
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001122 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001123 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001124
1125 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001126 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1127 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001128
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001129 IntrusiveRefCntPtr<CompilerInvocation>
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +00001130 CCInvocation(new CompilerInvocation(*Invocation));
1131
1132 Clang->setInvocation(CCInvocation.getPtr());
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001133 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001134
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001135 // Set up diagnostics, capturing any diagnostics that would
1136 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001137 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001138
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001139 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001140 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00001141 &Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001142 if (!Clang->hasTarget()) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001143 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001144 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001145 }
1146
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001147 // Inform the target of the language options.
1148 //
1149 // FIXME: We shouldn't need to do this, the target should be immutable once
1150 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001151 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001152
Ted Kremenek03201fb2011-03-21 18:40:07 +00001153 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001154 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001155 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001156 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001157 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +00001158 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001159
Douglas Gregorabc563f2010-07-19 21:46:24 +00001160 // Configure the various subsystems.
1161 // FIXME: Should we retain the previous file manager?
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001162 LangOpts = &Clang->getLangOpts();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001163 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001164 FileMgr = new FileManager(FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001165 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1166 UserFilesAreVolatile);
Douglas Gregor914ed9d2010-08-13 03:15:25 +00001167 TheSema.reset();
Ted Kremenek4f327862011-03-21 18:40:17 +00001168 Ctx = 0;
1169 PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001170 Reader = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001171
1172 // Clear out old caches and data.
1173 TopLevelDecls.clear();
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001174 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001175 CleanTemporaryFiles();
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001176
Douglas Gregorf128fed2010-08-20 00:02:33 +00001177 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001178 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf128fed2010-08-20 00:02:33 +00001179 TopLevelDeclsInPreamble.clear();
1180 }
1181
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001182 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001183 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001184
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001185 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001186 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001187
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001188 // If the main file has been overridden due to the use of a preamble,
1189 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001190 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001191 if (OverrideMainBuffer) {
1192 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1193 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1194 PreprocessorOpts.PrecompiledPreambleBytes.second
1195 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00001196 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001197 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +00001198
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001199 // The stored diagnostic has the old source manager in it; update
1200 // the locations to refer into the new source manager. Since we've
1201 // been careful to make sure that the source manager's state
1202 // before and after are identical, so that we can reuse the source
1203 // location itself.
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001204 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001205
1206 // Keep track of the override buffer;
1207 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001208 }
1209
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001210 OwningPtr<TopLevelDeclTrackerAction> Act(
Ted Kremenek25a11e12011-03-22 01:15:24 +00001211 new TopLevelDeclTrackerAction(*this));
1212
1213 // Recover resources if we crash before exiting this method.
1214 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1215 ActCleanup(Act.get());
1216
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001217 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001218 goto error;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001219
1220 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00001221 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001222 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1223 getSourceManager(), PreambleDiagnostics,
1224 StoredDiagnostics);
1225 }
1226
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001227 if (!Act->Execute())
1228 goto error;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001229
1230 transferASTDataFromCompilerInstance(*Clang);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001231
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001232 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001233
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001234 FailedParseDiagnostics.clear();
1235
Douglas Gregorabc563f2010-07-19 21:46:24 +00001236 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +00001237
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001238error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001239 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001240 if (OverrideMainBuffer) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001241 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +00001242 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001243 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001244
1245 // Keep the ownership of the data in the ASTUnit because the client may
1246 // want to see the diagnostics.
1247 transferASTDataFromCompilerInstance(*Clang);
1248 FailedParseDiagnostics.swap(StoredDiagnostics);
Douglas Gregord54eb442010-10-12 16:25:54 +00001249 StoredDiagnostics.clear();
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001250 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001251 return true;
1252}
1253
Douglas Gregor44c181a2010-07-23 00:33:23 +00001254/// \brief Simple function to retrieve a path for a preamble precompiled header.
1255static std::string GetPreamblePCHPath() {
Douglas Gregor424668c2010-09-11 18:05:19 +00001256 // FIXME: This is a hack so that we can override the preamble file during
1257 // crash-recovery testing, which is the only case where the preamble files
Rafael Espindola85d28482013-06-26 04:02:37 +00001258 // are not necessarily cleaned up.
Douglas Gregor424668c2010-09-11 18:05:19 +00001259 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1260 if (TmpFile)
1261 return TmpFile;
Rafael Espindola85d28482013-06-26 04:02:37 +00001262
1263 SmallString<128> Path;
Rafael Espindola1ec4a862013-07-05 20:00:06 +00001264 llvm::sys::fs::createTemporaryFile("preamble", "pch", Path);
Rafael Espindola85d28482013-06-26 04:02:37 +00001265
1266 return Path.str();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001267}
1268
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001269/// \brief Compute the preamble for the main file, providing the source buffer
1270/// that corresponds to the main file along with a pair (bytes, start-of-line)
1271/// that describes the preamble.
1272std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +00001273ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1274 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001275 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001276 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001277 CreatedBuffer = false;
1278
Douglas Gregor44c181a2010-07-23 00:33:23 +00001279 // Try to determine if the main file has been remapped, either from the
1280 // command line (to another file) or directly through the compiler invocation
1281 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +00001282 llvm::MemoryBuffer *Buffer = 0;
Rafael Espindola105b2072013-06-18 19:40:07 +00001283 std::string MainFilePath(FrontendOpts.Inputs[0].getFile());
Rafael Espindola44888352013-07-29 21:26:52 +00001284 llvm::sys::fs::UniqueID MainFileID;
Rafael Espindolada4cb0c2013-06-20 15:12:38 +00001285 if (!llvm::sys::fs::getUniqueID(MainFilePath, MainFileID)) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001286 // Check whether there is a file-file remapping of the main file
1287 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +00001288 M = PreprocessorOpts.remapped_file_begin(),
1289 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001290 M != E;
1291 ++M) {
Rafael Espindola105b2072013-06-18 19:40:07 +00001292 std::string MPath(M->first);
Rafael Espindola44888352013-07-29 21:26:52 +00001293 llvm::sys::fs::UniqueID MID;
Rafael Espindolada4cb0c2013-06-20 15:12:38 +00001294 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindola105b2072013-06-18 19:40:07 +00001295 if (MainFileID == MID) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001296 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001297 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001298 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001299 CreatedBuffer = false;
1300 }
1301
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001302 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001303 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001304 return std::make_pair((llvm::MemoryBuffer*)0,
1305 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001306 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001307 }
1308 }
1309 }
1310
1311 // Check whether there is a file-buffer remapping. It supercedes the
1312 // file-file remapping.
1313 for (PreprocessorOptions::remapped_file_buffer_iterator
1314 M = PreprocessorOpts.remapped_file_buffer_begin(),
1315 E = PreprocessorOpts.remapped_file_buffer_end();
1316 M != E;
1317 ++M) {
Rafael Espindola105b2072013-06-18 19:40:07 +00001318 std::string MPath(M->first);
Rafael Espindola44888352013-07-29 21:26:52 +00001319 llvm::sys::fs::UniqueID MID;
Rafael Espindolada4cb0c2013-06-20 15:12:38 +00001320 if (!llvm::sys::fs::getUniqueID(MPath, MID)) {
Rafael Espindola105b2072013-06-18 19:40:07 +00001321 if (MainFileID == MID) {
1322 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001323 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001324 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001325 CreatedBuffer = false;
1326 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001327
Douglas Gregor175c4a92010-07-23 23:58:40 +00001328 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001329 }
1330 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001331 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001332 }
1333
1334 // If the main source file was not remapped, load it now.
1335 if (!Buffer) {
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001336 Buffer = getBufferForFile(FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001337 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001338 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001339
1340 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001341 }
1342
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001343 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
Ted Kremenekd3b74d92011-11-17 23:01:24 +00001344 *Invocation.getLangOpts(),
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001345 MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001346}
1347
Douglas Gregor754f3492010-07-24 00:38:13 +00001348static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +00001349 unsigned NewSize,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001350 StringRef NewName) {
Douglas Gregor754f3492010-07-24 00:38:13 +00001351 llvm::MemoryBuffer *Result
1352 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1353 memcpy(const_cast<char*>(Result->getBufferStart()),
1354 Old->getBufferStart(), Old->getBufferSize());
1355 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001356 ' ', NewSize - Old->getBufferSize() - 1);
1357 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +00001358
Douglas Gregor754f3492010-07-24 00:38:13 +00001359 return Result;
1360}
1361
Douglas Gregor175c4a92010-07-23 23:58:40 +00001362/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1363/// the source file.
1364///
1365/// This routine will compute the preamble of the main source file. If a
1366/// non-trivial preamble is found, it will precompile that preamble into a
1367/// precompiled header so that the precompiled preamble can be used to reduce
1368/// reparsing time. If a precompiled preamble has already been constructed,
1369/// this routine will determine if it is still valid and, if so, avoid
1370/// rebuilding the precompiled preamble.
1371///
Douglas Gregordf95a132010-08-09 20:45:32 +00001372/// \param AllowRebuild When true (the default), this routine is
1373/// allowed to rebuild the precompiled preamble if it is found to be
1374/// out-of-date.
1375///
1376/// \param MaxLines When non-zero, the maximum number of lines that
1377/// can occur within the preamble.
1378///
Douglas Gregor754f3492010-07-24 00:38:13 +00001379/// \returns If the precompiled preamble can be used, returns a newly-allocated
1380/// buffer that should be used in place of the main file when doing so.
1381/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001382llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor01b6e312011-07-01 18:22:13 +00001383 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregordf95a132010-08-09 20:45:32 +00001384 bool AllowRebuild,
1385 unsigned MaxLines) {
Douglas Gregor01b6e312011-07-01 18:22:13 +00001386
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001387 IntrusiveRefCntPtr<CompilerInvocation>
Douglas Gregor01b6e312011-07-01 18:22:13 +00001388 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1389 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001390 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001391 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001392
1393 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001394 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor01b6e312011-07-01 18:22:13 +00001395 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001396
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001397 // If ComputePreamble() Take ownership of the preamble buffer.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001398 OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
Douglas Gregor73fc9122010-11-16 20:45:51 +00001399 if (CreatedPreambleBuffer)
1400 OwnedPreambleBuffer.reset(NewPreamble.first);
1401
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001402 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001403 // We couldn't find a preamble in the main source. Clear out the current
1404 // preamble, if we have one. It's obviously no good any more.
1405 Preamble.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001406 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001407
1408 // The next time we actually see a preamble, precompile it.
1409 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001410 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001411 }
1412
1413 if (!Preamble.empty()) {
1414 // We've previously computed a preamble. Check whether we have the same
1415 // preamble now that we did before, and that there's enough space in
1416 // the main-file buffer within the precompiled preamble to fit the
1417 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001418 if (Preamble.size() == NewPreamble.second.first &&
1419 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001420 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001421 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001422 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001423 // The preamble has not changed. We may be able to re-use the precompiled
1424 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001425
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001426 // Check that none of the files used by the preamble have changed.
1427 bool AnyFileChanged = false;
1428
1429 // First, make a record of those files that have been overridden via
1430 // remapping or unsaved_files.
1431 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1432 for (PreprocessorOptions::remapped_file_iterator
1433 R = PreprocessorOpts.remapped_file_begin(),
1434 REnd = PreprocessorOpts.remapped_file_end();
1435 !AnyFileChanged && R != REnd;
1436 ++R) {
Rafael Espindolaaefb1d32013-07-29 18:22:23 +00001437 llvm::sys::fs::file_status Status;
1438 if (FileMgr->getNoncachedStatValue(R->second, Status)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001439 // If we can't stat the file we're remapping to, assume that something
1440 // horrible happened.
1441 AnyFileChanged = true;
1442 break;
1443 }
Rafael Espindolaaefb1d32013-07-29 18:22:23 +00001444
1445 OverriddenFiles[R->first] = std::make_pair(
1446 Status.getSize(), Status.getLastModificationTime().toEpochTime());
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001447 }
1448 for (PreprocessorOptions::remapped_file_buffer_iterator
1449 R = PreprocessorOpts.remapped_file_buffer_begin(),
1450 REnd = PreprocessorOpts.remapped_file_buffer_end();
1451 !AnyFileChanged && R != REnd;
1452 ++R) {
1453 // FIXME: Should we actually compare the contents of file->buffer
1454 // remappings?
1455 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1456 0);
1457 }
1458
1459 // Check whether anything has changed.
1460 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1461 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1462 !AnyFileChanged && F != FEnd;
1463 ++F) {
1464 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1465 = OverriddenFiles.find(F->first());
1466 if (Overridden != OverriddenFiles.end()) {
1467 // This file was remapped; check whether the newly-mapped file
1468 // matches up with the previous mapping.
1469 if (Overridden->second != F->second)
1470 AnyFileChanged = true;
1471 continue;
1472 }
1473
1474 // The file was not remapped; check whether it has changed on disk.
Rafael Espindolaaefb1d32013-07-29 18:22:23 +00001475 llvm::sys::fs::file_status Status;
1476 if (FileMgr->getNoncachedStatValue(F->first(), Status)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001477 // If we can't stat the file, assume that something horrible happened.
1478 AnyFileChanged = true;
Rafael Espindolaaefb1d32013-07-29 18:22:23 +00001479 } else if (Status.getSize() != uint64_t(F->second.first) ||
1480 Status.getLastModificationTime().toEpochTime() !=
1481 uint64_t(F->second.second))
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001482 AnyFileChanged = true;
1483 }
1484
1485 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001486 // Okay! We can re-use the precompiled preamble.
1487
1488 // Set the state of the diagnostic object to mimic its state
1489 // after parsing the preamble.
1490 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001491 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001492 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001493 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001494
1495 // Create a version of the main file buffer that is padded to
1496 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001497 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001498 PreambleReservedSize,
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001499 FrontendOpts.Inputs[0].getFile());
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001500 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001501 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001502
1503 // If we aren't allowed to rebuild the precompiled preamble, just
1504 // return now.
1505 if (!AllowRebuild)
1506 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001507
Douglas Gregor175c4a92010-07-23 23:58:40 +00001508 // We can't reuse the previously-computed preamble. Build a new one.
1509 Preamble.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001510 PreambleDiagnostics.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001511 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001512 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001513 } else if (!AllowRebuild) {
1514 // We aren't allowed to rebuild the precompiled preamble; just
1515 // return now.
1516 return 0;
1517 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001518
1519 // If the preamble rebuild counter > 1, it's because we previously
1520 // failed to build a preamble and we're not yet ready to try
1521 // again. Decrement the counter and return a failure.
1522 if (PreambleRebuildCounter > 1) {
1523 --PreambleRebuildCounter;
1524 return 0;
1525 }
1526
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001527 // Create a temporary file for the precompiled preamble. In rare
1528 // circumstances, this can fail.
1529 std::string PreamblePCHPath = GetPreamblePCHPath();
1530 if (PreamblePCHPath.empty()) {
1531 // Try again next time.
1532 PreambleRebuildCounter = 1;
1533 return 0;
1534 }
1535
Douglas Gregor175c4a92010-07-23 23:58:40 +00001536 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001537 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001538 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001539
1540 // Create a new buffer that stores the preamble. The buffer also contains
1541 // extra space for the original contents of the file (which will be present
1542 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001543 // grows.
1544 PreambleReservedSize = NewPreamble.first->getBufferSize();
1545 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001546 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001547 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001548 PreambleReservedSize *= 2;
1549
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001550 // Save the preamble text for later; we'll need to compare against it for
1551 // subsequent reparses.
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001552 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001553 Preamble.assign(FileMgr->getFile(MainFilename),
1554 NewPreamble.first->getBufferStart(),
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001555 NewPreamble.first->getBufferStart()
1556 + NewPreamble.second.first);
1557 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1558
Douglas Gregor671947b2010-08-19 01:33:06 +00001559 delete PreambleBuffer;
1560 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001561 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001562 FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001563 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001564 NewPreamble.first->getBufferStart(), Preamble.size());
1565 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001566 ' ', PreambleReservedSize - Preamble.size() - 1);
1567 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Rafael Espindola1cd7df42013-06-26 04:12:57 +00001568
Douglas Gregor44c181a2010-07-23 00:33:23 +00001569 // Remap the main source file to the preamble buffer.
Rafael Espindola1cd7df42013-06-26 04:12:57 +00001570 StringRef MainFilePath = FrontendOpts.Inputs[0].getFile();
1571 PreprocessorOpts.addRemappedFile(MainFilePath, PreambleBuffer);
1572
Douglas Gregor44c181a2010-07-23 00:33:23 +00001573 // Tell the compiler invocation to generate a temporary precompiled header.
1574 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001575 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001576 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001577 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1578 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001579
1580 // Create the compiler instance to use for building the precompiled preamble.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001581 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001582
1583 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001584 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1585 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001586
Douglas Gregor01b6e312011-07-01 18:22:13 +00001587 Clang->setInvocation(&*PreambleInvocation);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001588 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001589
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001590 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001591 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001592
1593 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001594 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00001595 &Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001596 if (!Clang->hasTarget()) {
Rafael Espindola21b18242013-06-26 04:26:38 +00001597 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001598 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001599 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001600 PreprocessorOpts.eraseRemappedFile(
1601 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001602 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001603 }
1604
1605 // Inform the target of the language options.
1606 //
1607 // FIXME: We shouldn't need to do this, the target should be immutable once
1608 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001609 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001610
Ted Kremenek03201fb2011-03-21 18:40:07 +00001611 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001612 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001613 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001614 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001615 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001616 "IR inputs not support here!");
1617
1618 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001619 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001620 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001621 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001622 TopLevelDecls.clear();
1623 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001624
1625 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001626 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001627
1628 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001629 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001630 Clang->getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001631
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001632 OwningPtr<PrecompilePreambleAction> Act;
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001633 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00001634 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Rafael Espindola21b18242013-06-26 04:26:38 +00001635 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001636 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001637 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001638 PreprocessorOpts.eraseRemappedFile(
1639 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001640 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001641 }
1642
1643 Act->Execute();
1644 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001645
Argyrios Kyrtzidis1f01f7c2013-06-11 00:36:55 +00001646 if (!Act->hasEmittedPreamblePCH()) {
Argyrios Kyrtzidis739f9e52013-06-11 16:42:34 +00001647 // The preamble PCH failed (e.g. there was a module loading fatal error),
1648 // so no precompiled header was generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001649 // FIXME: Should we leave a note for ourselves to try again?
Rafael Espindola21b18242013-06-26 04:26:38 +00001650 llvm::sys::fs::remove(FrontendOpts.OutputFile);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001651 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001652 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001653 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001654 PreprocessorOpts.eraseRemappedFile(
1655 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001656 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001657 }
1658
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001659 // Transfer any diagnostics generated when parsing the preamble into the set
1660 // of preamble diagnostics.
1661 PreambleDiagnostics.clear();
1662 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001663 stored_diag_afterDriver_begin(), stored_diag_end());
Argyrios Kyrtzidis7f3a4582012-02-01 19:54:02 +00001664 checkAndRemoveNonDriverDiags(StoredDiagnostics);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001665
Douglas Gregor175c4a92010-07-23 23:58:40 +00001666 // Keep track of the preamble we precompiled.
Ted Kremenek1872b312011-10-27 17:55:18 +00001667 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001668 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001669
1670 // Keep track of all of the files that the source manager knows about,
1671 // so we can verify whether they have changed or not.
1672 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001673 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001674 const llvm::MemoryBuffer *MainFileBuffer
1675 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1676 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1677 FEnd = SourceMgr.fileinfo_end();
1678 F != FEnd;
1679 ++F) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001680 const FileEntry *File = F->second->OrigEntry;
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001681 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1682 continue;
1683
1684 FilesInPreamble[File->getName()]
1685 = std::make_pair(F->second->getSize(), File->getModificationTime());
1686 }
1687
Douglas Gregoreababfb2010-08-04 05:53:38 +00001688 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001689 PreprocessorOpts.eraseRemappedFile(
1690 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor9b7db622011-02-16 18:16:54 +00001691
1692 // If the hash of top-level entities differs from the hash of the top-level
1693 // entities the last time we rebuilt the preamble, clear out the completion
1694 // cache.
1695 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1696 CompletionCacheTopLevelHashValue = 0;
1697 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1698 }
1699
Douglas Gregor754f3492010-07-24 00:38:13 +00001700 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001701 PreambleReservedSize,
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001702 FrontendOpts.Inputs[0].getFile());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001703}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001704
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001705void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1706 std::vector<Decl *> Resolved;
1707 Resolved.reserve(TopLevelDeclsInPreamble.size());
1708 ExternalASTSource &Source = *getASTContext().getExternalSource();
1709 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1710 // Resolve the declaration ID to an actual declaration, possibly
1711 // deserializing the declaration in the process.
1712 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1713 if (D)
1714 Resolved.push_back(D);
1715 }
1716 TopLevelDeclsInPreamble.clear();
1717 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1718}
1719
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001720void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1721 // Steal the created target, context, and preprocessor.
1722 TheSema.reset(CI.takeSema());
1723 Consumer.reset(CI.takeASTConsumer());
1724 Ctx = &CI.getASTContext();
1725 PP = &CI.getPreprocessor();
1726 CI.setSourceManager(0);
1727 CI.setFileManager(0);
1728 Target = &CI.getTarget();
1729 Reader = CI.getModuleManager();
Argyrios Kyrtzidis3b7deda2013-05-24 05:44:08 +00001730 HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001731}
1732
Chris Lattner5f9e2722011-07-23 10:55:15 +00001733StringRef ASTUnit::getMainFileName() const {
Argyrios Kyrtzidis814b51a2013-01-11 22:11:14 +00001734 if (Invocation && !Invocation->getFrontendOpts().Inputs.empty()) {
1735 const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1736 if (Input.isFile())
1737 return Input.getFile();
1738 else
1739 return Input.getBuffer()->getBufferIdentifier();
1740 }
1741
1742 if (SourceMgr) {
1743 if (const FileEntry *
1744 FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1745 return FE->getName();
1746 }
1747
1748 return StringRef();
Douglas Gregor213f18b2010-10-28 15:44:59 +00001749}
1750
Argyrios Kyrtzidis44f65a52013-03-05 20:21:14 +00001751StringRef ASTUnit::getASTFileName() const {
1752 if (!isMainFileAST())
1753 return StringRef();
1754
1755 serialization::ModuleFile &
1756 Mod = Reader->getModuleManager().getPrimaryModule();
1757 return Mod.FileName;
1758}
1759
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001760ASTUnit *ASTUnit::create(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001761 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001762 bool CaptureDiagnostics,
1763 bool UserFilesAreVolatile) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001764 OwningPtr<ASTUnit> AST;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001765 AST.reset(new ASTUnit(false));
Argyrios Kyrtzidis991bf492011-11-28 04:55:55 +00001766 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001767 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001768 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001769 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001770 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001771 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1772 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1773 UserFilesAreVolatile);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001774
1775 return AST.take();
1776}
1777
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001778ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001779 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001780 ASTFrontendAction *Action,
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001781 ASTUnit *Unit,
1782 bool Persistent,
1783 StringRef ResourceFilesPath,
1784 bool OnlyLocalDecls,
1785 bool CaptureDiagnostics,
1786 bool PrecompilePreamble,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001787 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001788 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001789 bool UserFilesAreVolatile,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001790 OwningPtr<ASTUnit> *ErrAST) {
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001791 assert(CI && "A CompilerInvocation is required");
1792
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001793 OwningPtr<ASTUnit> OwnAST;
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001794 ASTUnit *AST = Unit;
1795 if (!AST) {
1796 // Create the AST unit.
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001797 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001798 AST = OwnAST.get();
1799 }
1800
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001801 if (!ResourceFilesPath.empty()) {
1802 // Override the resources path.
1803 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1804 }
1805 AST->OnlyLocalDecls = OnlyLocalDecls;
1806 AST->CaptureDiagnostics = CaptureDiagnostics;
1807 if (PrecompilePreamble)
1808 AST->PreambleRebuildCounter = 2;
Douglas Gregor467dc882011-08-25 22:30:56 +00001809 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001810 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001811 AST->IncludeBriefCommentsInCodeCompletion
1812 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001813
1814 // Recover resources if we crash before exiting this method.
1815 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001816 ASTUnitCleanup(OwnAST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001817 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1818 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001819 DiagCleanup(Diags.getPtr());
1820
1821 // We'll manage file buffers ourselves.
1822 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1823 CI->getFrontendOpts().DisableFree = false;
1824 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1825
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001826 // Create the compiler instance to use for building the AST.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001827 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001828
1829 // Recover resources if we crash before exiting this method.
1830 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1831 CICleanup(Clang.get());
1832
1833 Clang->setInvocation(CI);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001834 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001835
1836 // Set up diagnostics, capturing any diagnostics that would
1837 // otherwise be dropped.
1838 Clang->setDiagnostics(&AST->getDiagnostics());
1839
1840 // Create the target instance.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001841 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00001842 &Clang->getTargetOpts()));
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001843 if (!Clang->hasTarget())
1844 return 0;
1845
1846 // Inform the target of the language options.
1847 //
1848 // FIXME: We shouldn't need to do this, the target should be immutable once
1849 // created. This complexity should be lifted elsewhere.
1850 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1851
1852 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1853 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001854 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001855 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00001856 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001857 "IR inputs not supported here!");
1858
1859 // Configure the various subsystems.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001860 AST->TheSema.reset();
1861 AST->Ctx = 0;
1862 AST->PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001863 AST->Reader = 0;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001864
1865 // Create a file manager object to provide access to and cache the filesystem.
1866 Clang->setFileManager(&AST->getFileManager());
1867
1868 // Create the source manager.
1869 Clang->setSourceManager(&AST->getSourceManager());
1870
1871 ASTFrontendAction *Act = Action;
1872
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001873 OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001874 if (!Act) {
1875 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1876 Act = TrackerAct.get();
1877 }
1878
1879 // Recover resources if we crash before exiting this method.
1880 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1881 ActCleanup(TrackerAct.get());
1882
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001883 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1884 AST->transferASTDataFromCompilerInstance(*Clang);
1885 if (OwnAST && ErrAST)
1886 ErrAST->swap(OwnAST);
1887
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001888 return 0;
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001889 }
Argyrios Kyrtzidis6f3ce972011-11-28 04:56:00 +00001890
1891 if (Persistent && !TrackerAct) {
1892 Clang->getPreprocessor().addPPCallbacks(
1893 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1894 std::vector<ASTConsumer*> Consumers;
1895 if (Clang->hasASTConsumer())
1896 Consumers.push_back(Clang->takeASTConsumer());
1897 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1898 AST->getCurrentTopLevelHashValue()));
1899 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1900 }
Argyrios Kyrtzidis374a00b2012-06-08 05:48:06 +00001901 if (!Act->Execute()) {
1902 AST->transferASTDataFromCompilerInstance(*Clang);
1903 if (OwnAST && ErrAST)
1904 ErrAST->swap(OwnAST);
1905
1906 return 0;
1907 }
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001908
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001909 // Steal the created target, context, and preprocessor.
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001910 AST->transferASTDataFromCompilerInstance(*Clang);
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001911
1912 Act->EndSourceFile();
1913
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001914 if (OwnAST)
1915 return OwnAST.take();
1916 else
1917 return AST;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001918}
1919
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001920bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1921 if (!Invocation)
1922 return true;
1923
1924 // We'll manage file buffers ourselves.
1925 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1926 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001927 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001928
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001929 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001930 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001931 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001932 OverrideMainBuffer
1933 = getMainBufferWithPrecompiledPreamble(*Invocation);
1934 }
1935
Douglas Gregor213f18b2010-10-28 15:44:59 +00001936 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001937 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001938
Ted Kremenek25a11e12011-03-22 01:15:24 +00001939 // Recover resources if we crash before exiting this method.
1940 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1941 MemBufferCleanup(OverrideMainBuffer);
1942
Douglas Gregor213f18b2010-10-28 15:44:59 +00001943 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001944}
1945
Douglas Gregorabc563f2010-07-19 21:46:24 +00001946ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001947 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregorabc563f2010-07-19 21:46:24 +00001948 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001949 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001950 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001951 TranslationUnitKind TUKind,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001952 bool CacheCodeCompletionResults,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001953 bool IncludeBriefCommentsInCodeCompletion,
1954 bool UserFilesAreVolatile) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001955 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00001956 OwningPtr<ASTUnit> AST;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001957 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001958 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001959 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001960 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001961 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001962 AST->TUKind = TUKind;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001963 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001964 AST->IncludeBriefCommentsInCodeCompletion
1965 = IncludeBriefCommentsInCodeCompletion;
Ted Kremenek4f327862011-03-21 18:40:17 +00001966 AST->Invocation = CI;
Argyrios Kyrtzidiseb8fc582013-01-21 18:45:42 +00001967 AST->FileSystemOpts = CI->getFileSystemOpts();
1968 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001969 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001970
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001971 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001972 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1973 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001974 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1975 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00001976 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001977
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001978 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001979}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001980
1981ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1982 const char **ArgEnd,
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00001983 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001984 StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001985 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001986 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001987 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001988 unsigned NumRemappedFiles,
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001989 bool RemappedFilesKeepOriginalName,
Douglas Gregordf95a132010-08-09 20:45:32 +00001990 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001991 TranslationUnitKind TUKind,
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00001992 bool CacheCodeCompletionResults,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00001993 bool IncludeBriefCommentsInCodeCompletion,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001994 bool AllowPCHWithCompilerErrors,
Erik Verbruggen6a91d382012-04-12 10:11:59 +00001995 bool SkipFunctionBodies,
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00001996 bool UserFilesAreVolatile,
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00001997 bool ForSerialization,
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00001998 OwningPtr<ASTUnit> *ErrAST) {
Douglas Gregor28019772010-04-05 23:52:57 +00001999 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00002000 // No diagnostics engine was provided, so create our own diagnostics object
2001 // with the default options.
Sean Silvad47afb92013-01-20 01:58:28 +00002002 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00002003 }
Daniel Dunbar7b556682009-12-02 03:23:45 +00002004
Chris Lattner5f9e2722011-07-23 10:55:15 +00002005 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002006
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002007 IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00002008
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002009 {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002010
Douglas Gregore47be3e2010-11-11 00:39:14 +00002011 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002012 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00002013
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00002014 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00002015 llvm::makeArrayRef(ArgBegin, ArgEnd),
2016 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00002017 if (!CI)
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +00002018 return 0;
Daniel Dunbar7b556682009-12-02 03:23:45 +00002019 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00002020
Douglas Gregor4db64a42010-01-23 00:14:00 +00002021 // Override any files that need remapping
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002022 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
2023 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2024 if (const llvm::MemoryBuffer *
2025 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2026 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
2027 } else {
2028 const char *fname = fileOrBuf.get<const char *>();
2029 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
2030 }
2031 }
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002032 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
2033 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
2034 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
Douglas Gregor4db64a42010-01-23 00:14:00 +00002035
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00002036 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00002037 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00002038
Erik Verbruggen6a91d382012-04-12 10:11:59 +00002039 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
2040
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002041 // Create the AST unit.
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002042 OwningPtr<ASTUnit> AST;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002043 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00002044 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002045 AST->Diagnostics = Diags;
Ted Kremenekd04a9822011-11-17 23:01:17 +00002046 Diags = 0; // Zero out now to ease cleanup during crash recovery.
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00002047 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00002048 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002049 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00002050 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00002051 AST->TUKind = TUKind;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002052 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002053 AST->IncludeBriefCommentsInCodeCompletion
2054 = IncludeBriefCommentsInCodeCompletion;
Argyrios Kyrtzidisff398962012-07-11 20:59:04 +00002055 AST->UserFilesAreVolatile = UserFilesAreVolatile;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002056 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002057 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00002058 AST->Invocation = CI;
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002059 if (ForSerialization)
2060 AST->WriterData.reset(new ASTWriterData());
Ted Kremenekd04a9822011-11-17 23:01:17 +00002061 CI = 0; // Zero out now to ease cleanup during crash recovery.
Ted Kremenekb547eeb2011-03-18 02:06:56 +00002062
2063 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002064 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
2065 ASTUnitCleanup(AST.get());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00002066
Argyrios Kyrtzidise722ed62012-04-11 02:11:16 +00002067 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
2068 // Some error occurred, if caller wants to examine diagnostics, pass it the
2069 // ASTUnit.
2070 if (ErrAST) {
2071 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2072 ErrAST->swap(AST);
2073 }
2074 return 0;
2075 }
2076
2077 return AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00002078}
Douglas Gregorabc563f2010-07-19 21:46:24 +00002079
2080bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002081 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00002082 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002083
2084 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00002085
Douglas Gregor213f18b2010-10-28 15:44:59 +00002086 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002087 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00002088
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002089 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00002090 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
2091 for (PreprocessorOptions::remapped_file_buffer_iterator
2092 R = PPOpts.remapped_file_buffer_begin(),
2093 REnd = PPOpts.remapped_file_buffer_end();
2094 R != REnd;
2095 ++R) {
2096 delete R->second;
2097 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002098 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002099 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
2100 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2101 if (const llvm::MemoryBuffer *
2102 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2103 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2104 memBuf);
2105 } else {
2106 const char *fname = fileOrBuf.get<const char *>();
2107 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2108 fname);
2109 }
2110 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00002111
Douglas Gregoreababfb2010-08-04 05:53:38 +00002112 // If we have a preamble file lying around, or if we might try to
2113 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00002114 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002115 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00002116 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00002117
Douglas Gregorabc563f2010-07-19 21:46:24 +00002118 // Clear out the diagnostics state.
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002119 getDiagnostics().Reset();
2120 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Argyrios Kyrtzidis27368f92011-11-03 20:57:33 +00002121 if (OverrideMainBuffer)
2122 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Argyrios Kyrtzidise6825d32011-11-03 20:28:19 +00002123
Douglas Gregor175c4a92010-07-23 23:58:40 +00002124 // Parse the sources
Douglas Gregor9b7db622011-02-16 18:16:54 +00002125 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis2fe17fc2011-10-31 21:25:31 +00002126
2127 // If we're caching global code-completion results, and the top-level
2128 // declarations have changed, clear out the code-completion cache.
2129 if (!Result && ShouldCacheCodeCompletionResults &&
2130 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2131 CacheCodeCompletionResults();
Douglas Gregor9b7db622011-02-16 18:16:54 +00002132
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002133 // We now need to clear out the completion info related to this translation
2134 // unit; it'll be recreated if necessary.
2135 CCTUInfo.reset();
Douglas Gregor8fa0a802011-08-04 20:04:59 +00002136
Douglas Gregor175c4a92010-07-23 23:58:40 +00002137 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002138}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002139
Douglas Gregor87c08a52010-08-13 22:48:40 +00002140//----------------------------------------------------------------------------//
2141// Code completion
2142//----------------------------------------------------------------------------//
2143
2144namespace {
2145 /// \brief Code completion consumer that combines the cached code-completion
2146 /// results from an ASTUnit with the code-completion results provided to it,
2147 /// then passes the result on to
2148 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Richard Smith026b3582012-08-14 03:13:00 +00002149 uint64_t NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002150 ASTUnit &AST;
2151 CodeCompleteConsumer &Next;
2152
2153 public:
2154 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002155 const CodeCompleteOptions &CodeCompleteOpts)
2156 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2157 AST(AST), Next(Next)
Douglas Gregor87c08a52010-08-13 22:48:40 +00002158 {
2159 // Compute the set of contexts in which we will look when we don't have
2160 // any information about the specific context.
2161 NormalContexts
Richard Smith026b3582012-08-14 03:13:00 +00002162 = (1LL << CodeCompletionContext::CCC_TopLevel)
2163 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2164 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2165 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2166 | (1LL << CodeCompletionContext::CCC_Statement)
2167 | (1LL << CodeCompletionContext::CCC_Expression)
2168 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2169 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2170 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2171 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2172 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2173 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2174 | (1LL << CodeCompletionContext::CCC_Recovery);
Douglas Gregor02688102010-09-14 23:59:36 +00002175
David Blaikie4e4d0842012-03-11 07:00:24 +00002176 if (AST.getASTContext().getLangOpts().CPlusPlus)
Richard Smith026b3582012-08-14 03:13:00 +00002177 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2178 | (1LL << CodeCompletionContext::CCC_UnionTag)
2179 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002180 }
2181
2182 virtual void ProcessCodeCompleteResults(Sema &S,
2183 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002184 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002185 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002186
2187 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2188 OverloadCandidate *Candidates,
2189 unsigned NumCandidates) {
2190 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2191 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002192
Douglas Gregordae68752011-02-01 22:57:45 +00002193 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +00002194 return Next.getAllocator();
2195 }
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002196
2197 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() {
2198 return Next.getCodeCompletionTUInfo();
2199 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00002200 };
2201}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002202
Douglas Gregor5f808c22010-08-16 21:18:39 +00002203/// \brief Helper function that computes which global names are hidden by the
2204/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002205static void CalculateHiddenNames(const CodeCompletionContext &Context,
2206 CodeCompletionResult *Results,
2207 unsigned NumResults,
2208 ASTContext &Ctx,
2209 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00002210 bool OnlyTagNames = false;
2211 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00002212 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002213 case CodeCompletionContext::CCC_TopLevel:
2214 case CodeCompletionContext::CCC_ObjCInterface:
2215 case CodeCompletionContext::CCC_ObjCImplementation:
2216 case CodeCompletionContext::CCC_ObjCIvarList:
2217 case CodeCompletionContext::CCC_ClassStructUnion:
2218 case CodeCompletionContext::CCC_Statement:
2219 case CodeCompletionContext::CCC_Expression:
2220 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002221 case CodeCompletionContext::CCC_DotMemberAccess:
2222 case CodeCompletionContext::CCC_ArrowMemberAccess:
2223 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002224 case CodeCompletionContext::CCC_Namespace:
2225 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002226 case CodeCompletionContext::CCC_Name:
2227 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00002228 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00002229 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002230 break;
2231
2232 case CodeCompletionContext::CCC_EnumTag:
2233 case CodeCompletionContext::CCC_UnionTag:
2234 case CodeCompletionContext::CCC_ClassOrStructTag:
2235 OnlyTagNames = true;
2236 break;
2237
2238 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002239 case CodeCompletionContext::CCC_MacroName:
2240 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00002241 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00002242 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00002243 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00002244 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00002245 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002246 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00002247 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002248 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2249 case CodeCompletionContext::CCC_ObjCClassMessage:
2250 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00002251 // We're looking for nothing, or we're looking for names that cannot
2252 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00002253 return;
2254 }
2255
John McCall0a2c5e22010-08-25 06:19:51 +00002256 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002257 for (unsigned I = 0; I != NumResults; ++I) {
2258 if (Results[I].Kind != Result::RK_Declaration)
2259 continue;
2260
2261 unsigned IDNS
2262 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2263
2264 bool Hiding = false;
2265 if (OnlyTagNames)
2266 Hiding = (IDNS & Decl::IDNS_Tag);
2267 else {
2268 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00002269 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2270 Decl::IDNS_NonMemberOperator);
David Blaikie4e4d0842012-03-11 07:00:24 +00002271 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor5f808c22010-08-16 21:18:39 +00002272 HiddenIDNS |= Decl::IDNS_Tag;
2273 Hiding = (IDNS & HiddenIDNS);
2274 }
2275
2276 if (!Hiding)
2277 continue;
2278
2279 DeclarationName Name = Results[I].Declaration->getDeclName();
2280 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2281 HiddenNames.insert(Identifier->getName());
2282 else
2283 HiddenNames.insert(Name.getAsString());
2284 }
2285}
2286
2287
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002288void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2289 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002290 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002291 unsigned NumResults) {
2292 // Merge the results we were given with the results we cached.
2293 bool AddedResult = false;
Richard Smith026b3582012-08-14 03:13:00 +00002294 uint64_t InContexts =
2295 Context.getKind() == CodeCompletionContext::CCC_Recovery
2296 ? NormalContexts : (1LL << Context.getKind());
Douglas Gregor5f808c22010-08-16 21:18:39 +00002297 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002298 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00002299 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002300 SmallVector<Result, 8> AllResults;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002301 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00002302 C = AST.cached_completion_begin(),
2303 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002304 C != CEnd; ++C) {
2305 // If the context we are in matches any of the contexts we are
2306 // interested in, we'll add this result.
2307 if ((C->ShowInContexts & InContexts) == 0)
2308 continue;
2309
2310 // If we haven't added any results previously, do so now.
2311 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00002312 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2313 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002314 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2315 AddedResult = true;
2316 }
2317
Douglas Gregor5f808c22010-08-16 21:18:39 +00002318 // Determine whether this global completion result is hidden by a local
2319 // completion result. If so, skip it.
2320 if (C->Kind != CXCursor_MacroDefinition &&
2321 HiddenNames.count(C->Completion->getTypedText()))
2322 continue;
2323
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002324 // Adjust priority based on similar type classes.
2325 unsigned Priority = C->Priority;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002326 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002327 if (!Context.getPreferredType().isNull()) {
2328 if (C->Kind == CXCursor_MacroDefinition) {
2329 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002330 S.getLangOpts(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002331 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002332 } else if (C->Type) {
2333 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002334 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002335 Context.getPreferredType().getUnqualifiedType());
2336 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2337 if (ExpectedSTC == C->TypeClass) {
2338 // We know this type is similar; check for an exact match.
2339 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002340 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002341 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002342 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002343 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2344 Priority /= CCF_ExactTypeMatch;
2345 else
2346 Priority /= CCF_SimilarTypeMatch;
2347 }
2348 }
2349 }
2350
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002351 // Adjust the completion string, if required.
2352 if (C->Kind == CXCursor_MacroDefinition &&
2353 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2354 // Create a new code-completion string that just contains the
2355 // macro name, without its arguments.
Argyrios Kyrtzidis28a83f52012-04-10 17:23:48 +00002356 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2357 CCP_CodePattern, C->Availability);
Douglas Gregor218937c2011-02-01 19:23:04 +00002358 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002359 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002360 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002361 }
2362
Argyrios Kyrtzidisc04bb922012-09-27 00:24:09 +00002363 AllResults.push_back(Result(Completion, Priority, C->Kind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002364 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002365 }
2366
2367 // If we did not add any cached completion results, just forward the
2368 // results we were given to the next consumer.
2369 if (!AddedResult) {
2370 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2371 return;
2372 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002373
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002374 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2375 AllResults.size());
2376}
2377
2378
2379
Chris Lattner5f9e2722011-07-23 10:55:15 +00002380void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002381 RemappedFile *RemappedFiles,
2382 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002383 bool IncludeMacros,
2384 bool IncludeCodePatterns,
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002385 bool IncludeBriefComments,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002386 CodeCompleteConsumer &Consumer,
David Blaikied6471f72011-09-25 23:23:43 +00002387 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002388 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002389 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2390 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002391 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002392 return;
2393
Douglas Gregor213f18b2010-10-28 15:44:59 +00002394 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002395 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner5f9e2722011-07-23 10:55:15 +00002396 Twine(Line) + ":" + Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002397
Dylan Noblesmithc93dc782012-02-20 14:00:23 +00002398 IntrusiveRefCntPtr<CompilerInvocation>
Ted Kremenek4f327862011-03-21 18:40:17 +00002399 CCInvocation(new CompilerInvocation(*Invocation));
2400
2401 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002402 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
Ted Kremenek4f327862011-03-21 18:40:17 +00002403 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002404
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002405 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2406 CachedCompletionResults.empty();
2407 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2408 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2409 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2410
2411 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2412
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002413 FrontendOpts.CodeCompletionAt.FileName = File;
2414 FrontendOpts.CodeCompletionAt.Line = Line;
2415 FrontendOpts.CodeCompletionAt.Column = Column;
2416
2417 // Set the language options appropriately.
Ted Kremenekd3b74d92011-11-17 23:01:24 +00002418 LangOpts = *CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002419
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002420 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002421
2422 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002423 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2424 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002425
Ted Kremenek4f327862011-03-21 18:40:17 +00002426 Clang->setInvocation(&*CCInvocation);
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002427 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002428
2429 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002430 Clang->setDiagnostics(&Diag);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002431 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002432 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002433 StoredDiagnostics);
Manuel Klimekf0c06a32013-07-18 14:23:12 +00002434 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002435
2436 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002437 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Douglas Gregor49a87542012-11-16 04:24:59 +00002438 &Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00002439 if (!Clang->hasTarget()) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002440 Clang->setInvocation(0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002441 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002442 }
2443
2444 // Inform the target of the language options.
2445 //
2446 // FIXME: We shouldn't need to do this, the target should be immutable once
2447 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002448 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002449
Ted Kremenek03201fb2011-03-21 18:40:07 +00002450 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002451 "Invocation must have exactly one source file!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002452 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002453 "FIXME: AST inputs not yet supported here!");
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +00002454 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002455 "IR inputs not support here!");
2456
2457
2458 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002459 Clang->setFileManager(&FileMgr);
2460 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002461
2462 // Remap files.
2463 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002464 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00002465 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002466 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2467 if (const llvm::MemoryBuffer *
2468 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2469 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2470 OwnedBuffers.push_back(memBuf);
2471 } else {
2472 const char *fname = fileOrBuf.get<const char *>();
2473 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2474 }
Douglas Gregor2283d792010-08-20 00:59:43 +00002475 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002476
Douglas Gregor87c08a52010-08-13 22:48:40 +00002477 // Use the code completion consumer we were given, but adding any cached
2478 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002479 AugmentedCodeCompleteConsumer *AugmentedConsumer
Dmitri Gribenkod99ef532012-07-02 17:35:10 +00002480 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002481 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002482
Douglas Gregordf95a132010-08-09 20:45:32 +00002483 // If we have a precompiled preamble, try to use it. We only allow
2484 // the use of the precompiled preamble if we're if the completion
2485 // point is within the main file, after the end of the precompiled
2486 // preamble.
2487 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002488 if (!getPreambleFile(this).empty()) {
Rafael Espindola105b2072013-06-18 19:40:07 +00002489 std::string CompleteFilePath(File);
Rafael Espindola44888352013-07-29 21:26:52 +00002490 llvm::sys::fs::UniqueID CompleteFileID;
Rafael Espindola105b2072013-06-18 19:40:07 +00002491
Rafael Espindolada4cb0c2013-06-20 15:12:38 +00002492 if (!llvm::sys::fs::getUniqueID(CompleteFilePath, CompleteFileID)) {
Rafael Espindola105b2072013-06-18 19:40:07 +00002493 std::string MainPath(OriginalSourceFile);
Rafael Espindola44888352013-07-29 21:26:52 +00002494 llvm::sys::fs::UniqueID MainID;
Rafael Espindolada4cb0c2013-06-20 15:12:38 +00002495 if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) {
Rafael Espindola105b2072013-06-18 19:40:07 +00002496 if (CompleteFileID == MainID && Line > 1)
Douglas Gregor2283d792010-08-20 00:59:43 +00002497 OverrideMainBuffer
Ted Kremenek4f327862011-03-21 18:40:17 +00002498 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregorc9c29a82010-08-25 18:04:15 +00002499 Line - 1);
Rafael Espindola105b2072013-06-18 19:40:07 +00002500 }
2501 }
Douglas Gregordf95a132010-08-09 20:45:32 +00002502 }
2503
2504 // If the main file has been overridden due to the use of a preamble,
2505 // make that override happen and introduce the preamble.
2506 if (OverrideMainBuffer) {
2507 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2508 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2509 PreprocessorOpts.PrecompiledPreambleBytes.second
2510 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00002511 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregordf95a132010-08-09 20:45:32 +00002512 PreprocessorOpts.DisablePCHValidation = true;
2513
Douglas Gregor2283d792010-08-20 00:59:43 +00002514 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00002515 } else {
2516 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2517 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002518 }
2519
Argyrios Kyrtzidise50904f2012-11-02 22:18:44 +00002520 // Disable the preprocessing record if modules are not enabled.
2521 if (!Clang->getLangOpts().Modules)
2522 PreprocessorOpts.DetailedRecord = false;
Douglas Gregordca8ee82011-05-06 16:33:08 +00002523
Dylan Noblesmith6f42b622012-02-05 02:12:40 +00002524 OwningPtr<SyntaxOnlyAction> Act;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002525 Act.reset(new SyntaxOnlyAction);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +00002526 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002527 Act->Execute();
2528 Act->EndSourceFile();
2529 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002530}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002531
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002532bool ASTUnit::Save(StringRef File) {
Argyrios Kyrtzidis3b7deda2013-05-24 05:44:08 +00002533 if (HadModuleLoaderFatalFailure)
2534 return true;
2535
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002536 // Write to a temporary file and later rename it to the actual file, to avoid
2537 // possible race conditions.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002538 SmallString<128> TempPath;
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002539 TempPath = File;
2540 TempPath += "-%%%%%%%%";
2541 int fd;
Rafael Espindola70e7aec2013-07-05 21:13:58 +00002542 if (llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath))
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002543 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002544
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002545 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2546 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002547 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002548
2549 serialize(Out);
2550 Out.close();
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002551 if (Out.has_error()) {
2552 Out.clear_error();
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002553 return true;
Argyrios Kyrtzidis4bd26542012-03-13 02:17:06 +00002554 }
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002555
Rafael Espindola8d2a7012011-12-25 01:18:52 +00002556 if (llvm::sys::fs::rename(TempPath.str(), File)) {
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002557 bool exists;
2558 llvm::sys::fs::remove(TempPath.str(), exists);
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002559 return true;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002560 }
2561
Argyrios Kyrtzidise6d22022012-09-26 16:39:46 +00002562 return false;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002563}
2564
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002565static bool serializeUnit(ASTWriter &Writer,
2566 SmallVectorImpl<char> &Buffer,
2567 Sema &S,
2568 bool hasErrors,
2569 raw_ostream &OS) {
Argyrios Kyrtzidis4182ed62012-10-31 20:59:50 +00002570 Writer.WriteAST(S, std::string(), 0, "", hasErrors);
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002571
2572 // Write the generated bitstream to "Out".
2573 if (!Buffer.empty())
2574 OS.write(Buffer.data(), Buffer.size());
2575
2576 return false;
2577}
2578
Chris Lattner5f9e2722011-07-23 10:55:15 +00002579bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidisbef35c92012-03-07 01:51:17 +00002580 bool hasErrors = getDiagnostics().hasErrorOccurred();
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002581
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002582 if (WriterData)
2583 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2584 getSema(), hasErrors, OS);
2585
Daniel Dunbar8d6ff022012-02-29 20:31:23 +00002586 SmallString<128> Buffer;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002587 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002588 ASTWriter Writer(Stream);
Argyrios Kyrtzidis900ab952012-10-11 16:05:00 +00002589 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002590}
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002591
2592typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2593
2594static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2595 unsigned Raw = L.getRawEncoding();
2596 const unsigned MacroBit = 1U << 31;
2597 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2598 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2599}
2600
2601void ASTUnit::TranslateStoredDiagnostics(
2602 ASTReader *MMan,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002603 StringRef ModName,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002604 SourceManager &SrcMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002605 const SmallVectorImpl<StoredDiagnostic> &Diags,
2606 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002607 // The stored diagnostic has the old source manager in it; update
2608 // the locations to refer into the new source manager. We also need to remap
2609 // all the locations to the new view. This includes the diag location, any
2610 // associated source ranges, and the source ranges of associated fix-its.
2611 // FIXME: There should be a cleaner way to do this.
2612
Chris Lattner5f9e2722011-07-23 10:55:15 +00002613 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002614 Result.reserve(Diags.size());
2615 assert(MMan && "Don't have a module manager");
Douglas Gregor1a4761e2011-11-30 23:21:26 +00002616 serialization::ModuleFile *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002617 assert(Mod && "Don't have preamble module");
2618 SLocRemap &Remap = Mod->SLocRemap;
2619 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2620 // Rebuild the StoredDiagnostic.
2621 const StoredDiagnostic &SD = Diags[I];
2622 SourceLocation L = SD.getLocation();
2623 TranslateSLoc(L, Remap);
2624 FullSourceLoc Loc(L, SrcMgr);
2625
Chris Lattner5f9e2722011-07-23 10:55:15 +00002626 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002627 Ranges.reserve(SD.range_size());
2628 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2629 E = SD.range_end();
2630 I != E; ++I) {
2631 SourceLocation BL = I->getBegin();
2632 TranslateSLoc(BL, Remap);
2633 SourceLocation EL = I->getEnd();
2634 TranslateSLoc(EL, Remap);
2635 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2636 }
2637
Chris Lattner5f9e2722011-07-23 10:55:15 +00002638 SmallVector<FixItHint, 2> FixIts;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002639 FixIts.reserve(SD.fixit_size());
2640 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2641 E = SD.fixit_end();
2642 I != E; ++I) {
2643 FixIts.push_back(FixItHint());
2644 FixItHint &FH = FixIts.back();
2645 FH.CodeToInsert = I->CodeToInsert;
2646 SourceLocation BL = I->RemoveRange.getBegin();
2647 TranslateSLoc(BL, Remap);
2648 SourceLocation EL = I->RemoveRange.getEnd();
2649 TranslateSLoc(EL, Remap);
2650 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2651 I->RemoveRange.isTokenRange());
2652 }
2653
2654 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2655 SD.getMessage(), Loc, Ranges, FixIts));
2656 }
2657 Result.swap(Out);
2658}
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002659
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002660void ASTUnit::addFileLevelDecl(Decl *D) {
2661 assert(D);
Douglas Gregor66e87002011-11-07 18:53:57 +00002662
2663 // We only care about local declarations.
2664 if (D->isFromASTFile())
2665 return;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002666
2667 SourceManager &SM = *SourceMgr;
2668 SourceLocation Loc = D->getLocation();
2669 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2670 return;
2671
2672 // We only keep track of the file-level declarations of each file.
2673 if (!D->getLexicalDeclContext()->isFileContext())
2674 return;
2675
2676 SourceLocation FileLoc = SM.getFileLoc(Loc);
2677 assert(SM.isLocalSourceLocation(FileLoc));
2678 FileID FID;
2679 unsigned Offset;
2680 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2681 if (FID.isInvalid())
2682 return;
2683
2684 LocDeclsTy *&Decls = FileDecls[FID];
2685 if (!Decls)
2686 Decls = new LocDeclsTy();
2687
2688 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2689
2690 if (Decls->empty() || Decls->back().first <= Offset) {
2691 Decls->push_back(LocDecl);
2692 return;
2693 }
2694
Benjamin Kramer809d2542013-08-24 13:22:59 +00002695 LocDeclsTy::iterator I = std::upper_bound(Decls->begin(), Decls->end(),
2696 LocDecl, llvm::less_first());
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002697
2698 Decls->insert(I, LocDecl);
2699}
2700
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002701void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2702 SmallVectorImpl<Decl *> &Decls) {
2703 if (File.isInvalid())
2704 return;
2705
2706 if (SourceMgr->isLoadedFileID(File)) {
2707 assert(Ctx->getExternalSource() && "No external source!");
2708 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2709 Decls);
2710 }
2711
2712 FileDeclsTy::iterator I = FileDecls.find(File);
2713 if (I == FileDecls.end())
2714 return;
2715
2716 LocDeclsTy &LocDecls = *I->second;
2717 if (LocDecls.empty())
2718 return;
2719
Benjamin Kramera9bdbce2013-08-24 13:12:34 +00002720 LocDeclsTy::iterator BeginIt =
2721 std::lower_bound(LocDecls.begin(), LocDecls.end(),
Benjamin Kramer809d2542013-08-24 13:22:59 +00002722 std::make_pair(Offset, (Decl *)0), llvm::less_first());
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002723 if (BeginIt != LocDecls.begin())
2724 --BeginIt;
2725
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00002726 // If we are pointing at a top-level decl inside an objc container, we need
2727 // to backtrack until we find it otherwise we will fail to report that the
2728 // region overlaps with an objc container.
2729 while (BeginIt != LocDecls.begin() &&
2730 BeginIt->second->isTopLevelDeclInObjCContainer())
2731 --BeginIt;
2732
Benjamin Kramera9bdbce2013-08-24 13:12:34 +00002733 LocDeclsTy::iterator EndIt = std::upper_bound(
2734 LocDecls.begin(), LocDecls.end(),
Benjamin Kramer809d2542013-08-24 13:22:59 +00002735 std::make_pair(Offset + Length, (Decl *)0), llvm::less_first());
Argyrios Kyrtzidisdfb332d2011-11-03 02:20:32 +00002736 if (EndIt != LocDecls.end())
2737 ++EndIt;
2738
2739 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2740 Decls.push_back(DIt->second);
2741}
2742
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002743SourceLocation ASTUnit::getLocation(const FileEntry *File,
2744 unsigned Line, unsigned Col) const {
2745 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002746 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002747 return SM.getMacroArgExpandedLocation(Loc);
2748}
2749
2750SourceLocation ASTUnit::getLocation(const FileEntry *File,
2751 unsigned Offset) const {
2752 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002753 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002754 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2755}
2756
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002757/// \brief If \arg Loc is a loaded location from the preamble, returns
2758/// the corresponding local location of the main file, otherwise it returns
2759/// \arg Loc.
2760SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2761 FileID PreambleID;
2762 if (SourceMgr)
2763 PreambleID = SourceMgr->getPreambleFileID();
2764
2765 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2766 return Loc;
2767
2768 unsigned Offs;
2769 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2770 SourceLocation FileLoc
2771 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2772 return FileLoc.getLocWithOffset(Offs);
2773 }
2774
2775 return Loc;
2776}
2777
2778/// \brief If \arg Loc is a local location of the main file but inside the
2779/// preamble chunk, returns the corresponding loaded location from the
2780/// preamble, otherwise it returns \arg Loc.
2781SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2782 FileID PreambleID;
2783 if (SourceMgr)
2784 PreambleID = SourceMgr->getPreambleFileID();
2785
2786 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2787 return Loc;
2788
2789 unsigned Offs;
2790 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2791 Offs < Preamble.size()) {
2792 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2793 return FileLoc.getLocWithOffset(Offs);
2794 }
2795
2796 return Loc;
2797}
2798
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002799bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2800 FileID FID;
2801 if (SourceMgr)
2802 FID = SourceMgr->getPreambleFileID();
2803
2804 if (Loc.isInvalid() || FID.isInvalid())
2805 return false;
2806
2807 return SourceMgr->isInFileID(Loc, FID);
2808}
2809
2810bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2811 FileID FID;
2812 if (SourceMgr)
2813 FID = SourceMgr->getMainFileID();
2814
2815 if (Loc.isInvalid() || FID.isInvalid())
2816 return false;
2817
2818 return SourceMgr->isInFileID(Loc, FID);
2819}
2820
2821SourceLocation ASTUnit::getEndOfPreambleFileID() {
2822 FileID FID;
2823 if (SourceMgr)
2824 FID = SourceMgr->getPreambleFileID();
2825
2826 if (FID.isInvalid())
2827 return SourceLocation();
2828
2829 return SourceMgr->getLocForEndOfFile(FID);
2830}
2831
2832SourceLocation ASTUnit::getStartOfMainFileID() {
2833 FileID FID;
2834 if (SourceMgr)
2835 FID = SourceMgr->getMainFileID();
2836
2837 if (FID.isInvalid())
2838 return SourceLocation();
2839
2840 return SourceMgr->getLocForStartOfFile(FID);
2841}
2842
Argyrios Kyrtzidis632dcc92012-10-02 16:10:51 +00002843std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
2844ASTUnit::getLocalPreprocessingEntities() const {
2845 if (isMainFileAST()) {
2846 serialization::ModuleFile &
2847 Mod = Reader->getModuleManager().getPrimaryModule();
2848 return Reader->getModulePreprocessedEntities(Mod);
2849 }
2850
2851 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2852 return std::make_pair(PPRec->local_begin(), PPRec->local_end());
2853
2854 return std::make_pair(PreprocessingRecord::iterator(),
2855 PreprocessingRecord::iterator());
2856}
2857
Argyrios Kyrtzidis95c579c2012-10-03 01:58:28 +00002858bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
Argyrios Kyrtzidis2093e0b2012-10-02 21:09:13 +00002859 if (isMainFileAST()) {
2860 serialization::ModuleFile &
2861 Mod = Reader->getModuleManager().getPrimaryModule();
2862 ASTReader::ModuleDeclIterator MDI, MDE;
2863 llvm::tie(MDI, MDE) = Reader->getModuleFileLevelDecls(Mod);
2864 for (; MDI != MDE; ++MDI) {
2865 if (!Fn(context, *MDI))
2866 return false;
2867 }
2868
2869 return true;
2870 }
2871
2872 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2873 TLEnd = top_level_end();
2874 TL != TLEnd; ++TL) {
2875 if (!Fn(context, *TL))
2876 return false;
2877 }
2878
2879 return true;
2880}
2881
Argyrios Kyrtzidis3da76bf2012-10-03 21:05:51 +00002882namespace {
2883struct PCHLocatorInfo {
2884 serialization::ModuleFile *Mod;
2885 PCHLocatorInfo() : Mod(0) {}
2886};
2887}
2888
2889static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
2890 PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
2891 switch (M.Kind) {
2892 case serialization::MK_Module:
2893 return true; // skip dependencies.
2894 case serialization::MK_PCH:
2895 Info.Mod = &M;
2896 return true; // found it.
2897 case serialization::MK_Preamble:
2898 return false; // look in dependencies.
2899 case serialization::MK_MainFile:
2900 return false; // look in dependencies.
2901 }
2902
2903 return true;
2904}
2905
2906const FileEntry *ASTUnit::getPCHFile() {
2907 if (!Reader)
2908 return 0;
2909
2910 PCHLocatorInfo Info;
2911 Reader->getModuleManager().visit(PCHLocator, &Info);
2912 if (Info.Mod)
2913 return Info.Mod->File;
2914
2915 return 0;
2916}
2917
Argyrios Kyrtzidis62288ed2012-10-10 02:12:47 +00002918bool ASTUnit::isModuleFile() {
2919 return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2920}
2921
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002922void ASTUnit::PreambleData::countLines() const {
2923 NumLines = 0;
2924 if (empty())
2925 return;
2926
2927 for (std::vector<char>::const_iterator
2928 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2929 if (*I == '\n')
2930 ++NumLines;
2931 }
2932 if (Buffer.back() != '\n')
2933 ++NumLines;
2934}
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002935
2936#ifndef NDEBUG
2937ASTUnit::ConcurrencyState::ConcurrencyState() {
2938 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2939}
2940
2941ASTUnit::ConcurrencyState::~ConcurrencyState() {
2942 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2943}
2944
2945void ASTUnit::ConcurrencyState::start() {
2946 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2947 assert(acquired && "Concurrent access to ASTUnit!");
2948}
2949
2950void ASTUnit::ConcurrencyState::finish() {
2951 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2952}
2953
2954#else // NDEBUG
2955
2956ASTUnit::ConcurrencyState::ConcurrencyState() {}
2957ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2958void ASTUnit::ConcurrencyState::start() {}
2959void ASTUnit::ConcurrencyState::finish() {}
2960
2961#endif