blob: 0600203eae556d4ca40b4e0933f3357593136a57 [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"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000015#include "clang/AST/ASTContext.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000016#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
Douglas Gregorf5586f62010-08-16 18:08:11 +000018#include "clang/AST/TypeOrdering.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000019#include "clang/AST/StmtVisitor.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000020#include "clang/Driver/Compilation.h"
21#include "clang/Driver/Driver.h"
22#include "clang/Driver/Job.h"
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +000023#include "clang/Driver/ArgList.h"
24#include "clang/Driver/Options.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000025#include "clang/Driver/Tool.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000026#include "clang/Frontend/CompilerInstance.h"
27#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000028#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000029#include "clang/Frontend/FrontendOptions.h"
Douglas Gregor32be4a52010-10-11 21:37:58 +000030#include "clang/Frontend/Utils.h"
Sebastian Redl6ab7cd82010-08-18 23:57:17 +000031#include "clang/Serialization/ASTReader.h"
Sebastian Redl7faa2ec2010-08-18 23:56:37 +000032#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000033#include "clang/Lex/HeaderSearch.h"
34#include "clang/Lex/Preprocessor.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000035#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000036#include "clang/Basic/TargetInfo.h"
37#include "clang/Basic/Diagnostic.h"
Chris Lattner7f9fc3f2011-03-23 04:04:01 +000038#include "llvm/ADT/ArrayRef.h"
Douglas Gregor9b7db622011-02-16 18:16:54 +000039#include "llvm/ADT/StringExtras.h"
Douglas Gregor349d38c2010-08-16 23:08:34 +000040#include "llvm/ADT/StringSet.h"
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +000041#include "llvm/Support/Atomic.h"
Douglas Gregor4db64a42010-01-23 00:14:00 +000042#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000043#include "llvm/Support/Host.h"
44#include "llvm/Support/Path.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000045#include "llvm/Support/raw_ostream.h"
Douglas Gregor385103b2010-07-30 20:58:08 +000046#include "llvm/Support/Timer.h"
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +000047#include "llvm/Support/FileSystem.h"
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +000048#include "llvm/Support/Mutex.h"
Ted Kremeneke055f8a2011-10-27 19:44:25 +000049#include "llvm/Support/MutexGuard.h"
Ted Kremenekb547eeb2011-03-18 02:06:56 +000050#include "llvm/Support/CrashRecoveryContext.h"
Douglas Gregor44c181a2010-07-23 00:33:23 +000051#include <cstdlib>
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000052#include <cstdio>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000053#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000054using namespace clang;
55
Douglas Gregor213f18b2010-10-28 15:44:59 +000056using llvm::TimeRecord;
57
58namespace {
59 class SimpleTimer {
60 bool WantTiming;
61 TimeRecord Start;
62 std::string Output;
63
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000064 public:
Douglas Gregor9dba61a2010-11-01 13:48:43 +000065 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000066 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000067 Start = TimeRecord::getCurrentTime();
Douglas Gregor213f18b2010-10-28 15:44:59 +000068 }
69
Chris Lattner5f9e2722011-07-23 10:55:15 +000070 void setOutput(const Twine &Output) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000071 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000072 this->Output = Output.str();
Douglas Gregor213f18b2010-10-28 15:44:59 +000073 }
74
Douglas Gregor213f18b2010-10-28 15:44:59 +000075 ~SimpleTimer() {
76 if (WantTiming) {
77 TimeRecord Elapsed = TimeRecord::getCurrentTime();
78 Elapsed -= Start;
79 llvm::errs() << Output << ':';
80 Elapsed.print(Elapsed, llvm::errs());
81 llvm::errs() << '\n';
82 }
83 }
84 };
Ted Kremenek1872b312011-10-27 17:55:18 +000085
86 struct OnDiskData {
87 /// \brief The file in which the precompiled preamble is stored.
88 std::string PreambleFile;
89
90 /// \brief Temporary files that should be removed when the ASTUnit is
91 /// destroyed.
92 SmallVector<llvm::sys::Path, 4> TemporaryFiles;
93
94 /// \brief Erase temporary files.
95 void CleanTemporaryFiles();
96
97 /// \brief Erase the preamble file.
98 void CleanPreambleFile();
99
100 /// \brief Erase temporary files and the preamble file.
101 void Cleanup();
102 };
103}
104
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000105static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
106 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
107 return M;
108}
109
Ted Kremenek1872b312011-10-27 17:55:18 +0000110static void cleanupOnDiskMapAtExit(void);
111
112typedef llvm::DenseMap<const ASTUnit *, OnDiskData *> OnDiskDataMap;
113static OnDiskDataMap &getOnDiskDataMap() {
114 static OnDiskDataMap M;
115 static bool hasRegisteredAtExit = false;
116 if (!hasRegisteredAtExit) {
117 hasRegisteredAtExit = true;
118 atexit(cleanupOnDiskMapAtExit);
119 }
120 return M;
121}
122
123static void cleanupOnDiskMapAtExit(void) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000124 // No mutex required here since we are leaving the program.
Ted Kremenek1872b312011-10-27 17:55:18 +0000125 OnDiskDataMap &M = getOnDiskDataMap();
126 for (OnDiskDataMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
127 // We don't worry about freeing the memory associated with OnDiskDataMap.
128 // All we care about is erasing stale files.
129 I->second->Cleanup();
130 }
131}
132
133static OnDiskData &getOnDiskData(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000134 // We require the mutex since we are modifying the structure of the
135 // DenseMap.
136 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000137 OnDiskDataMap &M = getOnDiskDataMap();
138 OnDiskData *&D = M[AU];
139 if (!D)
140 D = new OnDiskData();
141 return *D;
142}
143
144static void erasePreambleFile(const ASTUnit *AU) {
145 getOnDiskData(AU).CleanPreambleFile();
146}
147
148static void removeOnDiskEntry(const ASTUnit *AU) {
Ted Kremeneke055f8a2011-10-27 19:44:25 +0000149 // We require the mutex since we are modifying the structure of the
150 // DenseMap.
151 llvm::MutexGuard Guard(getOnDiskMutex());
Ted Kremenek1872b312011-10-27 17:55:18 +0000152 OnDiskDataMap &M = getOnDiskDataMap();
153 OnDiskDataMap::iterator I = M.find(AU);
154 if (I != M.end()) {
155 I->second->Cleanup();
156 delete I->second;
157 M.erase(AU);
158 }
159}
160
161static void setPreambleFile(const ASTUnit *AU, llvm::StringRef preambleFile) {
162 getOnDiskData(AU).PreambleFile = preambleFile;
163}
164
165static const std::string &getPreambleFile(const ASTUnit *AU) {
166 return getOnDiskData(AU).PreambleFile;
167}
168
169void OnDiskData::CleanTemporaryFiles() {
170 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
171 TemporaryFiles[I].eraseFromDisk();
172 TemporaryFiles.clear();
173}
174
175void OnDiskData::CleanPreambleFile() {
176 if (!PreambleFile.empty()) {
177 llvm::sys::Path(PreambleFile).eraseFromDisk();
178 PreambleFile.clear();
179 }
180}
181
182void OnDiskData::Cleanup() {
183 CleanTemporaryFiles();
184 CleanPreambleFile();
185}
186
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000187void ASTUnit::clearFileLevelDecls() {
188 for (FileDeclsTy::iterator
189 I = FileDecls.begin(), E = FileDecls.end(); I != E; ++I)
190 delete I->second;
191 FileDecls.clear();
192}
193
Ted Kremenek1872b312011-10-27 17:55:18 +0000194void ASTUnit::CleanTemporaryFiles() {
195 getOnDiskData(this).CleanTemporaryFiles();
196}
197
198void ASTUnit::addTemporaryFile(const llvm::sys::Path &TempFile) {
199 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
Douglas Gregor213f18b2010-10-28 15:44:59 +0000200}
201
Douglas Gregoreababfb2010-08-04 05:53:38 +0000202/// \brief After failing to build a precompiled preamble (due to
203/// errors in the source that occurs in the preamble), the number of
204/// reparses during which we'll skip even trying to precompile the
205/// preamble.
206const unsigned DefaultPreambleRebuildInterval = 5;
207
Douglas Gregore3c60a72010-11-17 00:13:31 +0000208/// \brief Tracks the number of ASTUnit objects that are currently active.
209///
210/// Used for debugging purposes only.
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000211static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregore3c60a72010-11-17 00:13:31 +0000212
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000213ASTUnit::ASTUnit(bool _MainFileIsAST)
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000214 : Reader(0), OnlyLocalDecls(false), CaptureDiagnostics(false),
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +0000215 MainFileIsAST(_MainFileIsAST),
Douglas Gregor467dc882011-08-25 22:30:56 +0000216 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
Argyrios Kyrtzidis15727dd2011-03-05 01:03:48 +0000217 OwnsRemappedFileBuffers(true),
Douglas Gregor213f18b2010-10-28 15:44:59 +0000218 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor671947b2010-08-19 01:33:06 +0000219 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +0000220 ShouldCacheCodeCompletionResults(false),
Chandler Carruthba7537f2011-07-14 09:02:10 +0000221 NestedMacroExpansions(true),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000222 CompletionCacheTopLevelHashValue(0),
223 PreambleTopLevelHashValue(0),
224 CurrentTopLevelHashValue(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +0000225 UnsafeToFree(false) {
Douglas Gregore3c60a72010-11-17 00:13:31 +0000226 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000227 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000228 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
229 }
Douglas Gregor385103b2010-07-30 20:58:08 +0000230}
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000231
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000232ASTUnit::~ASTUnit() {
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000233 clearFileLevelDecls();
234
Ted Kremenek1872b312011-10-27 17:55:18 +0000235 // Clean up the temporary files and the preamble file.
236 removeOnDiskEntry(this);
237
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000238 // Free the buffers associated with remapped files. We are required to
239 // perform this operation here because we explicitly request that the
240 // compiler instance *not* free these buffers for each invocation of the
241 // parser.
Ted Kremenek4f327862011-03-21 18:40:17 +0000242 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000243 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
244 for (PreprocessorOptions::remapped_file_buffer_iterator
245 FB = PPOpts.remapped_file_buffer_begin(),
246 FBEnd = PPOpts.remapped_file_buffer_end();
247 FB != FBEnd;
248 ++FB)
249 delete FB->second;
250 }
Douglas Gregor28233422010-07-27 14:52:07 +0000251
252 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +0000253 delete PreambleBuffer;
254
Douglas Gregor213f18b2010-10-28 15:44:59 +0000255 ClearCachedCompletionResults();
Douglas Gregore3c60a72010-11-17 00:13:31 +0000256
257 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000258 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000259 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
260 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000261}
262
Douglas Gregor8071e422010-08-15 06:18:01 +0000263/// \brief Determine the set of code-completion contexts in which this
264/// declaration should be shown.
265static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000266 const LangOptions &LangOpts,
267 bool &IsNestedNameSpecifier) {
268 IsNestedNameSpecifier = false;
269
Douglas Gregor8071e422010-08-15 06:18:01 +0000270 if (isa<UsingShadowDecl>(ND))
271 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
272 if (!ND)
273 return 0;
274
275 unsigned Contexts = 0;
276 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
277 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
278 // Types can appear in these contexts.
279 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
280 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
281 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
282 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
283 | (1 << (CodeCompletionContext::CCC_Statement - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000284 | (1 << (CodeCompletionContext::CCC_Type - 1))
285 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000286
287 // In C++, types can appear in expressions contexts (for functional casts).
288 if (LangOpts.CPlusPlus)
289 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
290
291 // In Objective-C, message sends can send interfaces. In Objective-C++,
292 // all types are available due to functional casts.
293 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
294 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
Douglas Gregor3da626b2011-07-07 16:03:39 +0000295
296 // In Objective-C, you can only be a subclass of another Objective-C class
297 if (isa<ObjCInterfaceDecl>(ND))
Douglas Gregor0f91c8c2011-07-30 06:55:39 +0000298 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCInterfaceName - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000299
300 // Deal with tag names.
301 if (isa<EnumDecl>(ND)) {
302 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
303
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000304 // Part of the nested-name-specifier in C++0x.
Douglas Gregor8071e422010-08-15 06:18:01 +0000305 if (LangOpts.CPlusPlus0x)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000306 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000307 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
308 if (Record->isUnion())
309 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
310 else
311 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
312
Douglas Gregor8071e422010-08-15 06:18:01 +0000313 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000314 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000315 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000316 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000317 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
318 // Values can appear in these contexts.
319 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
320 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000321 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor8071e422010-08-15 06:18:01 +0000322 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
323 } else if (isa<ObjCProtocolDecl>(ND)) {
324 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
Douglas Gregor3da626b2011-07-07 16:03:39 +0000325 } else if (isa<ObjCCategoryDecl>(ND)) {
326 Contexts = (1 << (CodeCompletionContext::CCC_ObjCCategoryName - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000327 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000328 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000329
330 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000331 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000332 }
333
334 return Contexts;
335}
336
Douglas Gregor87c08a52010-08-13 22:48:40 +0000337void ASTUnit::CacheCodeCompletionResults() {
338 if (!TheSema)
339 return;
340
Douglas Gregor213f18b2010-10-28 15:44:59 +0000341 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000342 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000343
344 // Clear out the previous results.
345 ClearCachedCompletionResults();
346
347 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000348 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000349 SmallVector<Result, 8> Results;
Douglas Gregor48601b32011-02-16 19:08:06 +0000350 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
351 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator, Results);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000352
353 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000354 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
355
Douglas Gregor87c08a52010-08-13 22:48:40 +0000356 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
357 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000358 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000359 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000360 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000361 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor48601b32011-02-16 19:08:06 +0000362 *CachedCompletionAllocator);
Douglas Gregor8071e422010-08-15 06:18:01 +0000363 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000364 Ctx->getLangOptions(),
365 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000366 CachedResult.Priority = Results[I].Priority;
367 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000368 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000369
Douglas Gregorf5586f62010-08-16 18:08:11 +0000370 // Keep track of the type of this completion in an ASTContext-agnostic
371 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000372 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000373 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000374 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000375 CachedResult.Type = 0;
376 } else {
377 CanQualType CanUsageType
378 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
379 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
380
381 // Determine whether we have already seen this type. If so, we save
382 // ourselves the work of formatting the type string by using the
383 // temporary, CanQualType-based hash table to find the associated value.
384 unsigned &TypeValue = CompletionTypes[CanUsageType];
385 if (TypeValue == 0) {
386 TypeValue = CompletionTypes.size();
387 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
388 = TypeValue;
389 }
390
391 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000392 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000393
Douglas Gregor8071e422010-08-15 06:18:01 +0000394 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000395
396 /// Handle nested-name-specifiers in C++.
397 if (TheSema->Context.getLangOptions().CPlusPlus &&
398 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
399 // The contexts in which a nested-name-specifier can appear in C++.
400 unsigned NNSContexts
401 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
402 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
403 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
404 | (1 << (CodeCompletionContext::CCC_Statement - 1))
405 | (1 << (CodeCompletionContext::CCC_Expression - 1))
406 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
407 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
408 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
409 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000410 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000411 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
412 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000413
414 if (isa<NamespaceDecl>(Results[I].Declaration) ||
415 isa<NamespaceAliasDecl>(Results[I].Declaration))
416 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
417
418 if (unsigned RemainingContexts
419 = NNSContexts & ~CachedResult.ShowInContexts) {
420 // If there any contexts where this completion can be a
421 // nested-name-specifier but isn't already an option, create a
422 // nested-name-specifier completion.
423 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregor218937c2011-02-01 19:23:04 +0000424 CachedResult.Completion
425 = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor48601b32011-02-16 19:08:06 +0000426 *CachedCompletionAllocator);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000427 CachedResult.ShowInContexts = RemainingContexts;
428 CachedResult.Priority = CCP_NestedNameSpecifier;
429 CachedResult.TypeClass = STC_Void;
430 CachedResult.Type = 0;
431 CachedCompletionResults.push_back(CachedResult);
432 }
433 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000434 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000435 }
436
Douglas Gregor87c08a52010-08-13 22:48:40 +0000437 case Result::RK_Keyword:
438 case Result::RK_Pattern:
439 // Ignore keywords and patterns; we don't care, since they are so
440 // easily regenerated.
441 break;
442
443 case Result::RK_Macro: {
444 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000445 CachedResult.Completion
446 = Results[I].CreateCodeCompletionString(*TheSema,
Douglas Gregor48601b32011-02-16 19:08:06 +0000447 *CachedCompletionAllocator);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000448 CachedResult.ShowInContexts
449 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
450 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
451 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
452 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
453 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
454 | (1 << (CodeCompletionContext::CCC_Statement - 1))
455 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000456 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorf29c5232010-08-24 22:20:20 +0000457 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000458 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
Douglas Gregor5c722c702011-02-18 23:30:37 +0000459 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
460 | (1 << (CodeCompletionContext::CCC_OtherWithMacros - 1));
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000461
Douglas Gregor87c08a52010-08-13 22:48:40 +0000462 CachedResult.Priority = Results[I].Priority;
463 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000464 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000465 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000466 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000467 CachedCompletionResults.push_back(CachedResult);
468 break;
469 }
470 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000471 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000472
473 // Save the current top-level hash value.
474 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000475}
476
477void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregor87c08a52010-08-13 22:48:40 +0000478 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000479 CachedCompletionTypes.clear();
Douglas Gregor48601b32011-02-16 19:08:06 +0000480 CachedCompletionAllocator = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000481}
482
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000483namespace {
484
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000485/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000486/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000487class ASTInfoCollector : public ASTReaderListener {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000488 Preprocessor &PP;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000489 ASTContext &Context;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000490 LangOptions &LangOpt;
491 HeaderSearch &HSI;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000492 llvm::IntrusiveRefCntPtr<TargetInfo> &Target;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000493 std::string &Predefines;
494 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000496 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000497
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000498 bool InitializedLanguage;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000499public:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000500 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
501 HeaderSearch &HSI,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000502 llvm::IntrusiveRefCntPtr<TargetInfo> &Target,
503 std::string &Predefines,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000504 unsigned &Counter)
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000505 : PP(PP), Context(Context), LangOpt(LangOpt), HSI(HSI), Target(Target),
Douglas Gregor998b3d32011-09-01 23:39:15 +0000506 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000507 InitializedLanguage(false) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000508
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000509 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000510 if (InitializedLanguage)
Douglas Gregor998b3d32011-09-01 23:39:15 +0000511 return false;
512
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000513 LangOpt = LangOpts;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000514
515 // Initialize the preprocessor.
516 PP.Initialize(*Target);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000517
518 // Initialize the ASTContext
519 Context.InitBuiltinTypes(*Target);
520
521 InitializedLanguage = true;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000522 return false;
523 }
Mike Stump1eb44332009-09-09 15:08:12 +0000524
Chris Lattner5f9e2722011-07-23 10:55:15 +0000525 virtual bool ReadTargetTriple(StringRef Triple) {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000526 // If we've already initialized the target, don't do it again.
527 if (Target)
528 return false;
529
530 // FIXME: This is broken, we should store the TargetOptions in the AST file.
531 TargetOptions TargetOpts;
532 TargetOpts.ABI = "";
533 TargetOpts.CXXABI = "";
534 TargetOpts.CPU = "";
535 TargetOpts.Features.clear();
536 TargetOpts.Triple = Triple;
537 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(), TargetOpts);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000538 return false;
539 }
Mike Stump1eb44332009-09-09 15:08:12 +0000540
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000541 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000542 StringRef OriginalFileName,
Nick Lewycky277a6e72011-02-23 21:16:44 +0000543 std::string &SuggestedPredefines,
544 FileManager &FileMgr) {
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000545 Predefines = Buffers[0].Data;
546 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
547 Predefines += Buffers[I].Data;
548 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000549 return false;
550 }
Mike Stump1eb44332009-09-09 15:08:12 +0000551
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000552 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000553 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
554 }
Mike Stump1eb44332009-09-09 15:08:12 +0000555
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000556 virtual void ReadCounter(unsigned Value) {
557 Counter = Value;
558 }
559};
560
David Blaikie26e7a902011-09-26 00:01:39 +0000561class StoredDiagnosticConsumer : public DiagnosticConsumer {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000562 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
Douglas Gregora88084b2010-02-18 18:08:43 +0000563
564public:
David Blaikie26e7a902011-09-26 00:01:39 +0000565 explicit StoredDiagnosticConsumer(
Chris Lattner5f9e2722011-07-23 10:55:15 +0000566 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregora88084b2010-02-18 18:08:43 +0000567 : StoredDiags(StoredDiags) { }
568
David Blaikied6471f72011-09-25 23:23:43 +0000569 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000570 const Diagnostic &Info);
Douglas Gregoraee526e2011-09-29 00:38:00 +0000571
572 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
573 // Just drop any diagnostics that come from cloned consumers; they'll
574 // have different source managers anyway.
575 return new IgnoringDiagConsumer();
576 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000577};
578
579/// \brief RAII object that optionally captures diagnostics, if
580/// there is no diagnostic client to capture them already.
581class CaptureDroppedDiagnostics {
David Blaikied6471f72011-09-25 23:23:43 +0000582 DiagnosticsEngine &Diags;
David Blaikie26e7a902011-09-26 00:01:39 +0000583 StoredDiagnosticConsumer Client;
David Blaikie78ad0b92011-09-25 23:39:51 +0000584 DiagnosticConsumer *PreviousClient;
Douglas Gregora88084b2010-02-18 18:08:43 +0000585
586public:
David Blaikied6471f72011-09-25 23:23:43 +0000587 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000588 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000589 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000590 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000591 if (RequestCapture || Diags.getClient() == 0) {
592 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000593 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000594 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000595 }
596
597 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000598 if (Diags.getClient() == &Client) {
599 Diags.takeClient();
600 Diags.setClient(PreviousClient);
601 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000602 }
603};
604
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000605} // anonymous namespace
606
David Blaikie26e7a902011-09-26 00:01:39 +0000607void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
David Blaikie40847cf2011-09-26 01:18:08 +0000608 const Diagnostic &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000609 // Default implementation (Warnings/errors count).
David Blaikie78ad0b92011-09-25 23:39:51 +0000610 DiagnosticConsumer::HandleDiagnostic(Level, Info);
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000611
Douglas Gregora88084b2010-02-18 18:08:43 +0000612 StoredDiags.push_back(StoredDiagnostic(Level, Info));
613}
614
Steve Naroff77accc12009-09-03 18:19:54 +0000615const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000616 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000617}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000618
Chris Lattner5f9e2722011-07-23 10:55:15 +0000619llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
Chris Lattner75dfb652010-11-23 09:19:42 +0000620 std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000621 assert(FileMgr);
Chris Lattner75dfb652010-11-23 09:19:42 +0000622 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000623}
624
Douglas Gregore47be3e2010-11-11 00:39:14 +0000625/// \brief Configure the diagnostics object for use with ASTUnit.
David Blaikied6471f72011-09-25 23:23:43 +0000626void ASTUnit::ConfigureDiags(llvm::IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000627 const char **ArgBegin, const char **ArgEnd,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000628 ASTUnit &AST, bool CaptureDiagnostics) {
629 if (!Diags.getPtr()) {
630 // No diagnostics engine was provided, so create our own diagnostics object
631 // with the default options.
632 DiagnosticOptions DiagOpts;
David Blaikie78ad0b92011-09-25 23:39:51 +0000633 DiagnosticConsumer *Client = 0;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000634 if (CaptureDiagnostics)
David Blaikie26e7a902011-09-26 00:01:39 +0000635 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000636 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd- ArgBegin,
637 ArgBegin, Client);
Douglas Gregore47be3e2010-11-11 00:39:14 +0000638 } else if (CaptureDiagnostics) {
David Blaikie26e7a902011-09-26 00:01:39 +0000639 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
Douglas Gregore47be3e2010-11-11 00:39:14 +0000640 }
641}
642
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000643ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
David Blaikied6471f72011-09-25 23:23:43 +0000644 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000645 const FileSystemOptions &FileSystemOpts,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000646 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000647 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000648 unsigned NumRemappedFiles,
649 bool CaptureDiagnostics) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000650 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000651
652 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +0000653 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
654 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +0000655 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
656 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +0000657 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +0000658
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000659 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000660
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000661 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000662 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000663 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +0000664 AST->FileMgr = new FileManager(FileSystemOpts);
665 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
666 AST->getFileManager());
Chris Lattner39b49bc2010-11-23 08:35:12 +0000667 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000668
Douglas Gregor4db64a42010-01-23 00:14:00 +0000669 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +0000670 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
671 if (const llvm::MemoryBuffer *
672 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
673 // Create the file entry for the file that we're mapping from.
674 const FileEntry *FromFile
675 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
676 memBuf->getBufferSize(),
677 0);
678 if (!FromFile) {
679 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
680 << RemappedFiles[I].first;
681 delete memBuf;
682 continue;
683 }
684
685 // Override the contents of the "from" file with the contents of
686 // the "to" file.
687 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
688
689 } else {
690 const char *fname = fileOrBuf.get<const char *>();
691 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
692 if (!ToFile) {
693 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
694 << RemappedFiles[I].first << fname;
695 continue;
696 }
697
698 // Create the file entry for the file that we're mapping from.
699 const FileEntry *FromFile
700 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
701 ToFile->getSize(),
702 0);
703 if (!FromFile) {
704 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
705 << RemappedFiles[I].first;
706 delete memBuf;
707 continue;
708 }
709
710 // Override the contents of the "from" file with the contents of
711 // the "to" file.
712 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000713 }
Douglas Gregor4db64a42010-01-23 00:14:00 +0000714 }
715
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000716 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000717
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000718 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000719 std::string Predefines;
720 unsigned Counter;
721
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000722 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000723
Douglas Gregor998b3d32011-09-01 23:39:15 +0000724 AST->PP = new Preprocessor(AST->getDiagnostics(), AST->ASTFileLangOpts,
725 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
726 *AST,
727 /*IILookup=*/0,
728 /*OwnsHeaderSearch=*/false,
729 /*DelayInitialization=*/true);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000730 Preprocessor &PP = *AST->PP;
731
732 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
733 AST->getSourceManager(),
734 /*Target=*/0,
735 PP.getIdentifierTable(),
736 PP.getSelectorTable(),
737 PP.getBuiltinInfo(),
738 /* size_reserve = */0,
739 /*DelayInitialization=*/true);
740 ASTContext &Context = *AST->Ctx;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000741
Douglas Gregorf8a1e512011-09-02 00:26:20 +0000742 Reader.reset(new ASTReader(PP, Context));
Ted Kremenek8c647de2011-05-04 23:27:12 +0000743
744 // Recover resources if we crash before exiting this method.
745 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
746 ReaderCleanup(Reader.get());
747
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000748 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
Douglas Gregor998b3d32011-09-01 23:39:15 +0000749 AST->ASTFileLangOpts, HeaderInfo,
750 AST->Target, Predefines, Counter));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000751
Douglas Gregor72a9ae12011-07-22 16:00:58 +0000752 switch (Reader->ReadAST(Filename, serialization::MK_MainFile)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000753 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000754 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000755
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000756 case ASTReader::Failure:
757 case ASTReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000758 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000759 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000760 }
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000762 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
763
Daniel Dunbard5b61262009-09-21 03:03:47 +0000764 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000765 PP.setCounterValue(Counter);
Mike Stump1eb44332009-09-09 15:08:12 +0000766
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000767 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000768 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000769 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000770 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000771 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Ted Kremenek8c647de2011-05-04 23:27:12 +0000772
773 // Unregister the cleanup for ASTReader. It will get cleaned up
774 // by the ASTUnit cleanup.
775 ReaderCleanup.unregister();
776
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000777 Context.setExternalSource(Source);
778
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000779 // Create an AST consumer, even though it isn't used.
780 AST->Consumer.reset(new ASTConsumer);
781
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000782 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000783 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
784 AST->TheSema->Initialize();
785 ReaderPtr->InitializeSema(*AST->TheSema);
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +0000786 AST->Reader = ReaderPtr;
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000787
Mike Stump1eb44332009-09-09 15:08:12 +0000788 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000789}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000790
791namespace {
792
Douglas Gregor9b7db622011-02-16 18:16:54 +0000793/// \brief Preprocessor callback class that updates a hash value with the names
794/// of all macros that have been defined by the translation unit.
795class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
796 unsigned &Hash;
797
798public:
799 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
800
801 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
802 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
803 }
804};
805
806/// \brief Add the given declaration to the hash of all top-level entities.
807void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
808 if (!D)
809 return;
810
811 DeclContext *DC = D->getDeclContext();
812 if (!DC)
813 return;
814
815 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
816 return;
817
818 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
819 if (ND->getIdentifier())
820 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
821 else if (DeclarationName Name = ND->getDeclName()) {
822 std::string NameStr = Name.getAsString();
823 Hash = llvm::HashString(NameStr, Hash);
824 }
825 return;
826 }
827
828 if (ObjCForwardProtocolDecl *Forward
829 = dyn_cast<ObjCForwardProtocolDecl>(D)) {
830 for (ObjCForwardProtocolDecl::protocol_iterator
831 P = Forward->protocol_begin(),
832 PEnd = Forward->protocol_end();
833 P != PEnd; ++P)
834 AddTopLevelDeclarationToHash(*P, Hash);
835 return;
836 }
837
Chris Lattner5f9e2722011-07-23 10:55:15 +0000838 if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(D)) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000839 AddTopLevelDeclarationToHash(Class->getForwardInterfaceDecl(), Hash);
Douglas Gregor9b7db622011-02-16 18:16:54 +0000840 return;
841 }
842}
843
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000844class TopLevelDeclTrackerConsumer : public ASTConsumer {
845 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000846 unsigned &Hash;
847
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000848public:
Douglas Gregor9b7db622011-02-16 18:16:54 +0000849 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
850 : Unit(_Unit), Hash(Hash) {
851 Hash = 0;
852 }
Douglas Gregor9b7db622011-02-16 18:16:54 +0000853
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000854 void handleTopLevelDecl(Decl *D) {
855 // FIXME: Currently ObjC method declarations are incorrectly being
856 // reported as top-level declarations, even though their DeclContext
857 // is the containing ObjC @interface/@implementation. This is a
858 // fundamental problem in the parser right now.
859 if (isa<ObjCMethodDecl>(D))
860 return;
861
862 AddTopLevelDeclarationToHash(D, Hash);
863 Unit.addTopLevelDecl(D);
864
865 handleFileLevelDecl(D);
866 }
867
868 void handleFileLevelDecl(Decl *D) {
869 Unit.addFileLevelDecl(D);
870 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
871 for (NamespaceDecl::decl_iterator
872 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
873 handleFileLevelDecl(*I);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000874 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000875 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000876
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000877 void HandleTopLevelDecl(DeclGroupRef D) {
878 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
879 handleTopLevelDecl(*it);
880 }
881
Sebastian Redl27372b42010-08-11 18:52:41 +0000882 // We're not interested in "interesting" decls.
883 void HandleInterestingDecl(DeclGroupRef) {}
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +0000884
885 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
886 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
887 handleTopLevelDecl(*it);
888 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000889};
890
891class TopLevelDeclTrackerAction : public ASTFrontendAction {
892public:
893 ASTUnit &Unit;
894
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000895 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000896 StringRef InFile) {
Douglas Gregor9b7db622011-02-16 18:16:54 +0000897 CI.getPreprocessor().addPPCallbacks(
898 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
899 return new TopLevelDeclTrackerConsumer(Unit,
900 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000901 }
902
903public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000904 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
905
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000906 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000907 virtual TranslationUnitKind getTranslationUnitKind() {
908 return Unit.getTranslationUnitKind();
Douglas Gregordf95a132010-08-09 20:45:32 +0000909 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000910};
911
Argyrios Kyrtzidis92ddef12011-09-19 20:40:48 +0000912class PrecompilePreambleConsumer : public PCHGenerator {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000913 ASTUnit &Unit;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000914 unsigned &Hash;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000915 std::vector<Decl *> TopLevelDecls;
Douglas Gregor89d99802010-11-30 06:16:57 +0000916
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000917public:
Douglas Gregor9293ba82011-08-25 22:35:51 +0000918 PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000919 StringRef isysroot, raw_ostream *Out)
Douglas Gregor7143aab2011-09-01 17:04:32 +0000920 : PCHGenerator(PP, "", /*IsModule=*/false, isysroot, Out), Unit(Unit),
Douglas Gregor9b7db622011-02-16 18:16:54 +0000921 Hash(Unit.getCurrentTopLevelHashValue()) {
922 Hash = 0;
923 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000924
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000925 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000926 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
927 Decl *D = *it;
928 // FIXME: Currently ObjC method declarations are incorrectly being
929 // reported as top-level declarations, even though their DeclContext
930 // is the containing ObjC @interface/@implementation. This is a
931 // fundamental problem in the parser right now.
932 if (isa<ObjCMethodDecl>(D))
933 continue;
Douglas Gregor9b7db622011-02-16 18:16:54 +0000934 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000935 TopLevelDecls.push_back(D);
936 }
937 }
938
939 virtual void HandleTranslationUnit(ASTContext &Ctx) {
940 PCHGenerator::HandleTranslationUnit(Ctx);
941 if (!Unit.getDiagnostics().hasErrorOccurred()) {
942 // Translate the top-level declarations we captured during
943 // parsing into declaration IDs in the precompiled
944 // preamble. This will allow us to deserialize those top-level
945 // declarations when requested.
946 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
947 Unit.addTopLevelDeclFromPreamble(
948 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000949 }
950 }
951};
952
953class PrecompilePreambleAction : public ASTFrontendAction {
954 ASTUnit &Unit;
955
956public:
957 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
958
959 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000960 StringRef InFile) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000961 std::string Sysroot;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000962 std::string OutputFile;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000963 raw_ostream *OS = 0;
Argyrios Kyrtzidis8e3df4d2011-02-15 17:54:22 +0000964 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
965 OutputFile,
Douglas Gregor9293ba82011-08-25 22:35:51 +0000966 OS))
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000967 return 0;
968
Douglas Gregor832d6202011-07-22 16:35:34 +0000969 if (!CI.getFrontendOpts().RelocatablePCH)
970 Sysroot.clear();
971
Douglas Gregor9b7db622011-02-16 18:16:54 +0000972 CI.getPreprocessor().addPPCallbacks(
973 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor9293ba82011-08-25 22:35:51 +0000974 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
975 OS);
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000976 }
977
978 virtual bool hasCodeCompletionSupport() const { return false; }
979 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor467dc882011-08-25 22:30:56 +0000980 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000981};
982
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000983}
984
Douglas Gregorabc563f2010-07-19 21:46:24 +0000985/// Parse the source file into a translation unit using the given compiler
986/// invocation, replacing the current translation unit.
987///
988/// \returns True if a failure occurred that causes the ASTUnit not to
989/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +0000990bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +0000991 delete SavedMainFileBuffer;
992 SavedMainFileBuffer = 0;
993
Ted Kremenek4f327862011-03-21 18:40:17 +0000994 if (!Invocation) {
Douglas Gregor671947b2010-08-19 01:33:06 +0000995 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000996 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +0000997 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000998
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000999 // Create the compiler instance to use for building the AST.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001000 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1001
1002 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001003 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1004 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001005
Argyrios Kyrtzidis26d43cd2011-09-12 18:09:38 +00001006 llvm::IntrusiveRefCntPtr<CompilerInvocation>
1007 CCInvocation(new CompilerInvocation(*Invocation));
1008
1009 Clang->setInvocation(CCInvocation.getPtr());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001010 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001011
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001012 // Set up diagnostics, capturing any diagnostics that would
1013 // otherwise be dropped.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001014 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001015
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001016 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001017 Clang->getTargetOpts().Features = TargetFeatures;
1018 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001019 Clang->getTargetOpts()));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001020 if (!Clang->hasTarget()) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001021 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001022 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +00001023 }
1024
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001025 // Inform the target of the language options.
1026 //
1027 // FIXME: We shouldn't need to do this, the target should be immutable once
1028 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001029 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001030
Ted Kremenek03201fb2011-03-21 18:40:07 +00001031 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001032 "Invocation must have exactly one source file!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00001033 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001034 "FIXME: AST inputs not yet supported here!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00001035 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +00001036 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001037
Douglas Gregorabc563f2010-07-19 21:46:24 +00001038 // Configure the various subsystems.
1039 // FIXME: Should we retain the previous file manager?
Ted Kremenek03201fb2011-03-21 18:40:07 +00001040 FileSystemOpts = Clang->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001041 FileMgr = new FileManager(FileSystemOpts);
1042 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr);
Douglas Gregor914ed9d2010-08-13 03:15:25 +00001043 TheSema.reset();
Ted Kremenek4f327862011-03-21 18:40:17 +00001044 Ctx = 0;
1045 PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001046 Reader = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001047
1048 // Clear out old caches and data.
1049 TopLevelDecls.clear();
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001050 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001051 CleanTemporaryFiles();
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001052
Douglas Gregorf128fed2010-08-20 00:02:33 +00001053 if (!OverrideMainBuffer) {
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001054 StoredDiagnostics.erase(stored_diag_afterDriver_begin(), stored_diag_end());
Douglas Gregorf128fed2010-08-20 00:02:33 +00001055 TopLevelDeclsInPreamble.clear();
1056 }
1057
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001058 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001059 Clang->setFileManager(&getFileManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001060
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001061 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001062 Clang->setSourceManager(&getSourceManager());
Douglas Gregorabc563f2010-07-19 21:46:24 +00001063
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001064 // If the main file has been overridden due to the use of a preamble,
1065 // make that override happen and introduce the preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001066 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
Chandler Carruthba7537f2011-07-14 09:02:10 +00001067 PreprocessorOpts.DetailedRecordIncludesNestedMacroExpansions
1068 = NestedMacroExpansions;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001069 if (OverrideMainBuffer) {
1070 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1071 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1072 PreprocessorOpts.PrecompiledPreambleBytes.second
1073 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00001074 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001075 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +00001076
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001077 // The stored diagnostic has the old source manager in it; update
1078 // the locations to refer into the new source manager. Since we've
1079 // been careful to make sure that the source manager's state
1080 // before and after are identical, so that we can reuse the source
1081 // location itself.
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001082 for (unsigned I = NumStoredDiagnosticsFromDriver,
1083 N = StoredDiagnostics.size();
1084 I < N; ++I) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001085 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
1086 getSourceManager());
1087 StoredDiagnostics[I].setLocation(Loc);
1088 }
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001089
1090 // Keep track of the override buffer;
1091 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001092 }
1093
Ted Kremenek25a11e12011-03-22 01:15:24 +00001094 llvm::OwningPtr<TopLevelDeclTrackerAction> Act(
1095 new TopLevelDeclTrackerAction(*this));
1096
1097 // Recover resources if we crash before exiting this method.
1098 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1099 ActCleanup(Act.get());
1100
Ted Kremenek03201fb2011-03-21 18:40:07 +00001101 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
1102 Clang->getFrontendOpts().Inputs[0].first))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001103 goto error;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001104
1105 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00001106 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001107 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1108 getSourceManager(), PreambleDiagnostics,
1109 StoredDiagnostics);
1110 }
1111
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001112 Act->Execute();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001113
Ted Kremenek4f327862011-03-21 18:40:17 +00001114 // Steal the created target, context, and preprocessor.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001115 TheSema.reset(Clang->takeSema());
1116 Consumer.reset(Clang->takeASTConsumer());
Ted Kremenek4f327862011-03-21 18:40:17 +00001117 Ctx = &Clang->getASTContext();
1118 PP = &Clang->getPreprocessor();
1119 Clang->setSourceManager(0);
1120 Clang->setFileManager(0);
1121 Target = &Clang->getTarget();
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001122 Reader = Clang->getModuleManager();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001123
Daniel Dunbarf772d1e2009-12-04 08:17:33 +00001124 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001125
Douglas Gregorabc563f2010-07-19 21:46:24 +00001126 return false;
Ted Kremenek4f327862011-03-21 18:40:17 +00001127
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001128error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001129 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001130 if (OverrideMainBuffer) {
Douglas Gregor671947b2010-08-19 01:33:06 +00001131 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +00001132 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +00001133 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001134
Douglas Gregord54eb442010-10-12 16:25:54 +00001135 StoredDiagnostics.clear();
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001136 NumStoredDiagnosticsFromDriver = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001137 return true;
1138}
1139
Douglas Gregor44c181a2010-07-23 00:33:23 +00001140/// \brief Simple function to retrieve a path for a preamble precompiled header.
1141static std::string GetPreamblePCHPath() {
1142 // FIXME: This is lame; sys::Path should provide this function (in particular,
1143 // it should know how to find the temporary files dir).
1144 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +00001145 // FIXME: This is a hack so that we can override the preamble file during
1146 // crash-recovery testing, which is the only case where the preamble files
1147 // are not necessarily cleaned up.
1148 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1149 if (TmpFile)
1150 return TmpFile;
1151
Douglas Gregor44c181a2010-07-23 00:33:23 +00001152 std::string Error;
1153 const char *TmpDir = ::getenv("TMPDIR");
1154 if (!TmpDir)
1155 TmpDir = ::getenv("TEMP");
1156 if (!TmpDir)
1157 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001158#ifdef LLVM_ON_WIN32
1159 if (!TmpDir)
1160 TmpDir = ::getenv("USERPROFILE");
1161#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +00001162 if (!TmpDir)
1163 TmpDir = "/tmp";
1164 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +00001165 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001166 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +00001167 P.appendSuffix("pch");
Argyrios Kyrtzidisbc9d5a32011-07-21 18:44:46 +00001168 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
Douglas Gregor44c181a2010-07-23 00:33:23 +00001169 return std::string();
1170
Douglas Gregor44c181a2010-07-23 00:33:23 +00001171 return P.str();
1172}
1173
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001174/// \brief Compute the preamble for the main file, providing the source buffer
1175/// that corresponds to the main file along with a pair (bytes, start-of-line)
1176/// that describes the preamble.
1177std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +00001178ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1179 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001180 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +00001181 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001182 CreatedBuffer = false;
1183
Douglas Gregor44c181a2010-07-23 00:33:23 +00001184 // Try to determine if the main file has been remapped, either from the
1185 // command line (to another file) or directly through the compiler invocation
1186 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +00001187 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001188 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
1189 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1190 // Check whether there is a file-file remapping of the main file
1191 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +00001192 M = PreprocessorOpts.remapped_file_begin(),
1193 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001194 M != E;
1195 ++M) {
1196 llvm::sys::PathWithStatus MPath(M->first);
1197 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1198 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1199 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001200 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001201 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001202 CreatedBuffer = false;
1203 }
1204
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001205 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001206 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001207 return std::make_pair((llvm::MemoryBuffer*)0,
1208 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001209 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001210 }
1211 }
1212 }
1213
1214 // Check whether there is a file-buffer remapping. It supercedes the
1215 // file-file remapping.
1216 for (PreprocessorOptions::remapped_file_buffer_iterator
1217 M = PreprocessorOpts.remapped_file_buffer_begin(),
1218 E = PreprocessorOpts.remapped_file_buffer_end();
1219 M != E;
1220 ++M) {
1221 llvm::sys::PathWithStatus MPath(M->first);
1222 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1223 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1224 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001225 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001226 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001227 CreatedBuffer = false;
1228 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001229
Douglas Gregor175c4a92010-07-23 23:58:40 +00001230 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001231 }
1232 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001233 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001234 }
1235
1236 // If the main source file was not remapped, load it now.
1237 if (!Buffer) {
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001238 Buffer = getBufferForFile(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001239 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001240 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001241
1242 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001243 }
1244
Argyrios Kyrtzidis03c107a2011-08-25 20:39:19 +00001245 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
1246 Invocation.getLangOpts(),
1247 MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +00001248}
1249
Douglas Gregor754f3492010-07-24 00:38:13 +00001250static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +00001251 unsigned NewSize,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001252 StringRef NewName) {
Douglas Gregor754f3492010-07-24 00:38:13 +00001253 llvm::MemoryBuffer *Result
1254 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1255 memcpy(const_cast<char*>(Result->getBufferStart()),
1256 Old->getBufferStart(), Old->getBufferSize());
1257 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001258 ' ', NewSize - Old->getBufferSize() - 1);
1259 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +00001260
Douglas Gregor754f3492010-07-24 00:38:13 +00001261 return Result;
1262}
1263
Douglas Gregor175c4a92010-07-23 23:58:40 +00001264/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1265/// the source file.
1266///
1267/// This routine will compute the preamble of the main source file. If a
1268/// non-trivial preamble is found, it will precompile that preamble into a
1269/// precompiled header so that the precompiled preamble can be used to reduce
1270/// reparsing time. If a precompiled preamble has already been constructed,
1271/// this routine will determine if it is still valid and, if so, avoid
1272/// rebuilding the precompiled preamble.
1273///
Douglas Gregordf95a132010-08-09 20:45:32 +00001274/// \param AllowRebuild When true (the default), this routine is
1275/// allowed to rebuild the precompiled preamble if it is found to be
1276/// out-of-date.
1277///
1278/// \param MaxLines When non-zero, the maximum number of lines that
1279/// can occur within the preamble.
1280///
Douglas Gregor754f3492010-07-24 00:38:13 +00001281/// \returns If the precompiled preamble can be used, returns a newly-allocated
1282/// buffer that should be used in place of the main file when doing so.
1283/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001284llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor01b6e312011-07-01 18:22:13 +00001285 const CompilerInvocation &PreambleInvocationIn,
Douglas Gregordf95a132010-08-09 20:45:32 +00001286 bool AllowRebuild,
1287 unsigned MaxLines) {
Douglas Gregor01b6e312011-07-01 18:22:13 +00001288
1289 llvm::IntrusiveRefCntPtr<CompilerInvocation>
1290 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1291 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001292 PreprocessorOptions &PreprocessorOpts
Douglas Gregor01b6e312011-07-01 18:22:13 +00001293 = PreambleInvocation->getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001294
1295 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001296 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor01b6e312011-07-01 18:22:13 +00001297 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001298
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001299 // If ComputePreamble() Take ownership of the preamble buffer.
Douglas Gregor73fc9122010-11-16 20:45:51 +00001300 llvm::OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
1301 if (CreatedPreambleBuffer)
1302 OwnedPreambleBuffer.reset(NewPreamble.first);
1303
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001304 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001305 // We couldn't find a preamble in the main source. Clear out the current
1306 // preamble, if we have one. It's obviously no good any more.
1307 Preamble.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001308 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001309
1310 // The next time we actually see a preamble, precompile it.
1311 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001312 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001313 }
1314
1315 if (!Preamble.empty()) {
1316 // We've previously computed a preamble. Check whether we have the same
1317 // preamble now that we did before, and that there's enough space in
1318 // the main-file buffer within the precompiled preamble to fit the
1319 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001320 if (Preamble.size() == NewPreamble.second.first &&
1321 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001322 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001323 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001324 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001325 // The preamble has not changed. We may be able to re-use the precompiled
1326 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001327
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001328 // Check that none of the files used by the preamble have changed.
1329 bool AnyFileChanged = false;
1330
1331 // First, make a record of those files that have been overridden via
1332 // remapping or unsaved_files.
1333 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1334 for (PreprocessorOptions::remapped_file_iterator
1335 R = PreprocessorOpts.remapped_file_begin(),
1336 REnd = PreprocessorOpts.remapped_file_end();
1337 !AnyFileChanged && R != REnd;
1338 ++R) {
1339 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001340 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001341 // If we can't stat the file we're remapping to, assume that something
1342 // horrible happened.
1343 AnyFileChanged = true;
1344 break;
1345 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001346
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001347 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1348 StatBuf.st_mtime);
1349 }
1350 for (PreprocessorOptions::remapped_file_buffer_iterator
1351 R = PreprocessorOpts.remapped_file_buffer_begin(),
1352 REnd = PreprocessorOpts.remapped_file_buffer_end();
1353 !AnyFileChanged && R != REnd;
1354 ++R) {
1355 // FIXME: Should we actually compare the contents of file->buffer
1356 // remappings?
1357 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1358 0);
1359 }
1360
1361 // Check whether anything has changed.
1362 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1363 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1364 !AnyFileChanged && F != FEnd;
1365 ++F) {
1366 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1367 = OverriddenFiles.find(F->first());
1368 if (Overridden != OverriddenFiles.end()) {
1369 // This file was remapped; check whether the newly-mapped file
1370 // matches up with the previous mapping.
1371 if (Overridden->second != F->second)
1372 AnyFileChanged = true;
1373 continue;
1374 }
1375
1376 // The file was not remapped; check whether it has changed on disk.
1377 struct stat StatBuf;
Anders Carlsson340415c2011-03-18 19:23:38 +00001378 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001379 // If we can't stat the file, assume that something horrible happened.
1380 AnyFileChanged = true;
1381 } else if (StatBuf.st_size != F->second.first ||
1382 StatBuf.st_mtime != F->second.second)
1383 AnyFileChanged = true;
1384 }
1385
1386 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001387 // Okay! We can re-use the precompiled preamble.
1388
1389 // Set the state of the diagnostic object to mimic its state
1390 // after parsing the preamble.
Douglas Gregor32be4a52010-10-11 21:37:58 +00001391 // FIXME: This won't catch any #pragma push warning changes that
1392 // have occurred in the preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001393 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001394 ProcessWarningOptions(getDiagnostics(),
Douglas Gregor01b6e312011-07-01 18:22:13 +00001395 PreambleInvocation->getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001396 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001397
1398 // Create a version of the main file buffer that is padded to
1399 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001400 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001401 PreambleReservedSize,
1402 FrontendOpts.Inputs[0].second);
1403 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001404 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001405
1406 // If we aren't allowed to rebuild the precompiled preamble, just
1407 // return now.
1408 if (!AllowRebuild)
1409 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001410
Douglas Gregor175c4a92010-07-23 23:58:40 +00001411 // We can't reuse the previously-computed preamble. Build a new one.
1412 Preamble.clear();
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001413 PreambleDiagnostics.clear();
Ted Kremenek1872b312011-10-27 17:55:18 +00001414 erasePreambleFile(this);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001415 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001416 } else if (!AllowRebuild) {
1417 // We aren't allowed to rebuild the precompiled preamble; just
1418 // return now.
1419 return 0;
1420 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001421
1422 // If the preamble rebuild counter > 1, it's because we previously
1423 // failed to build a preamble and we're not yet ready to try
1424 // again. Decrement the counter and return a failure.
1425 if (PreambleRebuildCounter > 1) {
1426 --PreambleRebuildCounter;
1427 return 0;
1428 }
1429
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001430 // Create a temporary file for the precompiled preamble. In rare
1431 // circumstances, this can fail.
1432 std::string PreamblePCHPath = GetPreamblePCHPath();
1433 if (PreamblePCHPath.empty()) {
1434 // Try again next time.
1435 PreambleRebuildCounter = 1;
1436 return 0;
1437 }
1438
Douglas Gregor175c4a92010-07-23 23:58:40 +00001439 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001440 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001441 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001442
1443 // Create a new buffer that stores the preamble. The buffer also contains
1444 // extra space for the original contents of the file (which will be present
1445 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001446 // grows.
1447 PreambleReservedSize = NewPreamble.first->getBufferSize();
1448 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001449 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001450 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001451 PreambleReservedSize *= 2;
1452
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001453 // Save the preamble text for later; we'll need to compare against it for
1454 // subsequent reparses.
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00001455 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].second;
1456 Preamble.assign(FileMgr->getFile(MainFilename),
1457 NewPreamble.first->getBufferStart(),
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001458 NewPreamble.first->getBufferStart()
1459 + NewPreamble.second.first);
1460 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1461
Douglas Gregor671947b2010-08-19 01:33:06 +00001462 delete PreambleBuffer;
1463 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001464 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001465 FrontendOpts.Inputs[0].second);
1466 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001467 NewPreamble.first->getBufferStart(), Preamble.size());
1468 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001469 ' ', PreambleReservedSize - Preamble.size() - 1);
1470 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001471
1472 // Remap the main source file to the preamble buffer.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001473 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001474 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1475
1476 // Tell the compiler invocation to generate a temporary precompiled header.
1477 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001478 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001479 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001480 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1481 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001482
1483 // Create the compiler instance to use for building the precompiled preamble.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001484 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1485
1486 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001487 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1488 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00001489
Douglas Gregor01b6e312011-07-01 18:22:13 +00001490 Clang->setInvocation(&*PreambleInvocation);
Ted Kremenek03201fb2011-03-21 18:40:07 +00001491 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001492
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001493 // Set up diagnostics, capturing all of the diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001494 Clang->setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001495
1496 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001497 Clang->getTargetOpts().Features = TargetFeatures;
1498 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1499 Clang->getTargetOpts()));
1500 if (!Clang->hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001501 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1502 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001503 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001504 PreprocessorOpts.eraseRemappedFile(
1505 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001506 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001507 }
1508
1509 // Inform the target of the language options.
1510 //
1511 // FIXME: We shouldn't need to do this, the target should be immutable once
1512 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001513 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001514
Ted Kremenek03201fb2011-03-21 18:40:07 +00001515 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001516 "Invocation must have exactly one source file!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00001517 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001518 "FIXME: AST inputs not yet supported here!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00001519 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Douglas Gregor44c181a2010-07-23 00:33:23 +00001520 "IR inputs not support here!");
1521
1522 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001523 getDiagnostics().Reset();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001524 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001525 StoredDiagnostics.erase(stored_diag_afterDriver_begin(), stored_diag_end());
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001526 TopLevelDecls.clear();
1527 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001528
1529 // Create a file manager object to provide access to and cache the filesystem.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001530 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001531
1532 // Create the source manager.
Ted Kremenek03201fb2011-03-21 18:40:07 +00001533 Clang->setSourceManager(new SourceManager(getDiagnostics(),
Ted Kremenek4f327862011-03-21 18:40:17 +00001534 Clang->getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001535
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001536 llvm::OwningPtr<PrecompilePreambleAction> Act;
1537 Act.reset(new PrecompilePreambleAction(*this));
Ted Kremenek03201fb2011-03-21 18:40:07 +00001538 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
1539 Clang->getFrontendOpts().Inputs[0].first)) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001540 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1541 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001542 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001543 PreprocessorOpts.eraseRemappedFile(
1544 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001545 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001546 }
1547
1548 Act->Execute();
1549 Act->EndSourceFile();
Ted Kremenek4f327862011-03-21 18:40:17 +00001550
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001551 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001552 // There were errors parsing the preamble, so no precompiled header was
1553 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001554 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001555 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1556 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001557 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001558 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001559 PreprocessorOpts.eraseRemappedFile(
1560 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001561 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001562 }
1563
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001564 // Transfer any diagnostics generated when parsing the preamble into the set
1565 // of preamble diagnostics.
1566 PreambleDiagnostics.clear();
1567 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00001568 stored_diag_afterDriver_begin(), stored_diag_end());
1569 StoredDiagnostics.erase(stored_diag_afterDriver_begin(), stored_diag_end());
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001570
Douglas Gregor175c4a92010-07-23 23:58:40 +00001571 // Keep track of the preamble we precompiled.
Ted Kremenek1872b312011-10-27 17:55:18 +00001572 setPreambleFile(this, FrontendOpts.OutputFile);
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001573 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001574
1575 // Keep track of all of the files that the source manager knows about,
1576 // so we can verify whether they have changed or not.
1577 FilesInPreamble.clear();
Ted Kremenek03201fb2011-03-21 18:40:07 +00001578 SourceManager &SourceMgr = Clang->getSourceManager();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001579 const llvm::MemoryBuffer *MainFileBuffer
1580 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1581 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1582 FEnd = SourceMgr.fileinfo_end();
1583 F != FEnd;
1584 ++F) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001585 const FileEntry *File = F->second->OrigEntry;
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001586 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1587 continue;
1588
1589 FilesInPreamble[File->getName()]
1590 = std::make_pair(F->second->getSize(), File->getModificationTime());
1591 }
1592
Douglas Gregoreababfb2010-08-04 05:53:38 +00001593 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001594 PreprocessorOpts.eraseRemappedFile(
1595 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor9b7db622011-02-16 18:16:54 +00001596
1597 // If the hash of top-level entities differs from the hash of the top-level
1598 // entities the last time we rebuilt the preamble, clear out the completion
1599 // cache.
1600 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1601 CompletionCacheTopLevelHashValue = 0;
1602 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1603 }
1604
Douglas Gregor754f3492010-07-24 00:38:13 +00001605 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001606 PreambleReservedSize,
1607 FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001608}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001609
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001610void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1611 std::vector<Decl *> Resolved;
1612 Resolved.reserve(TopLevelDeclsInPreamble.size());
1613 ExternalASTSource &Source = *getASTContext().getExternalSource();
1614 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1615 // Resolve the declaration ID to an actual declaration, possibly
1616 // deserializing the declaration in the process.
1617 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1618 if (D)
1619 Resolved.push_back(D);
1620 }
1621 TopLevelDeclsInPreamble.clear();
1622 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1623}
1624
Chris Lattner5f9e2722011-07-23 10:55:15 +00001625StringRef ASTUnit::getMainFileName() const {
Douglas Gregor213f18b2010-10-28 15:44:59 +00001626 return Invocation->getFrontendOpts().Inputs[0].second;
1627}
1628
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001629ASTUnit *ASTUnit::create(CompilerInvocation *CI,
David Blaikied6471f72011-09-25 23:23:43 +00001630 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags) {
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001631 llvm::OwningPtr<ASTUnit> AST;
1632 AST.reset(new ASTUnit(false));
1633 ConfigureDiags(Diags, 0, 0, *AST, /*CaptureDiagnostics=*/false);
1634 AST->Diagnostics = Diags;
Ted Kremenek4f327862011-03-21 18:40:17 +00001635 AST->Invocation = CI;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001636 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001637 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001638 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00001639
1640 return AST.take();
1641}
1642
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001643ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
David Blaikied6471f72011-09-25 23:23:43 +00001644 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001645 ASTFrontendAction *Action,
1646 ASTUnit *Unit) {
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001647 assert(CI && "A CompilerInvocation is required");
1648
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001649 llvm::OwningPtr<ASTUnit> OwnAST;
1650 ASTUnit *AST = Unit;
1651 if (!AST) {
1652 // Create the AST unit.
1653 OwnAST.reset(create(CI, Diags));
1654 AST = OwnAST.get();
1655 }
1656
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001657 AST->OnlyLocalDecls = false;
1658 AST->CaptureDiagnostics = false;
Douglas Gregor467dc882011-08-25 22:30:56 +00001659 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001660 AST->ShouldCacheCodeCompletionResults = false;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001661
1662 // Recover resources if we crash before exiting this method.
1663 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001664 ASTUnitCleanup(OwnAST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001665 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1666 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001667 DiagCleanup(Diags.getPtr());
1668
1669 // We'll manage file buffers ourselves.
1670 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1671 CI->getFrontendOpts().DisableFree = false;
1672 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1673
1674 // Save the target features.
1675 AST->TargetFeatures = CI->getTargetOpts().Features;
1676
1677 // Create the compiler instance to use for building the AST.
1678 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1679
1680 // Recover resources if we crash before exiting this method.
1681 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1682 CICleanup(Clang.get());
1683
1684 Clang->setInvocation(CI);
1685 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
1686
1687 // Set up diagnostics, capturing any diagnostics that would
1688 // otherwise be dropped.
1689 Clang->setDiagnostics(&AST->getDiagnostics());
1690
1691 // Create the target instance.
1692 Clang->getTargetOpts().Features = AST->TargetFeatures;
1693 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1694 Clang->getTargetOpts()));
1695 if (!Clang->hasTarget())
1696 return 0;
1697
1698 // Inform the target of the language options.
1699 //
1700 // FIXME: We shouldn't need to do this, the target should be immutable once
1701 // created. This complexity should be lifted elsewhere.
1702 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1703
1704 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1705 "Invocation must have exactly one source file!");
1706 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
1707 "FIXME: AST inputs not yet supported here!");
1708 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1709 "IR inputs not supported here!");
1710
1711 // Configure the various subsystems.
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001712 AST->TheSema.reset();
1713 AST->Ctx = 0;
1714 AST->PP = 0;
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001715 AST->Reader = 0;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001716
1717 // Create a file manager object to provide access to and cache the filesystem.
1718 Clang->setFileManager(&AST->getFileManager());
1719
1720 // Create the source manager.
1721 Clang->setSourceManager(&AST->getSourceManager());
1722
1723 ASTFrontendAction *Act = Action;
1724
1725 llvm::OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
1726 if (!Act) {
1727 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1728 Act = TrackerAct.get();
1729 }
1730
1731 // Recover resources if we crash before exiting this method.
1732 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1733 ActCleanup(TrackerAct.get());
1734
1735 if (!Act->BeginSourceFile(*Clang.get(),
1736 Clang->getFrontendOpts().Inputs[0].second,
1737 Clang->getFrontendOpts().Inputs[0].first))
1738 return 0;
1739
1740 Act->Execute();
1741
1742 // Steal the created target, context, and preprocessor.
1743 AST->TheSema.reset(Clang->takeSema());
1744 AST->Consumer.reset(Clang->takeASTConsumer());
1745 AST->Ctx = &Clang->getASTContext();
1746 AST->PP = &Clang->getPreprocessor();
1747 Clang->setSourceManager(0);
1748 Clang->setFileManager(0);
1749 AST->Target = &Clang->getTarget();
Argyrios Kyrtzidis62ba9f62011-11-01 17:14:15 +00001750 AST->Reader = Clang->getModuleManager();
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001751
1752 Act->EndSourceFile();
1753
Argyrios Kyrtzidisabb5afa2011-10-14 21:22:05 +00001754 if (OwnAST)
1755 return OwnAST.take();
1756 else
1757 return AST;
Argyrios Kyrtzidisd808bd22011-05-03 23:26:34 +00001758}
1759
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001760bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1761 if (!Invocation)
1762 return true;
1763
1764 // We'll manage file buffers ourselves.
1765 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1766 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001767 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001768
Douglas Gregor1aa27302011-01-27 18:02:58 +00001769 // Save the target features.
1770 TargetFeatures = Invocation->getTargetOpts().Features;
1771
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001772 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001773 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001774 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001775 OverrideMainBuffer
1776 = getMainBufferWithPrecompiledPreamble(*Invocation);
1777 }
1778
Douglas Gregor213f18b2010-10-28 15:44:59 +00001779 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001780 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001781
Ted Kremenek25a11e12011-03-22 01:15:24 +00001782 // Recover resources if we crash before exiting this method.
1783 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1784 MemBufferCleanup(OverrideMainBuffer);
1785
Douglas Gregor213f18b2010-10-28 15:44:59 +00001786 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001787}
1788
Douglas Gregorabc563f2010-07-19 21:46:24 +00001789ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
David Blaikied6471f72011-09-25 23:23:43 +00001790 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Douglas Gregorabc563f2010-07-19 21:46:24 +00001791 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001792 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001793 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001794 TranslationUnitKind TUKind,
Douglas Gregordca8ee82011-05-06 16:33:08 +00001795 bool CacheCodeCompletionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00001796 bool NestedMacroExpansions) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001797 // Create the AST unit.
1798 llvm::OwningPtr<ASTUnit> AST;
1799 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001800 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001801 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001802 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001803 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001804 AST->TUKind = TUKind;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001805 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Ted Kremenek4f327862011-03-21 18:40:17 +00001806 AST->Invocation = CI;
Chandler Carruthba7537f2011-07-14 09:02:10 +00001807 AST->NestedMacroExpansions = NestedMacroExpansions;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001808
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001809 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001810 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1811 ASTUnitCleanup(AST.get());
David Blaikied6471f72011-09-25 23:23:43 +00001812 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1813 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00001814 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001815
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001816 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001817}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001818
1819ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1820 const char **ArgEnd,
David Blaikied6471f72011-09-25 23:23:43 +00001821 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001822 StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001823 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001824 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001825 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001826 unsigned NumRemappedFiles,
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001827 bool RemappedFilesKeepOriginalName,
Douglas Gregordf95a132010-08-09 20:45:32 +00001828 bool PrecompilePreamble,
Douglas Gregor467dc882011-08-25 22:30:56 +00001829 TranslationUnitKind TUKind,
Douglas Gregor99ba2022010-10-27 17:24:53 +00001830 bool CacheCodeCompletionResults,
Chandler Carruthba7537f2011-07-14 09:02:10 +00001831 bool NestedMacroExpansions) {
Douglas Gregor28019772010-04-05 23:52:57 +00001832 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001833 // No diagnostics engine was provided, so create our own diagnostics object
1834 // with the default options.
1835 DiagnosticOptions DiagOpts;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001836 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1837 ArgBegin);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001838 }
Daniel Dunbar7b556682009-12-02 03:23:45 +00001839
Chris Lattner5f9e2722011-07-23 10:55:15 +00001840 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001841
Ted Kremenek4f327862011-03-21 18:40:17 +00001842 llvm::IntrusiveRefCntPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001843
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001844 {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00001845
Douglas Gregore47be3e2010-11-11 00:39:14 +00001846 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001847 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001848
Argyrios Kyrtzidis832316e2011-04-04 23:11:45 +00001849 CI = clang::createInvocationFromCommandLine(
Frits van Bommele9c02652011-07-18 12:00:32 +00001850 llvm::makeArrayRef(ArgBegin, ArgEnd),
1851 Diags);
Argyrios Kyrtzidis054e4f52011-04-04 21:38:51 +00001852 if (!CI)
Argyrios Kyrtzidis4e03c2b2011-03-07 22:45:01 +00001853 return 0;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001854 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001855
Douglas Gregor4db64a42010-01-23 00:14:00 +00001856 // Override any files that need remapping
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001857 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1858 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1859 if (const llvm::MemoryBuffer *
1860 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1861 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1862 } else {
1863 const char *fname = fileOrBuf.get<const char *>();
1864 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1865 }
1866 }
Argyrios Kyrtzidis299a4a92011-03-08 23:35:24 +00001867 CI->getPreprocessorOpts().RemappedFilesKeepOriginalName =
1868 RemappedFilesKeepOriginalName;
Douglas Gregor4db64a42010-01-23 00:14:00 +00001869
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001870 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001871 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001872
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001873 // Create the AST unit.
1874 llvm::OwningPtr<ASTUnit> AST;
1875 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001876 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001877 AST->Diagnostics = Diags;
Anders Carlsson0d8d7e62011-03-18 18:22:40 +00001878
1879 AST->FileSystemOpts = CI->getFileSystemOpts();
Ted Kremenek4f327862011-03-21 18:40:17 +00001880 AST->FileMgr = new FileManager(AST->FileSystemOpts);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001881 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001882 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor467dc882011-08-25 22:30:56 +00001883 AST->TUKind = TUKind;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001884 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1885 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001886 AST->StoredDiagnostics.swap(StoredDiagnostics);
Ted Kremenek4f327862011-03-21 18:40:17 +00001887 AST->Invocation = CI;
Chandler Carruthba7537f2011-07-14 09:02:10 +00001888 AST->NestedMacroExpansions = NestedMacroExpansions;
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001889
1890 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00001891 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1892 ASTUnitCleanup(AST.get());
1893 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInvocation,
1894 llvm::CrashRecoveryContextReleaseRefCleanup<CompilerInvocation> >
1895 CICleanup(CI.getPtr());
David Blaikied6471f72011-09-25 23:23:43 +00001896 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1897 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
Ted Kremenek25a11e12011-03-22 01:15:24 +00001898 DiagCleanup(Diags.getPtr());
Ted Kremenekb547eeb2011-03-18 02:06:56 +00001899
Chris Lattner39b49bc2010-11-23 08:35:12 +00001900 return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001901}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001902
1903bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
Ted Kremenek4f327862011-03-21 18:40:17 +00001904 if (!Invocation)
Douglas Gregorabc563f2010-07-19 21:46:24 +00001905 return true;
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00001906
1907 clearFileLevelDecls();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001908
Douglas Gregor213f18b2010-10-28 15:44:59 +00001909 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001910 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00001911
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001912 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00001913 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00001914 PPOpts.DisableStatCache = true;
Douglas Gregorf128fed2010-08-20 00:02:33 +00001915 for (PreprocessorOptions::remapped_file_buffer_iterator
1916 R = PPOpts.remapped_file_buffer_begin(),
1917 REnd = PPOpts.remapped_file_buffer_end();
1918 R != REnd;
1919 ++R) {
1920 delete R->second;
1921 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001922 Invocation->getPreprocessorOpts().clearRemappedFiles();
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00001923 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1924 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1925 if (const llvm::MemoryBuffer *
1926 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1927 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1928 memBuf);
1929 } else {
1930 const char *fname = fileOrBuf.get<const char *>();
1931 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1932 fname);
1933 }
1934 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001935
Douglas Gregoreababfb2010-08-04 05:53:38 +00001936 // If we have a preamble file lying around, or if we might try to
1937 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00001938 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00001939 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00001940 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001941
Douglas Gregorabc563f2010-07-19 21:46:24 +00001942 // Clear out the diagnostics state.
Douglas Gregor32be4a52010-10-11 21:37:58 +00001943 if (!OverrideMainBuffer) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001944 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001945 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1946 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001947
Douglas Gregor175c4a92010-07-23 23:58:40 +00001948 // Parse the sources
Douglas Gregor9b7db622011-02-16 18:16:54 +00001949 bool Result = Parse(OverrideMainBuffer);
Argyrios Kyrtzidis2fe17fc2011-10-31 21:25:31 +00001950
1951 // If we're caching global code-completion results, and the top-level
1952 // declarations have changed, clear out the code-completion cache.
1953 if (!Result && ShouldCacheCodeCompletionResults &&
1954 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1955 CacheCodeCompletionResults();
Douglas Gregor9b7db622011-02-16 18:16:54 +00001956
Douglas Gregor8fa0a802011-08-04 20:04:59 +00001957 // We now need to clear out the completion allocator for
1958 // clang_getCursorCompletionString; it'll be recreated if necessary.
1959 CursorCompletionAllocator = 0;
1960
Douglas Gregor175c4a92010-07-23 23:58:40 +00001961 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001962}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001963
Douglas Gregor87c08a52010-08-13 22:48:40 +00001964//----------------------------------------------------------------------------//
1965// Code completion
1966//----------------------------------------------------------------------------//
1967
1968namespace {
1969 /// \brief Code completion consumer that combines the cached code-completion
1970 /// results from an ASTUnit with the code-completion results provided to it,
1971 /// then passes the result on to
1972 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
Douglas Gregor3da626b2011-07-07 16:03:39 +00001973 unsigned long long NormalContexts;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001974 ASTUnit &AST;
1975 CodeCompleteConsumer &Next;
1976
1977 public:
1978 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor8071e422010-08-15 06:18:01 +00001979 bool IncludeMacros, bool IncludeCodePatterns,
1980 bool IncludeGlobals)
1981 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001982 Next.isOutputBinary()), AST(AST), Next(Next)
1983 {
1984 // Compute the set of contexts in which we will look when we don't have
1985 // any information about the specific context.
1986 NormalContexts
Douglas Gregor3da626b2011-07-07 16:03:39 +00001987 = (1LL << (CodeCompletionContext::CCC_TopLevel - 1))
1988 | (1LL << (CodeCompletionContext::CCC_ObjCInterface - 1))
1989 | (1LL << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1990 | (1LL << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1991 | (1LL << (CodeCompletionContext::CCC_Statement - 1))
1992 | (1LL << (CodeCompletionContext::CCC_Expression - 1))
1993 | (1LL << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1994 | (1LL << (CodeCompletionContext::CCC_DotMemberAccess - 1))
1995 | (1LL << (CodeCompletionContext::CCC_ArrowMemberAccess - 1))
1996 | (1LL << (CodeCompletionContext::CCC_ObjCPropertyAccess - 1))
1997 | (1LL << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
1998 | (1LL << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
1999 | (1LL << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor02688102010-09-14 23:59:36 +00002000
Douglas Gregor87c08a52010-08-13 22:48:40 +00002001 if (AST.getASTContext().getLangOptions().CPlusPlus)
Douglas Gregor3da626b2011-07-07 16:03:39 +00002002 NormalContexts |= (1LL << (CodeCompletionContext::CCC_EnumTag - 1))
2003 | (1LL << (CodeCompletionContext::CCC_UnionTag - 1))
2004 | (1LL << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
Douglas Gregor87c08a52010-08-13 22:48:40 +00002005 }
2006
2007 virtual void ProcessCodeCompleteResults(Sema &S,
2008 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002009 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002010 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002011
2012 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2013 OverloadCandidate *Candidates,
2014 unsigned NumCandidates) {
2015 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2016 }
Douglas Gregor218937c2011-02-01 19:23:04 +00002017
Douglas Gregordae68752011-02-01 22:57:45 +00002018 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +00002019 return Next.getAllocator();
2020 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00002021 };
2022}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002023
Douglas Gregor5f808c22010-08-16 21:18:39 +00002024/// \brief Helper function that computes which global names are hidden by the
2025/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002026static void CalculateHiddenNames(const CodeCompletionContext &Context,
2027 CodeCompletionResult *Results,
2028 unsigned NumResults,
2029 ASTContext &Ctx,
2030 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00002031 bool OnlyTagNames = false;
2032 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00002033 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002034 case CodeCompletionContext::CCC_TopLevel:
2035 case CodeCompletionContext::CCC_ObjCInterface:
2036 case CodeCompletionContext::CCC_ObjCImplementation:
2037 case CodeCompletionContext::CCC_ObjCIvarList:
2038 case CodeCompletionContext::CCC_ClassStructUnion:
2039 case CodeCompletionContext::CCC_Statement:
2040 case CodeCompletionContext::CCC_Expression:
2041 case CodeCompletionContext::CCC_ObjCMessageReceiver:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002042 case CodeCompletionContext::CCC_DotMemberAccess:
2043 case CodeCompletionContext::CCC_ArrowMemberAccess:
2044 case CodeCompletionContext::CCC_ObjCPropertyAccess:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002045 case CodeCompletionContext::CCC_Namespace:
2046 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00002047 case CodeCompletionContext::CCC_Name:
2048 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00002049 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor0f91c8c2011-07-30 06:55:39 +00002050 case CodeCompletionContext::CCC_ObjCInterfaceName:
Douglas Gregor5f808c22010-08-16 21:18:39 +00002051 break;
2052
2053 case CodeCompletionContext::CCC_EnumTag:
2054 case CodeCompletionContext::CCC_UnionTag:
2055 case CodeCompletionContext::CCC_ClassOrStructTag:
2056 OnlyTagNames = true;
2057 break;
2058
2059 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002060 case CodeCompletionContext::CCC_MacroName:
2061 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00002062 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00002063 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00002064 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00002065 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00002066 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00002067 case CodeCompletionContext::CCC_Other:
Douglas Gregor5c722c702011-02-18 23:30:37 +00002068 case CodeCompletionContext::CCC_OtherWithMacros:
Douglas Gregor3da626b2011-07-07 16:03:39 +00002069 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2070 case CodeCompletionContext::CCC_ObjCClassMessage:
2071 case CodeCompletionContext::CCC_ObjCCategoryName:
Douglas Gregor721f3592010-08-25 18:41:16 +00002072 // We're looking for nothing, or we're looking for names that cannot
2073 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00002074 return;
2075 }
2076
John McCall0a2c5e22010-08-25 06:19:51 +00002077 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002078 for (unsigned I = 0; I != NumResults; ++I) {
2079 if (Results[I].Kind != Result::RK_Declaration)
2080 continue;
2081
2082 unsigned IDNS
2083 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2084
2085 bool Hiding = false;
2086 if (OnlyTagNames)
2087 Hiding = (IDNS & Decl::IDNS_Tag);
2088 else {
2089 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00002090 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2091 Decl::IDNS_NonMemberOperator);
Douglas Gregor5f808c22010-08-16 21:18:39 +00002092 if (Ctx.getLangOptions().CPlusPlus)
2093 HiddenIDNS |= Decl::IDNS_Tag;
2094 Hiding = (IDNS & HiddenIDNS);
2095 }
2096
2097 if (!Hiding)
2098 continue;
2099
2100 DeclarationName Name = Results[I].Declaration->getDeclName();
2101 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2102 HiddenNames.insert(Identifier->getName());
2103 else
2104 HiddenNames.insert(Name.getAsString());
2105 }
2106}
2107
2108
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002109void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2110 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00002111 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002112 unsigned NumResults) {
2113 // Merge the results we were given with the results we cached.
2114 bool AddedResult = false;
Douglas Gregor5f808c22010-08-16 21:18:39 +00002115 unsigned InContexts
Douglas Gregor52779fb2010-09-23 23:01:17 +00002116 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
NAKAMURA Takumi01a429a2011-08-17 01:46:16 +00002117 : (1ULL << (Context.getKind() - 1)));
Douglas Gregor5f808c22010-08-16 21:18:39 +00002118 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00002119 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00002120 typedef CodeCompletionResult Result;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002121 SmallVector<Result, 8> AllResults;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002122 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00002123 C = AST.cached_completion_begin(),
2124 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002125 C != CEnd; ++C) {
2126 // If the context we are in matches any of the contexts we are
2127 // interested in, we'll add this result.
2128 if ((C->ShowInContexts & InContexts) == 0)
2129 continue;
2130
2131 // If we haven't added any results previously, do so now.
2132 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00002133 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2134 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002135 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2136 AddedResult = true;
2137 }
2138
Douglas Gregor5f808c22010-08-16 21:18:39 +00002139 // Determine whether this global completion result is hidden by a local
2140 // completion result. If so, skip it.
2141 if (C->Kind != CXCursor_MacroDefinition &&
2142 HiddenNames.count(C->Completion->getTypedText()))
2143 continue;
2144
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002145 // Adjust priority based on similar type classes.
2146 unsigned Priority = C->Priority;
Douglas Gregor4125c372010-08-25 18:03:13 +00002147 CXCursorKind CursorKind = C->Kind;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002148 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002149 if (!Context.getPreferredType().isNull()) {
2150 if (C->Kind == CXCursor_MacroDefinition) {
2151 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00002152 S.getLangOptions(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002153 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002154 } else if (C->Type) {
2155 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00002156 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002157 Context.getPreferredType().getUnqualifiedType());
2158 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2159 if (ExpectedSTC == C->TypeClass) {
2160 // We know this type is similar; check for an exact match.
2161 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00002162 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002163 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00002164 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002165 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2166 Priority /= CCF_ExactTypeMatch;
2167 else
2168 Priority /= CCF_SimilarTypeMatch;
2169 }
2170 }
2171 }
2172
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002173 // Adjust the completion string, if required.
2174 if (C->Kind == CXCursor_MacroDefinition &&
2175 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2176 // Create a new code-completion string that just contains the
2177 // macro name, without its arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00002178 CodeCompletionBuilder Builder(getAllocator(), CCP_CodePattern,
2179 C->Availability);
2180 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00002181 CursorKind = CXCursor_NotImplemented;
2182 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00002183 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00002184 }
2185
Douglas Gregor4125c372010-08-25 18:03:13 +00002186 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00002187 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002188 }
2189
2190 // If we did not add any cached completion results, just forward the
2191 // results we were given to the next consumer.
2192 if (!AddedResult) {
2193 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2194 return;
2195 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00002196
Douglas Gregor697ca6d2010-08-16 20:01:48 +00002197 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2198 AllResults.size());
2199}
2200
2201
2202
Chris Lattner5f9e2722011-07-23 10:55:15 +00002203void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002204 RemappedFile *RemappedFiles,
2205 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00002206 bool IncludeMacros,
2207 bool IncludeCodePatterns,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002208 CodeCompleteConsumer &Consumer,
David Blaikied6471f72011-09-25 23:23:43 +00002209 DiagnosticsEngine &Diag, LangOptions &LangOpts,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002210 SourceManager &SourceMgr, FileManager &FileMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002211 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2212 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002213 if (!Invocation)
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002214 return;
2215
Douglas Gregor213f18b2010-10-28 15:44:59 +00002216 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00002217 CompletionTimer.setOutput("Code completion @ " + File + ":" +
Chris Lattner5f9e2722011-07-23 10:55:15 +00002218 Twine(Line) + ":" + Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00002219
Ted Kremenek4f327862011-03-21 18:40:17 +00002220 llvm::IntrusiveRefCntPtr<CompilerInvocation>
2221 CCInvocation(new CompilerInvocation(*Invocation));
2222
2223 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2224 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002225
Douglas Gregor87c08a52010-08-13 22:48:40 +00002226 FrontendOpts.ShowMacrosInCodeCompletion
2227 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorcee235c2010-08-05 09:09:23 +00002228 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor8071e422010-08-15 06:18:01 +00002229 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
2230 = CachedCompletionResults.empty();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002231 FrontendOpts.CodeCompletionAt.FileName = File;
2232 FrontendOpts.CodeCompletionAt.Line = Line;
2233 FrontendOpts.CodeCompletionAt.Column = Column;
2234
2235 // Set the language options appropriately.
Ted Kremenek4f327862011-03-21 18:40:17 +00002236 LangOpts = CCInvocation->getLangOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002237
Ted Kremenek03201fb2011-03-21 18:40:07 +00002238 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
2239
2240 // Recover resources if we crash before exiting this method.
Ted Kremenek25a11e12011-03-22 01:15:24 +00002241 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2242 CICleanup(Clang.get());
Ted Kremenek03201fb2011-03-21 18:40:07 +00002243
Ted Kremenek4f327862011-03-21 18:40:17 +00002244 Clang->setInvocation(&*CCInvocation);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002245 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002246
2247 // Set up diagnostics, capturing any diagnostics produced.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002248 Clang->setDiagnostics(&Diag);
Ted Kremenek4f327862011-03-21 18:40:17 +00002249 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002250 CaptureDroppedDiagnostics Capture(true,
Ted Kremenek03201fb2011-03-21 18:40:07 +00002251 Clang->getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002252 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002253
2254 // Create the target instance.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002255 Clang->getTargetOpts().Features = TargetFeatures;
2256 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2257 Clang->getTargetOpts()));
2258 if (!Clang->hasTarget()) {
Ted Kremenek4f327862011-03-21 18:40:17 +00002259 Clang->setInvocation(0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002260 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002261 }
2262
2263 // Inform the target of the language options.
2264 //
2265 // FIXME: We shouldn't need to do this, the target should be immutable once
2266 // created. This complexity should be lifted elsewhere.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002267 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002268
Ted Kremenek03201fb2011-03-21 18:40:07 +00002269 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002270 "Invocation must have exactly one source file!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00002271 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002272 "FIXME: AST inputs not yet supported here!");
Ted Kremenek03201fb2011-03-21 18:40:07 +00002273 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002274 "IR inputs not support here!");
2275
2276
2277 // Use the source and file managers that we were given.
Ted Kremenek03201fb2011-03-21 18:40:07 +00002278 Clang->setFileManager(&FileMgr);
2279 Clang->setSourceManager(&SourceMgr);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002280
2281 // Remap files.
2282 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00002283 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00002284 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Argyrios Kyrtzidisb1c86492011-03-05 01:03:53 +00002285 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2286 if (const llvm::MemoryBuffer *
2287 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2288 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2289 OwnedBuffers.push_back(memBuf);
2290 } else {
2291 const char *fname = fileOrBuf.get<const char *>();
2292 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2293 }
Douglas Gregor2283d792010-08-20 00:59:43 +00002294 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002295
Douglas Gregor87c08a52010-08-13 22:48:40 +00002296 // Use the code completion consumer we were given, but adding any cached
2297 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00002298 AugmentedCodeCompleteConsumer *AugmentedConsumer
2299 = new AugmentedCodeCompleteConsumer(*this, Consumer,
2300 FrontendOpts.ShowMacrosInCodeCompletion,
2301 FrontendOpts.ShowCodePatternsInCodeCompletion,
2302 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002303 Clang->setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002304
Douglas Gregordf95a132010-08-09 20:45:32 +00002305 // If we have a precompiled preamble, try to use it. We only allow
2306 // the use of the precompiled preamble if we're if the completion
2307 // point is within the main file, after the end of the precompiled
2308 // preamble.
2309 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Ted Kremenek1872b312011-10-27 17:55:18 +00002310 if (!getPreambleFile(this).empty()) {
Douglas Gregordf95a132010-08-09 20:45:32 +00002311 using llvm::sys::FileStatus;
2312 llvm::sys::PathWithStatus CompleteFilePath(File);
2313 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2314 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2315 if (const FileStatus *MainStatus = MainPath.getFileStatus())
Argyrios Kyrtzidisc8c97a02011-09-04 03:32:04 +00002316 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2317 Line > 1)
Douglas Gregor2283d792010-08-20 00:59:43 +00002318 OverrideMainBuffer
Ted Kremenek4f327862011-03-21 18:40:17 +00002319 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
Douglas Gregorc9c29a82010-08-25 18:04:15 +00002320 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00002321 }
2322
2323 // If the main file has been overridden due to the use of a preamble,
2324 // make that override happen and introduce the preamble.
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00002325 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00002326 StoredDiagnostics.insert(StoredDiagnostics.end(),
Argyrios Kyrtzidis3e9d3262011-10-24 17:25:20 +00002327 stored_diag_begin(),
2328 stored_diag_afterDriver_begin());
Douglas Gregordf95a132010-08-09 20:45:32 +00002329 if (OverrideMainBuffer) {
2330 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2331 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2332 PreprocessorOpts.PrecompiledPreambleBytes.second
2333 = PreambleEndsAtStartOfLine;
Ted Kremenek1872b312011-10-27 17:55:18 +00002334 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
Douglas Gregordf95a132010-08-09 20:45:32 +00002335 PreprocessorOpts.DisablePCHValidation = true;
2336
Douglas Gregor2283d792010-08-20 00:59:43 +00002337 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00002338 } else {
2339 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2340 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00002341 }
2342
Douglas Gregordca8ee82011-05-06 16:33:08 +00002343 // Disable the preprocessing record
2344 PreprocessorOpts.DetailedRecord = false;
2345
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002346 llvm::OwningPtr<SyntaxOnlyAction> Act;
2347 Act.reset(new SyntaxOnlyAction);
Ted Kremenek03201fb2011-03-21 18:40:07 +00002348 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
2349 Clang->getFrontendOpts().Inputs[0].first)) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002350 if (OverrideMainBuffer) {
Ted Kremenek1872b312011-10-27 17:55:18 +00002351 std::string ModName = getPreambleFile(this);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002352 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
2353 getSourceManager(), PreambleDiagnostics,
2354 StoredDiagnostics);
2355 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002356 Act->Execute();
2357 Act->EndSourceFile();
2358 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002359}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002360
Chris Lattner5f9e2722011-07-23 10:55:15 +00002361CXSaveError ASTUnit::Save(StringRef File) {
Douglas Gregor85bea972011-07-06 17:40:26 +00002362 if (getDiagnostics().hasUnrecoverableErrorOccurred())
Douglas Gregor39c411f2011-07-06 16:43:36 +00002363 return CXSaveError_TranslationErrors;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002364
2365 // Write to a temporary file and later rename it to the actual file, to avoid
2366 // possible race conditions.
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002367 llvm::SmallString<128> TempPath;
2368 TempPath = File;
2369 TempPath += "-%%%%%%%%";
2370 int fd;
2371 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2372 /*makeAbsolute=*/false))
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002373 return CXSaveError_Unknown;
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002374
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002375 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2376 // unconditionally create a stat cache when we parse the file?
Argyrios Kyrtzidis7e909852011-07-28 00:45:10 +00002377 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002378
2379 serialize(Out);
2380 Out.close();
Argyrios Kyrtzidis9cca68d2011-07-21 18:44:49 +00002381 if (Out.has_error())
2382 return CXSaveError_Unknown;
2383
2384 if (llvm::error_code ec = llvm::sys::fs::rename(TempPath.str(), File)) {
2385 bool exists;
2386 llvm::sys::fs::remove(TempPath.str(), exists);
2387 return CXSaveError_Unknown;
2388 }
2389
2390 return CXSaveError_None;
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002391}
2392
Chris Lattner5f9e2722011-07-23 10:55:15 +00002393bool ASTUnit::serialize(raw_ostream &OS) {
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002394 if (getDiagnostics().hasErrorOccurred())
2395 return true;
2396
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002397 std::vector<unsigned char> Buffer;
2398 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002399 ASTWriter Writer(Stream);
Douglas Gregor7143aab2011-09-01 17:04:32 +00002400 // FIXME: Handle modules
2401 Writer.WriteAST(getSema(), 0, std::string(), /*IsModule=*/false, "");
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002402
2403 // Write the generated bitstream to "Out".
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002404 if (!Buffer.empty())
Argyrios Kyrtzidisb0f4b9a2011-03-09 17:21:42 +00002405 OS.write((char *)&Buffer.front(), Buffer.size());
2406
2407 return false;
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002408}
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002409
2410typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2411
2412static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2413 unsigned Raw = L.getRawEncoding();
2414 const unsigned MacroBit = 1U << 31;
2415 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2416 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2417}
2418
2419void ASTUnit::TranslateStoredDiagnostics(
2420 ASTReader *MMan,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002421 StringRef ModName,
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002422 SourceManager &SrcMgr,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002423 const SmallVectorImpl<StoredDiagnostic> &Diags,
2424 SmallVectorImpl<StoredDiagnostic> &Out) {
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002425 // The stored diagnostic has the old source manager in it; update
2426 // the locations to refer into the new source manager. We also need to remap
2427 // all the locations to the new view. This includes the diag location, any
2428 // associated source ranges, and the source ranges of associated fix-its.
2429 // FIXME: There should be a cleaner way to do this.
2430
Chris Lattner5f9e2722011-07-23 10:55:15 +00002431 SmallVector<StoredDiagnostic, 4> Result;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002432 Result.reserve(Diags.size());
2433 assert(MMan && "Don't have a module manager");
Jonathan D. Turner48d2c3f2011-07-26 18:21:30 +00002434 serialization::Module *Mod = MMan->ModuleMgr.lookup(ModName);
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002435 assert(Mod && "Don't have preamble module");
2436 SLocRemap &Remap = Mod->SLocRemap;
2437 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2438 // Rebuild the StoredDiagnostic.
2439 const StoredDiagnostic &SD = Diags[I];
2440 SourceLocation L = SD.getLocation();
2441 TranslateSLoc(L, Remap);
2442 FullSourceLoc Loc(L, SrcMgr);
2443
Chris Lattner5f9e2722011-07-23 10:55:15 +00002444 SmallVector<CharSourceRange, 4> Ranges;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002445 Ranges.reserve(SD.range_size());
2446 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2447 E = SD.range_end();
2448 I != E; ++I) {
2449 SourceLocation BL = I->getBegin();
2450 TranslateSLoc(BL, Remap);
2451 SourceLocation EL = I->getEnd();
2452 TranslateSLoc(EL, Remap);
2453 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2454 }
2455
Chris Lattner5f9e2722011-07-23 10:55:15 +00002456 SmallVector<FixItHint, 2> FixIts;
Douglas Gregorf62d43d2011-07-19 16:10:42 +00002457 FixIts.reserve(SD.fixit_size());
2458 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2459 E = SD.fixit_end();
2460 I != E; ++I) {
2461 FixIts.push_back(FixItHint());
2462 FixItHint &FH = FixIts.back();
2463 FH.CodeToInsert = I->CodeToInsert;
2464 SourceLocation BL = I->RemoveRange.getBegin();
2465 TranslateSLoc(BL, Remap);
2466 SourceLocation EL = I->RemoveRange.getEnd();
2467 TranslateSLoc(EL, Remap);
2468 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2469 I->RemoveRange.isTokenRange());
2470 }
2471
2472 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2473 SD.getMessage(), Loc, Ranges, FixIts));
2474 }
2475 Result.swap(Out);
2476}
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002477
Argyrios Kyrtzidis332cb9b2011-10-31 07:19:59 +00002478static inline bool compLocDecl(std::pair<unsigned, Decl *> L,
2479 std::pair<unsigned, Decl *> R) {
2480 return L.first < R.first;
2481}
2482
2483void ASTUnit::addFileLevelDecl(Decl *D) {
2484 assert(D);
2485 assert(!D->isFromASTFile() && "This is only for local decl");
2486
2487 SourceManager &SM = *SourceMgr;
2488 SourceLocation Loc = D->getLocation();
2489 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2490 return;
2491
2492 // We only keep track of the file-level declarations of each file.
2493 if (!D->getLexicalDeclContext()->isFileContext())
2494 return;
2495
2496 SourceLocation FileLoc = SM.getFileLoc(Loc);
2497 assert(SM.isLocalSourceLocation(FileLoc));
2498 FileID FID;
2499 unsigned Offset;
2500 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2501 if (FID.isInvalid())
2502 return;
2503
2504 LocDeclsTy *&Decls = FileDecls[FID];
2505 if (!Decls)
2506 Decls = new LocDeclsTy();
2507
2508 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2509
2510 if (Decls->empty() || Decls->back().first <= Offset) {
2511 Decls->push_back(LocDecl);
2512 return;
2513 }
2514
2515 LocDeclsTy::iterator
2516 I = std::upper_bound(Decls->begin(), Decls->end(), LocDecl, compLocDecl);
2517
2518 Decls->insert(I, LocDecl);
2519}
2520
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002521SourceLocation ASTUnit::getLocation(const FileEntry *File,
2522 unsigned Line, unsigned Col) const {
2523 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002524 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002525 return SM.getMacroArgExpandedLocation(Loc);
2526}
2527
2528SourceLocation ASTUnit::getLocation(const FileEntry *File,
2529 unsigned Offset) const {
2530 const SourceManager &SM = getSourceManager();
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002531 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002532 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2533}
2534
Argyrios Kyrtzidisee0f84f2011-09-26 08:01:41 +00002535/// \brief If \arg Loc is a loaded location from the preamble, returns
2536/// the corresponding local location of the main file, otherwise it returns
2537/// \arg Loc.
2538SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2539 FileID PreambleID;
2540 if (SourceMgr)
2541 PreambleID = SourceMgr->getPreambleFileID();
2542
2543 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2544 return Loc;
2545
2546 unsigned Offs;
2547 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2548 SourceLocation FileLoc
2549 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2550 return FileLoc.getLocWithOffset(Offs);
2551 }
2552
2553 return Loc;
2554}
2555
2556/// \brief If \arg Loc is a local location of the main file but inside the
2557/// preamble chunk, returns the corresponding loaded location from the
2558/// preamble, otherwise it returns \arg Loc.
2559SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2560 FileID PreambleID;
2561 if (SourceMgr)
2562 PreambleID = SourceMgr->getPreambleFileID();
2563
2564 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2565 return Loc;
2566
2567 unsigned Offs;
2568 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2569 Offs < Preamble.size()) {
2570 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2571 return FileLoc.getLocWithOffset(Offs);
2572 }
2573
2574 return Loc;
2575}
2576
Argyrios Kyrtzidisf226ff92011-10-25 00:29:50 +00002577bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2578 FileID FID;
2579 if (SourceMgr)
2580 FID = SourceMgr->getPreambleFileID();
2581
2582 if (Loc.isInvalid() || FID.isInvalid())
2583 return false;
2584
2585 return SourceMgr->isInFileID(Loc, FID);
2586}
2587
2588bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2589 FileID FID;
2590 if (SourceMgr)
2591 FID = SourceMgr->getMainFileID();
2592
2593 if (Loc.isInvalid() || FID.isInvalid())
2594 return false;
2595
2596 return SourceMgr->isInFileID(Loc, FID);
2597}
2598
2599SourceLocation ASTUnit::getEndOfPreambleFileID() {
2600 FileID FID;
2601 if (SourceMgr)
2602 FID = SourceMgr->getPreambleFileID();
2603
2604 if (FID.isInvalid())
2605 return SourceLocation();
2606
2607 return SourceMgr->getLocForEndOfFile(FID);
2608}
2609
2610SourceLocation ASTUnit::getStartOfMainFileID() {
2611 FileID FID;
2612 if (SourceMgr)
2613 FID = SourceMgr->getMainFileID();
2614
2615 if (FID.isInvalid())
2616 return SourceLocation();
2617
2618 return SourceMgr->getLocForStartOfFile(FID);
2619}
2620
Argyrios Kyrtzidis507097e2011-09-19 20:40:35 +00002621void ASTUnit::PreambleData::countLines() const {
2622 NumLines = 0;
2623 if (empty())
2624 return;
2625
2626 for (std::vector<char>::const_iterator
2627 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2628 if (*I == '\n')
2629 ++NumLines;
2630 }
2631 if (Buffer.back() != '\n')
2632 ++NumLines;
2633}
Argyrios Kyrtzidisa696ece2011-10-10 21:57:12 +00002634
2635#ifndef NDEBUG
2636ASTUnit::ConcurrencyState::ConcurrencyState() {
2637 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2638}
2639
2640ASTUnit::ConcurrencyState::~ConcurrencyState() {
2641 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2642}
2643
2644void ASTUnit::ConcurrencyState::start() {
2645 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2646 assert(acquired && "Concurrent access to ASTUnit!");
2647}
2648
2649void ASTUnit::ConcurrencyState::finish() {
2650 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2651}
2652
2653#else // NDEBUG
2654
2655ASTUnit::ConcurrencyState::ConcurrencyState() {}
2656ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2657void ASTUnit::ConcurrencyState::start() {}
2658void ASTUnit::ConcurrencyState::finish() {}
2659
2660#endif