blob: 1db81cb13e8a293e10fd7d741a4eb95fc85cd6a5 [file] [log] [blame]
Argyrios Kyrtzidis3a08ec12009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000015#include "clang/AST/ASTContext.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000016#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
Douglas Gregorb61c07a2010-08-16 18:08:11 +000018#include "clang/AST/TypeOrdering.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000019#include "clang/AST/StmtVisitor.h"
Daniel Dunbar55a17b62009-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 Dunbar764c0822009-12-01 09:51:01 +000024#include "clang/Frontend/CompilerInstance.h"
25#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000026#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000027#include "clang/Frontend/FrontendOptions.h"
Douglas Gregor36e3b5c2010-10-11 21:37:58 +000028#include "clang/Frontend/Utils.h"
Sebastian Redlf5b13462010-08-18 23:57:17 +000029#include "clang/Serialization/ASTReader.h"
Douglas Gregorf88e35b2010-11-30 06:16:57 +000030#include "clang/Serialization/ASTSerializationListener.h"
Sebastian Redl1914c6f2010-08-18 23:56:37 +000031#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000032#include "clang/Lex/HeaderSearch.h"
33#include "clang/Lex/Preprocessor.h"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000034#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000035#include "clang/Basic/TargetInfo.h"
36#include "clang/Basic/Diagnostic.h"
Douglas Gregor40a5a7d2010-08-16 23:08:34 +000037#include "llvm/ADT/StringSet.h"
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +000038#include "llvm/Support/Atomic.h"
Douglas Gregoraa98ed92010-01-23 00:14:00 +000039#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000040#include "llvm/Support/Host.h"
41#include "llvm/Support/Path.h"
Douglas Gregor028d3e42010-08-09 20:45:32 +000042#include "llvm/Support/raw_ostream.h"
Douglas Gregor15ba0b32010-07-30 20:58:08 +000043#include "llvm/Support/Timer.h"
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000044#include <cstdlib>
Zhongxing Xu318e4032010-07-23 02:15:08 +000045#include <cstdio>
Douglas Gregor0e119552010-07-31 00:40:00 +000046#include <sys/stat.h>
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000047using namespace clang;
48
Douglas Gregor16896c42010-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 Kramerf2e5a912010-11-09 20:00:56 +000057 public:
Douglas Gregor1cbdd952010-11-01 13:48:43 +000058 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor16896c42010-10-28 15:44:59 +000059 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000060 Start = TimeRecord::getCurrentTime();
Douglas Gregor16896c42010-10-28 15:44:59 +000061 }
62
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000063 void setOutput(const llvm::Twine &Output) {
Douglas Gregor16896c42010-10-28 15:44:59 +000064 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000065 this->Output = Output.str();
Douglas Gregor16896c42010-10-28 15:44:59 +000066 }
67
Douglas Gregor16896c42010-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 Gregorbb420ab2010-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 Gregor68dbaea2010-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 Gregor9aeaa4d2010-12-07 00:05:48 +000089static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregor68dbaea2010-11-17 00:13:31 +000090
Douglas Gregord03e8232010-04-05 21:10:19 +000091ASTUnit::ASTUnit(bool _MainFileIsAST)
Douglas Gregoraa21cc42010-07-19 21:46:24 +000092 : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
Douglas Gregor16896c42010-10-28 15:44:59 +000093 CompleteTranslationUnit(true), WantTiming(getenv("LIBCLANG_TIMING")),
94 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor7bb8af62010-10-12 00:50:20 +000095 ConcurrencyCheckValue(CheckUnlocked),
Douglas Gregora0734c52010-08-19 01:33:06 +000096 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +000097 ShouldCacheCodeCompletionResults(false),
98 NumTopLevelDeclsAtLastCompletionCache(0),
Douglas Gregor4740c452010-08-19 00:45:44 +000099 CacheCodeCompletionCoolDown(0),
100 UnsafeToFree(false) {
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000101 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +0000102 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000103 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
104 }
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000105}
Douglas Gregord03e8232010-04-05 21:10:19 +0000106
Daniel Dunbar764c0822009-12-01 09:51:01 +0000107ASTUnit::~ASTUnit() {
Douglas Gregor0c7c2f82010-03-05 21:16:25 +0000108 ConcurrencyCheckValue = CheckLocked;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000109 CleanTemporaryFiles();
Douglas Gregor4dde7492010-07-23 23:58:40 +0000110 if (!PreambleFile.empty())
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000111 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor3f4bea02010-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 Gregor96c04262010-07-27 14:52:07 +0000126
127 delete SavedMainFileBuffer;
Douglas Gregora0734c52010-08-19 01:33:06 +0000128 delete PreambleBuffer;
129
Douglas Gregor16896c42010-10-28 15:44:59 +0000130 ClearCachedCompletionResults();
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000131
132 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +0000133 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000134 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
135 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000136}
137
138void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor6cb5ba42010-02-18 23:35:40 +0000139 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
140 TemporaryFiles[I].eraseFromDisk();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000141 TemporaryFiles.clear();
Steve Naroff44cd60e2009-10-15 22:23:48 +0000142}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000143
Douglas Gregor39982192010-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 Gregor59cab552010-08-16 23:05:20 +0000147 const LangOptions &LangOpts,
148 bool &IsNestedNameSpecifier) {
149 IsNestedNameSpecifier = false;
150
Douglas Gregor39982192010-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 Gregor5e35d592010-09-14 23:59:36 +0000165 | (1 << (CodeCompletionContext::CCC_Type - 1))
166 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor39982192010-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 Gregor59cab552010-08-16 23:05:20 +0000181 // Part of the nested-name-specifier in C++0x.
Douglas Gregor39982192010-08-15 06:18:01 +0000182 if (LangOpts.CPlusPlus0x)
Douglas Gregor59cab552010-08-16 23:05:20 +0000183 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-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 Gregor39982192010-08-15 06:18:01 +0000190 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000191 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000192 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000193 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-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 Gregor5e35d592010-09-14 23:59:36 +0000198 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor39982192010-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 Gregor59cab552010-08-16 23:05:20 +0000203 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000204
205 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000206 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000207 }
208
209 return Contexts;
210}
211
Douglas Gregorb14904c2010-08-13 22:48:40 +0000212void ASTUnit::CacheCodeCompletionResults() {
213 if (!TheSema)
214 return;
215
Douglas Gregor16896c42010-10-28 15:44:59 +0000216 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000217 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000218
219 // Clear out the previous results.
220 ClearCachedCompletionResults();
221
222 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000223 typedef CodeCompletionResult Result;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000224 llvm::SmallVector<Result, 8> Results;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000225 TheSema->GatherGlobalCodeCompletions(CachedCompletionAllocator, Results);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000226
227 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000228 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
229
Douglas Gregorb14904c2010-08-13 22:48:40 +0000230 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
231 switch (Results[I].Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000232 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000233 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000234 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000235 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
236 CachedCompletionAllocator);
Douglas Gregor39982192010-08-15 06:18:01 +0000237 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregor59cab552010-08-16 23:05:20 +0000238 Ctx->getLangOptions(),
239 IsNestedNameSpecifier);
Douglas Gregor39982192010-08-15 06:18:01 +0000240 CachedResult.Priority = Results[I].Priority;
241 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000242 CachedResult.Availability = Results[I].Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000243
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000244 // Keep track of the type of this completion in an ASTContext-agnostic
245 // way.
Douglas Gregor24747402010-08-16 16:46:30 +0000246 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000247 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000248 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-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 Gregor24747402010-08-16 16:46:30 +0000266 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000267
Douglas Gregor39982192010-08-15 06:18:01 +0000268 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-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 Gregorc49f5b22010-08-23 18:23:48 +0000284 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000285 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
286 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor59cab552010-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 Gregorb278aaf2011-02-01 19:23:04 +0000298 CachedResult.Completion
299 = Results[I].CreateCodeCompletionString(*TheSema,
300 CachedCompletionAllocator);
Douglas Gregor59cab552010-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 Gregorb14904c2010-08-13 22:48:40 +0000308 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000309 }
310
Douglas Gregorb14904c2010-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 Gregorb278aaf2011-02-01 19:23:04 +0000319 CachedResult.Completion
320 = Results[I].CreateCodeCompletionString(*TheSema,
321 CachedCompletionAllocator);
Douglas Gregorb14904c2010-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 Gregor12785102010-08-24 20:21:13 +0000330 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorec00a262010-08-24 22:20:20 +0000331 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000332 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
333 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
334
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000335
Douglas Gregorb14904c2010-08-13 22:48:40 +0000336 CachedResult.Priority = Results[I].Priority;
337 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000338 CachedResult.Availability = Results[I].Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000339 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000340 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000341 CachedCompletionResults.push_back(CachedResult);
342 break;
343 }
344 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000345 }
346
Douglas Gregor2c8bd472010-08-17 00:40:40 +0000347 // Make a note of the state when we performed this caching.
348 NumTopLevelDeclsAtLastCompletionCache = top_level_size();
Douglas Gregorb14904c2010-08-13 22:48:40 +0000349}
350
351void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregorb14904c2010-08-13 22:48:40 +0000352 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000353 CachedCompletionTypes.clear();
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000354 CachedCompletionAllocator.Reset();
Douglas Gregorb14904c2010-08-13 22:48:40 +0000355}
356
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000357namespace {
358
Sebastian Redl2c499f62010-08-18 23:56:43 +0000359/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000360/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000361class ASTInfoCollector : public ASTReaderListener {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000362 LangOptions &LangOpt;
363 HeaderSearch &HSI;
364 std::string &TargetTriple;
365 std::string &Predefines;
366 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000367
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000368 unsigned NumHeaderInfos;
Mike Stump11289f42009-09-09 15:08:12 +0000369
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000370public:
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000371 ASTInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
Argyrios Kyrtzidisce379752009-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 Stump11289f42009-09-09 15:08:12 +0000376
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000377 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
378 LangOpt = LangOpts;
379 return false;
380 }
Mike Stump11289f42009-09-09 15:08:12 +0000381
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000382 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000383 TargetTriple = Triple;
384 return false;
385 }
Mike Stump11289f42009-09-09 15:08:12 +0000386
Sebastian Redl8b41f302010-07-14 23:29:55 +0000387 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000388 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000389 std::string &SuggestedPredefines) {
Sebastian Redl8b41f302010-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 Kyrtzidisce379752009-06-20 08:08:23 +0000394 return false;
395 }
Mike Stump11289f42009-09-09 15:08:12 +0000396
Douglas Gregora2f49452010-03-16 19:09:18 +0000397 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000398 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
399 }
Mike Stump11289f42009-09-09 15:08:12 +0000400
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000401 virtual void ReadCounter(unsigned Value) {
402 Counter = Value;
403 }
404};
405
Douglas Gregor33cdd812010-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 Gregor44c6ee72010-11-11 00:39:14 +0000427 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000428 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000429 {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000430 if (RequestCapture || Diags.getClient() == 0) {
431 PreviousClient = Diags.takeClient();
Douglas Gregor33cdd812010-02-18 18:08:43 +0000432 Diags.setClient(&Client);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000433 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000434 }
435
436 ~CaptureDroppedDiagnostics() {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000437 if (Diags.getClient() == &Client) {
438 Diags.takeClient();
439 Diags.setClient(PreviousClient);
440 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000441 }
442};
443
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000444} // anonymous namespace
445
Douglas Gregor33cdd812010-02-18 18:08:43 +0000446void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
447 const DiagnosticInfo &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000448 // Default implementation (Warnings/errors count).
449 DiagnosticClient::HandleDiagnostic(Level, Info);
450
Douglas Gregor33cdd812010-02-18 18:08:43 +0000451 StoredDiags.push_back(StoredDiagnostic(Level, Info));
452}
453
Steve Naroffc0683b92009-09-03 18:19:54 +0000454const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbara8a50932009-12-02 08:44:16 +0000455 return OriginalSourceFile;
Steve Naroffc0683b92009-09-03 18:19:54 +0000456}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000457
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000458const std::string &ASTUnit::getASTFileName() {
459 assert(isMainFileAST() && "Not an ASTUnit from an AST file!");
Sebastian Redl2c499f62010-08-18 23:56:43 +0000460 return static_cast<ASTReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroff44cd60e2009-10-15 22:23:48 +0000461}
462
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000463llvm::MemoryBuffer *ASTUnit::getBufferForFile(llvm::StringRef Filename,
Chris Lattner26b5c192010-11-23 09:19:42 +0000464 std::string *ErrorStr) {
Chris Lattner5159f612010-11-23 08:35:12 +0000465 assert(FileMgr);
Chris Lattner26b5c192010-11-23 09:19:42 +0000466 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000467}
468
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000469/// \brief Configure the diagnostics object for use with ASTUnit.
470void ASTUnit::ConfigureDiags(llvm::IntrusiveRefCntPtr<Diagnostic> &Diags,
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000471 const char **ArgBegin, const char **ArgEnd,
Douglas Gregor44c6ee72010-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 Gregor345c1bc2011-01-19 01:02:47 +0000480 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd- ArgBegin,
481 ArgBegin, Client);
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000482 } else if (CaptureDiagnostics) {
483 Diags->setClient(new StoredDiagnosticClient(AST.StoredDiagnostics));
484 }
485}
486
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000487ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Douglas Gregor7f95d262010-04-05 23:52:57 +0000488 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000489 const FileSystemOptions &FileSystemOpts,
Ted Kremenek8bcb1c62009-10-17 00:34:24 +0000490 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000491 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +0000492 unsigned NumRemappedFiles,
493 bool CaptureDiagnostics) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000494 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000495 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000496
Douglas Gregor16bef852009-10-16 20:01:17 +0000497 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000498 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000499 AST->Diagnostics = Diags;
Chris Lattner3f5a9ef2010-11-23 07:51:02 +0000500 AST->FileMgr.reset(new FileManager(FileSystemOpts));
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000501 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics(),
Chris Lattner5159f612010-11-23 08:35:12 +0000502 AST->getFileManager()));
503 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000504
Douglas Gregoraa98ed92010-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 Lattner5159f612010-11-23 08:35:12 +0000510 0);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000511 if (!FromFile) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000512 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000513 << RemappedFiles[I].first;
Douglas Gregor89a56c52010-02-27 01:32:48 +0000514 delete RemappedFiles[I].second;
Douglas Gregoraa98ed92010-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 Kyrtzidisce379752009-06-20 08:08:23 +0000524 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000525
Argyrios Kyrtzidisce379752009-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 Redl2c499f62010-08-18 23:56:43 +0000532 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000533
Sebastian Redl2c499f62010-08-18 23:56:43 +0000534 Reader.reset(new ASTReader(AST->getSourceManager(), AST->getFileManager(),
Chris Lattner5159f612010-11-23 08:35:12 +0000535 AST->getDiagnostics()));
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000536 Reader->setListener(new ASTInfoCollector(LangInfo, HeaderInfo, TargetTriple,
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000537 Predefines, Counter));
538
Sebastian Redl009e7f22010-10-05 16:15:19 +0000539 switch (Reader->ReadAST(Filename, ASTReader::MainFile)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000540 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000541 break;
Mike Stump11289f42009-09-09 15:08:12 +0000542
Sebastian Redl2c499f62010-08-18 23:56:43 +0000543 case ASTReader::Failure:
544 case ASTReader::IgnorePCH:
Douglas Gregord03e8232010-04-05 21:10:19 +0000545 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000546 return NULL;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000547 }
Mike Stump11289f42009-09-09 15:08:12 +0000548
Daniel Dunbara8a50932009-12-02 08:44:16 +0000549 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
550
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000551 // AST file loaded successfully. Now create the preprocessor.
Mike Stump11289f42009-09-09 15:08:12 +0000552
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000553 // Get information about the target being compiled for.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000554 //
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000555 // FIXME: This is broken, we should store the TargetOptions in the AST file.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000556 TargetOptions TargetOpts;
557 TargetOpts.ABI = "";
John McCall1c456c82010-08-22 06:43:33 +0000558 TargetOpts.CXXABI = "";
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000559 TargetOpts.CPU = "";
560 TargetOpts.Features.clear();
561 TargetOpts.Triple = TargetTriple;
Douglas Gregord03e8232010-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 Dunbar7cd285f2009-09-21 03:03:39 +0000566 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000567 Preprocessor &PP = *AST->PP.get();
568
Daniel Dunbarb7bbfdd2009-09-21 03:03:47 +0000569 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000570 PP.setCounterValue(Counter);
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000571 Reader->setPreprocessor(PP);
Mike Stump11289f42009-09-09 15:08:12 +0000572
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000573 // Create and initialize the ASTContext.
574
575 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000576 AST->getSourceManager(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000577 *AST->Target.get(),
578 PP.getIdentifierTable(),
579 PP.getSelectorTable(),
580 PP.getBuiltinInfo(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000581 /* size_reserve = */0));
582 ASTContext &Context = *AST->Ctx.get();
Mike Stump11289f42009-09-09 15:08:12 +0000583
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000584 Reader->InitializeContext(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000585
Sebastian Redl2c499f62010-08-18 23:56:43 +0000586 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000587 // source, so that declarations will be deserialized from the
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000588 // AST file as needed.
Sebastian Redl2c499f62010-08-18 23:56:43 +0000589 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000590 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000591 Context.setExternalSource(Source);
592
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000593 // Create an AST consumer, even though it isn't used.
594 AST->Consumer.reset(new ASTConsumer);
595
Sebastian Redl2c499f62010-08-18 23:56:43 +0000596 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-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 Stump11289f42009-09-09 15:08:12 +0000601 return AST.take();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000602}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000603
604namespace {
605
Daniel Dunbar644dca02009-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 Kremenekacc59c32010-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 Gregore9db88f2010-08-03 19:06:41 +0000621 Unit.addTopLevelDecl(D);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000622 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000623 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000624
625 // We're not interested in "interesting" decls.
626 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbar644dca02009-12-04 08:17:33 +0000627};
628
629class TopLevelDeclTrackerAction : public ASTFrontendAction {
630public:
631 ASTUnit &Unit;
632
Daniel Dunbar764c0822009-12-01 09:51:01 +0000633 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
634 llvm::StringRef InFile) {
Daniel Dunbar644dca02009-12-04 08:17:33 +0000635 return new TopLevelDeclTrackerConsumer(Unit);
Daniel Dunbar764c0822009-12-01 09:51:01 +0000636 }
637
638public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000639 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
640
Daniel Dunbar764c0822009-12-01 09:51:01 +0000641 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000642 virtual bool usesCompleteTranslationUnit() {
643 return Unit.isCompleteTranslationUnit();
644 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000645};
646
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000647class PrecompilePreambleConsumer : public PCHGenerator,
648 public ASTSerializationListener {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000649 ASTUnit &Unit;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000650 std::vector<Decl *> TopLevelDecls;
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000651
Douglas Gregor48c8cd32010-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 Gregore9db88f2010-08-03 19:06:41 +0000658 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor48c8cd32010-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 Gregore9db88f2010-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 Gregor48c8cd32010-08-03 08:14:03 +0000681 }
682 }
Douglas Gregorf88e35b2010-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 Gregor48c8cd32010-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 Gregor028d3e42010-08-09 20:45:32 +0000717 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000718};
719
Daniel Dunbar764c0822009-12-01 09:51:01 +0000720}
721
Douglas Gregoraa21cc42010-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 Gregor6481ef12010-07-24 00:38:13 +0000727bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor96c04262010-07-27 14:52:07 +0000728 delete SavedMainFileBuffer;
729 SavedMainFileBuffer = 0;
730
Douglas Gregora0734c52010-08-19 01:33:06 +0000731 if (!Invocation.get()) {
732 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000733 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000734 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000735
Daniel Dunbar764c0822009-12-01 09:51:01 +0000736 // Create the compiler instance to use for building the AST.
Daniel Dunbar7afbb8c2009-12-02 08:43:56 +0000737 CompilerInstance Clang;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000738 Clang.setInvocation(Invocation.take());
739 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
740
Douglas Gregor8e984da2010-08-04 16:47:14 +0000741 // Set up diagnostics, capturing any diagnostics that would
742 // otherwise be dropped.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000743 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +0000744
Daniel Dunbar764c0822009-12-01 09:51:01 +0000745 // Create the target instance.
Douglas Gregorffd6dc42011-01-27 18:02:58 +0000746 Clang.getTargetOpts().Features = TargetFeatures;
Daniel Dunbar764c0822009-12-01 09:51:01 +0000747 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
748 Clang.getTargetOpts()));
Douglas Gregora0734c52010-08-19 01:33:06 +0000749 if (!Clang.hasTarget()) {
750 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000751 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000752 }
753
Daniel Dunbar764c0822009-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 Gregoraa21cc42010-07-19 21:46:24 +0000759
Daniel Dunbar764c0822009-12-01 09:51:01 +0000760 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
761 "Invocation must have exactly one source file!");
Daniel Dunbar9b491e72010-06-07 23:22:09 +0000762 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +0000763 "FIXME: AST inputs not yet supported here!");
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000764 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
765 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +0000766
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000767 // Configure the various subsystems.
768 // FIXME: Should we retain the previous file manager?
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000769 FileSystemOpts = Clang.getFileSystemOpts();
Chris Lattner5159f612010-11-23 08:35:12 +0000770 FileMgr.reset(new FileManager(Clang.getFileSystemOpts()));
771 SourceMgr.reset(new SourceManager(getDiagnostics(), *FileMgr));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000772 TheSema.reset();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000773 Ctx.reset();
774 PP.reset();
775
776 // Clear out old caches and data.
777 TopLevelDecls.clear();
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000778 PreprocessedEntities.clear();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000779 CleanTemporaryFiles();
780 PreprocessedEntitiesByFile.clear();
Douglas Gregord9a30af2010-08-02 20:51:39 +0000781
Douglas Gregor7b02b582010-08-20 00:02:33 +0000782 if (!OverrideMainBuffer) {
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000783 StoredDiagnostics.erase(
784 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
785 StoredDiagnostics.end());
Douglas Gregor7b02b582010-08-20 00:02:33 +0000786 TopLevelDeclsInPreamble.clear();
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000787 PreprocessedEntitiesInPreamble.clear();
Douglas Gregor7b02b582010-08-20 00:02:33 +0000788 }
789
Daniel Dunbar764c0822009-12-01 09:51:01 +0000790 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000791 Clang.setFileManager(&getFileManager());
792
Daniel Dunbar764c0822009-12-01 09:51:01 +0000793 // Create the source manager.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000794 Clang.setSourceManager(&getSourceManager());
795
Douglas Gregor3f4bea02010-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 Gregor8e984da2010-08-04 16:47:14 +0000799 std::string PriorImplicitPCHInclude;
Douglas Gregor3f4bea02010-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 Gregor8e984da2010-08-04 16:47:14 +0000805 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000806 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000807 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +0000808
Douglas Gregord9a30af2010-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 Gregor7bb8af62010-10-12 00:50:20 +0000814 for (unsigned I = NumStoredDiagnosticsFromDriver,
815 N = StoredDiagnostics.size();
816 I < N; ++I) {
Douglas Gregord9a30af2010-08-02 20:51:39 +0000817 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
818 getSourceManager());
819 StoredDiagnostics[I].setLocation(Loc);
820 }
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000821
822 // Keep track of the override buffer;
823 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregor7b02b582010-08-20 00:02:33 +0000824 } else {
825 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
826 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000827 }
828
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000829 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
830 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbar644dca02009-12-04 08:17:33 +0000831 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbar86546382010-06-07 23:23:06 +0000832 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar764c0822009-12-01 09:51:01 +0000833 goto error;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000834
Daniel Dunbar644dca02009-12-04 08:17:33 +0000835 Act->Execute();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000836
Daniel Dunbard2f8be32009-12-01 21:57:33 +0000837 // Steal the created target, context, and preprocessor, and take back the
838 // source and file managers.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000839 TheSema.reset(Clang.takeSema());
840 Consumer.reset(Clang.takeASTConsumer());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000841 Ctx.reset(Clang.takeASTContext());
842 PP.reset(Clang.takePreprocessor());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000843 Clang.takeSourceManager();
844 Clang.takeFileManager();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000845 Target.reset(Clang.takeTarget());
846
Daniel Dunbar644dca02009-12-04 08:17:33 +0000847 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000848
849 // Remove the overridden buffer we used for the preamble.
Douglas Gregor8e984da2010-08-04 16:47:14 +0000850 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000851 PreprocessorOpts.eraseRemappedFile(
852 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor8e984da2010-08-04 16:47:14 +0000853 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
854 }
855
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000856 Invocation.reset(Clang.takeInvocation());
Douglas Gregoraca48a52010-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 Gregoraa21cc42010-07-19 21:46:24 +0000865 return false;
866
Daniel Dunbar764c0822009-12-01 09:51:01 +0000867error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000868 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +0000869 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000870 PreprocessorOpts.eraseRemappedFile(
871 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor8e984da2010-08-04 16:47:14 +0000872 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregora0734c52010-08-19 01:33:06 +0000873 delete OverrideMainBuffer;
Douglas Gregora3d3ba12010-10-06 21:11:08 +0000874 SavedMainFileBuffer = 0;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000875 }
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000876
Douglas Gregorefc46952010-10-12 16:25:54 +0000877 StoredDiagnostics.clear();
Daniel Dunbar764c0822009-12-01 09:51:01 +0000878 Clang.takeSourceManager();
879 Clang.takeFileManager();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000880 Invocation.reset(Clang.takeInvocation());
881 return true;
882}
883
Douglas Gregorbe2d8c62010-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 Gregor250ab1d2010-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 Gregorbe2d8c62010-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 Gregorce3449f2010-09-11 17:51:16 +0000902#ifdef LLVM_ON_WIN32
903 if (!TmpDir)
904 TmpDir = ::getenv("USERPROFILE");
905#endif
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000906 if (!TmpDir)
907 TmpDir = "/tmp";
908 llvm::sys::Path P(TmpDir);
Douglas Gregorce3449f2010-09-11 17:51:16 +0000909 P.createDirectoryOnDisk(true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000910 P.appendComponent("preamble");
Douglas Gregor20975b22010-08-11 13:06:56 +0000911 P.appendSuffix("pch");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000912 if (P.createTemporaryFileOnDisk())
913 return std::string();
914
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000915 return P.str();
916}
917
Douglas Gregor3f4bea02010-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 Gregor028d3e42010-08-09 20:45:32 +0000922ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
923 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000924 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner5159f612010-11-23 08:35:12 +0000925 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +0000926 CreatedBuffer = false;
927
Douglas Gregorbe2d8c62010-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 Gregor4dde7492010-07-23 23:58:40 +0000931 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregorbe2d8c62010-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 Gregor4dde7492010-07-23 23:58:40 +0000936 M = PreprocessorOpts.remapped_file_begin(),
937 E = PreprocessorOpts.remapped_file_end();
Douglas Gregorbe2d8c62010-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 Gregor4dde7492010-07-23 23:58:40 +0000944 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000945 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000946 CreatedBuffer = false;
947 }
948
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000949 Buffer = getBufferForFile(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000950 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000951 return std::make_pair((llvm::MemoryBuffer*)0,
952 std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000953 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-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 Gregor4dde7492010-07-23 23:58:40 +0000969 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000970 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000971 CreatedBuffer = false;
972 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000973
Douglas Gregor4dde7492010-07-23 23:58:40 +0000974 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000975 }
976 }
Douglas Gregor4dde7492010-07-23 23:58:40 +0000977 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000978 }
979
980 // If the main source file was not remapped, load it now.
981 if (!Buffer) {
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000982 Buffer = getBufferForFile(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000983 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000984 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000985
986 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000987 }
988
Douglas Gregor028d3e42010-08-09 20:45:32 +0000989 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000990}
991
Douglas Gregor6481ef12010-07-24 00:38:13 +0000992static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor6481ef12010-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 Gregor3f4bea02010-07-26 21:36:20 +00001000 ' ', NewSize - Old->getBufferSize() - 1);
1001 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor6481ef12010-07-24 00:38:13 +00001002
Douglas Gregor6481ef12010-07-24 00:38:13 +00001003 return Result;
1004}
1005
Douglas Gregor4dde7492010-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 Gregor028d3e42010-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 Gregor6481ef12010-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 Gregor028d3e42010-08-09 20:45:32 +00001026llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregorb97b6662010-08-20 00:59:43 +00001027 CompilerInvocation PreambleInvocation,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001028 bool AllowRebuild,
1029 unsigned MaxLines) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001030 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
1031 PreprocessorOptions &PreprocessorOpts
1032 = PreambleInvocation.getPreprocessorOpts();
1033
1034 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001035 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor028d3e42010-08-09 20:45:32 +00001036 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001037
Douglas Gregor3edb1672010-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 Gregor3f4bea02010-07-26 21:36:20 +00001043 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-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 Gregor15ba0b32010-07-30 20:58:08 +00001048 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001049 PreambleFile.clear();
1050 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001051
1052 // The next time we actually see a preamble, precompile it.
1053 PreambleRebuildCounter = 1;
Douglas Gregor6481ef12010-07-24 00:38:13 +00001054 return 0;
Douglas Gregor4dde7492010-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 Gregor3f4bea02010-07-26 21:36:20 +00001062 if (Preamble.size() == NewPreamble.second.first &&
1063 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregorf5275a82010-07-24 00:42:07 +00001064 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor4dde7492010-07-23 23:58:40 +00001065 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001066 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001067 // The preamble has not changed. We may be able to re-use the precompiled
1068 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001069
Douglas Gregor0e119552010-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 Gregor6481ef12010-07-24 00:38:13 +00001088
Douglas Gregor0e119552010-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 Gregord9a30af2010-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 Gregor36e3b5c2010-10-11 21:37:58 +00001133 // FIXME: This won't catch any #pragma push warning changes that
1134 // have occurred in the preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001135 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001136 ProcessWarningOptions(getDiagnostics(),
1137 PreambleInvocation.getDiagnosticOpts());
Douglas Gregord9a30af2010-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 Gregor0e119552010-07-31 00:40:00 +00001146 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor0e119552010-07-31 00:40:00 +00001147 PreambleReservedSize,
1148 FrontendOpts.Inputs[0].second);
1149 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001150 }
Douglas Gregor028d3e42010-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 Gregorbb6a8812010-10-08 04:03:57 +00001156
Douglas Gregor4dde7492010-07-23 23:58:40 +00001157 // We can't reuse the previously-computed preamble. Build a new one.
1158 Preamble.clear();
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001159 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001160 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-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 Gregorbb420ab2010-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 Gregore10f0e52010-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 Gregor4dde7492010-07-23 23:58:40 +00001184 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001185 SimpleTimer PreambleTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001186 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregorbe2d8c62010-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 Gregor4dde7492010-07-23 23:58:40 +00001191 // grows.
1192 PreambleReservedSize = NewPreamble.first->getBufferSize();
1193 if (PreambleReservedSize < 4096)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001194 PreambleReservedSize = 8191;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001195 else
Douglas Gregor4dde7492010-07-23 23:58:40 +00001196 PreambleReservedSize *= 2;
1197
Douglas Gregord9a30af2010-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 Gregora0734c52010-08-19 01:33:06 +00001205 delete PreambleBuffer;
1206 PreambleBuffer
Douglas Gregor4dde7492010-07-23 23:58:40 +00001207 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001208 FrontendOpts.Inputs[0].second);
1209 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor4dde7492010-07-23 23:58:40 +00001210 NewPreamble.first->getBufferStart(), Preamble.size());
1211 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001212 ' ', PreambleReservedSize - Preamble.size() - 1);
1213 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001214
1215 // Remap the main source file to the preamble buffer.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001216 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-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 Gregor9e136b52010-10-01 01:05:22 +00001221 FrontendOpts.ChainedPCH = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001222 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001223 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001224 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1225 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-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 Gregor8e984da2010-08-04 16:47:14 +00001232 // Set up diagnostics, capturing all of the diagnostics produced.
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001233 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001234
1235 // Create the target instance.
Douglas Gregorffd6dc42011-01-27 18:02:58 +00001236 Clang.getTargetOpts().Features = TargetFeatures;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001237 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1238 Clang.getTargetOpts()));
1239 if (!Clang.hasTarget()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001240 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1241 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001242 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001243 PreprocessorOpts.eraseRemappedFile(
1244 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001245 return 0;
Douglas Gregorbe2d8c62010-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 Gregorbb6a8812010-10-08 04:03:57 +00001262 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001263 ProcessWarningOptions(getDiagnostics(), Clang.getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001264 StoredDiagnostics.erase(
1265 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1266 StoredDiagnostics.end());
Douglas Gregore9db88f2010-08-03 19:06:41 +00001267 TopLevelDecls.clear();
1268 TopLevelDeclsInPreamble.clear();
Douglas Gregorf88e35b2010-11-30 06:16:57 +00001269 PreprocessedEntities.clear();
1270 PreprocessedEntitiesInPreamble.clear();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001271
1272 // Create a file manager object to provide access to and cache the filesystem.
Chris Lattner3f5a9ef2010-11-23 07:51:02 +00001273 Clang.setFileManager(new FileManager(Clang.getFileSystemOpts()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001274
1275 // Create the source manager.
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001276 Clang.setSourceManager(new SourceManager(getDiagnostics(),
Chris Lattner5159f612010-11-23 08:35:12 +00001277 Clang.getFileManager()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001278
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001279 llvm::OwningPtr<PrecompilePreambleAction> Act;
1280 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001281 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1282 Clang.getFrontendOpts().Inputs[0].first)) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001283 Clang.takeInvocation();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001284 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1285 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001286 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001287 PreprocessorOpts.eraseRemappedFile(
1288 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001289 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001290 }
1291
1292 Act->Execute();
1293 Act->EndSourceFile();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001294 Clang.takeInvocation();
1295
Douglas Gregore9db88f2010-08-03 19:06:41 +00001296 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor4dde7492010-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 Gregora6f74e22010-09-27 16:43:25 +00001299 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor4dde7492010-07-23 23:58:40 +00001300 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1301 Preamble.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001302 TopLevelDeclsInPreamble.clear();
Douglas Gregorf88e35b2010-11-30 06:16:57 +00001303 PreprocessedEntities.clear();
1304 PreprocessedEntitiesInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001305 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001306 PreprocessorOpts.eraseRemappedFile(
1307 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001308 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001309 }
1310
1311 // Keep track of the preamble we precompiled.
1312 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregord9a30af2010-08-02 20:51:39 +00001313 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1314 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-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 Gregorbb420ab2010-08-04 05:53:38 +00001334 PreambleRebuildCounter = 1;
Douglas Gregora0734c52010-08-19 01:33:06 +00001335 PreprocessorOpts.eraseRemappedFile(
1336 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001337 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001338 PreambleReservedSize,
1339 FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001340}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001341
Douglas Gregore9db88f2010-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 Gregorf88e35b2010-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
1371 = External->ReadPreprocessedEntity(PreprocessedEntitiesInPreamble[I]))
1372 PreprocessedEntities.push_back(PE);
1373 }
1374
1375 if (PreprocessedEntities.empty())
1376 return;
1377
1378 PreprocessedEntities.insert(PreprocessedEntities.end(),
1379 PPRec->begin(true), PPRec->end(true));
1380}
1381
1382ASTUnit::pp_entity_iterator ASTUnit::pp_entity_begin() {
1383 if (!PreprocessedEntitiesInPreamble.empty() &&
1384 PreprocessedEntities.empty())
1385 RealizePreprocessedEntitiesFromPreamble();
1386
1387 if (PreprocessedEntities.empty())
1388 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
1389 return PPRec->begin(true);
1390
1391 return PreprocessedEntities.begin();
1392}
1393
1394ASTUnit::pp_entity_iterator ASTUnit::pp_entity_end() {
1395 if (!PreprocessedEntitiesInPreamble.empty() &&
1396 PreprocessedEntities.empty())
1397 RealizePreprocessedEntitiesFromPreamble();
1398
1399 if (PreprocessedEntities.empty())
1400 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
1401 return PPRec->end(true);
1402
1403 return PreprocessedEntities.end();
1404}
1405
Douglas Gregore9db88f2010-08-03 19:06:41 +00001406unsigned ASTUnit::getMaxPCHLevel() const {
1407 if (!getOnlyLocalDecls())
1408 return Decl::MaxPCHLevel;
1409
Sebastian Redl009e7f22010-10-05 16:15:19 +00001410 return 0;
Douglas Gregore9db88f2010-08-03 19:06:41 +00001411}
1412
Douglas Gregor16896c42010-10-28 15:44:59 +00001413llvm::StringRef ASTUnit::getMainFileName() const {
1414 return Invocation->getFrontendOpts().Inputs[0].second;
1415}
1416
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001417bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1418 if (!Invocation)
1419 return true;
1420
1421 // We'll manage file buffers ourselves.
1422 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1423 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001424 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001425
Douglas Gregorffd6dc42011-01-27 18:02:58 +00001426 // Save the target features.
1427 TargetFeatures = Invocation->getTargetOpts().Features;
1428
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001429 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorf5a18542010-10-27 17:24:53 +00001430 if (PrecompilePreamble) {
Douglas Gregorc6592922010-11-15 23:00:34 +00001431 PreambleRebuildCounter = 2;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001432 OverrideMainBuffer
1433 = getMainBufferWithPrecompiledPreamble(*Invocation);
1434 }
1435
Douglas Gregor16896c42010-10-28 15:44:59 +00001436 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001437 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001438
Douglas Gregor16896c42010-10-28 15:44:59 +00001439 return Parse(OverrideMainBuffer);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001440}
1441
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001442ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1443 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1444 bool OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001445 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001446 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001447 bool CompleteTranslationUnit,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001448 bool CacheCodeCompletionResults) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001449 // Create the AST unit.
1450 llvm::OwningPtr<ASTUnit> AST;
1451 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001452 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001453 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001454 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001455 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001456 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001457 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregorc6592922010-11-15 23:00:34 +00001458 AST->CacheCodeCompletionCoolDown = 1;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001459 AST->Invocation.reset(CI);
1460
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001461 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar764c0822009-12-01 09:51:01 +00001462}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001463
1464ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1465 const char **ArgEnd,
Douglas Gregor7f95d262010-04-05 23:52:57 +00001466 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar8d4a2022009-12-13 03:46:13 +00001467 llvm::StringRef ResourceFilesPath,
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001468 bool OnlyLocalDecls,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001469 bool CaptureDiagnostics,
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001470 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001471 unsigned NumRemappedFiles,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001472 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001473 bool CompleteTranslationUnit,
Douglas Gregorf5a18542010-10-27 17:24:53 +00001474 bool CacheCodeCompletionResults,
1475 bool CXXPrecompilePreamble,
1476 bool CXXChainedPCH) {
Douglas Gregor7f95d262010-04-05 23:52:57 +00001477 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00001478 // No diagnostics engine was provided, so create our own diagnostics object
1479 // with the default options.
1480 DiagnosticOptions DiagOpts;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001481 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1482 ArgBegin);
Douglas Gregord03e8232010-04-05 21:10:19 +00001483 }
1484
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001485 llvm::SmallVector<const char *, 16> Args;
1486 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1487 Args.insert(Args.end(), ArgBegin, ArgEnd);
1488
1489 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1490 // also want to force it to use clang.
1491 Args.push_back("-fsyntax-only");
1492
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001493 llvm::SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1494
1495 llvm::OwningPtr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001496
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001497 {
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001498 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001499 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001500
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001501 // FIXME: We shouldn't have to pass in the path info.
1502 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
1503 "a.out", false, false, *Diags);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001504
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001505 // Don't check that inputs exist, they have been remapped.
1506 TheDriver.setCheckInputsExist(false);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001507
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001508 llvm::OwningPtr<driver::Compilation> C(
1509 TheDriver.BuildCompilation(Args.size(), Args.data()));
1510
1511 // We expect to get back exactly one command job, if we didn't something
1512 // failed.
1513 const driver::JobList &Jobs = C->getJobs();
1514 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1515 llvm::SmallString<256> Msg;
1516 llvm::raw_svector_ostream OS(Msg);
1517 C->PrintJob(OS, C->getJobs(), "; ", true);
1518 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
1519 return 0;
1520 }
1521
1522 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1523 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
1524 Diags->Report(diag::err_fe_expected_clang_command);
1525 return 0;
1526 }
1527
1528 const driver::ArgStringList &CCArgs = Cmd->getArguments();
1529 CI.reset(new CompilerInvocation);
1530 CompilerInvocation::CreateFromArgs(*CI,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001531 const_cast<const char **>(CCArgs.data()),
1532 const_cast<const char **>(CCArgs.data()) +
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001533 CCArgs.size(),
1534 *Diags);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001535 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001536
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001537 // Override any files that need remapping
1538 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001539 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbar19511922010-02-16 01:55:04 +00001540 RemappedFiles[I].second);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001541
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001542 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001543 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001544
Douglas Gregorf5a18542010-10-27 17:24:53 +00001545 // Check whether we should precompile the preamble and/or use chained PCH.
1546 // FIXME: This is a temporary hack while we debug C++ chained PCH.
1547 if (CI->getLangOpts().CPlusPlus) {
1548 PrecompilePreamble = PrecompilePreamble && CXXPrecompilePreamble;
1549
1550 if (PrecompilePreamble && !CXXChainedPCH &&
1551 !CI->getPreprocessorOpts().ImplicitPCHInclude.empty())
1552 PrecompilePreamble = false;
1553 }
1554
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001555 // Create the AST unit.
1556 llvm::OwningPtr<ASTUnit> AST;
1557 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001558 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001559 AST->Diagnostics = Diags;
Chris Lattner5159f612010-11-23 08:35:12 +00001560
1561 AST->FileMgr.reset(new FileManager(FileSystemOptions()));
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001562 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001563 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001564 AST->CompleteTranslationUnit = CompleteTranslationUnit;
1565 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregorc6592922010-11-15 23:00:34 +00001566 AST->CacheCodeCompletionCoolDown = 1;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001567 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1568 AST->NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1569 AST->StoredDiagnostics.swap(StoredDiagnostics);
1570 AST->Invocation.reset(CI.take());
Chris Lattner5159f612010-11-23 08:35:12 +00001571 return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001572}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001573
1574bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1575 if (!Invocation.get())
1576 return true;
1577
Douglas Gregor16896c42010-10-28 15:44:59 +00001578 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001579 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00001580
Douglas Gregor0e119552010-07-31 00:40:00 +00001581 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00001582 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1583 for (PreprocessorOptions::remapped_file_buffer_iterator
1584 R = PPOpts.remapped_file_buffer_begin(),
1585 REnd = PPOpts.remapped_file_buffer_end();
1586 R != REnd;
1587 ++R) {
1588 delete R->second;
1589 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001590 Invocation->getPreprocessorOpts().clearRemappedFiles();
1591 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1592 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1593 RemappedFiles[I].second);
1594
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001595 // If we have a preamble file lying around, or if we might try to
1596 // build a precompiled preamble, do so now.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001597 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001598 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregorb97b6662010-08-20 00:59:43 +00001599 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001600
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001601 // Clear out the diagnostics state.
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001602 if (!OverrideMainBuffer) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001603 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001604 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1605 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001606
Douglas Gregor4dde7492010-07-23 23:58:40 +00001607 // Parse the sources
Douglas Gregor6481ef12010-07-24 00:38:13 +00001608 bool Result = Parse(OverrideMainBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001609 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001610}
Douglas Gregor8e984da2010-08-04 16:47:14 +00001611
Douglas Gregorb14904c2010-08-13 22:48:40 +00001612//----------------------------------------------------------------------------//
1613// Code completion
1614//----------------------------------------------------------------------------//
1615
1616namespace {
1617 /// \brief Code completion consumer that combines the cached code-completion
1618 /// results from an ASTUnit with the code-completion results provided to it,
1619 /// then passes the result on to
1620 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1621 unsigned NormalContexts;
1622 ASTUnit &AST;
1623 CodeCompleteConsumer &Next;
1624
1625 public:
1626 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor39982192010-08-15 06:18:01 +00001627 bool IncludeMacros, bool IncludeCodePatterns,
1628 bool IncludeGlobals)
1629 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001630 Next.isOutputBinary()), AST(AST), Next(Next)
1631 {
1632 // Compute the set of contexts in which we will look when we don't have
1633 // any information about the specific context.
1634 NormalContexts
1635 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
1636 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
1637 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1638 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1639 | (1 << (CodeCompletionContext::CCC_Statement - 1))
1640 | (1 << (CodeCompletionContext::CCC_Expression - 1))
1641 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1642 | (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +00001643 | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
Douglas Gregor0ac41382010-09-23 23:01:17 +00001644 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
1645 | (1 << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor5e35d592010-09-14 23:59:36 +00001646
Douglas Gregorb14904c2010-08-13 22:48:40 +00001647 if (AST.getASTContext().getLangOptions().CPlusPlus)
1648 NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1))
1649 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
1650 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
1651 }
1652
1653 virtual void ProcessCodeCompleteResults(Sema &S,
1654 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001655 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001656 unsigned NumResults);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001657
1658 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1659 OverloadCandidate *Candidates,
1660 unsigned NumCandidates) {
1661 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1662 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001663
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00001664 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001665 return Next.getAllocator();
1666 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00001667 };
1668}
Douglas Gregord46cf182010-08-16 20:01:48 +00001669
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001670/// \brief Helper function that computes which global names are hidden by the
1671/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00001672static void CalculateHiddenNames(const CodeCompletionContext &Context,
1673 CodeCompletionResult *Results,
1674 unsigned NumResults,
1675 ASTContext &Ctx,
1676 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001677 bool OnlyTagNames = false;
1678 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00001679 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001680 case CodeCompletionContext::CCC_TopLevel:
1681 case CodeCompletionContext::CCC_ObjCInterface:
1682 case CodeCompletionContext::CCC_ObjCImplementation:
1683 case CodeCompletionContext::CCC_ObjCIvarList:
1684 case CodeCompletionContext::CCC_ClassStructUnion:
1685 case CodeCompletionContext::CCC_Statement:
1686 case CodeCompletionContext::CCC_Expression:
1687 case CodeCompletionContext::CCC_ObjCMessageReceiver:
1688 case CodeCompletionContext::CCC_MemberAccess:
1689 case CodeCompletionContext::CCC_Namespace:
1690 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00001691 case CodeCompletionContext::CCC_Name:
1692 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001693 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001694 break;
1695
1696 case CodeCompletionContext::CCC_EnumTag:
1697 case CodeCompletionContext::CCC_UnionTag:
1698 case CodeCompletionContext::CCC_ClassOrStructTag:
1699 OnlyTagNames = true;
1700 break;
1701
1702 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00001703 case CodeCompletionContext::CCC_MacroName:
1704 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00001705 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001706 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00001707 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00001708 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00001709 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00001710 case CodeCompletionContext::CCC_Other:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001711 // We're looking for nothing, or we're looking for names that cannot
1712 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001713 return;
1714 }
1715
John McCall276321a2010-08-25 06:19:51 +00001716 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001717 for (unsigned I = 0; I != NumResults; ++I) {
1718 if (Results[I].Kind != Result::RK_Declaration)
1719 continue;
1720
1721 unsigned IDNS
1722 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1723
1724 bool Hiding = false;
1725 if (OnlyTagNames)
1726 Hiding = (IDNS & Decl::IDNS_Tag);
1727 else {
1728 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00001729 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1730 Decl::IDNS_NonMemberOperator);
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001731 if (Ctx.getLangOptions().CPlusPlus)
1732 HiddenIDNS |= Decl::IDNS_Tag;
1733 Hiding = (IDNS & HiddenIDNS);
1734 }
1735
1736 if (!Hiding)
1737 continue;
1738
1739 DeclarationName Name = Results[I].Declaration->getDeclName();
1740 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1741 HiddenNames.insert(Identifier->getName());
1742 else
1743 HiddenNames.insert(Name.getAsString());
1744 }
1745}
1746
1747
Douglas Gregord46cf182010-08-16 20:01:48 +00001748void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1749 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001750 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001751 unsigned NumResults) {
1752 // Merge the results we were given with the results we cached.
1753 bool AddedResult = false;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001754 unsigned InContexts
Douglas Gregor0ac41382010-09-23 23:01:17 +00001755 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001756 : (1 << (Context.getKind() - 1)));
1757
1758 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00001759 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall276321a2010-08-25 06:19:51 +00001760 typedef CodeCompletionResult Result;
Douglas Gregord46cf182010-08-16 20:01:48 +00001761 llvm::SmallVector<Result, 8> AllResults;
1762 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00001763 C = AST.cached_completion_begin(),
1764 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00001765 C != CEnd; ++C) {
1766 // If the context we are in matches any of the contexts we are
1767 // interested in, we'll add this result.
1768 if ((C->ShowInContexts & InContexts) == 0)
1769 continue;
1770
1771 // If we haven't added any results previously, do so now.
1772 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001773 CalculateHiddenNames(Context, Results, NumResults, S.Context,
1774 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00001775 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1776 AddedResult = true;
1777 }
1778
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001779 // Determine whether this global completion result is hidden by a local
1780 // completion result. If so, skip it.
1781 if (C->Kind != CXCursor_MacroDefinition &&
1782 HiddenNames.count(C->Completion->getTypedText()))
1783 continue;
1784
Douglas Gregord46cf182010-08-16 20:01:48 +00001785 // Adjust priority based on similar type classes.
1786 unsigned Priority = C->Priority;
Douglas Gregor8850aa32010-08-25 18:03:13 +00001787 CXCursorKind CursorKind = C->Kind;
Douglas Gregor12785102010-08-24 20:21:13 +00001788 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00001789 if (!Context.getPreferredType().isNull()) {
1790 if (C->Kind == CXCursor_MacroDefinition) {
1791 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00001792 S.getLangOptions(),
Douglas Gregor12785102010-08-24 20:21:13 +00001793 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00001794 } else if (C->Type) {
1795 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00001796 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00001797 Context.getPreferredType().getUnqualifiedType());
1798 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
1799 if (ExpectedSTC == C->TypeClass) {
1800 // We know this type is similar; check for an exact match.
1801 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00001802 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00001803 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00001804 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00001805 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
1806 Priority /= CCF_ExactTypeMatch;
1807 else
1808 Priority /= CCF_SimilarTypeMatch;
1809 }
1810 }
1811 }
1812
Douglas Gregor12785102010-08-24 20:21:13 +00001813 // Adjust the completion string, if required.
1814 if (C->Kind == CXCursor_MacroDefinition &&
1815 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
1816 // Create a new code-completion string that just contains the
1817 // macro name, without its arguments.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001818 CodeCompletionBuilder Builder(getAllocator(), CCP_CodePattern,
1819 C->Availability);
1820 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00001821 CursorKind = CXCursor_NotImplemented;
1822 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001823 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00001824 }
1825
Douglas Gregor8850aa32010-08-25 18:03:13 +00001826 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregorf757a122010-08-23 23:00:57 +00001827 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00001828 }
1829
1830 // If we did not add any cached completion results, just forward the
1831 // results we were given to the next consumer.
1832 if (!AddedResult) {
1833 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
1834 return;
1835 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00001836
Douglas Gregord46cf182010-08-16 20:01:48 +00001837 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
1838 AllResults.size());
1839}
1840
1841
1842
Douglas Gregor8e984da2010-08-04 16:47:14 +00001843void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
1844 RemappedFile *RemappedFiles,
1845 unsigned NumRemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00001846 bool IncludeMacros,
1847 bool IncludeCodePatterns,
Douglas Gregor8e984da2010-08-04 16:47:14 +00001848 CodeCompleteConsumer &Consumer,
1849 Diagnostic &Diag, LangOptions &LangOpts,
1850 SourceManager &SourceMgr, FileManager &FileMgr,
Douglas Gregorb97b6662010-08-20 00:59:43 +00001851 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
1852 llvm::SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001853 if (!Invocation.get())
1854 return;
1855
Douglas Gregor16896c42010-10-28 15:44:59 +00001856 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001857 CompletionTimer.setOutput("Code completion @ " + File + ":" +
1858 llvm::Twine(Line) + ":" + llvm::Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00001859
Douglas Gregor8e984da2010-08-04 16:47:14 +00001860 CompilerInvocation CCInvocation(*Invocation);
1861 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
1862 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00001863
Douglas Gregorb14904c2010-08-13 22:48:40 +00001864 FrontendOpts.ShowMacrosInCodeCompletion
1865 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorb68bc592010-08-05 09:09:23 +00001866 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor39982192010-08-15 06:18:01 +00001867 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
1868 = CachedCompletionResults.empty();
Douglas Gregor8e984da2010-08-04 16:47:14 +00001869 FrontendOpts.CodeCompletionAt.FileName = File;
1870 FrontendOpts.CodeCompletionAt.Line = Line;
1871 FrontendOpts.CodeCompletionAt.Column = Column;
1872
1873 // Set the language options appropriately.
1874 LangOpts = CCInvocation.getLangOpts();
1875
1876 CompilerInstance Clang;
1877 Clang.setInvocation(&CCInvocation);
1878 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1879
1880 // Set up diagnostics, capturing any diagnostics produced.
1881 Clang.setDiagnostics(&Diag);
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001882 ProcessWarningOptions(Diag, CCInvocation.getDiagnosticOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00001883 CaptureDroppedDiagnostics Capture(true,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001884 Clang.getDiagnostics(),
Douglas Gregor8e984da2010-08-04 16:47:14 +00001885 StoredDiagnostics);
Douglas Gregor8e984da2010-08-04 16:47:14 +00001886
1887 // Create the target instance.
Douglas Gregorffd6dc42011-01-27 18:02:58 +00001888 Clang.getTargetOpts().Features = TargetFeatures;
Douglas Gregor8e984da2010-08-04 16:47:14 +00001889 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1890 Clang.getTargetOpts()));
1891 if (!Clang.hasTarget()) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001892 Clang.takeInvocation();
Douglas Gregor2dd19f12010-08-18 22:29:43 +00001893 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00001894 }
1895
1896 // Inform the target of the language options.
1897 //
1898 // FIXME: We shouldn't need to do this, the target should be immutable once
1899 // created. This complexity should be lifted elsewhere.
1900 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1901
1902 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1903 "Invocation must have exactly one source file!");
1904 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1905 "FIXME: AST inputs not yet supported here!");
1906 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1907 "IR inputs not support here!");
1908
1909
1910 // Use the source and file managers that we were given.
1911 Clang.setFileManager(&FileMgr);
1912 Clang.setSourceManager(&SourceMgr);
1913
1914 // Remap files.
1915 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00001916 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregorb97b6662010-08-20 00:59:43 +00001917 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001918 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
1919 RemappedFiles[I].second);
Douglas Gregorb97b6662010-08-20 00:59:43 +00001920 OwnedBuffers.push_back(RemappedFiles[I].second);
1921 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00001922
Douglas Gregorb14904c2010-08-13 22:48:40 +00001923 // Use the code completion consumer we were given, but adding any cached
1924 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00001925 AugmentedCodeCompleteConsumer *AugmentedConsumer
1926 = new AugmentedCodeCompleteConsumer(*this, Consumer,
1927 FrontendOpts.ShowMacrosInCodeCompletion,
1928 FrontendOpts.ShowCodePatternsInCodeCompletion,
1929 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
1930 Clang.setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00001931
Douglas Gregor028d3e42010-08-09 20:45:32 +00001932 // If we have a precompiled preamble, try to use it. We only allow
1933 // the use of the precompiled preamble if we're if the completion
1934 // point is within the main file, after the end of the precompiled
1935 // preamble.
1936 llvm::MemoryBuffer *OverrideMainBuffer = 0;
1937 if (!PreambleFile.empty()) {
1938 using llvm::sys::FileStatus;
1939 llvm::sys::PathWithStatus CompleteFilePath(File);
1940 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
1941 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
1942 if (const FileStatus *MainStatus = MainPath.getFileStatus())
1943 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
Douglas Gregorb97b6662010-08-20 00:59:43 +00001944 OverrideMainBuffer
Douglas Gregor8e817b62010-08-25 18:04:15 +00001945 = getMainBufferWithPrecompiledPreamble(CCInvocation, false,
1946 Line - 1);
Douglas Gregor028d3e42010-08-09 20:45:32 +00001947 }
1948
1949 // If the main file has been overridden due to the use of a preamble,
1950 // make that override happen and introduce the preamble.
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001951 StoredDiagnostics.insert(StoredDiagnostics.end(),
1952 this->StoredDiagnostics.begin(),
1953 this->StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver);
Douglas Gregor028d3e42010-08-09 20:45:32 +00001954 if (OverrideMainBuffer) {
1955 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1956 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1957 PreprocessorOpts.PrecompiledPreambleBytes.second
1958 = PreambleEndsAtStartOfLine;
1959 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
1960 PreprocessorOpts.DisablePCHValidation = true;
1961
1962 // The stored diagnostics have the old source manager. Copy them
1963 // to our output set of stored diagnostics, updating the source
1964 // manager to the one we were given.
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001965 for (unsigned I = NumStoredDiagnosticsFromDriver,
1966 N = this->StoredDiagnostics.size();
1967 I < N; ++I) {
Douglas Gregor028d3e42010-08-09 20:45:32 +00001968 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
1969 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
1970 StoredDiagnostics[I].setLocation(Loc);
1971 }
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001972
Douglas Gregorb97b6662010-08-20 00:59:43 +00001973 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001974 } else {
1975 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1976 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001977 }
1978
Douglas Gregor8e984da2010-08-04 16:47:14 +00001979 llvm::OwningPtr<SyntaxOnlyAction> Act;
1980 Act.reset(new SyntaxOnlyAction);
1981 if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1982 Clang.getFrontendOpts().Inputs[0].first)) {
1983 Act->Execute();
1984 Act->EndSourceFile();
1985 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001986
Douglas Gregor8e984da2010-08-04 16:47:14 +00001987 // Steal back our resources.
1988 Clang.takeFileManager();
1989 Clang.takeSourceManager();
1990 Clang.takeInvocation();
Douglas Gregor8e984da2010-08-04 16:47:14 +00001991}
Douglas Gregore9386682010-08-13 05:36:37 +00001992
1993bool ASTUnit::Save(llvm::StringRef File) {
1994 if (getDiagnostics().hasErrorOccurred())
1995 return true;
1996
1997 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
1998 // unconditionally create a stat cache when we parse the file?
1999 std::string ErrorInfo;
Benjamin Kramer340045b2010-08-15 16:54:31 +00002000 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo,
2001 llvm::raw_fd_ostream::F_Binary);
Douglas Gregore9386682010-08-13 05:36:37 +00002002 if (!ErrorInfo.empty() || Out.has_error())
2003 return true;
2004
2005 std::vector<unsigned char> Buffer;
2006 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002007 ASTWriter Writer(Stream);
2008 Writer.WriteAST(getSema(), 0, 0);
Douglas Gregore9386682010-08-13 05:36:37 +00002009
2010 // Write the generated bitstream to "Out".
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002011 if (!Buffer.empty())
2012 Out.write((char *)&Buffer.front(), Buffer.size());
Douglas Gregore9386682010-08-13 05:36:37 +00002013 Out.close();
2014 return Out.has_error();
2015}