blob: a56fefc69f10d4a51d91bc3b7cda14fcda2f8cc1 [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 Gregordf7a79a2011-02-16 18:16:54 +000037#include "llvm/ADT/StringExtras.h"
Douglas Gregor40a5a7d2010-08-16 23:08:34 +000038#include "llvm/ADT/StringSet.h"
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +000039#include "llvm/Support/Atomic.h"
Douglas Gregoraa98ed92010-01-23 00:14:00 +000040#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000041#include "llvm/Support/Host.h"
42#include "llvm/Support/Path.h"
Douglas Gregor028d3e42010-08-09 20:45:32 +000043#include "llvm/Support/raw_ostream.h"
Douglas Gregor15ba0b32010-07-30 20:58:08 +000044#include "llvm/Support/Timer.h"
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000045#include <cstdlib>
Zhongxing Xu318e4032010-07-23 02:15:08 +000046#include <cstdio>
Douglas Gregor0e119552010-07-31 00:40:00 +000047#include <sys/stat.h>
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000048using namespace clang;
49
Douglas Gregor16896c42010-10-28 15:44:59 +000050using llvm::TimeRecord;
51
52namespace {
53 class SimpleTimer {
54 bool WantTiming;
55 TimeRecord Start;
56 std::string Output;
57
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000058 public:
Douglas Gregor1cbdd952010-11-01 13:48:43 +000059 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor16896c42010-10-28 15:44:59 +000060 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000061 Start = TimeRecord::getCurrentTime();
Douglas Gregor16896c42010-10-28 15:44:59 +000062 }
63
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000064 void setOutput(const llvm::Twine &Output) {
Douglas Gregor16896c42010-10-28 15:44:59 +000065 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000066 this->Output = Output.str();
Douglas Gregor16896c42010-10-28 15:44:59 +000067 }
68
Douglas Gregor16896c42010-10-28 15:44:59 +000069 ~SimpleTimer() {
70 if (WantTiming) {
71 TimeRecord Elapsed = TimeRecord::getCurrentTime();
72 Elapsed -= Start;
73 llvm::errs() << Output << ':';
74 Elapsed.print(Elapsed, llvm::errs());
75 llvm::errs() << '\n';
76 }
77 }
78 };
79}
80
Douglas Gregorbb420ab2010-08-04 05:53:38 +000081/// \brief After failing to build a precompiled preamble (due to
82/// errors in the source that occurs in the preamble), the number of
83/// reparses during which we'll skip even trying to precompile the
84/// preamble.
85const unsigned DefaultPreambleRebuildInterval = 5;
86
Douglas Gregor68dbaea2010-11-17 00:13:31 +000087/// \brief Tracks the number of ASTUnit objects that are currently active.
88///
89/// Used for debugging purposes only.
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +000090static llvm::sys::cas_flag ActiveASTUnitObjects;
Douglas Gregor68dbaea2010-11-17 00:13:31 +000091
Douglas Gregord03e8232010-04-05 21:10:19 +000092ASTUnit::ASTUnit(bool _MainFileIsAST)
Douglas Gregoraa21cc42010-07-19 21:46:24 +000093 : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
Douglas Gregor16896c42010-10-28 15:44:59 +000094 CompleteTranslationUnit(true), WantTiming(getenv("LIBCLANG_TIMING")),
95 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor7bb8af62010-10-12 00:50:20 +000096 ConcurrencyCheckValue(CheckUnlocked),
Douglas Gregora0734c52010-08-19 01:33:06 +000097 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +000098 ShouldCacheCodeCompletionResults(false),
Douglas Gregordf7a79a2011-02-16 18:16:54 +000099 CompletionCacheTopLevelHashValue(0),
100 PreambleTopLevelHashValue(0),
101 CurrentTopLevelHashValue(0),
Douglas Gregor4740c452010-08-19 00:45:44 +0000102 UnsafeToFree(false) {
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000103 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +0000104 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000105 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
106 }
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000107}
Douglas Gregord03e8232010-04-05 21:10:19 +0000108
Daniel Dunbar764c0822009-12-01 09:51:01 +0000109ASTUnit::~ASTUnit() {
Douglas Gregor0c7c2f82010-03-05 21:16:25 +0000110 ConcurrencyCheckValue = CheckLocked;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000111 CleanTemporaryFiles();
Douglas Gregor4dde7492010-07-23 23:58:40 +0000112 if (!PreambleFile.empty())
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000113 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000114
115 // Free the buffers associated with remapped files. We are required to
116 // perform this operation here because we explicitly request that the
117 // compiler instance *not* free these buffers for each invocation of the
118 // parser.
119 if (Invocation.get()) {
120 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
121 for (PreprocessorOptions::remapped_file_buffer_iterator
122 FB = PPOpts.remapped_file_buffer_begin(),
123 FBEnd = PPOpts.remapped_file_buffer_end();
124 FB != FBEnd;
125 ++FB)
126 delete FB->second;
127 }
Douglas Gregor96c04262010-07-27 14:52:07 +0000128
129 delete SavedMainFileBuffer;
Douglas Gregora0734c52010-08-19 01:33:06 +0000130 delete PreambleBuffer;
131
Douglas Gregor16896c42010-10-28 15:44:59 +0000132 ClearCachedCompletionResults();
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000133
134 if (getenv("LIBCLANG_OBJTRACKING")) {
Douglas Gregor9aeaa4d2010-12-07 00:05:48 +0000135 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000136 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
137 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000138}
139
140void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor6cb5ba42010-02-18 23:35:40 +0000141 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
142 TemporaryFiles[I].eraseFromDisk();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000143 TemporaryFiles.clear();
Steve Naroff44cd60e2009-10-15 22:23:48 +0000144}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000145
Douglas Gregor39982192010-08-15 06:18:01 +0000146/// \brief Determine the set of code-completion contexts in which this
147/// declaration should be shown.
148static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000149 const LangOptions &LangOpts,
150 bool &IsNestedNameSpecifier) {
151 IsNestedNameSpecifier = false;
152
Douglas Gregor39982192010-08-15 06:18:01 +0000153 if (isa<UsingShadowDecl>(ND))
154 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
155 if (!ND)
156 return 0;
157
158 unsigned Contexts = 0;
159 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
160 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
161 // Types can appear in these contexts.
162 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
163 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
164 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
165 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
166 | (1 << (CodeCompletionContext::CCC_Statement - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000167 | (1 << (CodeCompletionContext::CCC_Type - 1))
168 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000169
170 // In C++, types can appear in expressions contexts (for functional casts).
171 if (LangOpts.CPlusPlus)
172 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
173
174 // In Objective-C, message sends can send interfaces. In Objective-C++,
175 // all types are available due to functional casts.
176 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
177 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
178
179 // Deal with tag names.
180 if (isa<EnumDecl>(ND)) {
181 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
182
Douglas Gregor59cab552010-08-16 23:05:20 +0000183 // Part of the nested-name-specifier in C++0x.
Douglas Gregor39982192010-08-15 06:18:01 +0000184 if (LangOpts.CPlusPlus0x)
Douglas Gregor59cab552010-08-16 23:05:20 +0000185 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000186 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
187 if (Record->isUnion())
188 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
189 else
190 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
191
Douglas Gregor39982192010-08-15 06:18:01 +0000192 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000193 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000194 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000195 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000196 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
197 // Values can appear in these contexts.
198 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
199 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000200 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor39982192010-08-15 06:18:01 +0000201 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
202 } else if (isa<ObjCProtocolDecl>(ND)) {
203 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
204 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregor59cab552010-08-16 23:05:20 +0000205 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000206
207 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000208 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000209 }
210
211 return Contexts;
212}
213
Douglas Gregorb14904c2010-08-13 22:48:40 +0000214void ASTUnit::CacheCodeCompletionResults() {
215 if (!TheSema)
216 return;
217
Douglas Gregor16896c42010-10-28 15:44:59 +0000218 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000219 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000220
221 // Clear out the previous results.
222 ClearCachedCompletionResults();
223
224 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000225 typedef CodeCompletionResult Result;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000226 llvm::SmallVector<Result, 8> Results;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000227 TheSema->GatherGlobalCodeCompletions(CachedCompletionAllocator, Results);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000228
229 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000230 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
231
Douglas Gregorb14904c2010-08-13 22:48:40 +0000232 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
233 switch (Results[I].Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000234 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000235 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000236 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000237 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
238 CachedCompletionAllocator);
Douglas Gregor39982192010-08-15 06:18:01 +0000239 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregor59cab552010-08-16 23:05:20 +0000240 Ctx->getLangOptions(),
241 IsNestedNameSpecifier);
Douglas Gregor39982192010-08-15 06:18:01 +0000242 CachedResult.Priority = Results[I].Priority;
243 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000244 CachedResult.Availability = Results[I].Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000245
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000246 // Keep track of the type of this completion in an ASTContext-agnostic
247 // way.
Douglas Gregor24747402010-08-16 16:46:30 +0000248 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000249 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000250 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000251 CachedResult.Type = 0;
252 } else {
253 CanQualType CanUsageType
254 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
255 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
256
257 // Determine whether we have already seen this type. If so, we save
258 // ourselves the work of formatting the type string by using the
259 // temporary, CanQualType-based hash table to find the associated value.
260 unsigned &TypeValue = CompletionTypes[CanUsageType];
261 if (TypeValue == 0) {
262 TypeValue = CompletionTypes.size();
263 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
264 = TypeValue;
265 }
266
267 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000268 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000269
Douglas Gregor39982192010-08-15 06:18:01 +0000270 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000271
272 /// Handle nested-name-specifiers in C++.
273 if (TheSema->Context.getLangOptions().CPlusPlus &&
274 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
275 // The contexts in which a nested-name-specifier can appear in C++.
276 unsigned NNSContexts
277 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
278 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
279 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
280 | (1 << (CodeCompletionContext::CCC_Statement - 1))
281 | (1 << (CodeCompletionContext::CCC_Expression - 1))
282 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
283 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
284 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
285 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000286 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000287 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
288 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor59cab552010-08-16 23:05:20 +0000289
290 if (isa<NamespaceDecl>(Results[I].Declaration) ||
291 isa<NamespaceAliasDecl>(Results[I].Declaration))
292 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
293
294 if (unsigned RemainingContexts
295 = NNSContexts & ~CachedResult.ShowInContexts) {
296 // If there any contexts where this completion can be a
297 // nested-name-specifier but isn't already an option, create a
298 // nested-name-specifier completion.
299 Results[I].StartsNestedNameSpecifier = true;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000300 CachedResult.Completion
301 = Results[I].CreateCodeCompletionString(*TheSema,
302 CachedCompletionAllocator);
Douglas Gregor59cab552010-08-16 23:05:20 +0000303 CachedResult.ShowInContexts = RemainingContexts;
304 CachedResult.Priority = CCP_NestedNameSpecifier;
305 CachedResult.TypeClass = STC_Void;
306 CachedResult.Type = 0;
307 CachedCompletionResults.push_back(CachedResult);
308 }
309 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000310 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000311 }
312
Douglas Gregorb14904c2010-08-13 22:48:40 +0000313 case Result::RK_Keyword:
314 case Result::RK_Pattern:
315 // Ignore keywords and patterns; we don't care, since they are so
316 // easily regenerated.
317 break;
318
319 case Result::RK_Macro: {
320 CachedCodeCompletionResult CachedResult;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000321 CachedResult.Completion
322 = Results[I].CreateCodeCompletionString(*TheSema,
323 CachedCompletionAllocator);
Douglas Gregorb14904c2010-08-13 22:48:40 +0000324 CachedResult.ShowInContexts
325 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
326 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
327 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
328 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
329 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
330 | (1 << (CodeCompletionContext::CCC_Statement - 1))
331 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor12785102010-08-24 20:21:13 +0000332 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorec00a262010-08-24 22:20:20 +0000333 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000334 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
335 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
336
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000337
Douglas Gregorb14904c2010-08-13 22:48:40 +0000338 CachedResult.Priority = Results[I].Priority;
339 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000340 CachedResult.Availability = Results[I].Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000341 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000342 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000343 CachedCompletionResults.push_back(CachedResult);
344 break;
345 }
346 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000347 }
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000348
349 // Save the current top-level hash value.
350 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000351}
352
353void ASTUnit::ClearCachedCompletionResults() {
Douglas Gregorb14904c2010-08-13 22:48:40 +0000354 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000355 CachedCompletionTypes.clear();
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000356 CachedCompletionAllocator.Reset();
Douglas Gregorb14904c2010-08-13 22:48:40 +0000357}
358
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000359namespace {
360
Sebastian Redl2c499f62010-08-18 23:56:43 +0000361/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000362/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000363class ASTInfoCollector : public ASTReaderListener {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000364 LangOptions &LangOpt;
365 HeaderSearch &HSI;
366 std::string &TargetTriple;
367 std::string &Predefines;
368 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000369
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000370 unsigned NumHeaderInfos;
Mike Stump11289f42009-09-09 15:08:12 +0000371
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000372public:
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000373 ASTInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000374 std::string &TargetTriple, std::string &Predefines,
375 unsigned &Counter)
376 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
377 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump11289f42009-09-09 15:08:12 +0000378
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000379 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
380 LangOpt = LangOpts;
381 return false;
382 }
Mike Stump11289f42009-09-09 15:08:12 +0000383
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000384 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000385 TargetTriple = Triple;
386 return false;
387 }
Mike Stump11289f42009-09-09 15:08:12 +0000388
Sebastian Redl8b41f302010-07-14 23:29:55 +0000389 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000390 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000391 std::string &SuggestedPredefines) {
Sebastian Redl8b41f302010-07-14 23:29:55 +0000392 Predefines = Buffers[0].Data;
393 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
394 Predefines += Buffers[I].Data;
395 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000396 return false;
397 }
Mike Stump11289f42009-09-09 15:08:12 +0000398
Douglas Gregora2f49452010-03-16 19:09:18 +0000399 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000400 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
401 }
Mike Stump11289f42009-09-09 15:08:12 +0000402
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000403 virtual void ReadCounter(unsigned Value) {
404 Counter = Value;
405 }
406};
407
Douglas Gregor33cdd812010-02-18 18:08:43 +0000408class StoredDiagnosticClient : public DiagnosticClient {
409 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
410
411public:
412 explicit StoredDiagnosticClient(
413 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
414 : StoredDiags(StoredDiags) { }
415
416 virtual void HandleDiagnostic(Diagnostic::Level Level,
417 const DiagnosticInfo &Info);
418};
419
420/// \brief RAII object that optionally captures diagnostics, if
421/// there is no diagnostic client to capture them already.
422class CaptureDroppedDiagnostics {
423 Diagnostic &Diags;
424 StoredDiagnosticClient Client;
425 DiagnosticClient *PreviousClient;
426
427public:
428 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000429 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000430 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000431 {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000432 if (RequestCapture || Diags.getClient() == 0) {
433 PreviousClient = Diags.takeClient();
Douglas Gregor33cdd812010-02-18 18:08:43 +0000434 Diags.setClient(&Client);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000435 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000436 }
437
438 ~CaptureDroppedDiagnostics() {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000439 if (Diags.getClient() == &Client) {
440 Diags.takeClient();
441 Diags.setClient(PreviousClient);
442 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000443 }
444};
445
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000446} // anonymous namespace
447
Douglas Gregor33cdd812010-02-18 18:08:43 +0000448void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
449 const DiagnosticInfo &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000450 // Default implementation (Warnings/errors count).
451 DiagnosticClient::HandleDiagnostic(Level, Info);
452
Douglas Gregor33cdd812010-02-18 18:08:43 +0000453 StoredDiags.push_back(StoredDiagnostic(Level, Info));
454}
455
Steve Naroffc0683b92009-09-03 18:19:54 +0000456const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbara8a50932009-12-02 08:44:16 +0000457 return OriginalSourceFile;
Steve Naroffc0683b92009-09-03 18:19:54 +0000458}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000459
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000460const std::string &ASTUnit::getASTFileName() {
461 assert(isMainFileAST() && "Not an ASTUnit from an AST file!");
Sebastian Redl2c499f62010-08-18 23:56:43 +0000462 return static_cast<ASTReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroff44cd60e2009-10-15 22:23:48 +0000463}
464
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000465llvm::MemoryBuffer *ASTUnit::getBufferForFile(llvm::StringRef Filename,
Chris Lattner26b5c192010-11-23 09:19:42 +0000466 std::string *ErrorStr) {
Chris Lattner5159f612010-11-23 08:35:12 +0000467 assert(FileMgr);
Chris Lattner26b5c192010-11-23 09:19:42 +0000468 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000469}
470
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000471/// \brief Configure the diagnostics object for use with ASTUnit.
472void ASTUnit::ConfigureDiags(llvm::IntrusiveRefCntPtr<Diagnostic> &Diags,
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000473 const char **ArgBegin, const char **ArgEnd,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000474 ASTUnit &AST, bool CaptureDiagnostics) {
475 if (!Diags.getPtr()) {
476 // No diagnostics engine was provided, so create our own diagnostics object
477 // with the default options.
478 DiagnosticOptions DiagOpts;
479 DiagnosticClient *Client = 0;
480 if (CaptureDiagnostics)
481 Client = new StoredDiagnosticClient(AST.StoredDiagnostics);
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000482 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd- ArgBegin,
483 ArgBegin, Client);
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000484 } else if (CaptureDiagnostics) {
485 Diags->setClient(new StoredDiagnosticClient(AST.StoredDiagnostics));
486 }
487}
488
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000489ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Douglas Gregor7f95d262010-04-05 23:52:57 +0000490 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000491 const FileSystemOptions &FileSystemOpts,
Ted Kremenek8bcb1c62009-10-17 00:34:24 +0000492 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000493 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +0000494 unsigned NumRemappedFiles,
495 bool CaptureDiagnostics) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000496 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
Douglas Gregor345c1bc2011-01-19 01:02:47 +0000497 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000498
Douglas Gregor16bef852009-10-16 20:01:17 +0000499 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000500 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000501 AST->Diagnostics = Diags;
Chris Lattner3f5a9ef2010-11-23 07:51:02 +0000502 AST->FileMgr.reset(new FileManager(FileSystemOpts));
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000503 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics(),
Chris Lattner5159f612010-11-23 08:35:12 +0000504 AST->getFileManager()));
505 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000506
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000507 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
508 // Create the file entry for the file that we're mapping from.
509 const FileEntry *FromFile
510 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
511 RemappedFiles[I].second->getBufferSize(),
Chris Lattner5159f612010-11-23 08:35:12 +0000512 0);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000513 if (!FromFile) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000514 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000515 << RemappedFiles[I].first;
Douglas Gregor89a56c52010-02-27 01:32:48 +0000516 delete RemappedFiles[I].second;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000517 continue;
518 }
519
520 // Override the contents of the "from" file with the contents of
521 // the "to" file.
522 AST->getSourceManager().overrideFileContents(FromFile,
523 RemappedFiles[I].second);
524 }
525
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000526 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000527
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000528 LangOptions LangInfo;
529 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
530 std::string TargetTriple;
531 std::string Predefines;
532 unsigned Counter;
533
Sebastian Redl2c499f62010-08-18 23:56:43 +0000534 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000535
Sebastian Redl2c499f62010-08-18 23:56:43 +0000536 Reader.reset(new ASTReader(AST->getSourceManager(), AST->getFileManager(),
Chris Lattner5159f612010-11-23 08:35:12 +0000537 AST->getDiagnostics()));
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000538 Reader->setListener(new ASTInfoCollector(LangInfo, HeaderInfo, TargetTriple,
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000539 Predefines, Counter));
540
Sebastian Redl009e7f22010-10-05 16:15:19 +0000541 switch (Reader->ReadAST(Filename, ASTReader::MainFile)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000542 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000543 break;
Mike Stump11289f42009-09-09 15:08:12 +0000544
Sebastian Redl2c499f62010-08-18 23:56:43 +0000545 case ASTReader::Failure:
546 case ASTReader::IgnorePCH:
Douglas Gregord03e8232010-04-05 21:10:19 +0000547 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000548 return NULL;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000549 }
Mike Stump11289f42009-09-09 15:08:12 +0000550
Daniel Dunbara8a50932009-12-02 08:44:16 +0000551 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
552
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000553 // AST file loaded successfully. Now create the preprocessor.
Mike Stump11289f42009-09-09 15:08:12 +0000554
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000555 // Get information about the target being compiled for.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000556 //
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000557 // FIXME: This is broken, we should store the TargetOptions in the AST file.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000558 TargetOptions TargetOpts;
559 TargetOpts.ABI = "";
John McCall1c456c82010-08-22 06:43:33 +0000560 TargetOpts.CXXABI = "";
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000561 TargetOpts.CPU = "";
562 TargetOpts.Features.clear();
563 TargetOpts.Triple = TargetTriple;
Douglas Gregord03e8232010-04-05 21:10:19 +0000564 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
565 TargetOpts));
566 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
567 *AST->Target.get(),
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000568 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000569 Preprocessor &PP = *AST->PP.get();
570
Daniel Dunbarb7bbfdd2009-09-21 03:03:47 +0000571 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000572 PP.setCounterValue(Counter);
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000573 Reader->setPreprocessor(PP);
Mike Stump11289f42009-09-09 15:08:12 +0000574
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000575 // Create and initialize the ASTContext.
576
577 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000578 AST->getSourceManager(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000579 *AST->Target.get(),
580 PP.getIdentifierTable(),
581 PP.getSelectorTable(),
582 PP.getBuiltinInfo(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000583 /* size_reserve = */0));
584 ASTContext &Context = *AST->Ctx.get();
Mike Stump11289f42009-09-09 15:08:12 +0000585
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000586 Reader->InitializeContext(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000587
Sebastian Redl2c499f62010-08-18 23:56:43 +0000588 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000589 // source, so that declarations will be deserialized from the
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000590 // AST file as needed.
Sebastian Redl2c499f62010-08-18 23:56:43 +0000591 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000592 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000593 Context.setExternalSource(Source);
594
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000595 // Create an AST consumer, even though it isn't used.
596 AST->Consumer.reset(new ASTConsumer);
597
Sebastian Redl2c499f62010-08-18 23:56:43 +0000598 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000599 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
600 AST->TheSema->Initialize();
601 ReaderPtr->InitializeSema(*AST->TheSema);
602
Mike Stump11289f42009-09-09 15:08:12 +0000603 return AST.take();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000604}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000605
606namespace {
607
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000608/// \brief Preprocessor callback class that updates a hash value with the names
609/// of all macros that have been defined by the translation unit.
610class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
611 unsigned &Hash;
612
613public:
614 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
615
616 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
617 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
618 }
619};
620
621/// \brief Add the given declaration to the hash of all top-level entities.
622void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
623 if (!D)
624 return;
625
626 DeclContext *DC = D->getDeclContext();
627 if (!DC)
628 return;
629
630 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
631 return;
632
633 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
634 if (ND->getIdentifier())
635 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
636 else if (DeclarationName Name = ND->getDeclName()) {
637 std::string NameStr = Name.getAsString();
638 Hash = llvm::HashString(NameStr, Hash);
639 }
640 return;
641 }
642
643 if (ObjCForwardProtocolDecl *Forward
644 = dyn_cast<ObjCForwardProtocolDecl>(D)) {
645 for (ObjCForwardProtocolDecl::protocol_iterator
646 P = Forward->protocol_begin(),
647 PEnd = Forward->protocol_end();
648 P != PEnd; ++P)
649 AddTopLevelDeclarationToHash(*P, Hash);
650 return;
651 }
652
653 if (ObjCClassDecl *Class = llvm::dyn_cast<ObjCClassDecl>(D)) {
654 for (ObjCClassDecl::iterator I = Class->begin(), IEnd = Class->end();
655 I != IEnd; ++I)
656 AddTopLevelDeclarationToHash(I->getInterface(), Hash);
657 return;
658 }
659}
660
Daniel Dunbar644dca02009-12-04 08:17:33 +0000661class TopLevelDeclTrackerConsumer : public ASTConsumer {
662 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000663 unsigned &Hash;
664
Daniel Dunbar644dca02009-12-04 08:17:33 +0000665public:
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000666 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
667 : Unit(_Unit), Hash(Hash) {
668 Hash = 0;
669 }
670
Daniel Dunbar644dca02009-12-04 08:17:33 +0000671 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekacc59c32010-05-03 20:16:35 +0000672 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
673 Decl *D = *it;
674 // FIXME: Currently ObjC method declarations are incorrectly being
675 // reported as top-level declarations, even though their DeclContext
676 // is the containing ObjC @interface/@implementation. This is a
677 // fundamental problem in the parser right now.
678 if (isa<ObjCMethodDecl>(D))
679 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000680
681 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000682 Unit.addTopLevelDecl(D);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000683 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000684 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000685
686 // We're not interested in "interesting" decls.
687 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbar644dca02009-12-04 08:17:33 +0000688};
689
690class TopLevelDeclTrackerAction : public ASTFrontendAction {
691public:
692 ASTUnit &Unit;
693
Daniel Dunbar764c0822009-12-01 09:51:01 +0000694 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
695 llvm::StringRef InFile) {
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000696 CI.getPreprocessor().addPPCallbacks(
697 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
698 return new TopLevelDeclTrackerConsumer(Unit,
699 Unit.getCurrentTopLevelHashValue());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000700 }
701
702public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000703 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
704
Daniel Dunbar764c0822009-12-01 09:51:01 +0000705 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000706 virtual bool usesCompleteTranslationUnit() {
707 return Unit.isCompleteTranslationUnit();
708 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000709};
710
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000711class PrecompilePreambleConsumer : public PCHGenerator,
712 public ASTSerializationListener {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000713 ASTUnit &Unit;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000714 unsigned &Hash;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000715 std::vector<Decl *> TopLevelDecls;
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000716
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000717public:
718 PrecompilePreambleConsumer(ASTUnit &Unit,
719 const Preprocessor &PP, bool Chaining,
720 const char *isysroot, llvm::raw_ostream *Out)
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000721 : PCHGenerator(PP, "", Chaining, isysroot, Out), Unit(Unit),
722 Hash(Unit.getCurrentTopLevelHashValue()) {
723 Hash = 0;
724 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000725
Douglas Gregore9db88f2010-08-03 19:06:41 +0000726 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000727 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
728 Decl *D = *it;
729 // FIXME: Currently ObjC method declarations are incorrectly being
730 // reported as top-level declarations, even though their DeclContext
731 // is the containing ObjC @interface/@implementation. This is a
732 // fundamental problem in the parser right now.
733 if (isa<ObjCMethodDecl>(D))
734 continue;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000735 AddTopLevelDeclarationToHash(D, Hash);
Douglas Gregore9db88f2010-08-03 19:06:41 +0000736 TopLevelDecls.push_back(D);
737 }
738 }
739
740 virtual void HandleTranslationUnit(ASTContext &Ctx) {
741 PCHGenerator::HandleTranslationUnit(Ctx);
742 if (!Unit.getDiagnostics().hasErrorOccurred()) {
743 // Translate the top-level declarations we captured during
744 // parsing into declaration IDs in the precompiled
745 // preamble. This will allow us to deserialize those top-level
746 // declarations when requested.
747 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
748 Unit.addTopLevelDeclFromPreamble(
749 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000750 }
751 }
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000752
753 virtual void SerializedPreprocessedEntity(PreprocessedEntity *Entity,
754 uint64_t Offset) {
755 Unit.addPreprocessedEntityFromPreamble(Offset);
756 }
757
758 virtual ASTSerializationListener *GetASTSerializationListener() {
759 return this;
760 }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000761};
762
763class PrecompilePreambleAction : public ASTFrontendAction {
764 ASTUnit &Unit;
765
766public:
767 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
768
769 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
770 llvm::StringRef InFile) {
771 std::string Sysroot;
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000772 std::string OutputFile;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000773 llvm::raw_ostream *OS = 0;
774 bool Chaining;
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000775 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
776 OutputFile,
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000777 OS, Chaining))
778 return 0;
779
780 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
781 Sysroot.c_str() : 0;
Douglas Gregordf7a79a2011-02-16 18:16:54 +0000782 CI.getPreprocessor().addPPCallbacks(
783 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000784 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
785 isysroot, OS);
786 }
787
788 virtual bool hasCodeCompletionSupport() const { return false; }
789 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000790 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000791};
792
Daniel Dunbar764c0822009-12-01 09:51:01 +0000793}
794
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000795/// Parse the source file into a translation unit using the given compiler
796/// invocation, replacing the current translation unit.
797///
798/// \returns True if a failure occurred that causes the ASTUnit not to
799/// contain any translation-unit information, false otherwise.
Douglas Gregor6481ef12010-07-24 00:38:13 +0000800bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor96c04262010-07-27 14:52:07 +0000801 delete SavedMainFileBuffer;
802 SavedMainFileBuffer = 0;
803
Douglas Gregora0734c52010-08-19 01:33:06 +0000804 if (!Invocation.get()) {
805 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000806 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000807 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000808
Daniel Dunbar764c0822009-12-01 09:51:01 +0000809 // Create the compiler instance to use for building the AST.
Daniel Dunbar7afbb8c2009-12-02 08:43:56 +0000810 CompilerInstance Clang;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000811 Clang.setInvocation(Invocation.take());
812 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
813
Douglas Gregor8e984da2010-08-04 16:47:14 +0000814 // Set up diagnostics, capturing any diagnostics that would
815 // otherwise be dropped.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000816 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +0000817
Daniel Dunbar764c0822009-12-01 09:51:01 +0000818 // Create the target instance.
Douglas Gregorffd6dc42011-01-27 18:02:58 +0000819 Clang.getTargetOpts().Features = TargetFeatures;
Daniel Dunbar764c0822009-12-01 09:51:01 +0000820 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
821 Clang.getTargetOpts()));
Douglas Gregora0734c52010-08-19 01:33:06 +0000822 if (!Clang.hasTarget()) {
823 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000824 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000825 }
826
Daniel Dunbar764c0822009-12-01 09:51:01 +0000827 // Inform the target of the language options.
828 //
829 // FIXME: We shouldn't need to do this, the target should be immutable once
830 // created. This complexity should be lifted elsewhere.
831 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000832
Daniel Dunbar764c0822009-12-01 09:51:01 +0000833 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
834 "Invocation must have exactly one source file!");
Daniel Dunbar9b491e72010-06-07 23:22:09 +0000835 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +0000836 "FIXME: AST inputs not yet supported here!");
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000837 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
838 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +0000839
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000840 // Configure the various subsystems.
841 // FIXME: Should we retain the previous file manager?
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000842 FileSystemOpts = Clang.getFileSystemOpts();
Chris Lattner5159f612010-11-23 08:35:12 +0000843 FileMgr.reset(new FileManager(Clang.getFileSystemOpts()));
844 SourceMgr.reset(new SourceManager(getDiagnostics(), *FileMgr));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000845 TheSema.reset();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000846 Ctx.reset();
847 PP.reset();
848
849 // Clear out old caches and data.
850 TopLevelDecls.clear();
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000851 PreprocessedEntities.clear();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000852 CleanTemporaryFiles();
853 PreprocessedEntitiesByFile.clear();
Douglas Gregord9a30af2010-08-02 20:51:39 +0000854
Douglas Gregor7b02b582010-08-20 00:02:33 +0000855 if (!OverrideMainBuffer) {
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000856 StoredDiagnostics.erase(
857 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
858 StoredDiagnostics.end());
Douglas Gregor7b02b582010-08-20 00:02:33 +0000859 TopLevelDeclsInPreamble.clear();
Douglas Gregorf88e35b2010-11-30 06:16:57 +0000860 PreprocessedEntitiesInPreamble.clear();
Douglas Gregor7b02b582010-08-20 00:02:33 +0000861 }
862
Daniel Dunbar764c0822009-12-01 09:51:01 +0000863 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000864 Clang.setFileManager(&getFileManager());
865
Daniel Dunbar764c0822009-12-01 09:51:01 +0000866 // Create the source manager.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000867 Clang.setSourceManager(&getSourceManager());
868
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000869 // If the main file has been overridden due to the use of a preamble,
870 // make that override happen and introduce the preamble.
871 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +0000872 std::string PriorImplicitPCHInclude;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000873 if (OverrideMainBuffer) {
874 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
875 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
876 PreprocessorOpts.PrecompiledPreambleBytes.second
877 = PreambleEndsAtStartOfLine;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000878 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000879 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000880 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +0000881
Douglas Gregord9a30af2010-08-02 20:51:39 +0000882 // The stored diagnostic has the old source manager in it; update
883 // the locations to refer into the new source manager. Since we've
884 // been careful to make sure that the source manager's state
885 // before and after are identical, so that we can reuse the source
886 // location itself.
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000887 for (unsigned I = NumStoredDiagnosticsFromDriver,
888 N = StoredDiagnostics.size();
889 I < N; ++I) {
Douglas Gregord9a30af2010-08-02 20:51:39 +0000890 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
891 getSourceManager());
892 StoredDiagnostics[I].setLocation(Loc);
893 }
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000894
895 // Keep track of the override buffer;
896 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregor7b02b582010-08-20 00:02:33 +0000897 } else {
898 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
899 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000900 }
901
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000902 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
903 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbar644dca02009-12-04 08:17:33 +0000904 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbar86546382010-06-07 23:23:06 +0000905 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar764c0822009-12-01 09:51:01 +0000906 goto error;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000907
Daniel Dunbar644dca02009-12-04 08:17:33 +0000908 Act->Execute();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000909
Daniel Dunbard2f8be32009-12-01 21:57:33 +0000910 // Steal the created target, context, and preprocessor, and take back the
911 // source and file managers.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000912 TheSema.reset(Clang.takeSema());
913 Consumer.reset(Clang.takeASTConsumer());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000914 Ctx.reset(Clang.takeASTContext());
915 PP.reset(Clang.takePreprocessor());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000916 Clang.takeSourceManager();
917 Clang.takeFileManager();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000918 Target.reset(Clang.takeTarget());
919
Daniel Dunbar644dca02009-12-04 08:17:33 +0000920 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000921
922 // Remove the overridden buffer we used for the preamble.
Douglas Gregor8e984da2010-08-04 16:47:14 +0000923 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000924 PreprocessorOpts.eraseRemappedFile(
925 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor8e984da2010-08-04 16:47:14 +0000926 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
927 }
928
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000929 Invocation.reset(Clang.takeInvocation());
930 return false;
931
Daniel Dunbar764c0822009-12-01 09:51:01 +0000932error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000933 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +0000934 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000935 PreprocessorOpts.eraseRemappedFile(
936 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor8e984da2010-08-04 16:47:14 +0000937 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregora0734c52010-08-19 01:33:06 +0000938 delete OverrideMainBuffer;
Douglas Gregora3d3ba12010-10-06 21:11:08 +0000939 SavedMainFileBuffer = 0;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000940 }
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000941
Douglas Gregorefc46952010-10-12 16:25:54 +0000942 StoredDiagnostics.clear();
Daniel Dunbar764c0822009-12-01 09:51:01 +0000943 Clang.takeSourceManager();
944 Clang.takeFileManager();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000945 Invocation.reset(Clang.takeInvocation());
946 return true;
947}
948
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000949/// \brief Simple function to retrieve a path for a preamble precompiled header.
950static std::string GetPreamblePCHPath() {
951 // FIXME: This is lame; sys::Path should provide this function (in particular,
952 // it should know how to find the temporary files dir).
953 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor250ab1d2010-09-11 18:05:19 +0000954 // FIXME: This is a hack so that we can override the preamble file during
955 // crash-recovery testing, which is the only case where the preamble files
956 // are not necessarily cleaned up.
957 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
958 if (TmpFile)
959 return TmpFile;
960
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000961 std::string Error;
962 const char *TmpDir = ::getenv("TMPDIR");
963 if (!TmpDir)
964 TmpDir = ::getenv("TEMP");
965 if (!TmpDir)
966 TmpDir = ::getenv("TMP");
Douglas Gregorce3449f2010-09-11 17:51:16 +0000967#ifdef LLVM_ON_WIN32
968 if (!TmpDir)
969 TmpDir = ::getenv("USERPROFILE");
970#endif
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000971 if (!TmpDir)
972 TmpDir = "/tmp";
973 llvm::sys::Path P(TmpDir);
Douglas Gregorce3449f2010-09-11 17:51:16 +0000974 P.createDirectoryOnDisk(true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000975 P.appendComponent("preamble");
Douglas Gregor20975b22010-08-11 13:06:56 +0000976 P.appendSuffix("pch");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000977 if (P.createTemporaryFileOnDisk())
978 return std::string();
979
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000980 return P.str();
981}
982
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000983/// \brief Compute the preamble for the main file, providing the source buffer
984/// that corresponds to the main file along with a pair (bytes, start-of-line)
985/// that describes the preamble.
986std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor028d3e42010-08-09 20:45:32 +0000987ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
988 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000989 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner5159f612010-11-23 08:35:12 +0000990 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +0000991 CreatedBuffer = false;
992
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000993 // Try to determine if the main file has been remapped, either from the
994 // command line (to another file) or directly through the compiler invocation
995 // (to a memory buffer).
Douglas Gregor4dde7492010-07-23 23:58:40 +0000996 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000997 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
998 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
999 // Check whether there is a file-file remapping of the main file
1000 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor4dde7492010-07-23 23:58:40 +00001001 M = PreprocessorOpts.remapped_file_begin(),
1002 E = PreprocessorOpts.remapped_file_end();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001003 M != E;
1004 ++M) {
1005 llvm::sys::PathWithStatus MPath(M->first);
1006 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1007 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1008 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001009 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001010 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001011 CreatedBuffer = false;
1012 }
1013
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001014 Buffer = getBufferForFile(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001015 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001016 return std::make_pair((llvm::MemoryBuffer*)0,
1017 std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001018 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001019 }
1020 }
1021 }
1022
1023 // Check whether there is a file-buffer remapping. It supercedes the
1024 // file-file remapping.
1025 for (PreprocessorOptions::remapped_file_buffer_iterator
1026 M = PreprocessorOpts.remapped_file_buffer_begin(),
1027 E = PreprocessorOpts.remapped_file_buffer_end();
1028 M != E;
1029 ++M) {
1030 llvm::sys::PathWithStatus MPath(M->first);
1031 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1032 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1033 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001034 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001035 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001036 CreatedBuffer = false;
1037 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001038
Douglas Gregor4dde7492010-07-23 23:58:40 +00001039 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001040 }
1041 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001042 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001043 }
1044
1045 // If the main source file was not remapped, load it now.
1046 if (!Buffer) {
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001047 Buffer = getBufferForFile(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001048 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001049 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001050
1051 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001052 }
1053
Douglas Gregor028d3e42010-08-09 20:45:32 +00001054 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor4dde7492010-07-23 23:58:40 +00001055}
1056
Douglas Gregor6481ef12010-07-24 00:38:13 +00001057static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001058 unsigned NewSize,
1059 llvm::StringRef NewName) {
1060 llvm::MemoryBuffer *Result
1061 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1062 memcpy(const_cast<char*>(Result->getBufferStart()),
1063 Old->getBufferStart(), Old->getBufferSize());
1064 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001065 ' ', NewSize - Old->getBufferSize() - 1);
1066 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor6481ef12010-07-24 00:38:13 +00001067
Douglas Gregor6481ef12010-07-24 00:38:13 +00001068 return Result;
1069}
1070
Douglas Gregor4dde7492010-07-23 23:58:40 +00001071/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1072/// the source file.
1073///
1074/// This routine will compute the preamble of the main source file. If a
1075/// non-trivial preamble is found, it will precompile that preamble into a
1076/// precompiled header so that the precompiled preamble can be used to reduce
1077/// reparsing time. If a precompiled preamble has already been constructed,
1078/// this routine will determine if it is still valid and, if so, avoid
1079/// rebuilding the precompiled preamble.
1080///
Douglas Gregor028d3e42010-08-09 20:45:32 +00001081/// \param AllowRebuild When true (the default), this routine is
1082/// allowed to rebuild the precompiled preamble if it is found to be
1083/// out-of-date.
1084///
1085/// \param MaxLines When non-zero, the maximum number of lines that
1086/// can occur within the preamble.
1087///
Douglas Gregor6481ef12010-07-24 00:38:13 +00001088/// \returns If the precompiled preamble can be used, returns a newly-allocated
1089/// buffer that should be used in place of the main file when doing so.
1090/// Otherwise, returns a NULL pointer.
Douglas Gregor028d3e42010-08-09 20:45:32 +00001091llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregorb97b6662010-08-20 00:59:43 +00001092 CompilerInvocation PreambleInvocation,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001093 bool AllowRebuild,
1094 unsigned MaxLines) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001095 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
1096 PreprocessorOptions &PreprocessorOpts
1097 = PreambleInvocation.getPreprocessorOpts();
1098
1099 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001100 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor028d3e42010-08-09 20:45:32 +00001101 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001102
Douglas Gregor3edb1672010-11-16 20:45:51 +00001103 // If ComputePreamble() Take ownership of the
1104 llvm::OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
1105 if (CreatedPreambleBuffer)
1106 OwnedPreambleBuffer.reset(NewPreamble.first);
1107
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001108 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001109 // We couldn't find a preamble in the main source. Clear out the current
1110 // preamble, if we have one. It's obviously no good any more.
1111 Preamble.clear();
1112 if (!PreambleFile.empty()) {
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001113 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001114 PreambleFile.clear();
1115 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001116
1117 // The next time we actually see a preamble, precompile it.
1118 PreambleRebuildCounter = 1;
Douglas Gregor6481ef12010-07-24 00:38:13 +00001119 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001120 }
1121
1122 if (!Preamble.empty()) {
1123 // We've previously computed a preamble. Check whether we have the same
1124 // preamble now that we did before, and that there's enough space in
1125 // the main-file buffer within the precompiled preamble to fit the
1126 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001127 if (Preamble.size() == NewPreamble.second.first &&
1128 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregorf5275a82010-07-24 00:42:07 +00001129 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor4dde7492010-07-23 23:58:40 +00001130 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001131 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001132 // The preamble has not changed. We may be able to re-use the precompiled
1133 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001134
Douglas Gregor0e119552010-07-31 00:40:00 +00001135 // Check that none of the files used by the preamble have changed.
1136 bool AnyFileChanged = false;
1137
1138 // First, make a record of those files that have been overridden via
1139 // remapping or unsaved_files.
1140 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1141 for (PreprocessorOptions::remapped_file_iterator
1142 R = PreprocessorOpts.remapped_file_begin(),
1143 REnd = PreprocessorOpts.remapped_file_end();
1144 !AnyFileChanged && R != REnd;
1145 ++R) {
1146 struct stat StatBuf;
1147 if (stat(R->second.c_str(), &StatBuf)) {
1148 // If we can't stat the file we're remapping to, assume that something
1149 // horrible happened.
1150 AnyFileChanged = true;
1151 break;
1152 }
Douglas Gregor6481ef12010-07-24 00:38:13 +00001153
Douglas Gregor0e119552010-07-31 00:40:00 +00001154 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1155 StatBuf.st_mtime);
1156 }
1157 for (PreprocessorOptions::remapped_file_buffer_iterator
1158 R = PreprocessorOpts.remapped_file_buffer_begin(),
1159 REnd = PreprocessorOpts.remapped_file_buffer_end();
1160 !AnyFileChanged && R != REnd;
1161 ++R) {
1162 // FIXME: Should we actually compare the contents of file->buffer
1163 // remappings?
1164 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1165 0);
1166 }
1167
1168 // Check whether anything has changed.
1169 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1170 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1171 !AnyFileChanged && F != FEnd;
1172 ++F) {
1173 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1174 = OverriddenFiles.find(F->first());
1175 if (Overridden != OverriddenFiles.end()) {
1176 // This file was remapped; check whether the newly-mapped file
1177 // matches up with the previous mapping.
1178 if (Overridden->second != F->second)
1179 AnyFileChanged = true;
1180 continue;
1181 }
1182
1183 // The file was not remapped; check whether it has changed on disk.
1184 struct stat StatBuf;
1185 if (stat(F->first(), &StatBuf)) {
1186 // If we can't stat the file, assume that something horrible happened.
1187 AnyFileChanged = true;
1188 } else if (StatBuf.st_size != F->second.first ||
1189 StatBuf.st_mtime != F->second.second)
1190 AnyFileChanged = true;
1191 }
1192
1193 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001194 // Okay! We can re-use the precompiled preamble.
1195
1196 // Set the state of the diagnostic object to mimic its state
1197 // after parsing the preamble.
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001198 // FIXME: This won't catch any #pragma push warning changes that
1199 // have occurred in the preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001200 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001201 ProcessWarningOptions(getDiagnostics(),
1202 PreambleInvocation.getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001203 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1204 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
1205 StoredDiagnostics.erase(
1206 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
1207 StoredDiagnostics.end());
1208
1209 // Create a version of the main file buffer that is padded to
1210 // buffer size we reserved when creating the preamble.
Douglas Gregor0e119552010-07-31 00:40:00 +00001211 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor0e119552010-07-31 00:40:00 +00001212 PreambleReservedSize,
1213 FrontendOpts.Inputs[0].second);
1214 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001215 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001216
1217 // If we aren't allowed to rebuild the precompiled preamble, just
1218 // return now.
1219 if (!AllowRebuild)
1220 return 0;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001221
Douglas Gregor4dde7492010-07-23 23:58:40 +00001222 // We can't reuse the previously-computed preamble. Build a new one.
1223 Preamble.clear();
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001224 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001225 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001226 } else if (!AllowRebuild) {
1227 // We aren't allowed to rebuild the precompiled preamble; just
1228 // return now.
1229 return 0;
1230 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001231
1232 // If the preamble rebuild counter > 1, it's because we previously
1233 // failed to build a preamble and we're not yet ready to try
1234 // again. Decrement the counter and return a failure.
1235 if (PreambleRebuildCounter > 1) {
1236 --PreambleRebuildCounter;
1237 return 0;
1238 }
1239
Douglas Gregore10f0e52010-09-11 17:56:52 +00001240 // Create a temporary file for the precompiled preamble. In rare
1241 // circumstances, this can fail.
1242 std::string PreamblePCHPath = GetPreamblePCHPath();
1243 if (PreamblePCHPath.empty()) {
1244 // Try again next time.
1245 PreambleRebuildCounter = 1;
1246 return 0;
1247 }
1248
Douglas Gregor4dde7492010-07-23 23:58:40 +00001249 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001250 SimpleTimer PreambleTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001251 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001252
1253 // Create a new buffer that stores the preamble. The buffer also contains
1254 // extra space for the original contents of the file (which will be present
1255 // when we actually parse the file) along with more room in case the file
Douglas Gregor4dde7492010-07-23 23:58:40 +00001256 // grows.
1257 PreambleReservedSize = NewPreamble.first->getBufferSize();
1258 if (PreambleReservedSize < 4096)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001259 PreambleReservedSize = 8191;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001260 else
Douglas Gregor4dde7492010-07-23 23:58:40 +00001261 PreambleReservedSize *= 2;
1262
Douglas Gregord9a30af2010-08-02 20:51:39 +00001263 // Save the preamble text for later; we'll need to compare against it for
1264 // subsequent reparses.
1265 Preamble.assign(NewPreamble.first->getBufferStart(),
1266 NewPreamble.first->getBufferStart()
1267 + NewPreamble.second.first);
1268 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1269
Douglas Gregora0734c52010-08-19 01:33:06 +00001270 delete PreambleBuffer;
1271 PreambleBuffer
Douglas Gregor4dde7492010-07-23 23:58:40 +00001272 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001273 FrontendOpts.Inputs[0].second);
1274 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor4dde7492010-07-23 23:58:40 +00001275 NewPreamble.first->getBufferStart(), Preamble.size());
1276 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001277 ' ', PreambleReservedSize - Preamble.size() - 1);
1278 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001279
1280 // Remap the main source file to the preamble buffer.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001281 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001282 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1283
1284 // Tell the compiler invocation to generate a temporary precompiled header.
1285 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor9e136b52010-10-01 01:05:22 +00001286 FrontendOpts.ChainedPCH = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001287 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001288 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001289 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1290 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001291
1292 // Create the compiler instance to use for building the precompiled preamble.
1293 CompilerInstance Clang;
1294 Clang.setInvocation(&PreambleInvocation);
1295 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1296
Douglas Gregor8e984da2010-08-04 16:47:14 +00001297 // Set up diagnostics, capturing all of the diagnostics produced.
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001298 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001299
1300 // Create the target instance.
Douglas Gregorffd6dc42011-01-27 18:02:58 +00001301 Clang.getTargetOpts().Features = TargetFeatures;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001302 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1303 Clang.getTargetOpts()));
1304 if (!Clang.hasTarget()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001305 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1306 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001307 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001308 PreprocessorOpts.eraseRemappedFile(
1309 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001310 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001311 }
1312
1313 // Inform the target of the language options.
1314 //
1315 // FIXME: We shouldn't need to do this, the target should be immutable once
1316 // created. This complexity should be lifted elsewhere.
1317 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1318
1319 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1320 "Invocation must have exactly one source file!");
1321 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1322 "FIXME: AST inputs not yet supported here!");
1323 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1324 "IR inputs not support here!");
1325
1326 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001327 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001328 ProcessWarningOptions(getDiagnostics(), Clang.getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001329 StoredDiagnostics.erase(
1330 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1331 StoredDiagnostics.end());
Douglas Gregore9db88f2010-08-03 19:06:41 +00001332 TopLevelDecls.clear();
1333 TopLevelDeclsInPreamble.clear();
Douglas Gregorf88e35b2010-11-30 06:16:57 +00001334 PreprocessedEntities.clear();
1335 PreprocessedEntitiesInPreamble.clear();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001336
1337 // Create a file manager object to provide access to and cache the filesystem.
Chris Lattner3f5a9ef2010-11-23 07:51:02 +00001338 Clang.setFileManager(new FileManager(Clang.getFileSystemOpts()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001339
1340 // Create the source manager.
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001341 Clang.setSourceManager(new SourceManager(getDiagnostics(),
Chris Lattner5159f612010-11-23 08:35:12 +00001342 Clang.getFileManager()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001343
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001344 llvm::OwningPtr<PrecompilePreambleAction> Act;
1345 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001346 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1347 Clang.getFrontendOpts().Inputs[0].first)) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001348 Clang.takeInvocation();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001349 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1350 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001351 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001352 PreprocessorOpts.eraseRemappedFile(
1353 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001354 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001355 }
1356
1357 Act->Execute();
1358 Act->EndSourceFile();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001359 Clang.takeInvocation();
1360
Douglas Gregore9db88f2010-08-03 19:06:41 +00001361 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001362 // There were errors parsing the preamble, so no precompiled header was
1363 // generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001364 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor4dde7492010-07-23 23:58:40 +00001365 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1366 Preamble.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001367 TopLevelDeclsInPreamble.clear();
Douglas Gregorf88e35b2010-11-30 06:16:57 +00001368 PreprocessedEntities.clear();
1369 PreprocessedEntitiesInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001370 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001371 PreprocessorOpts.eraseRemappedFile(
1372 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001373 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001374 }
1375
1376 // Keep track of the preamble we precompiled.
1377 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregord9a30af2010-08-02 20:51:39 +00001378 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1379 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001380
1381 // Keep track of all of the files that the source manager knows about,
1382 // so we can verify whether they have changed or not.
1383 FilesInPreamble.clear();
1384 SourceManager &SourceMgr = Clang.getSourceManager();
1385 const llvm::MemoryBuffer *MainFileBuffer
1386 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1387 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1388 FEnd = SourceMgr.fileinfo_end();
1389 F != FEnd;
1390 ++F) {
1391 const FileEntry *File = F->second->Entry;
1392 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1393 continue;
1394
1395 FilesInPreamble[File->getName()]
1396 = std::make_pair(F->second->getSize(), File->getModificationTime());
1397 }
1398
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001399 PreambleRebuildCounter = 1;
Douglas Gregora0734c52010-08-19 01:33:06 +00001400 PreprocessorOpts.eraseRemappedFile(
1401 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001402
1403 // If the hash of top-level entities differs from the hash of the top-level
1404 // entities the last time we rebuilt the preamble, clear out the completion
1405 // cache.
1406 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1407 CompletionCacheTopLevelHashValue = 0;
1408 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1409 }
1410
Douglas Gregor6481ef12010-07-24 00:38:13 +00001411 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001412 PreambleReservedSize,
1413 FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001414}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001415
Douglas Gregore9db88f2010-08-03 19:06:41 +00001416void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1417 std::vector<Decl *> Resolved;
1418 Resolved.reserve(TopLevelDeclsInPreamble.size());
1419 ExternalASTSource &Source = *getASTContext().getExternalSource();
1420 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1421 // Resolve the declaration ID to an actual declaration, possibly
1422 // deserializing the declaration in the process.
1423 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1424 if (D)
1425 Resolved.push_back(D);
1426 }
1427 TopLevelDeclsInPreamble.clear();
1428 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1429}
1430
Douglas Gregorf88e35b2010-11-30 06:16:57 +00001431void ASTUnit::RealizePreprocessedEntitiesFromPreamble() {
1432 if (!PP)
1433 return;
1434
1435 PreprocessingRecord *PPRec = PP->getPreprocessingRecord();
1436 if (!PPRec)
1437 return;
1438
1439 ExternalPreprocessingRecordSource *External = PPRec->getExternalSource();
1440 if (!External)
1441 return;
1442
1443 for (unsigned I = 0, N = PreprocessedEntitiesInPreamble.size(); I != N; ++I) {
1444 if (PreprocessedEntity *PE
Douglas Gregor46c50012011-02-11 19:46:30 +00001445 = External->ReadPreprocessedEntityAtOffset(
1446 PreprocessedEntitiesInPreamble[I]))
Douglas Gregorf88e35b2010-11-30 06:16:57 +00001447 PreprocessedEntities.push_back(PE);
1448 }
1449
1450 if (PreprocessedEntities.empty())
1451 return;
1452
1453 PreprocessedEntities.insert(PreprocessedEntities.end(),
1454 PPRec->begin(true), PPRec->end(true));
1455}
1456
1457ASTUnit::pp_entity_iterator ASTUnit::pp_entity_begin() {
1458 if (!PreprocessedEntitiesInPreamble.empty() &&
1459 PreprocessedEntities.empty())
1460 RealizePreprocessedEntitiesFromPreamble();
1461
1462 if (PreprocessedEntities.empty())
1463 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
1464 return PPRec->begin(true);
1465
1466 return PreprocessedEntities.begin();
1467}
1468
1469ASTUnit::pp_entity_iterator ASTUnit::pp_entity_end() {
1470 if (!PreprocessedEntitiesInPreamble.empty() &&
1471 PreprocessedEntities.empty())
1472 RealizePreprocessedEntitiesFromPreamble();
1473
1474 if (PreprocessedEntities.empty())
1475 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
1476 return PPRec->end(true);
1477
1478 return PreprocessedEntities.end();
1479}
1480
Douglas Gregore9db88f2010-08-03 19:06:41 +00001481unsigned ASTUnit::getMaxPCHLevel() const {
1482 if (!getOnlyLocalDecls())
1483 return Decl::MaxPCHLevel;
1484
Sebastian Redl009e7f22010-10-05 16:15:19 +00001485 return 0;
Douglas Gregore9db88f2010-08-03 19:06:41 +00001486}
1487
Douglas Gregor16896c42010-10-28 15:44:59 +00001488llvm::StringRef ASTUnit::getMainFileName() const {
1489 return Invocation->getFrontendOpts().Inputs[0].second;
1490}
1491
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001492bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1493 if (!Invocation)
1494 return true;
1495
1496 // We'll manage file buffers ourselves.
1497 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1498 Invocation->getFrontendOpts().DisableFree = false;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001499 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001500
Douglas Gregorffd6dc42011-01-27 18:02:58 +00001501 // Save the target features.
1502 TargetFeatures = Invocation->getTargetOpts().Features;
1503
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001504 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorf5a18542010-10-27 17:24:53 +00001505 if (PrecompilePreamble) {
Douglas Gregorc6592922010-11-15 23:00:34 +00001506 PreambleRebuildCounter = 2;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001507 OverrideMainBuffer
1508 = getMainBufferWithPrecompiledPreamble(*Invocation);
1509 }
1510
Douglas Gregor16896c42010-10-28 15:44:59 +00001511 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001512 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001513
Douglas Gregor16896c42010-10-28 15:44:59 +00001514 return Parse(OverrideMainBuffer);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001515}
1516
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001517ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1518 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1519 bool OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001520 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001521 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001522 bool CompleteTranslationUnit,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001523 bool CacheCodeCompletionResults) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001524 // Create the AST unit.
1525 llvm::OwningPtr<ASTUnit> AST;
1526 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001527 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001528 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001529 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001530 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001531 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001532 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001533 AST->Invocation.reset(CI);
1534
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001535 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar764c0822009-12-01 09:51:01 +00001536}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001537
1538ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1539 const char **ArgEnd,
Douglas Gregor7f95d262010-04-05 23:52:57 +00001540 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar8d4a2022009-12-13 03:46:13 +00001541 llvm::StringRef ResourceFilesPath,
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001542 bool OnlyLocalDecls,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001543 bool CaptureDiagnostics,
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001544 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001545 unsigned NumRemappedFiles,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001546 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001547 bool CompleteTranslationUnit,
Douglas Gregorf5a18542010-10-27 17:24:53 +00001548 bool CacheCodeCompletionResults,
1549 bool CXXPrecompilePreamble,
1550 bool CXXChainedPCH) {
Douglas Gregor7f95d262010-04-05 23:52:57 +00001551 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00001552 // No diagnostics engine was provided, so create our own diagnostics object
1553 // with the default options.
1554 DiagnosticOptions DiagOpts;
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001555 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1556 ArgBegin);
Douglas Gregord03e8232010-04-05 21:10:19 +00001557 }
1558
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001559 llvm::SmallVector<const char *, 16> Args;
1560 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1561 Args.insert(Args.end(), ArgBegin, ArgEnd);
1562
1563 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1564 // also want to force it to use clang.
1565 Args.push_back("-fsyntax-only");
1566
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001567 llvm::SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1568
1569 llvm::OwningPtr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001570
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001571 {
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001572 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001573 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001574
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001575 // FIXME: We shouldn't have to pass in the path info.
1576 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
1577 "a.out", false, false, *Diags);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001578
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001579 // Don't check that inputs exist, they have been remapped.
1580 TheDriver.setCheckInputsExist(false);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001581
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001582 llvm::OwningPtr<driver::Compilation> C(
1583 TheDriver.BuildCompilation(Args.size(), Args.data()));
1584
1585 // We expect to get back exactly one command job, if we didn't something
1586 // failed.
1587 const driver::JobList &Jobs = C->getJobs();
1588 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1589 llvm::SmallString<256> Msg;
1590 llvm::raw_svector_ostream OS(Msg);
1591 C->PrintJob(OS, C->getJobs(), "; ", true);
1592 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
1593 return 0;
1594 }
1595
1596 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1597 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
1598 Diags->Report(diag::err_fe_expected_clang_command);
1599 return 0;
1600 }
1601
1602 const driver::ArgStringList &CCArgs = Cmd->getArguments();
1603 CI.reset(new CompilerInvocation);
1604 CompilerInvocation::CreateFromArgs(*CI,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001605 const_cast<const char **>(CCArgs.data()),
1606 const_cast<const char **>(CCArgs.data()) +
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001607 CCArgs.size(),
1608 *Diags);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001609 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001610
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001611 // Override any files that need remapping
1612 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001613 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbar19511922010-02-16 01:55:04 +00001614 RemappedFiles[I].second);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001615
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001616 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001617 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001618
Douglas Gregorf5a18542010-10-27 17:24:53 +00001619 // Check whether we should precompile the preamble and/or use chained PCH.
1620 // FIXME: This is a temporary hack while we debug C++ chained PCH.
1621 if (CI->getLangOpts().CPlusPlus) {
1622 PrecompilePreamble = PrecompilePreamble && CXXPrecompilePreamble;
1623
1624 if (PrecompilePreamble && !CXXChainedPCH &&
1625 !CI->getPreprocessorOpts().ImplicitPCHInclude.empty())
1626 PrecompilePreamble = false;
1627 }
1628
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001629 // Create the AST unit.
1630 llvm::OwningPtr<ASTUnit> AST;
1631 AST.reset(new ASTUnit(false));
Douglas Gregor345c1bc2011-01-19 01:02:47 +00001632 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001633 AST->Diagnostics = Diags;
Chris Lattner5159f612010-11-23 08:35:12 +00001634
1635 AST->FileMgr.reset(new FileManager(FileSystemOptions()));
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001636 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001637 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001638 AST->CompleteTranslationUnit = CompleteTranslationUnit;
1639 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1640 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1641 AST->NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1642 AST->StoredDiagnostics.swap(StoredDiagnostics);
1643 AST->Invocation.reset(CI.take());
Chris Lattner5159f612010-11-23 08:35:12 +00001644 return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001645}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001646
1647bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1648 if (!Invocation.get())
1649 return true;
1650
Douglas Gregor16896c42010-10-28 15:44:59 +00001651 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001652 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00001653
Douglas Gregor0e119552010-07-31 00:40:00 +00001654 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00001655 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
Douglas Gregor606c4ac2011-02-05 19:42:43 +00001656 PPOpts.DisableStatCache = true;
Douglas Gregor7b02b582010-08-20 00:02:33 +00001657 for (PreprocessorOptions::remapped_file_buffer_iterator
1658 R = PPOpts.remapped_file_buffer_begin(),
1659 REnd = PPOpts.remapped_file_buffer_end();
1660 R != REnd;
1661 ++R) {
1662 delete R->second;
1663 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001664 Invocation->getPreprocessorOpts().clearRemappedFiles();
1665 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1666 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1667 RemappedFiles[I].second);
1668
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001669 // If we have a preamble file lying around, or if we might try to
1670 // build a precompiled preamble, do so now.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001671 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001672 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregorb97b6662010-08-20 00:59:43 +00001673 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001674
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001675 // Clear out the diagnostics state.
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001676 if (!OverrideMainBuffer) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001677 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001678 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1679 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001680
Douglas Gregor4dde7492010-07-23 23:58:40 +00001681 // Parse the sources
Douglas Gregordf7a79a2011-02-16 18:16:54 +00001682 bool Result = Parse(OverrideMainBuffer);
1683
1684 // If we're caching global code-completion results, and the top-level
1685 // declarations have changed, clear out the code-completion cache.
1686 if (!Result && ShouldCacheCodeCompletionResults &&
1687 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1688 CacheCodeCompletionResults();
1689
Douglas Gregor4dde7492010-07-23 23:58:40 +00001690 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001691}
Douglas Gregor8e984da2010-08-04 16:47:14 +00001692
Douglas Gregorb14904c2010-08-13 22:48:40 +00001693//----------------------------------------------------------------------------//
1694// Code completion
1695//----------------------------------------------------------------------------//
1696
1697namespace {
1698 /// \brief Code completion consumer that combines the cached code-completion
1699 /// results from an ASTUnit with the code-completion results provided to it,
1700 /// then passes the result on to
1701 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1702 unsigned NormalContexts;
1703 ASTUnit &AST;
1704 CodeCompleteConsumer &Next;
1705
1706 public:
1707 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor39982192010-08-15 06:18:01 +00001708 bool IncludeMacros, bool IncludeCodePatterns,
1709 bool IncludeGlobals)
1710 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001711 Next.isOutputBinary()), AST(AST), Next(Next)
1712 {
1713 // Compute the set of contexts in which we will look when we don't have
1714 // any information about the specific context.
1715 NormalContexts
1716 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
1717 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
1718 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1719 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1720 | (1 << (CodeCompletionContext::CCC_Statement - 1))
1721 | (1 << (CodeCompletionContext::CCC_Expression - 1))
1722 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1723 | (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +00001724 | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
Douglas Gregor0ac41382010-09-23 23:01:17 +00001725 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
1726 | (1 << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor5e35d592010-09-14 23:59:36 +00001727
Douglas Gregorb14904c2010-08-13 22:48:40 +00001728 if (AST.getASTContext().getLangOptions().CPlusPlus)
1729 NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1))
1730 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
1731 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
1732 }
1733
1734 virtual void ProcessCodeCompleteResults(Sema &S,
1735 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001736 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001737 unsigned NumResults);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001738
1739 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1740 OverloadCandidate *Candidates,
1741 unsigned NumCandidates) {
1742 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1743 }
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001744
Douglas Gregorbcbf46c2011-02-01 22:57:45 +00001745 virtual CodeCompletionAllocator &getAllocator() {
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001746 return Next.getAllocator();
1747 }
Douglas Gregorb14904c2010-08-13 22:48:40 +00001748 };
1749}
Douglas Gregord46cf182010-08-16 20:01:48 +00001750
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001751/// \brief Helper function that computes which global names are hidden by the
1752/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00001753static void CalculateHiddenNames(const CodeCompletionContext &Context,
1754 CodeCompletionResult *Results,
1755 unsigned NumResults,
1756 ASTContext &Ctx,
1757 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001758 bool OnlyTagNames = false;
1759 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00001760 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001761 case CodeCompletionContext::CCC_TopLevel:
1762 case CodeCompletionContext::CCC_ObjCInterface:
1763 case CodeCompletionContext::CCC_ObjCImplementation:
1764 case CodeCompletionContext::CCC_ObjCIvarList:
1765 case CodeCompletionContext::CCC_ClassStructUnion:
1766 case CodeCompletionContext::CCC_Statement:
1767 case CodeCompletionContext::CCC_Expression:
1768 case CodeCompletionContext::CCC_ObjCMessageReceiver:
1769 case CodeCompletionContext::CCC_MemberAccess:
1770 case CodeCompletionContext::CCC_Namespace:
1771 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00001772 case CodeCompletionContext::CCC_Name:
1773 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001774 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001775 break;
1776
1777 case CodeCompletionContext::CCC_EnumTag:
1778 case CodeCompletionContext::CCC_UnionTag:
1779 case CodeCompletionContext::CCC_ClassOrStructTag:
1780 OnlyTagNames = true;
1781 break;
1782
1783 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00001784 case CodeCompletionContext::CCC_MacroName:
1785 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00001786 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001787 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00001788 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00001789 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00001790 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00001791 case CodeCompletionContext::CCC_Other:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001792 // We're looking for nothing, or we're looking for names that cannot
1793 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001794 return;
1795 }
1796
John McCall276321a2010-08-25 06:19:51 +00001797 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001798 for (unsigned I = 0; I != NumResults; ++I) {
1799 if (Results[I].Kind != Result::RK_Declaration)
1800 continue;
1801
1802 unsigned IDNS
1803 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1804
1805 bool Hiding = false;
1806 if (OnlyTagNames)
1807 Hiding = (IDNS & Decl::IDNS_Tag);
1808 else {
1809 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00001810 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1811 Decl::IDNS_NonMemberOperator);
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001812 if (Ctx.getLangOptions().CPlusPlus)
1813 HiddenIDNS |= Decl::IDNS_Tag;
1814 Hiding = (IDNS & HiddenIDNS);
1815 }
1816
1817 if (!Hiding)
1818 continue;
1819
1820 DeclarationName Name = Results[I].Declaration->getDeclName();
1821 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1822 HiddenNames.insert(Identifier->getName());
1823 else
1824 HiddenNames.insert(Name.getAsString());
1825 }
1826}
1827
1828
Douglas Gregord46cf182010-08-16 20:01:48 +00001829void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1830 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001831 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001832 unsigned NumResults) {
1833 // Merge the results we were given with the results we cached.
1834 bool AddedResult = false;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001835 unsigned InContexts
Douglas Gregor0ac41382010-09-23 23:01:17 +00001836 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001837 : (1 << (Context.getKind() - 1)));
1838
1839 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00001840 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
John McCall276321a2010-08-25 06:19:51 +00001841 typedef CodeCompletionResult Result;
Douglas Gregord46cf182010-08-16 20:01:48 +00001842 llvm::SmallVector<Result, 8> AllResults;
1843 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00001844 C = AST.cached_completion_begin(),
1845 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00001846 C != CEnd; ++C) {
1847 // If the context we are in matches any of the contexts we are
1848 // interested in, we'll add this result.
1849 if ((C->ShowInContexts & InContexts) == 0)
1850 continue;
1851
1852 // If we haven't added any results previously, do so now.
1853 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001854 CalculateHiddenNames(Context, Results, NumResults, S.Context,
1855 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00001856 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1857 AddedResult = true;
1858 }
1859
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001860 // Determine whether this global completion result is hidden by a local
1861 // completion result. If so, skip it.
1862 if (C->Kind != CXCursor_MacroDefinition &&
1863 HiddenNames.count(C->Completion->getTypedText()))
1864 continue;
1865
Douglas Gregord46cf182010-08-16 20:01:48 +00001866 // Adjust priority based on similar type classes.
1867 unsigned Priority = C->Priority;
Douglas Gregor8850aa32010-08-25 18:03:13 +00001868 CXCursorKind CursorKind = C->Kind;
Douglas Gregor12785102010-08-24 20:21:13 +00001869 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00001870 if (!Context.getPreferredType().isNull()) {
1871 if (C->Kind == CXCursor_MacroDefinition) {
1872 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00001873 S.getLangOptions(),
Douglas Gregor12785102010-08-24 20:21:13 +00001874 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00001875 } else if (C->Type) {
1876 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00001877 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00001878 Context.getPreferredType().getUnqualifiedType());
1879 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
1880 if (ExpectedSTC == C->TypeClass) {
1881 // We know this type is similar; check for an exact match.
1882 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00001883 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00001884 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00001885 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00001886 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
1887 Priority /= CCF_ExactTypeMatch;
1888 else
1889 Priority /= CCF_SimilarTypeMatch;
1890 }
1891 }
1892 }
1893
Douglas Gregor12785102010-08-24 20:21:13 +00001894 // Adjust the completion string, if required.
1895 if (C->Kind == CXCursor_MacroDefinition &&
1896 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
1897 // Create a new code-completion string that just contains the
1898 // macro name, without its arguments.
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001899 CodeCompletionBuilder Builder(getAllocator(), CCP_CodePattern,
1900 C->Availability);
1901 Builder.AddTypedTextChunk(C->Completion->getTypedText());
Douglas Gregor8850aa32010-08-25 18:03:13 +00001902 CursorKind = CXCursor_NotImplemented;
1903 Priority = CCP_CodePattern;
Douglas Gregorb278aaf2011-02-01 19:23:04 +00001904 Completion = Builder.TakeString();
Douglas Gregor12785102010-08-24 20:21:13 +00001905 }
1906
Douglas Gregor8850aa32010-08-25 18:03:13 +00001907 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregorf757a122010-08-23 23:00:57 +00001908 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00001909 }
1910
1911 // If we did not add any cached completion results, just forward the
1912 // results we were given to the next consumer.
1913 if (!AddedResult) {
1914 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
1915 return;
1916 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00001917
Douglas Gregord46cf182010-08-16 20:01:48 +00001918 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
1919 AllResults.size());
1920}
1921
1922
1923
Douglas Gregor8e984da2010-08-04 16:47:14 +00001924void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
1925 RemappedFile *RemappedFiles,
1926 unsigned NumRemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00001927 bool IncludeMacros,
1928 bool IncludeCodePatterns,
Douglas Gregor8e984da2010-08-04 16:47:14 +00001929 CodeCompleteConsumer &Consumer,
1930 Diagnostic &Diag, LangOptions &LangOpts,
1931 SourceManager &SourceMgr, FileManager &FileMgr,
Douglas Gregorb97b6662010-08-20 00:59:43 +00001932 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
1933 llvm::SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001934 if (!Invocation.get())
1935 return;
1936
Douglas Gregor16896c42010-10-28 15:44:59 +00001937 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001938 CompletionTimer.setOutput("Code completion @ " + File + ":" +
1939 llvm::Twine(Line) + ":" + llvm::Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00001940
Douglas Gregor8e984da2010-08-04 16:47:14 +00001941 CompilerInvocation CCInvocation(*Invocation);
1942 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
1943 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00001944
Douglas Gregorb14904c2010-08-13 22:48:40 +00001945 FrontendOpts.ShowMacrosInCodeCompletion
1946 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorb68bc592010-08-05 09:09:23 +00001947 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor39982192010-08-15 06:18:01 +00001948 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
1949 = CachedCompletionResults.empty();
Douglas Gregor8e984da2010-08-04 16:47:14 +00001950 FrontendOpts.CodeCompletionAt.FileName = File;
1951 FrontendOpts.CodeCompletionAt.Line = Line;
1952 FrontendOpts.CodeCompletionAt.Column = Column;
1953
1954 // Set the language options appropriately.
1955 LangOpts = CCInvocation.getLangOpts();
1956
1957 CompilerInstance Clang;
1958 Clang.setInvocation(&CCInvocation);
1959 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1960
1961 // Set up diagnostics, capturing any diagnostics produced.
1962 Clang.setDiagnostics(&Diag);
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001963 ProcessWarningOptions(Diag, CCInvocation.getDiagnosticOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00001964 CaptureDroppedDiagnostics Capture(true,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001965 Clang.getDiagnostics(),
Douglas Gregor8e984da2010-08-04 16:47:14 +00001966 StoredDiagnostics);
Douglas Gregor8e984da2010-08-04 16:47:14 +00001967
1968 // Create the target instance.
Douglas Gregorffd6dc42011-01-27 18:02:58 +00001969 Clang.getTargetOpts().Features = TargetFeatures;
Douglas Gregor8e984da2010-08-04 16:47:14 +00001970 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1971 Clang.getTargetOpts()));
1972 if (!Clang.hasTarget()) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001973 Clang.takeInvocation();
Douglas Gregor2dd19f12010-08-18 22:29:43 +00001974 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00001975 }
1976
1977 // Inform the target of the language options.
1978 //
1979 // FIXME: We shouldn't need to do this, the target should be immutable once
1980 // created. This complexity should be lifted elsewhere.
1981 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1982
1983 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1984 "Invocation must have exactly one source file!");
1985 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1986 "FIXME: AST inputs not yet supported here!");
1987 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1988 "IR inputs not support here!");
1989
1990
1991 // Use the source and file managers that we were given.
1992 Clang.setFileManager(&FileMgr);
1993 Clang.setSourceManager(&SourceMgr);
1994
1995 // Remap files.
1996 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00001997 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregorb97b6662010-08-20 00:59:43 +00001998 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001999 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
2000 RemappedFiles[I].second);
Douglas Gregorb97b6662010-08-20 00:59:43 +00002001 OwnedBuffers.push_back(RemappedFiles[I].second);
2002 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00002003
Douglas Gregorb14904c2010-08-13 22:48:40 +00002004 // Use the code completion consumer we were given, but adding any cached
2005 // code-completion results.
Douglas Gregore9186e62010-11-29 16:13:56 +00002006 AugmentedCodeCompleteConsumer *AugmentedConsumer
2007 = new AugmentedCodeCompleteConsumer(*this, Consumer,
2008 FrontendOpts.ShowMacrosInCodeCompletion,
2009 FrontendOpts.ShowCodePatternsInCodeCompletion,
2010 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
2011 Clang.setCodeCompletionConsumer(AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00002012
Douglas Gregor028d3e42010-08-09 20:45:32 +00002013 // If we have a precompiled preamble, try to use it. We only allow
2014 // the use of the precompiled preamble if we're if the completion
2015 // point is within the main file, after the end of the precompiled
2016 // preamble.
2017 llvm::MemoryBuffer *OverrideMainBuffer = 0;
2018 if (!PreambleFile.empty()) {
2019 using llvm::sys::FileStatus;
2020 llvm::sys::PathWithStatus CompleteFilePath(File);
2021 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2022 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2023 if (const FileStatus *MainStatus = MainPath.getFileStatus())
2024 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
Douglas Gregorb97b6662010-08-20 00:59:43 +00002025 OverrideMainBuffer
Douglas Gregor8e817b62010-08-25 18:04:15 +00002026 = getMainBufferWithPrecompiledPreamble(CCInvocation, false,
2027 Line - 1);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002028 }
2029
2030 // If the main file has been overridden due to the use of a preamble,
2031 // make that override happen and introduce the preamble.
Douglas Gregor606c4ac2011-02-05 19:42:43 +00002032 PreprocessorOpts.DisableStatCache = true;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002033 StoredDiagnostics.insert(StoredDiagnostics.end(),
2034 this->StoredDiagnostics.begin(),
2035 this->StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver);
Douglas Gregor028d3e42010-08-09 20:45:32 +00002036 if (OverrideMainBuffer) {
2037 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2038 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2039 PreprocessorOpts.PrecompiledPreambleBytes.second
2040 = PreambleEndsAtStartOfLine;
2041 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
2042 PreprocessorOpts.DisablePCHValidation = true;
2043
2044 // The stored diagnostics have the old source manager. Copy them
2045 // to our output set of stored diagnostics, updating the source
2046 // manager to the one we were given.
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002047 for (unsigned I = NumStoredDiagnosticsFromDriver,
2048 N = this->StoredDiagnostics.size();
2049 I < N; ++I) {
Douglas Gregor028d3e42010-08-09 20:45:32 +00002050 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
2051 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
2052 StoredDiagnostics[I].setLocation(Loc);
2053 }
Douglas Gregor7bb8af62010-10-12 00:50:20 +00002054
Douglas Gregorb97b6662010-08-20 00:59:43 +00002055 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregor7b02b582010-08-20 00:02:33 +00002056 } else {
2057 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2058 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00002059 }
2060
Douglas Gregor8e984da2010-08-04 16:47:14 +00002061 llvm::OwningPtr<SyntaxOnlyAction> Act;
2062 Act.reset(new SyntaxOnlyAction);
2063 if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
2064 Clang.getFrontendOpts().Inputs[0].first)) {
2065 Act->Execute();
2066 Act->EndSourceFile();
2067 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00002068
Douglas Gregor8e984da2010-08-04 16:47:14 +00002069 // Steal back our resources.
2070 Clang.takeFileManager();
2071 Clang.takeSourceManager();
2072 Clang.takeInvocation();
Douglas Gregor8e984da2010-08-04 16:47:14 +00002073}
Douglas Gregore9386682010-08-13 05:36:37 +00002074
2075bool ASTUnit::Save(llvm::StringRef File) {
2076 if (getDiagnostics().hasErrorOccurred())
2077 return true;
2078
2079 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2080 // unconditionally create a stat cache when we parse the file?
2081 std::string ErrorInfo;
Benjamin Kramer340045b2010-08-15 16:54:31 +00002082 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo,
2083 llvm::raw_fd_ostream::F_Binary);
Douglas Gregore9386682010-08-13 05:36:37 +00002084 if (!ErrorInfo.empty() || Out.has_error())
2085 return true;
2086
2087 std::vector<unsigned char> Buffer;
2088 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redl55c0ad52010-08-18 23:56:21 +00002089 ASTWriter Writer(Stream);
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +00002090 Writer.WriteAST(getSema(), 0, std::string(), 0);
Douglas Gregore9386682010-08-13 05:36:37 +00002091
2092 // Write the generated bitstream to "Out".
Douglas Gregor2dd19f12010-08-18 22:29:43 +00002093 if (!Buffer.empty())
2094 Out.write((char *)&Buffer.front(), Buffer.size());
Douglas Gregore9386682010-08-13 05:36:37 +00002095 Out.close();
2096 return Out.has_error();
2097}