blob: 00902e810c272ca39fae7874b3980a4eb042126c [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"
23#include "clang/Driver/Tool.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000024#include "clang/Frontend/CompilerInstance.h"
25#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000026#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000027#include "clang/Frontend/FrontendOptions.h"
Douglas Gregor32be4a52010-10-11 21:37:58 +000028#include "clang/Frontend/Utils.h"
Sebastian Redl6ab7cd82010-08-18 23:57:17 +000029#include "clang/Serialization/ASTReader.h"
Douglas Gregor89d99802010-11-30 06:16:57 +000030#include "clang/Serialization/ASTSerializationListener.h"
Sebastian Redl7faa2ec2010-08-18 23:56:37 +000031#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000032#include "clang/Lex/HeaderSearch.h"
33#include "clang/Lex/Preprocessor.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000034#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000035#include "clang/Basic/TargetInfo.h"
36#include "clang/Basic/Diagnostic.h"
Douglas Gregor349d38c2010-08-16 23:08:34 +000037#include "llvm/ADT/StringSet.h"
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +000038#include "llvm/Support/Atomic.h"
Douglas Gregor4db64a42010-01-23 00:14:00 +000039#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000040#include "llvm/Support/Host.h"
41#include "llvm/Support/Path.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000042#include "llvm/Support/raw_ostream.h"
Douglas Gregor385103b2010-07-30 20:58:08 +000043#include "llvm/Support/Timer.h"
Douglas Gregor44c181a2010-07-23 00:33:23 +000044#include <cstdlib>
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000045#include <cstdio>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000046#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000047using namespace clang;
48
Douglas Gregor213f18b2010-10-28 15:44:59 +000049using llvm::TimeRecord;
50
51namespace {
52 class SimpleTimer {
53 bool WantTiming;
54 TimeRecord Start;
55 std::string Output;
56
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000057 public:
Douglas Gregor9dba61a2010-11-01 13:48:43 +000058 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000059 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000060 Start = TimeRecord::getCurrentTime();
Douglas Gregor213f18b2010-10-28 15:44:59 +000061 }
62
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000063 void setOutput(const llvm::Twine &Output) {
Douglas Gregor213f18b2010-10-28 15:44:59 +000064 if (WantTiming)
Benjamin Krameredfb7ec2010-11-09 20:00:56 +000065 this->Output = Output.str();
Douglas Gregor213f18b2010-10-28 15:44:59 +000066 }
67
Douglas Gregor213f18b2010-10-28 15:44:59 +000068 ~SimpleTimer() {
69 if (WantTiming) {
70 TimeRecord Elapsed = TimeRecord::getCurrentTime();
71 Elapsed -= Start;
72 llvm::errs() << Output << ':';
73 Elapsed.print(Elapsed, llvm::errs());
74 llvm::errs() << '\n';
75 }
76 }
77 };
78}
79
Douglas Gregoreababfb2010-08-04 05:53:38 +000080/// \brief After failing to build a precompiled preamble (due to
81/// errors in the source that occurs in the preamble), the number of
82/// reparses during which we'll skip even trying to precompile the
83/// preamble.
84const unsigned DefaultPreambleRebuildInterval = 5;
85
Douglas Gregore3c60a72010-11-17 00:13:31 +000086/// \brief Tracks the number of ASTUnit objects that are currently active.
87///
88/// Used for debugging purposes only.
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +000089static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregore3c60a72010-11-17 00:13:31 +000090
Douglas Gregor3687e9d2010-04-05 21:10:19 +000091ASTUnit::ASTUnit(bool _MainFileIsAST)
Douglas Gregorabc563f2010-07-19 21:46:24 +000092 : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
Douglas Gregor213f18b2010-10-28 15:44:59 +000093 CompleteTranslationUnit(true), WantTiming(getenv("LIBCLANG_TIMING")),
94 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor4cd912a2010-10-12 00:50:20 +000095 ConcurrencyCheckValue(CheckUnlocked),
Douglas Gregor671947b2010-08-19 01:33:06 +000096 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +000097 ShouldCacheCodeCompletionResults(false),
98 NumTopLevelDeclsAtLastCompletionCache(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +000099 CacheCodeCompletionCoolDown(0),
100 UnsafeToFree(false) {
Douglas Gregore3c60a72010-11-17 00:13:31 +0000101 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000102 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000103 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
104 }
Douglas Gregor385103b2010-07-30 20:58:08 +0000105}
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000106
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000107ASTUnit::~ASTUnit() {
Douglas Gregorbdf60622010-03-05 21:16:25 +0000108 ConcurrencyCheckValue = CheckLocked;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000109 CleanTemporaryFiles();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000110 if (!PreambleFile.empty())
Douglas Gregor385103b2010-07-30 20:58:08 +0000111 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000112
113 // Free the buffers associated with remapped files. We are required to
114 // perform this operation here because we explicitly request that the
115 // compiler instance *not* free these buffers for each invocation of the
116 // parser.
117 if (Invocation.get()) {
118 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
119 for (PreprocessorOptions::remapped_file_buffer_iterator
120 FB = PPOpts.remapped_file_buffer_begin(),
121 FBEnd = PPOpts.remapped_file_buffer_end();
122 FB != FBEnd;
123 ++FB)
124 delete FB->second;
125 }
Douglas Gregor28233422010-07-27 14:52:07 +0000126
127 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +0000128 delete PreambleBuffer;
129
Douglas Gregor213f18b2010-10-28 15:44:59 +0000130 ClearCachedCompletionResults();
Douglas Gregore3c60a72010-11-17 00:13:31 +0000131
132 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor1fd9e0d2010-12-07 00:05:48 +0000133 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregore3c60a72010-11-17 00:13:31 +0000134 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
135 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000136}
137
138void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor313e26c2010-02-18 23:35:40 +0000139 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
140 TemporaryFiles[I].eraseFromDisk();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000141 TemporaryFiles.clear();
Steve Naroffe19944c2009-10-15 22:23:48 +0000142}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000143
Douglas Gregor8071e422010-08-15 06:18:01 +0000144/// \brief Determine the set of code-completion contexts in which this
145/// declaration should be shown.
146static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000147 const LangOptions &LangOpts,
148 bool &IsNestedNameSpecifier) {
149 IsNestedNameSpecifier = false;
150
Douglas Gregor8071e422010-08-15 06:18:01 +0000151 if (isa<UsingShadowDecl>(ND))
152 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
153 if (!ND)
154 return 0;
155
156 unsigned Contexts = 0;
157 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
158 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
159 // Types can appear in these contexts.
160 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
161 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
162 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
163 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
164 | (1 << (CodeCompletionContext::CCC_Statement - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000165 | (1 << (CodeCompletionContext::CCC_Type - 1))
166 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000167
168 // In C++, types can appear in expressions contexts (for functional casts).
169 if (LangOpts.CPlusPlus)
170 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
171
172 // In Objective-C, message sends can send interfaces. In Objective-C++,
173 // all types are available due to functional casts.
174 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
175 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
176
177 // Deal with tag names.
178 if (isa<EnumDecl>(ND)) {
179 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
180
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000181 // Part of the nested-name-specifier in C++0x.
Douglas Gregor8071e422010-08-15 06:18:01 +0000182 if (LangOpts.CPlusPlus0x)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000183 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000184 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
185 if (Record->isUnion())
186 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
187 else
188 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
189
Douglas Gregor8071e422010-08-15 06:18:01 +0000190 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000191 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000192 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000193 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000194 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
195 // Values can appear in these contexts.
196 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
197 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000198 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor8071e422010-08-15 06:18:01 +0000199 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
200 } else if (isa<ObjCProtocolDecl>(ND)) {
201 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
202 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000203 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000204
205 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000206 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000207 }
208
209 return Contexts;
210}
211
Douglas Gregor87c08a52010-08-13 22:48:40 +0000212void ASTUnit::CacheCodeCompletionResults() {
213 if (!TheSema)
214 return;
215
Douglas Gregor213f18b2010-10-28 15:44:59 +0000216 SimpleTimer Timer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +0000217 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000218
219 // Clear out the previous results.
220 ClearCachedCompletionResults();
221
222 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000223 typedef CodeCompletionResult Result;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000224 llvm::SmallVector<Result, 8> Results;
Douglas Gregor218937c2011-02-01 19:23:04 +0000225 TheSema->GatherGlobalCodeCompletions(CachedCompletionAllocator, Results);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000226
227 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000228 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
229
Douglas Gregor87c08a52010-08-13 22:48:40 +0000230 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
231 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000232 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000233 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000234 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000235 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
236 CachedCompletionAllocator);
Douglas Gregor8071e422010-08-15 06:18:01 +0000237 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000238 Ctx->getLangOptions(),
239 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000240 CachedResult.Priority = Results[I].Priority;
241 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000242 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000243
Douglas Gregorf5586f62010-08-16 18:08:11 +0000244 // Keep track of the type of this completion in an ASTContext-agnostic
245 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000246 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000247 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000248 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000249 CachedResult.Type = 0;
250 } else {
251 CanQualType CanUsageType
252 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
253 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
254
255 // Determine whether we have already seen this type. If so, we save
256 // ourselves the work of formatting the type string by using the
257 // temporary, CanQualType-based hash table to find the associated value.
258 unsigned &TypeValue = CompletionTypes[CanUsageType];
259 if (TypeValue == 0) {
260 TypeValue = CompletionTypes.size();
261 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
262 = TypeValue;
263 }
264
265 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000266 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000267
Douglas Gregor8071e422010-08-15 06:18:01 +0000268 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000269
270 /// Handle nested-name-specifiers in C++.
271 if (TheSema->Context.getLangOptions().CPlusPlus &&
272 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
273 // The contexts in which a nested-name-specifier can appear in C++.
274 unsigned NNSContexts
275 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
276 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
277 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
278 | (1 << (CodeCompletionContext::CCC_Statement - 1))
279 | (1 << (CodeCompletionContext::CCC_Expression - 1))
280 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
281 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
282 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
283 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000284 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000285 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
286 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000287
288 if (isa<NamespaceDecl>(Results[I].Declaration) ||
289 isa<NamespaceAliasDecl>(Results[I].Declaration))
290 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
291
292 if (unsigned RemainingContexts
293 = NNSContexts & ~CachedResult.ShowInContexts) {
294 // If there any contexts where this completion can be a
295 // nested-name-specifier but isn't already an option, create a
296 // nested-name-specifier completion.
297 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregor218937c2011-02-01 19:23:04 +0000298 CachedResult.Completion
299 = Results[I].CreateCodeCompletionString(*TheSema,
300 CachedCompletionAllocator);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000301 CachedResult.ShowInContexts = RemainingContexts;
302 CachedResult.Priority = CCP_NestedNameSpecifier;
303 CachedResult.TypeClass = STC_Void;
304 CachedResult.Type = 0;
305 CachedCompletionResults.push_back(CachedResult);
306 }
307 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000308 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000309 }
310
Douglas Gregor87c08a52010-08-13 22:48:40 +0000311 case Result::RK_Keyword:
312 case Result::RK_Pattern:
313 // Ignore keywords and patterns; we don't care, since they are so
314 // easily regenerated.
315 break;
316
317 case Result::RK_Macro: {
318 CachedCodeCompletionResult CachedResult;
Douglas Gregor218937c2011-02-01 19:23:04 +0000319 CachedResult.Completion
320 = Results[I].CreateCodeCompletionString(*TheSema,
321 CachedCompletionAllocator);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000322 CachedResult.ShowInContexts
323 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
324 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
325 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
326 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
327 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
328 | (1 << (CodeCompletionContext::CCC_Statement - 1))
329 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000330 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorf29c5232010-08-24 22:20:20 +0000331 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000332 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
333 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
334
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000335
Douglas Gregor87c08a52010-08-13 22:48:40 +0000336 CachedResult.Priority = Results[I].Priority;
337 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000338 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000339 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000340 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000341 CachedCompletionResults.push_back(CachedResult);
342 break;
343 }
344 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000345 }
346
Douglas Gregor727d93e2010-08-17 00:40:40 +0000347 // Make a note of the state when we performed this caching.
348 NumTopLevelDeclsAtLastCompletionCache = top_level_size();
Douglas Gregor87c08a52010-08-13 22:48:40 +0000349}
350
351void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregor87c08a52010-08-13 22:48:40 +0000352 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000353 CachedCompletionTypes.clear();
Douglas Gregor218937c2011-02-01 19:23:04 +0000354 CachedCompletionAllocator.Reset();
Douglas Gregor87c08a52010-08-13 22:48:40 +0000355}
356
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000357namespace {
358
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000359/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000360/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000361class ASTInfoCollector : public ASTReaderListener {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000362 LangOptions &LangOpt;
363 HeaderSearch &HSI;
364 std::string &TargetTriple;
365 std::string &Predefines;
366 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000367
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000368 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000370public:
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000371 ASTInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000372 std::string &TargetTriple, std::string &Predefines,
373 unsigned &Counter)
374 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
375 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000377 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
378 LangOpt = LangOpts;
379 return false;
380 }
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000382 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000383 TargetTriple = Triple;
384 return false;
385 }
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000387 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000388 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000389 std::string &SuggestedPredefines) {
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000390 Predefines = Buffers[0].Data;
391 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
392 Predefines += Buffers[I].Data;
393 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000394 return false;
395 }
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000397 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000398 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
399 }
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000401 virtual void ReadCounter(unsigned Value) {
402 Counter = Value;
403 }
404};
405
Douglas Gregora88084b2010-02-18 18:08:43 +0000406class StoredDiagnosticClient : public DiagnosticClient {
407 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
408
409public:
410 explicit StoredDiagnosticClient(
411 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
412 : StoredDiags(StoredDiags) { }
413
414 virtual void HandleDiagnostic(Diagnostic::Level Level,
415 const DiagnosticInfo &Info);
416};
417
418/// \brief RAII object that optionally captures diagnostics, if
419/// there is no diagnostic client to capture them already.
420class CaptureDroppedDiagnostics {
421 Diagnostic &Diags;
422 StoredDiagnosticClient Client;
423 DiagnosticClient *PreviousClient;
424
425public:
426 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000427 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000428 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000429 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000430 if (RequestCapture || Diags.getClient() == 0) {
431 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000432 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000433 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000434 }
435
436 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000437 if (Diags.getClient() == &Client) {
438 Diags.takeClient();
439 Diags.setClient(PreviousClient);
440 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000441 }
442};
443
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000444} // anonymous namespace
445
Douglas Gregora88084b2010-02-18 18:08:43 +0000446void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
447 const DiagnosticInfo &Info) {
Argyrios Kyrtzidisf2224d82010-11-18 20:06:46 +0000448 // Default implementation (Warnings/errors count).
449 DiagnosticClient::HandleDiagnostic(Level, Info);
450
Douglas Gregora88084b2010-02-18 18:08:43 +0000451 StoredDiags.push_back(StoredDiagnostic(Level, Info));
452}
453
Steve Naroff77accc12009-09-03 18:19:54 +0000454const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000455 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000456}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000457
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000458const std::string &ASTUnit::getASTFileName() {
459 assert(isMainFileAST() && "Not an ASTUnit from an AST file!");
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000460 return static_cast<ASTReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroffe19944c2009-10-15 22:23:48 +0000461}
462
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000463llvm::MemoryBuffer *ASTUnit::getBufferForFile(llvm::StringRef Filename,
Chris Lattner75dfb652010-11-23 09:19:42 +0000464 std::string *ErrorStr) {
Chris Lattner39b49bc2010-11-23 08:35:12 +0000465 assert(FileMgr);
Chris Lattner75dfb652010-11-23 09:19:42 +0000466 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000467}
468
Douglas Gregore47be3e2010-11-11 00:39:14 +0000469/// \brief Configure the diagnostics object for use with ASTUnit.
470void ASTUnit::ConfigureDiags(llvm::IntrusiveRefCntPtr<Diagnostic> &Diags,
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000471 const char **ArgBegin, const char **ArgEnd,
Douglas Gregore47be3e2010-11-11 00:39:14 +0000472 ASTUnit &AST, bool CaptureDiagnostics) {
473 if (!Diags.getPtr()) {
474 // No diagnostics engine was provided, so create our own diagnostics object
475 // with the default options.
476 DiagnosticOptions DiagOpts;
477 DiagnosticClient *Client = 0;
478 if (CaptureDiagnostics)
479 Client = new StoredDiagnosticClient(AST.StoredDiagnostics);
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000480 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd- ArgBegin,
481 ArgBegin, Client);
Douglas Gregore47be3e2010-11-11 00:39:14 +0000482 } else if (CaptureDiagnostics) {
483 Diags->setClient(new StoredDiagnosticClient(AST.StoredDiagnostics));
484 }
485}
486
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000487ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Douglas Gregor28019772010-04-05 23:52:57 +0000488 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000489 const FileSystemOptions &FileSystemOpts,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000490 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000491 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000492 unsigned NumRemappedFiles,
493 bool CaptureDiagnostics) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000494 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
Douglas Gregor0b53cf82011-01-19 01:02:47 +0000495 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000496
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000497 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +0000498 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor28019772010-04-05 23:52:57 +0000499 AST->Diagnostics = Diags;
Chris Lattner7ad97ff2010-11-23 07:51:02 +0000500 AST->FileMgr.reset(new FileManager(FileSystemOpts));
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000501 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics(),
Chris Lattner39b49bc2010-11-23 08:35:12 +0000502 AST->getFileManager()));
503 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000504
Douglas Gregor4db64a42010-01-23 00:14:00 +0000505 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
506 // Create the file entry for the file that we're mapping from.
507 const FileEntry *FromFile
508 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
509 RemappedFiles[I].second->getBufferSize(),
Chris Lattner39b49bc2010-11-23 08:35:12 +0000510 0);
Douglas Gregor4db64a42010-01-23 00:14:00 +0000511 if (!FromFile) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000512 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregor4db64a42010-01-23 00:14:00 +0000513 << RemappedFiles[I].first;
Douglas Gregorc8dfe5e2010-02-27 01:32:48 +0000514 delete RemappedFiles[I].second;
Douglas Gregor4db64a42010-01-23 00:14:00 +0000515 continue;
516 }
517
518 // Override the contents of the "from" file with the contents of
519 // the "to" file.
520 AST->getSourceManager().overrideFileContents(FromFile,
521 RemappedFiles[I].second);
522 }
523
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000524 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000525
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000526 LangOptions LangInfo;
527 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
528 std::string TargetTriple;
529 std::string Predefines;
530 unsigned Counter;
531
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000532 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000533
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000534 Reader.reset(new ASTReader(AST->getSourceManager(), AST->getFileManager(),
Chris Lattner39b49bc2010-11-23 08:35:12 +0000535 AST->getDiagnostics()));
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000536 Reader->setListener(new ASTInfoCollector(LangInfo, HeaderInfo, TargetTriple,
Daniel Dunbarcc318932009-09-03 05:59:35 +0000537 Predefines, Counter));
538
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000539 switch (Reader->ReadAST(Filename, ASTReader::MainFile)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000540 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000541 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000542
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000543 case ASTReader::Failure:
544 case ASTReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000545 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000546 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000547 }
Mike Stump1eb44332009-09-09 15:08:12 +0000548
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000549 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
550
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000551 // AST file loaded successfully. Now create the preprocessor.
Mike Stump1eb44332009-09-09 15:08:12 +0000552
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000553 // Get information about the target being compiled for.
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000554 //
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000555 // FIXME: This is broken, we should store the TargetOptions in the AST file.
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000556 TargetOptions TargetOpts;
557 TargetOpts.ABI = "";
John McCall875ab102010-08-22 06:43:33 +0000558 TargetOpts.CXXABI = "";
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000559 TargetOpts.CPU = "";
560 TargetOpts.Features.clear();
561 TargetOpts.Triple = TargetTriple;
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000562 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
563 TargetOpts));
564 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
565 *AST->Target.get(),
Daniel Dunbar31b87d82009-09-21 03:03:39 +0000566 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000567 Preprocessor &PP = *AST->PP.get();
568
Daniel Dunbard5b61262009-09-21 03:03:47 +0000569 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000570 PP.setCounterValue(Counter);
Daniel Dunbarcc318932009-09-03 05:59:35 +0000571 Reader->setPreprocessor(PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000572
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000573 // Create and initialize the ASTContext.
574
575 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar31b87d82009-09-21 03:03:39 +0000576 AST->getSourceManager(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000577 *AST->Target.get(),
578 PP.getIdentifierTable(),
579 PP.getSelectorTable(),
580 PP.getBuiltinInfo(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000581 /* size_reserve = */0));
582 ASTContext &Context = *AST->Ctx.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000583
Daniel Dunbarcc318932009-09-03 05:59:35 +0000584 Reader->InitializeContext(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000585
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000586 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000587 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000588 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000589 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000590 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000591 Context.setExternalSource(Source);
592
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000593 // Create an AST consumer, even though it isn't used.
594 AST->Consumer.reset(new ASTConsumer);
595
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000596 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000597 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
598 AST->TheSema->Initialize();
599 ReaderPtr->InitializeSema(*AST->TheSema);
600
Mike Stump1eb44332009-09-09 15:08:12 +0000601 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000602}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000603
604namespace {
605
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000606class TopLevelDeclTrackerConsumer : public ASTConsumer {
607 ASTUnit &Unit;
608
609public:
610 TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {}
611
612 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekda5a4282010-05-03 20:16:35 +0000613 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
614 Decl *D = *it;
615 // FIXME: Currently ObjC method declarations are incorrectly being
616 // reported as top-level declarations, even though their DeclContext
617 // is the containing ObjC @interface/@implementation. This is a
618 // fundamental problem in the parser right now.
619 if (isa<ObjCMethodDecl>(D))
620 continue;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000621 Unit.addTopLevelDecl(D);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000622 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000623 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000624
625 // We're not interested in "interesting" decls.
626 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000627};
628
629class TopLevelDeclTrackerAction : public ASTFrontendAction {
630public:
631 ASTUnit &Unit;
632
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000633 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
634 llvm::StringRef InFile) {
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000635 return new TopLevelDeclTrackerConsumer(Unit);
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000636 }
637
638public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000639 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
640
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000641 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000642 virtual bool usesCompleteTranslationUnit() {
643 return Unit.isCompleteTranslationUnit();
644 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000645};
646
Douglas Gregor89d99802010-11-30 06:16:57 +0000647class PrecompilePreambleConsumer : public PCHGenerator,
648 public ASTSerializationListener {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000649 ASTUnit &Unit;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000650 std::vector<Decl *> TopLevelDecls;
Douglas Gregor89d99802010-11-30 06:16:57 +0000651
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000652public:
653 PrecompilePreambleConsumer(ASTUnit &Unit,
654 const Preprocessor &PP, bool Chaining,
655 const char *isysroot, llvm::raw_ostream *Out)
656 : PCHGenerator(PP, Chaining, isysroot, Out), Unit(Unit) { }
657
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000658 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000659 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
660 Decl *D = *it;
661 // FIXME: Currently ObjC method declarations are incorrectly being
662 // reported as top-level declarations, even though their DeclContext
663 // is the containing ObjC @interface/@implementation. This is a
664 // fundamental problem in the parser right now.
665 if (isa<ObjCMethodDecl>(D))
666 continue;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000667 TopLevelDecls.push_back(D);
668 }
669 }
670
671 virtual void HandleTranslationUnit(ASTContext &Ctx) {
672 PCHGenerator::HandleTranslationUnit(Ctx);
673 if (!Unit.getDiagnostics().hasErrorOccurred()) {
674 // Translate the top-level declarations we captured during
675 // parsing into declaration IDs in the precompiled
676 // preamble. This will allow us to deserialize those top-level
677 // declarations when requested.
678 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
679 Unit.addTopLevelDeclFromPreamble(
680 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000681 }
682 }
Douglas Gregor89d99802010-11-30 06:16:57 +0000683
684 virtual void SerializedPreprocessedEntity(PreprocessedEntity *Entity,
685 uint64_t Offset) {
686 Unit.addPreprocessedEntityFromPreamble(Offset);
687 }
688
689 virtual ASTSerializationListener *GetASTSerializationListener() {
690 return this;
691 }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000692};
693
694class PrecompilePreambleAction : public ASTFrontendAction {
695 ASTUnit &Unit;
696
697public:
698 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
699
700 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
701 llvm::StringRef InFile) {
702 std::string Sysroot;
703 llvm::raw_ostream *OS = 0;
704 bool Chaining;
705 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
706 OS, Chaining))
707 return 0;
708
709 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
710 Sysroot.c_str() : 0;
711 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
712 isysroot, OS);
713 }
714
715 virtual bool hasCodeCompletionSupport() const { return false; }
716 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000717 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000718};
719
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000720}
721
Douglas Gregorabc563f2010-07-19 21:46:24 +0000722/// Parse the source file into a translation unit using the given compiler
723/// invocation, replacing the current translation unit.
724///
725/// \returns True if a failure occurred that causes the ASTUnit not to
726/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +0000727bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +0000728 delete SavedMainFileBuffer;
729 SavedMainFileBuffer = 0;
730
Douglas Gregor671947b2010-08-19 01:33:06 +0000731 if (!Invocation.get()) {
732 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000733 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +0000734 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000735
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000736 // Create the compiler instance to use for building the AST.
Daniel Dunbarcb6dda12009-12-02 08:43:56 +0000737 CompilerInstance Clang;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000738 Clang.setInvocation(Invocation.take());
739 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
740
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000741 // Set up diagnostics, capturing any diagnostics that would
742 // otherwise be dropped.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000743 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000744
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000745 // Create the target instance.
Douglas Gregor1aa27302011-01-27 18:02:58 +0000746 Clang.getTargetOpts().Features = TargetFeatures;
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000747 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
748 Clang.getTargetOpts()));
Douglas Gregor671947b2010-08-19 01:33:06 +0000749 if (!Clang.hasTarget()) {
750 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000751 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +0000752 }
753
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000754 // Inform the target of the language options.
755 //
756 // FIXME: We shouldn't need to do this, the target should be immutable once
757 // created. This complexity should be lifted elsewhere.
758 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000759
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000760 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
761 "Invocation must have exactly one source file!");
Daniel Dunbarc34ce3f2010-06-07 23:22:09 +0000762 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000763 "FIXME: AST inputs not yet supported here!");
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +0000764 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
765 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000766
Douglas Gregorabc563f2010-07-19 21:46:24 +0000767 // Configure the various subsystems.
768 // FIXME: Should we retain the previous file manager?
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000769 FileSystemOpts = Clang.getFileSystemOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +0000770 FileMgr.reset(new FileManager(Clang.getFileSystemOpts()));
771 SourceMgr.reset(new SourceManager(getDiagnostics(), *FileMgr));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000772 TheSema.reset();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000773 Ctx.reset();
774 PP.reset();
775
776 // Clear out old caches and data.
777 TopLevelDecls.clear();
Douglas Gregor89d99802010-11-30 06:16:57 +0000778 PreprocessedEntities.clear();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000779 CleanTemporaryFiles();
780 PreprocessedEntitiesByFile.clear();
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000781
Douglas Gregorf128fed2010-08-20 00:02:33 +0000782 if (!OverrideMainBuffer) {
Douglas Gregor4cd912a2010-10-12 00:50:20 +0000783 StoredDiagnostics.erase(
784 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
785 StoredDiagnostics.end());
Douglas Gregorf128fed2010-08-20 00:02:33 +0000786 TopLevelDeclsInPreamble.clear();
Douglas Gregor89d99802010-11-30 06:16:57 +0000787 PreprocessedEntitiesInPreamble.clear();
Douglas Gregorf128fed2010-08-20 00:02:33 +0000788 }
789
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000790 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000791 Clang.setFileManager(&getFileManager());
792
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000793 // Create the source manager.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000794 Clang.setSourceManager(&getSourceManager());
795
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000796 // If the main file has been overridden due to the use of a preamble,
797 // make that override happen and introduce the preamble.
798 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000799 std::string PriorImplicitPCHInclude;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000800 if (OverrideMainBuffer) {
801 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
802 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
803 PreprocessorOpts.PrecompiledPreambleBytes.second
804 = PreambleEndsAtStartOfLine;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000805 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor385103b2010-07-30 20:58:08 +0000806 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000807 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +0000808
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000809 // The stored diagnostic has the old source manager in it; update
810 // the locations to refer into the new source manager. Since we've
811 // been careful to make sure that the source manager's state
812 // before and after are identical, so that we can reuse the source
813 // location itself.
Douglas Gregor4cd912a2010-10-12 00:50:20 +0000814 for (unsigned I = NumStoredDiagnosticsFromDriver,
815 N = StoredDiagnostics.size();
816 I < N; ++I) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000817 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
818 getSourceManager());
819 StoredDiagnostics[I].setLocation(Loc);
820 }
Douglas Gregor4cd912a2010-10-12 00:50:20 +0000821
822 // Keep track of the override buffer;
823 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf128fed2010-08-20 00:02:33 +0000824 } else {
825 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
826 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000827 }
828
Douglas Gregorabc563f2010-07-19 21:46:24 +0000829 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
830 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000831 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbard3598a62010-06-07 23:23:06 +0000832 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000833 goto error;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000834
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000835 Act->Execute();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000836
Daniel Dunbar64a32ba2009-12-01 21:57:33 +0000837 // Steal the created target, context, and preprocessor, and take back the
838 // source and file managers.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000839 TheSema.reset(Clang.takeSema());
840 Consumer.reset(Clang.takeASTConsumer());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000841 Ctx.reset(Clang.takeASTContext());
842 PP.reset(Clang.takePreprocessor());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000843 Clang.takeSourceManager();
844 Clang.takeFileManager();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000845 Target.reset(Clang.takeTarget());
846
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000847 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000848
849 // Remove the overridden buffer we used for the preamble.
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000850 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000851 PreprocessorOpts.eraseRemappedFile(
852 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000853 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
854 }
855
Douglas Gregorabc563f2010-07-19 21:46:24 +0000856 Invocation.reset(Clang.takeInvocation());
Douglas Gregord64f4c12010-12-09 21:27:43 +0000857
858 if (ShouldCacheCodeCompletionResults) {
859 if (CacheCodeCompletionCoolDown > 0)
860 --CacheCodeCompletionCoolDown;
861 else if (top_level_size() != NumTopLevelDeclsAtLastCompletionCache)
862 CacheCodeCompletionResults();
863 }
864
Douglas Gregorabc563f2010-07-19 21:46:24 +0000865 return false;
866
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000867error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000868 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000869 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000870 PreprocessorOpts.eraseRemappedFile(
871 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000872 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregor671947b2010-08-19 01:33:06 +0000873 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +0000874 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000875 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000876
Douglas Gregord54eb442010-10-12 16:25:54 +0000877 StoredDiagnostics.clear();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000878 Clang.takeSourceManager();
879 Clang.takeFileManager();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000880 Invocation.reset(Clang.takeInvocation());
881 return true;
882}
883
Douglas Gregor44c181a2010-07-23 00:33:23 +0000884/// \brief Simple function to retrieve a path for a preamble precompiled header.
885static std::string GetPreamblePCHPath() {
886 // FIXME: This is lame; sys::Path should provide this function (in particular,
887 // it should know how to find the temporary files dir).
888 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +0000889 // FIXME: This is a hack so that we can override the preamble file during
890 // crash-recovery testing, which is the only case where the preamble files
891 // are not necessarily cleaned up.
892 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
893 if (TmpFile)
894 return TmpFile;
895
Douglas Gregor44c181a2010-07-23 00:33:23 +0000896 std::string Error;
897 const char *TmpDir = ::getenv("TMPDIR");
898 if (!TmpDir)
899 TmpDir = ::getenv("TEMP");
900 if (!TmpDir)
901 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +0000902#ifdef LLVM_ON_WIN32
903 if (!TmpDir)
904 TmpDir = ::getenv("USERPROFILE");
905#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +0000906 if (!TmpDir)
907 TmpDir = "/tmp";
908 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +0000909 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +0000910 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +0000911 P.appendSuffix("pch");
Douglas Gregor44c181a2010-07-23 00:33:23 +0000912 if (P.createTemporaryFileOnDisk())
913 return std::string();
914
Douglas Gregor44c181a2010-07-23 00:33:23 +0000915 return P.str();
916}
917
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000918/// \brief Compute the preamble for the main file, providing the source buffer
919/// that corresponds to the main file along with a pair (bytes, start-of-line)
920/// that describes the preamble.
921std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +0000922ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
923 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000924 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner39b49bc2010-11-23 08:35:12 +0000925 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000926 CreatedBuffer = false;
927
Douglas Gregor44c181a2010-07-23 00:33:23 +0000928 // Try to determine if the main file has been remapped, either from the
929 // command line (to another file) or directly through the compiler invocation
930 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +0000931 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000932 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
933 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
934 // Check whether there is a file-file remapping of the main file
935 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +0000936 M = PreprocessorOpts.remapped_file_begin(),
937 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000938 M != E;
939 ++M) {
940 llvm::sys::PathWithStatus MPath(M->first);
941 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
942 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
943 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000944 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000945 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000946 CreatedBuffer = false;
947 }
948
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000949 Buffer = getBufferForFile(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +0000950 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000951 return std::make_pair((llvm::MemoryBuffer*)0,
952 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000953 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000954 }
955 }
956 }
957
958 // Check whether there is a file-buffer remapping. It supercedes the
959 // file-file remapping.
960 for (PreprocessorOptions::remapped_file_buffer_iterator
961 M = PreprocessorOpts.remapped_file_buffer_begin(),
962 E = PreprocessorOpts.remapped_file_buffer_end();
963 M != E;
964 ++M) {
965 llvm::sys::PathWithStatus MPath(M->first);
966 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
967 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
968 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000969 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000970 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000971 CreatedBuffer = false;
972 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000973
Douglas Gregor175c4a92010-07-23 23:58:40 +0000974 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +0000975 }
976 }
Douglas Gregor175c4a92010-07-23 23:58:40 +0000977 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000978 }
979
980 // If the main source file was not remapped, load it now.
981 if (!Buffer) {
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +0000982 Buffer = getBufferForFile(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +0000983 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000984 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000985
986 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000987 }
988
Douglas Gregordf95a132010-08-09 20:45:32 +0000989 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000990}
991
Douglas Gregor754f3492010-07-24 00:38:13 +0000992static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor754f3492010-07-24 00:38:13 +0000993 unsigned NewSize,
994 llvm::StringRef NewName) {
995 llvm::MemoryBuffer *Result
996 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
997 memcpy(const_cast<char*>(Result->getBufferStart()),
998 Old->getBufferStart(), Old->getBufferSize());
999 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001000 ' ', NewSize - Old->getBufferSize() - 1);
1001 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +00001002
Douglas Gregor754f3492010-07-24 00:38:13 +00001003 return Result;
1004}
1005
Douglas Gregor175c4a92010-07-23 23:58:40 +00001006/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1007/// the source file.
1008///
1009/// This routine will compute the preamble of the main source file. If a
1010/// non-trivial preamble is found, it will precompile that preamble into a
1011/// precompiled header so that the precompiled preamble can be used to reduce
1012/// reparsing time. If a precompiled preamble has already been constructed,
1013/// this routine will determine if it is still valid and, if so, avoid
1014/// rebuilding the precompiled preamble.
1015///
Douglas Gregordf95a132010-08-09 20:45:32 +00001016/// \param AllowRebuild When true (the default), this routine is
1017/// allowed to rebuild the precompiled preamble if it is found to be
1018/// out-of-date.
1019///
1020/// \param MaxLines When non-zero, the maximum number of lines that
1021/// can occur within the preamble.
1022///
Douglas Gregor754f3492010-07-24 00:38:13 +00001023/// \returns If the precompiled preamble can be used, returns a newly-allocated
1024/// buffer that should be used in place of the main file when doing so.
1025/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +00001026llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor2283d792010-08-20 00:59:43 +00001027 CompilerInvocation PreambleInvocation,
Douglas Gregordf95a132010-08-09 20:45:32 +00001028 bool AllowRebuild,
1029 unsigned MaxLines) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001030 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
1031 PreprocessorOptions &PreprocessorOpts
1032 = PreambleInvocation.getPreprocessorOpts();
1033
1034 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001035 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregordf95a132010-08-09 20:45:32 +00001036 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001037
Douglas Gregor73fc9122010-11-16 20:45:51 +00001038 // If ComputePreamble() Take ownership of the
1039 llvm::OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
1040 if (CreatedPreambleBuffer)
1041 OwnedPreambleBuffer.reset(NewPreamble.first);
1042
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001043 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001044 // We couldn't find a preamble in the main source. Clear out the current
1045 // preamble, if we have one. It's obviously no good any more.
1046 Preamble.clear();
1047 if (!PreambleFile.empty()) {
Douglas Gregor385103b2010-07-30 20:58:08 +00001048 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001049 PreambleFile.clear();
1050 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001051
1052 // The next time we actually see a preamble, precompile it.
1053 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001054 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001055 }
1056
1057 if (!Preamble.empty()) {
1058 // We've previously computed a preamble. Check whether we have the same
1059 // preamble now that we did before, and that there's enough space in
1060 // the main-file buffer within the precompiled preamble to fit the
1061 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001062 if (Preamble.size() == NewPreamble.second.first &&
1063 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001064 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor175c4a92010-07-23 23:58:40 +00001065 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001066 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001067 // The preamble has not changed. We may be able to re-use the precompiled
1068 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001069
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001070 // Check that none of the files used by the preamble have changed.
1071 bool AnyFileChanged = false;
1072
1073 // First, make a record of those files that have been overridden via
1074 // remapping or unsaved_files.
1075 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1076 for (PreprocessorOptions::remapped_file_iterator
1077 R = PreprocessorOpts.remapped_file_begin(),
1078 REnd = PreprocessorOpts.remapped_file_end();
1079 !AnyFileChanged && R != REnd;
1080 ++R) {
1081 struct stat StatBuf;
1082 if (stat(R->second.c_str(), &StatBuf)) {
1083 // If we can't stat the file we're remapping to, assume that something
1084 // horrible happened.
1085 AnyFileChanged = true;
1086 break;
1087 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001088
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001089 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1090 StatBuf.st_mtime);
1091 }
1092 for (PreprocessorOptions::remapped_file_buffer_iterator
1093 R = PreprocessorOpts.remapped_file_buffer_begin(),
1094 REnd = PreprocessorOpts.remapped_file_buffer_end();
1095 !AnyFileChanged && R != REnd;
1096 ++R) {
1097 // FIXME: Should we actually compare the contents of file->buffer
1098 // remappings?
1099 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1100 0);
1101 }
1102
1103 // Check whether anything has changed.
1104 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1105 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1106 !AnyFileChanged && F != FEnd;
1107 ++F) {
1108 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1109 = OverriddenFiles.find(F->first());
1110 if (Overridden != OverriddenFiles.end()) {
1111 // This file was remapped; check whether the newly-mapped file
1112 // matches up with the previous mapping.
1113 if (Overridden->second != F->second)
1114 AnyFileChanged = true;
1115 continue;
1116 }
1117
1118 // The file was not remapped; check whether it has changed on disk.
1119 struct stat StatBuf;
1120 if (stat(F->first(), &StatBuf)) {
1121 // If we can't stat the file, assume that something horrible happened.
1122 AnyFileChanged = true;
1123 } else if (StatBuf.st_size != F->second.first ||
1124 StatBuf.st_mtime != F->second.second)
1125 AnyFileChanged = true;
1126 }
1127
1128 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001129 // Okay! We can re-use the precompiled preamble.
1130
1131 // Set the state of the diagnostic object to mimic its state
1132 // after parsing the preamble.
Douglas Gregor32be4a52010-10-11 21:37:58 +00001133 // FIXME: This won't catch any #pragma push warning changes that
1134 // have occurred in the preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001135 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001136 ProcessWarningOptions(getDiagnostics(),
1137 PreambleInvocation.getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001138 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1139 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
1140 StoredDiagnostics.erase(
1141 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
1142 StoredDiagnostics.end());
1143
1144 // Create a version of the main file buffer that is padded to
1145 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001146 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001147 PreambleReservedSize,
1148 FrontendOpts.Inputs[0].second);
1149 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001150 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001151
1152 // If we aren't allowed to rebuild the precompiled preamble, just
1153 // return now.
1154 if (!AllowRebuild)
1155 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001156
Douglas Gregor175c4a92010-07-23 23:58:40 +00001157 // We can't reuse the previously-computed preamble. Build a new one.
1158 Preamble.clear();
Douglas Gregor385103b2010-07-30 20:58:08 +00001159 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001160 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001161 } else if (!AllowRebuild) {
1162 // We aren't allowed to rebuild the precompiled preamble; just
1163 // return now.
1164 return 0;
1165 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001166
1167 // If the preamble rebuild counter > 1, it's because we previously
1168 // failed to build a preamble and we're not yet ready to try
1169 // again. Decrement the counter and return a failure.
1170 if (PreambleRebuildCounter > 1) {
1171 --PreambleRebuildCounter;
1172 return 0;
1173 }
1174
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001175 // Create a temporary file for the precompiled preamble. In rare
1176 // circumstances, this can fail.
1177 std::string PreamblePCHPath = GetPreamblePCHPath();
1178 if (PreamblePCHPath.empty()) {
1179 // Try again next time.
1180 PreambleRebuildCounter = 1;
1181 return 0;
1182 }
1183
Douglas Gregor175c4a92010-07-23 23:58:40 +00001184 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor213f18b2010-10-28 15:44:59 +00001185 SimpleTimer PreambleTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001186 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregor44c181a2010-07-23 00:33:23 +00001187
1188 // Create a new buffer that stores the preamble. The buffer also contains
1189 // extra space for the original contents of the file (which will be present
1190 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001191 // grows.
1192 PreambleReservedSize = NewPreamble.first->getBufferSize();
1193 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001194 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001195 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001196 PreambleReservedSize *= 2;
1197
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001198 // Save the preamble text for later; we'll need to compare against it for
1199 // subsequent reparses.
1200 Preamble.assign(NewPreamble.first->getBufferStart(),
1201 NewPreamble.first->getBufferStart()
1202 + NewPreamble.second.first);
1203 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1204
Douglas Gregor671947b2010-08-19 01:33:06 +00001205 delete PreambleBuffer;
1206 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001207 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001208 FrontendOpts.Inputs[0].second);
1209 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001210 NewPreamble.first->getBufferStart(), Preamble.size());
1211 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001212 ' ', PreambleReservedSize - Preamble.size() - 1);
1213 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001214
1215 // Remap the main source file to the preamble buffer.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001216 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001217 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1218
1219 // Tell the compiler invocation to generate a temporary precompiled header.
1220 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor85e51912010-10-01 01:05:22 +00001221 FrontendOpts.ChainedPCH = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001222 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001223 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001224 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1225 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001226
1227 // Create the compiler instance to use for building the precompiled preamble.
1228 CompilerInstance Clang;
1229 Clang.setInvocation(&PreambleInvocation);
1230 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1231
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001232 // Set up diagnostics, capturing all of the diagnostics produced.
Douglas Gregor44c181a2010-07-23 00:33:23 +00001233 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor44c181a2010-07-23 00:33:23 +00001234
1235 // Create the target instance.
Douglas Gregor1aa27302011-01-27 18:02:58 +00001236 Clang.getTargetOpts().Features = TargetFeatures;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001237 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1238 Clang.getTargetOpts()));
1239 if (!Clang.hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001240 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1241 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001242 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001243 PreprocessorOpts.eraseRemappedFile(
1244 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001245 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001246 }
1247
1248 // Inform the target of the language options.
1249 //
1250 // FIXME: We shouldn't need to do this, the target should be immutable once
1251 // created. This complexity should be lifted elsewhere.
1252 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1253
1254 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1255 "Invocation must have exactly one source file!");
1256 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1257 "FIXME: AST inputs not yet supported here!");
1258 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1259 "IR inputs not support here!");
1260
1261 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001262 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001263 ProcessWarningOptions(getDiagnostics(), Clang.getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001264 StoredDiagnostics.erase(
1265 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1266 StoredDiagnostics.end());
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001267 TopLevelDecls.clear();
1268 TopLevelDeclsInPreamble.clear();
Douglas Gregor89d99802010-11-30 06:16:57 +00001269 PreprocessedEntities.clear();
1270 PreprocessedEntitiesInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001271
1272 // Create a file manager object to provide access to and cache the filesystem.
Chris Lattner7ad97ff2010-11-23 07:51:02 +00001273 Clang.setFileManager(new FileManager(Clang.getFileSystemOpts()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001274
1275 // Create the source manager.
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00001276 Clang.setSourceManager(new SourceManager(getDiagnostics(),
Chris Lattner39b49bc2010-11-23 08:35:12 +00001277 Clang.getFileManager()));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001278
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001279 llvm::OwningPtr<PrecompilePreambleAction> Act;
1280 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001281 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1282 Clang.getFrontendOpts().Inputs[0].first)) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001283 Clang.takeInvocation();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001284 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1285 Preamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001286 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001287 PreprocessorOpts.eraseRemappedFile(
1288 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001289 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001290 }
1291
1292 Act->Execute();
1293 Act->EndSourceFile();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001294 Clang.takeInvocation();
1295
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001296 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001297 // There were errors parsing the preamble, so no precompiled header was
1298 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001299 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001300 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1301 Preamble.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001302 TopLevelDeclsInPreamble.clear();
Douglas Gregor89d99802010-11-30 06:16:57 +00001303 PreprocessedEntities.clear();
1304 PreprocessedEntitiesInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001305 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001306 PreprocessorOpts.eraseRemappedFile(
1307 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001308 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001309 }
1310
1311 // Keep track of the preamble we precompiled.
1312 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001313 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1314 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001315
1316 // Keep track of all of the files that the source manager knows about,
1317 // so we can verify whether they have changed or not.
1318 FilesInPreamble.clear();
1319 SourceManager &SourceMgr = Clang.getSourceManager();
1320 const llvm::MemoryBuffer *MainFileBuffer
1321 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1322 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1323 FEnd = SourceMgr.fileinfo_end();
1324 F != FEnd;
1325 ++F) {
1326 const FileEntry *File = F->second->Entry;
1327 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1328 continue;
1329
1330 FilesInPreamble[File->getName()]
1331 = std::make_pair(F->second->getSize(), File->getModificationTime());
1332 }
1333
Douglas Gregoreababfb2010-08-04 05:53:38 +00001334 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001335 PreprocessorOpts.eraseRemappedFile(
1336 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001337 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor754f3492010-07-24 00:38:13 +00001338 PreambleReservedSize,
1339 FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001340}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001341
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001342void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1343 std::vector<Decl *> Resolved;
1344 Resolved.reserve(TopLevelDeclsInPreamble.size());
1345 ExternalASTSource &Source = *getASTContext().getExternalSource();
1346 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1347 // Resolve the declaration ID to an actual declaration, possibly
1348 // deserializing the declaration in the process.
1349 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1350 if (D)
1351 Resolved.push_back(D);
1352 }
1353 TopLevelDeclsInPreamble.clear();
1354 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1355}
1356
Douglas Gregor89d99802010-11-30 06:16:57 +00001357void ASTUnit::RealizePreprocessedEntitiesFromPreamble() {
1358 if (!PP)
1359 return;
1360
1361 PreprocessingRecord *PPRec = PP->getPreprocessingRecord();
1362 if (!PPRec)
1363 return;
1364
1365 ExternalPreprocessingRecordSource *External = PPRec->getExternalSource();
1366 if (!External)
1367 return;
1368
1369 for (unsigned I = 0, N = PreprocessedEntitiesInPreamble.size(); I != N; ++I) {
1370 if (PreprocessedEntity *PE
Douglas Gregor0a480292011-02-11 19:46:30 +00001371 = External->ReadPreprocessedEntityAtOffset(
1372 PreprocessedEntitiesInPreamble[I]))
Douglas Gregor89d99802010-11-30 06:16:57 +00001373 PreprocessedEntities.push_back(PE);
1374 }
1375
1376 if (PreprocessedEntities.empty())
1377 return;
1378
1379 PreprocessedEntities.insert(PreprocessedEntities.end(),
1380 PPRec->begin(true), PPRec->end(true));
1381}
1382
1383ASTUnit::pp_entity_iterator ASTUnit::pp_entity_begin() {
1384 if (!PreprocessedEntitiesInPreamble.empty() &&
1385 PreprocessedEntities.empty())
1386 RealizePreprocessedEntitiesFromPreamble();
1387
1388 if (PreprocessedEntities.empty())
1389 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
1390 return PPRec->begin(true);
1391
1392 return PreprocessedEntities.begin();
1393}
1394
1395ASTUnit::pp_entity_iterator ASTUnit::pp_entity_end() {
1396 if (!PreprocessedEntitiesInPreamble.empty() &&
1397 PreprocessedEntities.empty())
1398 RealizePreprocessedEntitiesFromPreamble();
1399
1400 if (PreprocessedEntities.empty())
1401 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
1402 return PPRec->end(true);
1403
1404 return PreprocessedEntities.end();
1405}
1406
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001407unsigned ASTUnit::getMaxPCHLevel() const {
1408 if (!getOnlyLocalDecls())
1409 return Decl::MaxPCHLevel;
1410
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +00001411 return 0;
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001412}
1413
Douglas Gregor213f18b2010-10-28 15:44:59 +00001414llvm::StringRef ASTUnit::getMainFileName() const {
1415 return Invocation->getFrontendOpts().Inputs[0].second;
1416}
1417
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001418bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1419 if (!Invocation)
1420 return true;
1421
1422 // We'll manage file buffers ourselves.
1423 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1424 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001425 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001426
Douglas Gregor1aa27302011-01-27 18:02:58 +00001427 // Save the target features.
1428 TargetFeatures = Invocation->getTargetOpts().Features;
1429
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001430 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregor99ba2022010-10-27 17:24:53 +00001431 if (PrecompilePreamble) {
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001432 PreambleRebuildCounter = 2;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001433 OverrideMainBuffer
1434 = getMainBufferWithPrecompiledPreamble(*Invocation);
1435 }
1436
Douglas Gregor213f18b2010-10-28 15:44:59 +00001437 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001438 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001439
Douglas Gregor213f18b2010-10-28 15:44:59 +00001440 return Parse(OverrideMainBuffer);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001441}
1442
Douglas Gregorabc563f2010-07-19 21:46:24 +00001443ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1444 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1445 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001446 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001447 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001448 bool CompleteTranslationUnit,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001449 bool CacheCodeCompletionResults) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001450 // Create the AST unit.
1451 llvm::OwningPtr<ASTUnit> AST;
1452 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001453 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +00001454 AST->Diagnostics = Diags;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001455 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001456 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregordf95a132010-08-09 20:45:32 +00001457 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001458 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001459 AST->CacheCodeCompletionCoolDown = 1;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001460 AST->Invocation.reset(CI);
1461
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001462 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001463}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001464
1465ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1466 const char **ArgEnd,
Douglas Gregor28019772010-04-05 23:52:57 +00001467 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001468 llvm::StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001469 bool OnlyLocalDecls,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001470 bool CaptureDiagnostics,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001471 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001472 unsigned NumRemappedFiles,
Douglas Gregordf95a132010-08-09 20:45:32 +00001473 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001474 bool CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00001475 bool CacheCodeCompletionResults,
1476 bool CXXPrecompilePreamble,
1477 bool CXXChainedPCH) {
Douglas Gregor28019772010-04-05 23:52:57 +00001478 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001479 // No diagnostics engine was provided, so create our own diagnostics object
1480 // with the default options.
1481 DiagnosticOptions DiagOpts;
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001482 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1483 ArgBegin);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001484 }
1485
Daniel Dunbar7b556682009-12-02 03:23:45 +00001486 llvm::SmallVector<const char *, 16> Args;
1487 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1488 Args.insert(Args.end(), ArgBegin, ArgEnd);
1489
1490 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1491 // also want to force it to use clang.
1492 Args.push_back("-fsyntax-only");
1493
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001494 llvm::SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1495
1496 llvm::OwningPtr<CompilerInvocation> CI;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001497
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001498 {
Douglas Gregore47be3e2010-11-11 00:39:14 +00001499 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001500 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001501
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001502 // FIXME: We shouldn't have to pass in the path info.
1503 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
1504 "a.out", false, false, *Diags);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001505
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001506 // Don't check that inputs exist, they have been remapped.
1507 TheDriver.setCheckInputsExist(false);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001508
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001509 llvm::OwningPtr<driver::Compilation> C(
1510 TheDriver.BuildCompilation(Args.size(), Args.data()));
1511
1512 // We expect to get back exactly one command job, if we didn't something
1513 // failed.
1514 const driver::JobList &Jobs = C->getJobs();
1515 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1516 llvm::SmallString<256> Msg;
1517 llvm::raw_svector_ostream OS(Msg);
1518 C->PrintJob(OS, C->getJobs(), "; ", true);
1519 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
1520 return 0;
1521 }
1522
1523 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1524 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
1525 Diags->Report(diag::err_fe_expected_clang_command);
1526 return 0;
1527 }
1528
1529 const driver::ArgStringList &CCArgs = Cmd->getArguments();
1530 CI.reset(new CompilerInvocation);
1531 CompilerInvocation::CreateFromArgs(*CI,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001532 const_cast<const char **>(CCArgs.data()),
1533 const_cast<const char **>(CCArgs.data()) +
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001534 CCArgs.size(),
1535 *Diags);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001536 }
Douglas Gregore47be3e2010-11-11 00:39:14 +00001537
Douglas Gregor4db64a42010-01-23 00:14:00 +00001538 // Override any files that need remapping
1539 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar807b0612010-01-30 21:47:16 +00001540 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbarb26d4832010-02-16 01:55:04 +00001541 RemappedFiles[I].second);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001542
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001543 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001544 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001545
Douglas Gregor99ba2022010-10-27 17:24:53 +00001546 // Check whether we should precompile the preamble and/or use chained PCH.
1547 // FIXME: This is a temporary hack while we debug C++ chained PCH.
1548 if (CI->getLangOpts().CPlusPlus) {
1549 PrecompilePreamble = PrecompilePreamble && CXXPrecompilePreamble;
1550
1551 if (PrecompilePreamble && !CXXChainedPCH &&
1552 !CI->getPreprocessorOpts().ImplicitPCHInclude.empty())
1553 PrecompilePreamble = false;
1554 }
1555
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001556 // Create the AST unit.
1557 llvm::OwningPtr<ASTUnit> AST;
1558 AST.reset(new ASTUnit(false));
Douglas Gregor0b53cf82011-01-19 01:02:47 +00001559 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001560 AST->Diagnostics = Diags;
Chris Lattner39b49bc2010-11-23 08:35:12 +00001561
1562 AST->FileMgr.reset(new FileManager(FileSystemOptions()));
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001563 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregore47be3e2010-11-11 00:39:14 +00001564 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001565 AST->CompleteTranslationUnit = CompleteTranslationUnit;
1566 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregor08bb4c62010-11-15 23:00:34 +00001567 AST->CacheCodeCompletionCoolDown = 1;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001568 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1569 AST->NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1570 AST->StoredDiagnostics.swap(StoredDiagnostics);
1571 AST->Invocation.reset(CI.take());
Chris Lattner39b49bc2010-11-23 08:35:12 +00001572 return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001573}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001574
1575bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1576 if (!Invocation.get())
1577 return true;
1578
Douglas Gregor213f18b2010-10-28 15:44:59 +00001579 SimpleTimer ParsingTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001580 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor213f18b2010-10-28 15:44:59 +00001581
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001582 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00001583 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00001584 PPOpts.DisableStatCache = true;
Douglas Gregorf128fed2010-08-20 00:02:33 +00001585 for (PreprocessorOptions::remapped_file_buffer_iterator
1586 R = PPOpts.remapped_file_buffer_begin(),
1587 REnd = PPOpts.remapped_file_buffer_end();
1588 R != REnd;
1589 ++R) {
1590 delete R->second;
1591 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001592 Invocation->getPreprocessorOpts().clearRemappedFiles();
1593 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1594 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1595 RemappedFiles[I].second);
1596
Douglas Gregoreababfb2010-08-04 05:53:38 +00001597 // If we have a preamble file lying around, or if we might try to
1598 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00001599 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregoreababfb2010-08-04 05:53:38 +00001600 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00001601 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001602
Douglas Gregorabc563f2010-07-19 21:46:24 +00001603 // Clear out the diagnostics state.
Douglas Gregor32be4a52010-10-11 21:37:58 +00001604 if (!OverrideMainBuffer) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001605 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001606 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1607 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001608
Douglas Gregor175c4a92010-07-23 23:58:40 +00001609 // Parse the sources
Douglas Gregor754f3492010-07-24 00:38:13 +00001610 bool Result = Parse(OverrideMainBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001611 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001612}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001613
Douglas Gregor87c08a52010-08-13 22:48:40 +00001614//----------------------------------------------------------------------------//
1615// Code completion
1616//----------------------------------------------------------------------------//
1617
1618namespace {
1619 /// \brief Code completion consumer that combines the cached code-completion
1620 /// results from an ASTUnit with the code-completion results provided to it,
1621 /// then passes the result on to
1622 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1623 unsigned NormalContexts;
1624 ASTUnit &AST;
1625 CodeCompleteConsumer &Next;
1626
1627 public:
1628 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor8071e422010-08-15 06:18:01 +00001629 bool IncludeMacros, bool IncludeCodePatterns,
1630 bool IncludeGlobals)
1631 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001632 Next.isOutputBinary()), AST(AST), Next(Next)
1633 {
1634 // Compute the set of contexts in which we will look when we don't have
1635 // any information about the specific context.
1636 NormalContexts
1637 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
1638 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
1639 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1640 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1641 | (1 << (CodeCompletionContext::CCC_Statement - 1))
1642 | (1 << (CodeCompletionContext::CCC_Expression - 1))
1643 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1644 | (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
Douglas Gregor02688102010-09-14 23:59:36 +00001645 | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
Douglas Gregor52779fb2010-09-23 23:01:17 +00001646 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
1647 | (1 << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor02688102010-09-14 23:59:36 +00001648
Douglas Gregor87c08a52010-08-13 22:48:40 +00001649 if (AST.getASTContext().getLangOptions().CPlusPlus)
1650 NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1))
1651 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
1652 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
1653 }
1654
1655 virtual void ProcessCodeCompleteResults(Sema &S,
1656 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00001657 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001658 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001659
1660 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1661 OverloadCandidate *Candidates,
1662 unsigned NumCandidates) {
1663 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1664 }
Douglas Gregor218937c2011-02-01 19:23:04 +00001665
Douglas Gregordae68752011-02-01 22:57:45 +00001666 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregor218937c2011-02-01 19:23:04 +00001667 return Next.getAllocator();
1668 }
Douglas Gregor87c08a52010-08-13 22:48:40 +00001669 };
1670}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001671
Douglas Gregor5f808c22010-08-16 21:18:39 +00001672/// \brief Helper function that computes which global names are hidden by the
1673/// local code-completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00001674static void CalculateHiddenNames(const CodeCompletionContext &Context,
1675 CodeCompletionResult *Results,
1676 unsigned NumResults,
1677 ASTContext &Ctx,
1678 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor5f808c22010-08-16 21:18:39 +00001679 bool OnlyTagNames = false;
1680 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00001681 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00001682 case CodeCompletionContext::CCC_TopLevel:
1683 case CodeCompletionContext::CCC_ObjCInterface:
1684 case CodeCompletionContext::CCC_ObjCImplementation:
1685 case CodeCompletionContext::CCC_ObjCIvarList:
1686 case CodeCompletionContext::CCC_ClassStructUnion:
1687 case CodeCompletionContext::CCC_Statement:
1688 case CodeCompletionContext::CCC_Expression:
1689 case CodeCompletionContext::CCC_ObjCMessageReceiver:
1690 case CodeCompletionContext::CCC_MemberAccess:
1691 case CodeCompletionContext::CCC_Namespace:
1692 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00001693 case CodeCompletionContext::CCC_Name:
1694 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00001695 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor5f808c22010-08-16 21:18:39 +00001696 break;
1697
1698 case CodeCompletionContext::CCC_EnumTag:
1699 case CodeCompletionContext::CCC_UnionTag:
1700 case CodeCompletionContext::CCC_ClassOrStructTag:
1701 OnlyTagNames = true;
1702 break;
1703
1704 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001705 case CodeCompletionContext::CCC_MacroName:
1706 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00001707 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00001708 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00001709 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00001710 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00001711 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00001712 case CodeCompletionContext::CCC_Other:
Douglas Gregor721f3592010-08-25 18:41:16 +00001713 // We're looking for nothing, or we're looking for names that cannot
1714 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00001715 return;
1716 }
1717
John McCall0a2c5e22010-08-25 06:19:51 +00001718 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00001719 for (unsigned I = 0; I != NumResults; ++I) {
1720 if (Results[I].Kind != Result::RK_Declaration)
1721 continue;
1722
1723 unsigned IDNS
1724 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1725
1726 bool Hiding = false;
1727 if (OnlyTagNames)
1728 Hiding = (IDNS & Decl::IDNS_Tag);
1729 else {
1730 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00001731 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1732 Decl::IDNS_NonMemberOperator);
Douglas Gregor5f808c22010-08-16 21:18:39 +00001733 if (Ctx.getLangOptions().CPlusPlus)
1734 HiddenIDNS |= Decl::IDNS_Tag;
1735 Hiding = (IDNS & HiddenIDNS);
1736 }
1737
1738 if (!Hiding)
1739 continue;
1740
1741 DeclarationName Name = Results[I].Declaration->getDeclName();
1742 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1743 HiddenNames.insert(Identifier->getName());
1744 else
1745 HiddenNames.insert(Name.getAsString());
1746 }
1747}
1748
1749
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001750void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1751 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00001752 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001753 unsigned NumResults) {
1754 // Merge the results we were given with the results we cached.
1755 bool AddedResult = false;
Douglas Gregor5f808c22010-08-16 21:18:39 +00001756 unsigned InContexts
Douglas Gregor52779fb2010-09-23 23:01:17 +00001757 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
Douglas Gregor5f808c22010-08-16 21:18:39 +00001758 : (1 << (Context.getKind() - 1)));
1759
1760 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenekc198f612010-11-07 06:11:36 +00001761 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall0a2c5e22010-08-25 06:19:51 +00001762 typedef CodeCompletionResult Result;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001763 llvm::SmallVector<Result, 8> AllResults;
1764 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00001765 C = AST.cached_completion_begin(),
1766 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001767 C != CEnd; ++C) {
1768 // If the context we are in matches any of the contexts we are
1769 // interested in, we'll add this result.
1770 if ((C->ShowInContexts & InContexts) == 0)
1771 continue;
1772
1773 // If we haven't added any results previously, do so now.
1774 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00001775 CalculateHiddenNames(Context, Results, NumResults, S.Context,
1776 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001777 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1778 AddedResult = true;
1779 }
1780
Douglas Gregor5f808c22010-08-16 21:18:39 +00001781 // Determine whether this global completion result is hidden by a local
1782 // completion result. If so, skip it.
1783 if (C->Kind != CXCursor_MacroDefinition &&
1784 HiddenNames.count(C->Completion->getTypedText()))
1785 continue;
1786
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001787 // Adjust priority based on similar type classes.
1788 unsigned Priority = C->Priority;
Douglas Gregor4125c372010-08-25 18:03:13 +00001789 CXCursorKind CursorKind = C->Kind;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001790 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001791 if (!Context.getPreferredType().isNull()) {
1792 if (C->Kind == CXCursor_MacroDefinition) {
1793 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00001794 S.getLangOptions(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001795 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001796 } else if (C->Type) {
1797 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00001798 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001799 Context.getPreferredType().getUnqualifiedType());
1800 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
1801 if (ExpectedSTC == C->TypeClass) {
1802 // We know this type is similar; check for an exact match.
1803 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00001804 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001805 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00001806 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001807 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
1808 Priority /= CCF_ExactTypeMatch;
1809 else
1810 Priority /= CCF_SimilarTypeMatch;
1811 }
1812 }
1813 }
1814
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001815 // Adjust the completion string, if required.
1816 if (C->Kind == CXCursor_MacroDefinition &&
1817 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
1818 // Create a new code-completion string that just contains the
1819 // macro name, without its arguments.
Douglas Gregor218937c2011-02-01 19:23:04 +00001820 CodeCompletionBuilder Builder(getAllocator(), CCP_CodePattern,
1821 C->Availability);
1822 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor4125c372010-08-25 18:03:13 +00001823 CursorKind = CXCursor_NotImplemented;
1824 Priority = CCP_CodePattern;
Douglas Gregor218937c2011-02-01 19:23:04 +00001825 Completion = Builder.TakeString();
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001826 }
1827
Douglas Gregor4125c372010-08-25 18:03:13 +00001828 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00001829 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001830 }
1831
1832 // If we did not add any cached completion results, just forward the
1833 // results we were given to the next consumer.
1834 if (!AddedResult) {
1835 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
1836 return;
1837 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00001838
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001839 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
1840 AllResults.size());
1841}
1842
1843
1844
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001845void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
1846 RemappedFile *RemappedFiles,
1847 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00001848 bool IncludeMacros,
1849 bool IncludeCodePatterns,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001850 CodeCompleteConsumer &Consumer,
1851 Diagnostic &Diag, LangOptions &LangOpts,
1852 SourceManager &SourceMgr, FileManager &FileMgr,
Douglas Gregor2283d792010-08-20 00:59:43 +00001853 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
1854 llvm::SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001855 if (!Invocation.get())
1856 return;
1857
Douglas Gregor213f18b2010-10-28 15:44:59 +00001858 SimpleTimer CompletionTimer(WantTiming);
Benjamin Krameredfb7ec2010-11-09 20:00:56 +00001859 CompletionTimer.setOutput("Code completion @ " + File + ":" +
1860 llvm::Twine(Line) + ":" + llvm::Twine(Column));
Douglas Gregordf95a132010-08-09 20:45:32 +00001861
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001862 CompilerInvocation CCInvocation(*Invocation);
1863 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
1864 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001865
Douglas Gregor87c08a52010-08-13 22:48:40 +00001866 FrontendOpts.ShowMacrosInCodeCompletion
1867 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001868 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor8071e422010-08-15 06:18:01 +00001869 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
1870 = CachedCompletionResults.empty();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001871 FrontendOpts.CodeCompletionAt.FileName = File;
1872 FrontendOpts.CodeCompletionAt.Line = Line;
1873 FrontendOpts.CodeCompletionAt.Column = Column;
1874
1875 // Set the language options appropriately.
1876 LangOpts = CCInvocation.getLangOpts();
1877
1878 CompilerInstance Clang;
1879 Clang.setInvocation(&CCInvocation);
1880 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1881
1882 // Set up diagnostics, capturing any diagnostics produced.
1883 Clang.setDiagnostics(&Diag);
Douglas Gregor32be4a52010-10-11 21:37:58 +00001884 ProcessWarningOptions(Diag, CCInvocation.getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001885 CaptureDroppedDiagnostics Capture(true,
Douglas Gregore47be3e2010-11-11 00:39:14 +00001886 Clang.getDiagnostics(),
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001887 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001888
1889 // Create the target instance.
Douglas Gregor1aa27302011-01-27 18:02:58 +00001890 Clang.getTargetOpts().Features = TargetFeatures;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001891 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1892 Clang.getTargetOpts()));
1893 if (!Clang.hasTarget()) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001894 Clang.takeInvocation();
Douglas Gregorbdbb0042010-08-18 22:29:43 +00001895 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001896 }
1897
1898 // Inform the target of the language options.
1899 //
1900 // FIXME: We shouldn't need to do this, the target should be immutable once
1901 // created. This complexity should be lifted elsewhere.
1902 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1903
1904 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1905 "Invocation must have exactly one source file!");
1906 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1907 "FIXME: AST inputs not yet supported here!");
1908 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1909 "IR inputs not support here!");
1910
1911
1912 // Use the source and file managers that we were given.
1913 Clang.setFileManager(&FileMgr);
1914 Clang.setSourceManager(&SourceMgr);
1915
1916 // Remap files.
1917 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00001918 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00001919 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001920 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
1921 RemappedFiles[I].second);
Douglas Gregor2283d792010-08-20 00:59:43 +00001922 OwnedBuffers.push_back(RemappedFiles[I].second);
1923 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001924
Douglas Gregor87c08a52010-08-13 22:48:40 +00001925 // Use the code completion consumer we were given, but adding any cached
1926 // code-completion results.
Douglas Gregor7f946ad2010-11-29 16:13:56 +00001927 AugmentedCodeCompleteConsumer *AugmentedConsumer
1928 = new AugmentedCodeCompleteConsumer(*this, Consumer,
1929 FrontendOpts.ShowMacrosInCodeCompletion,
1930 FrontendOpts.ShowCodePatternsInCodeCompletion,
1931 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
1932 Clang.setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001933
Douglas Gregordf95a132010-08-09 20:45:32 +00001934 // If we have a precompiled preamble, try to use it. We only allow
1935 // the use of the precompiled preamble if we're if the completion
1936 // point is within the main file, after the end of the precompiled
1937 // preamble.
1938 llvm::MemoryBuffer *OverrideMainBuffer = 0;
1939 if (!PreambleFile.empty()) {
1940 using llvm::sys::FileStatus;
1941 llvm::sys::PathWithStatus CompleteFilePath(File);
1942 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
1943 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
1944 if (const FileStatus *MainStatus = MainPath.getFileStatus())
1945 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
Douglas Gregor2283d792010-08-20 00:59:43 +00001946 OverrideMainBuffer
Douglas Gregorc9c29a82010-08-25 18:04:15 +00001947 = getMainBufferWithPrecompiledPreamble(CCInvocation, false,
1948 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00001949 }
1950
1951 // If the main file has been overridden due to the use of a preamble,
1952 // make that override happen and introduce the preamble.
Douglas Gregor8ef6c8c2011-02-05 19:42:43 +00001953 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001954 StoredDiagnostics.insert(StoredDiagnostics.end(),
1955 this->StoredDiagnostics.begin(),
1956 this->StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver);
Douglas Gregordf95a132010-08-09 20:45:32 +00001957 if (OverrideMainBuffer) {
1958 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1959 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1960 PreprocessorOpts.PrecompiledPreambleBytes.second
1961 = PreambleEndsAtStartOfLine;
1962 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
1963 PreprocessorOpts.DisablePCHValidation = true;
1964
1965 // The stored diagnostics have the old source manager. Copy them
1966 // to our output set of stored diagnostics, updating the source
1967 // manager to the one we were given.
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001968 for (unsigned I = NumStoredDiagnosticsFromDriver,
1969 N = this->StoredDiagnostics.size();
1970 I < N; ++I) {
Douglas Gregordf95a132010-08-09 20:45:32 +00001971 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
1972 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
1973 StoredDiagnostics[I].setLocation(Loc);
1974 }
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001975
Douglas Gregor2283d792010-08-20 00:59:43 +00001976 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00001977 } else {
1978 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1979 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00001980 }
1981
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001982 llvm::OwningPtr<SyntaxOnlyAction> Act;
1983 Act.reset(new SyntaxOnlyAction);
1984 if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1985 Clang.getFrontendOpts().Inputs[0].first)) {
1986 Act->Execute();
1987 Act->EndSourceFile();
1988 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001989
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001990 // Steal back our resources.
1991 Clang.takeFileManager();
1992 Clang.takeSourceManager();
1993 Clang.takeInvocation();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001994}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001995
1996bool ASTUnit::Save(llvm::StringRef File) {
1997 if (getDiagnostics().hasErrorOccurred())
1998 return true;
1999
2000 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2001 // unconditionally create a stat cache when we parse the file?
2002 std::string ErrorInfo;
Benjamin Kramer1395c5d2010-08-15 16:54:31 +00002003 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo,
2004 llvm::raw_fd_ostream::F_Binary);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002005 if (!ErrorInfo.empty() || Out.has_error())
2006 return true;
2007
2008 std::vector<unsigned char> Buffer;
2009 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00002010 ASTWriter Writer(Stream);
2011 Writer.WriteAST(getSema(), 0, 0);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002012
2013 // Write the generated bitstream to "Out".
Douglas Gregorbdbb0042010-08-18 22:29:43 +00002014 if (!Buffer.empty())
2015 Out.write((char *)&Buffer.front(), Buffer.size());
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002016 Out.close();
2017 return Out.has_error();
2018}