blob: b55001e2b1bf652fb17e504923f7e2a13d8ded3b [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"
Sebastian Redl1914c6f2010-08-18 23:56:37 +000030#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000031#include "clang/Lex/HeaderSearch.h"
32#include "clang/Lex/Preprocessor.h"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000033#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000034#include "clang/Basic/TargetInfo.h"
35#include "clang/Basic/Diagnostic.h"
Douglas Gregor40a5a7d2010-08-16 23:08:34 +000036#include "llvm/ADT/StringSet.h"
Douglas Gregoraa98ed92010-01-23 00:14:00 +000037#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000038#include "llvm/System/Host.h"
Benjamin Kramer6c839f82009-10-18 11:34:14 +000039#include "llvm/System/Path.h"
Douglas Gregor028d3e42010-08-09 20:45:32 +000040#include "llvm/Support/raw_ostream.h"
Douglas Gregor15ba0b32010-07-30 20:58:08 +000041#include "llvm/Support/Timer.h"
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000042#include <cstdlib>
Zhongxing Xu318e4032010-07-23 02:15:08 +000043#include <cstdio>
Douglas Gregor0e119552010-07-31 00:40:00 +000044#include <sys/stat.h>
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000045using namespace clang;
46
Douglas Gregor16896c42010-10-28 15:44:59 +000047using llvm::TimeRecord;
48
49namespace {
50 class SimpleTimer {
51 bool WantTiming;
52 TimeRecord Start;
53 std::string Output;
54
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000055 public:
Douglas Gregor1cbdd952010-11-01 13:48:43 +000056 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
Douglas Gregor16896c42010-10-28 15:44:59 +000057 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000058 Start = TimeRecord::getCurrentTime();
Douglas Gregor16896c42010-10-28 15:44:59 +000059 }
60
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000061 void setOutput(const llvm::Twine &Output) {
Douglas Gregor16896c42010-10-28 15:44:59 +000062 if (WantTiming)
Benjamin Kramerf2e5a912010-11-09 20:00:56 +000063 this->Output = Output.str();
Douglas Gregor16896c42010-10-28 15:44:59 +000064 }
65
Douglas Gregor16896c42010-10-28 15:44:59 +000066 ~SimpleTimer() {
67 if (WantTiming) {
68 TimeRecord Elapsed = TimeRecord::getCurrentTime();
69 Elapsed -= Start;
70 llvm::errs() << Output << ':';
71 Elapsed.print(Elapsed, llvm::errs());
72 llvm::errs() << '\n';
73 }
74 }
75 };
76}
77
Douglas Gregorbb420ab2010-08-04 05:53:38 +000078/// \brief After failing to build a precompiled preamble (due to
79/// errors in the source that occurs in the preamble), the number of
80/// reparses during which we'll skip even trying to precompile the
81/// preamble.
82const unsigned DefaultPreambleRebuildInterval = 5;
83
Douglas Gregor68dbaea2010-11-17 00:13:31 +000084/// \brief Tracks the number of ASTUnit objects that are currently active.
85///
86/// Used for debugging purposes only.
87static unsigned ActiveASTUnitObjects;
88
Douglas Gregord03e8232010-04-05 21:10:19 +000089ASTUnit::ASTUnit(bool _MainFileIsAST)
Douglas Gregoraa21cc42010-07-19 21:46:24 +000090 : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
Douglas Gregor16896c42010-10-28 15:44:59 +000091 CompleteTranslationUnit(true), WantTiming(getenv("LIBCLANG_TIMING")),
92 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor7bb8af62010-10-12 00:50:20 +000093 ConcurrencyCheckValue(CheckUnlocked),
Douglas Gregora0734c52010-08-19 01:33:06 +000094 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +000095 ShouldCacheCodeCompletionResults(false),
96 NumTopLevelDeclsAtLastCompletionCache(0),
Douglas Gregor4740c452010-08-19 00:45:44 +000097 CacheCodeCompletionCoolDown(0),
98 UnsafeToFree(false) {
Douglas Gregor68dbaea2010-11-17 00:13:31 +000099 if (getenv("LIBCLANG_OBJTRACKING")) {
100 ++ActiveASTUnitObjects;
101 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
102 }
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000103}
Douglas Gregord03e8232010-04-05 21:10:19 +0000104
Daniel Dunbar764c0822009-12-01 09:51:01 +0000105ASTUnit::~ASTUnit() {
Douglas Gregor0c7c2f82010-03-05 21:16:25 +0000106 ConcurrencyCheckValue = CheckLocked;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000107 CleanTemporaryFiles();
Douglas Gregor4dde7492010-07-23 23:58:40 +0000108 if (!PreambleFile.empty())
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000109 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000110
111 // Free the buffers associated with remapped files. We are required to
112 // perform this operation here because we explicitly request that the
113 // compiler instance *not* free these buffers for each invocation of the
114 // parser.
115 if (Invocation.get()) {
116 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
117 for (PreprocessorOptions::remapped_file_buffer_iterator
118 FB = PPOpts.remapped_file_buffer_begin(),
119 FBEnd = PPOpts.remapped_file_buffer_end();
120 FB != FBEnd;
121 ++FB)
122 delete FB->second;
123 }
Douglas Gregor96c04262010-07-27 14:52:07 +0000124
125 delete SavedMainFileBuffer;
Douglas Gregora0734c52010-08-19 01:33:06 +0000126 delete PreambleBuffer;
127
Douglas Gregor16896c42010-10-28 15:44:59 +0000128 ClearCachedCompletionResults();
Douglas Gregor68dbaea2010-11-17 00:13:31 +0000129
130 if (getenv("LIBCLANG_OBJTRACKING")) {
131 --ActiveASTUnitObjects;
132 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
133 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000134}
135
136void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor6cb5ba42010-02-18 23:35:40 +0000137 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
138 TemporaryFiles[I].eraseFromDisk();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000139 TemporaryFiles.clear();
Steve Naroff44cd60e2009-10-15 22:23:48 +0000140}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000141
Douglas Gregor39982192010-08-15 06:18:01 +0000142/// \brief Determine the set of code-completion contexts in which this
143/// declaration should be shown.
144static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000145 const LangOptions &LangOpts,
146 bool &IsNestedNameSpecifier) {
147 IsNestedNameSpecifier = false;
148
Douglas Gregor39982192010-08-15 06:18:01 +0000149 if (isa<UsingShadowDecl>(ND))
150 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
151 if (!ND)
152 return 0;
153
154 unsigned Contexts = 0;
155 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
156 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
157 // Types can appear in these contexts.
158 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
159 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
160 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
161 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
162 | (1 << (CodeCompletionContext::CCC_Statement - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000163 | (1 << (CodeCompletionContext::CCC_Type - 1))
164 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000165
166 // In C++, types can appear in expressions contexts (for functional casts).
167 if (LangOpts.CPlusPlus)
168 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
169
170 // In Objective-C, message sends can send interfaces. In Objective-C++,
171 // all types are available due to functional casts.
172 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
173 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
174
175 // Deal with tag names.
176 if (isa<EnumDecl>(ND)) {
177 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
178
Douglas Gregor59cab552010-08-16 23:05:20 +0000179 // Part of the nested-name-specifier in C++0x.
Douglas Gregor39982192010-08-15 06:18:01 +0000180 if (LangOpts.CPlusPlus0x)
Douglas Gregor59cab552010-08-16 23:05:20 +0000181 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000182 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
183 if (Record->isUnion())
184 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
185 else
186 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
187
Douglas Gregor39982192010-08-15 06:18:01 +0000188 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000189 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000190 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000191 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000192 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
193 // Values can appear in these contexts.
194 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
195 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000196 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor39982192010-08-15 06:18:01 +0000197 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
198 } else if (isa<ObjCProtocolDecl>(ND)) {
199 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
200 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregor59cab552010-08-16 23:05:20 +0000201 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000202
203 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000204 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000205 }
206
207 return Contexts;
208}
209
Douglas Gregorb14904c2010-08-13 22:48:40 +0000210void ASTUnit::CacheCodeCompletionResults() {
211 if (!TheSema)
212 return;
213
Douglas Gregor16896c42010-10-28 15:44:59 +0000214 SimpleTimer Timer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +0000215 Timer.setOutput("Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000216
217 // Clear out the previous results.
218 ClearCachedCompletionResults();
219
220 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000221 typedef CodeCompletionResult Result;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000222 llvm::SmallVector<Result, 8> Results;
223 TheSema->GatherGlobalCodeCompletions(Results);
224
225 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000226 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
227
Douglas Gregorb14904c2010-08-13 22:48:40 +0000228 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
229 switch (Results[I].Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000230 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000231 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000232 CachedCodeCompletionResult CachedResult;
233 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
234 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregor59cab552010-08-16 23:05:20 +0000235 Ctx->getLangOptions(),
236 IsNestedNameSpecifier);
Douglas Gregor39982192010-08-15 06:18:01 +0000237 CachedResult.Priority = Results[I].Priority;
238 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000239 CachedResult.Availability = Results[I].Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000240
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000241 // Keep track of the type of this completion in an ASTContext-agnostic
242 // way.
Douglas Gregor24747402010-08-16 16:46:30 +0000243 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000244 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000245 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000246 CachedResult.Type = 0;
247 } else {
248 CanQualType CanUsageType
249 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
250 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
251
252 // Determine whether we have already seen this type. If so, we save
253 // ourselves the work of formatting the type string by using the
254 // temporary, CanQualType-based hash table to find the associated value.
255 unsigned &TypeValue = CompletionTypes[CanUsageType];
256 if (TypeValue == 0) {
257 TypeValue = CompletionTypes.size();
258 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
259 = TypeValue;
260 }
261
262 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000263 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000264
Douglas Gregor39982192010-08-15 06:18:01 +0000265 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000266
267 /// Handle nested-name-specifiers in C++.
268 if (TheSema->Context.getLangOptions().CPlusPlus &&
269 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
270 // The contexts in which a nested-name-specifier can appear in C++.
271 unsigned NNSContexts
272 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
273 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
274 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
275 | (1 << (CodeCompletionContext::CCC_Statement - 1))
276 | (1 << (CodeCompletionContext::CCC_Expression - 1))
277 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
278 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
279 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
280 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000281 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000282 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
283 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor59cab552010-08-16 23:05:20 +0000284
285 if (isa<NamespaceDecl>(Results[I].Declaration) ||
286 isa<NamespaceAliasDecl>(Results[I].Declaration))
287 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
288
289 if (unsigned RemainingContexts
290 = NNSContexts & ~CachedResult.ShowInContexts) {
291 // If there any contexts where this completion can be a
292 // nested-name-specifier but isn't already an option, create a
293 // nested-name-specifier completion.
294 Results[I].StartsNestedNameSpecifier = true;
295 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
296 CachedResult.ShowInContexts = RemainingContexts;
297 CachedResult.Priority = CCP_NestedNameSpecifier;
298 CachedResult.TypeClass = STC_Void;
299 CachedResult.Type = 0;
300 CachedCompletionResults.push_back(CachedResult);
301 }
302 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000303 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000304 }
305
Douglas Gregorb14904c2010-08-13 22:48:40 +0000306 case Result::RK_Keyword:
307 case Result::RK_Pattern:
308 // Ignore keywords and patterns; we don't care, since they are so
309 // easily regenerated.
310 break;
311
312 case Result::RK_Macro: {
313 CachedCodeCompletionResult CachedResult;
314 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
315 CachedResult.ShowInContexts
316 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
317 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
318 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
319 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
320 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
321 | (1 << (CodeCompletionContext::CCC_Statement - 1))
322 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor12785102010-08-24 20:21:13 +0000323 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorec00a262010-08-24 22:20:20 +0000324 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000325 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
326 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
327
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000328
Douglas Gregorb14904c2010-08-13 22:48:40 +0000329 CachedResult.Priority = Results[I].Priority;
330 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000331 CachedResult.Availability = Results[I].Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000332 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000333 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000334 CachedCompletionResults.push_back(CachedResult);
335 break;
336 }
337 }
338 Results[I].Destroy();
339 }
340
Douglas Gregor2c8bd472010-08-17 00:40:40 +0000341 // Make a note of the state when we performed this caching.
342 NumTopLevelDeclsAtLastCompletionCache = top_level_size();
Douglas Gregorb14904c2010-08-13 22:48:40 +0000343}
344
345void ASTUnit::ClearCachedCompletionResults() {
346 for (unsigned I = 0, N = CachedCompletionResults.size(); I != N; ++I)
347 delete CachedCompletionResults[I].Completion;
348 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000349 CachedCompletionTypes.clear();
Douglas Gregorb14904c2010-08-13 22:48:40 +0000350}
351
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000352namespace {
353
Sebastian Redl2c499f62010-08-18 23:56:43 +0000354/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000355/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000356class ASTInfoCollector : public ASTReaderListener {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000357 LangOptions &LangOpt;
358 HeaderSearch &HSI;
359 std::string &TargetTriple;
360 std::string &Predefines;
361 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000362
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000363 unsigned NumHeaderInfos;
Mike Stump11289f42009-09-09 15:08:12 +0000364
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000365public:
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000366 ASTInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000367 std::string &TargetTriple, std::string &Predefines,
368 unsigned &Counter)
369 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
370 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump11289f42009-09-09 15:08:12 +0000371
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000372 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
373 LangOpt = LangOpts;
374 return false;
375 }
Mike Stump11289f42009-09-09 15:08:12 +0000376
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000377 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000378 TargetTriple = Triple;
379 return false;
380 }
Mike Stump11289f42009-09-09 15:08:12 +0000381
Sebastian Redl8b41f302010-07-14 23:29:55 +0000382 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000383 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000384 std::string &SuggestedPredefines) {
Sebastian Redl8b41f302010-07-14 23:29:55 +0000385 Predefines = Buffers[0].Data;
386 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
387 Predefines += Buffers[I].Data;
388 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000389 return false;
390 }
Mike Stump11289f42009-09-09 15:08:12 +0000391
Douglas Gregora2f49452010-03-16 19:09:18 +0000392 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000393 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
394 }
Mike Stump11289f42009-09-09 15:08:12 +0000395
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000396 virtual void ReadCounter(unsigned Value) {
397 Counter = Value;
398 }
399};
400
Douglas Gregor33cdd812010-02-18 18:08:43 +0000401class StoredDiagnosticClient : public DiagnosticClient {
402 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
403
404public:
405 explicit StoredDiagnosticClient(
406 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
407 : StoredDiags(StoredDiags) { }
408
409 virtual void HandleDiagnostic(Diagnostic::Level Level,
410 const DiagnosticInfo &Info);
411};
412
413/// \brief RAII object that optionally captures diagnostics, if
414/// there is no diagnostic client to capture them already.
415class CaptureDroppedDiagnostics {
416 Diagnostic &Diags;
417 StoredDiagnosticClient Client;
418 DiagnosticClient *PreviousClient;
419
420public:
421 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000422 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000423 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000424 {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000425 if (RequestCapture || Diags.getClient() == 0) {
426 PreviousClient = Diags.takeClient();
Douglas Gregor33cdd812010-02-18 18:08:43 +0000427 Diags.setClient(&Client);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000428 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000429 }
430
431 ~CaptureDroppedDiagnostics() {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000432 if (Diags.getClient() == &Client) {
433 Diags.takeClient();
434 Diags.setClient(PreviousClient);
435 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000436 }
437};
438
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000439} // anonymous namespace
440
Douglas Gregor33cdd812010-02-18 18:08:43 +0000441void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
442 const DiagnosticInfo &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000443 // Default implementation (Warnings/errors count).
444 DiagnosticClient::HandleDiagnostic(Level, Info);
445
Douglas Gregor33cdd812010-02-18 18:08:43 +0000446 StoredDiags.push_back(StoredDiagnostic(Level, Info));
447}
448
Steve Naroffc0683b92009-09-03 18:19:54 +0000449const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbara8a50932009-12-02 08:44:16 +0000450 return OriginalSourceFile;
Steve Naroffc0683b92009-09-03 18:19:54 +0000451}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000452
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000453const std::string &ASTUnit::getASTFileName() {
454 assert(isMainFileAST() && "Not an ASTUnit from an AST file!");
Sebastian Redl2c499f62010-08-18 23:56:43 +0000455 return static_cast<ASTReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroff44cd60e2009-10-15 22:23:48 +0000456}
457
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000458llvm::MemoryBuffer *ASTUnit::getBufferForFile(llvm::StringRef Filename,
Chris Lattner26b5c192010-11-23 09:19:42 +0000459 std::string *ErrorStr) {
Chris Lattner5159f612010-11-23 08:35:12 +0000460 assert(FileMgr);
Chris Lattner26b5c192010-11-23 09:19:42 +0000461 return FileMgr->getBufferForFile(Filename, ErrorStr);
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000462}
463
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000464/// \brief Configure the diagnostics object for use with ASTUnit.
465void ASTUnit::ConfigureDiags(llvm::IntrusiveRefCntPtr<Diagnostic> &Diags,
466 ASTUnit &AST, bool CaptureDiagnostics) {
467 if (!Diags.getPtr()) {
468 // No diagnostics engine was provided, so create our own diagnostics object
469 // with the default options.
470 DiagnosticOptions DiagOpts;
471 DiagnosticClient *Client = 0;
472 if (CaptureDiagnostics)
473 Client = new StoredDiagnosticClient(AST.StoredDiagnostics);
474 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0, Client);
475 } else if (CaptureDiagnostics) {
476 Diags->setClient(new StoredDiagnosticClient(AST.StoredDiagnostics));
477 }
478}
479
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000480ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Douglas Gregor7f95d262010-04-05 23:52:57 +0000481 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000482 const FileSystemOptions &FileSystemOpts,
Ted Kremenek8bcb1c62009-10-17 00:34:24 +0000483 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000484 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +0000485 unsigned NumRemappedFiles,
486 bool CaptureDiagnostics) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000487 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000488 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000489
Douglas Gregor16bef852009-10-16 20:01:17 +0000490 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +0000491 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000492 AST->Diagnostics = Diags;
Chris Lattner3f5a9ef2010-11-23 07:51:02 +0000493 AST->FileMgr.reset(new FileManager(FileSystemOpts));
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000494 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics(),
Chris Lattner5159f612010-11-23 08:35:12 +0000495 AST->getFileManager()));
496 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000497
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000498 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
499 // Create the file entry for the file that we're mapping from.
500 const FileEntry *FromFile
501 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
502 RemappedFiles[I].second->getBufferSize(),
Chris Lattner5159f612010-11-23 08:35:12 +0000503 0);
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000504 if (!FromFile) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000505 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000506 << RemappedFiles[I].first;
Douglas Gregor89a56c52010-02-27 01:32:48 +0000507 delete RemappedFiles[I].second;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000508 continue;
509 }
510
511 // Override the contents of the "from" file with the contents of
512 // the "to" file.
513 AST->getSourceManager().overrideFileContents(FromFile,
514 RemappedFiles[I].second);
515 }
516
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000517 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000518
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000519 LangOptions LangInfo;
520 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
521 std::string TargetTriple;
522 std::string Predefines;
523 unsigned Counter;
524
Sebastian Redl2c499f62010-08-18 23:56:43 +0000525 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000526
Sebastian Redl2c499f62010-08-18 23:56:43 +0000527 Reader.reset(new ASTReader(AST->getSourceManager(), AST->getFileManager(),
Chris Lattner5159f612010-11-23 08:35:12 +0000528 AST->getDiagnostics()));
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000529 Reader->setListener(new ASTInfoCollector(LangInfo, HeaderInfo, TargetTriple,
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000530 Predefines, Counter));
531
Sebastian Redl009e7f22010-10-05 16:15:19 +0000532 switch (Reader->ReadAST(Filename, ASTReader::MainFile)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000533 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000534 break;
Mike Stump11289f42009-09-09 15:08:12 +0000535
Sebastian Redl2c499f62010-08-18 23:56:43 +0000536 case ASTReader::Failure:
537 case ASTReader::IgnorePCH:
Douglas Gregord03e8232010-04-05 21:10:19 +0000538 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000539 return NULL;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000540 }
Mike Stump11289f42009-09-09 15:08:12 +0000541
Daniel Dunbara8a50932009-12-02 08:44:16 +0000542 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
543
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000544 // AST file loaded successfully. Now create the preprocessor.
Mike Stump11289f42009-09-09 15:08:12 +0000545
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000546 // Get information about the target being compiled for.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000547 //
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000548 // FIXME: This is broken, we should store the TargetOptions in the AST file.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000549 TargetOptions TargetOpts;
550 TargetOpts.ABI = "";
John McCall1c456c82010-08-22 06:43:33 +0000551 TargetOpts.CXXABI = "";
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000552 TargetOpts.CPU = "";
553 TargetOpts.Features.clear();
554 TargetOpts.Triple = TargetTriple;
Douglas Gregord03e8232010-04-05 21:10:19 +0000555 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
556 TargetOpts));
557 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
558 *AST->Target.get(),
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000559 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000560 Preprocessor &PP = *AST->PP.get();
561
Daniel Dunbarb7bbfdd2009-09-21 03:03:47 +0000562 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000563 PP.setCounterValue(Counter);
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000564 Reader->setPreprocessor(PP);
Mike Stump11289f42009-09-09 15:08:12 +0000565
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000566 // Create and initialize the ASTContext.
567
568 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000569 AST->getSourceManager(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000570 *AST->Target.get(),
571 PP.getIdentifierTable(),
572 PP.getSelectorTable(),
573 PP.getBuiltinInfo(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000574 /* size_reserve = */0));
575 ASTContext &Context = *AST->Ctx.get();
Mike Stump11289f42009-09-09 15:08:12 +0000576
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000577 Reader->InitializeContext(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000578
Sebastian Redl2c499f62010-08-18 23:56:43 +0000579 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000580 // source, so that declarations will be deserialized from the
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000581 // AST file as needed.
Sebastian Redl2c499f62010-08-18 23:56:43 +0000582 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000583 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000584 Context.setExternalSource(Source);
585
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000586 // Create an AST consumer, even though it isn't used.
587 AST->Consumer.reset(new ASTConsumer);
588
Sebastian Redl2c499f62010-08-18 23:56:43 +0000589 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000590 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
591 AST->TheSema->Initialize();
592 ReaderPtr->InitializeSema(*AST->TheSema);
593
Mike Stump11289f42009-09-09 15:08:12 +0000594 return AST.take();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000595}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000596
597namespace {
598
Daniel Dunbar644dca02009-12-04 08:17:33 +0000599class TopLevelDeclTrackerConsumer : public ASTConsumer {
600 ASTUnit &Unit;
601
602public:
603 TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {}
604
605 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekacc59c32010-05-03 20:16:35 +0000606 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
607 Decl *D = *it;
608 // FIXME: Currently ObjC method declarations are incorrectly being
609 // reported as top-level declarations, even though their DeclContext
610 // is the containing ObjC @interface/@implementation. This is a
611 // fundamental problem in the parser right now.
612 if (isa<ObjCMethodDecl>(D))
613 continue;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000614 Unit.addTopLevelDecl(D);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000615 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000616 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000617
618 // We're not interested in "interesting" decls.
619 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbar644dca02009-12-04 08:17:33 +0000620};
621
622class TopLevelDeclTrackerAction : public ASTFrontendAction {
623public:
624 ASTUnit &Unit;
625
Daniel Dunbar764c0822009-12-01 09:51:01 +0000626 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
627 llvm::StringRef InFile) {
Daniel Dunbar644dca02009-12-04 08:17:33 +0000628 return new TopLevelDeclTrackerConsumer(Unit);
Daniel Dunbar764c0822009-12-01 09:51:01 +0000629 }
630
631public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000632 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
633
Daniel Dunbar764c0822009-12-01 09:51:01 +0000634 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000635 virtual bool usesCompleteTranslationUnit() {
636 return Unit.isCompleteTranslationUnit();
637 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000638};
639
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000640class PrecompilePreambleConsumer : public PCHGenerator {
641 ASTUnit &Unit;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000642 std::vector<Decl *> TopLevelDecls;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000643
644public:
645 PrecompilePreambleConsumer(ASTUnit &Unit,
646 const Preprocessor &PP, bool Chaining,
647 const char *isysroot, llvm::raw_ostream *Out)
648 : PCHGenerator(PP, Chaining, isysroot, Out), Unit(Unit) { }
649
Douglas Gregore9db88f2010-08-03 19:06:41 +0000650 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000651 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
652 Decl *D = *it;
653 // FIXME: Currently ObjC method declarations are incorrectly being
654 // reported as top-level declarations, even though their DeclContext
655 // is the containing ObjC @interface/@implementation. This is a
656 // fundamental problem in the parser right now.
657 if (isa<ObjCMethodDecl>(D))
658 continue;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000659 TopLevelDecls.push_back(D);
660 }
661 }
662
663 virtual void HandleTranslationUnit(ASTContext &Ctx) {
664 PCHGenerator::HandleTranslationUnit(Ctx);
665 if (!Unit.getDiagnostics().hasErrorOccurred()) {
666 // Translate the top-level declarations we captured during
667 // parsing into declaration IDs in the precompiled
668 // preamble. This will allow us to deserialize those top-level
669 // declarations when requested.
670 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
671 Unit.addTopLevelDeclFromPreamble(
672 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000673 }
674 }
675};
676
677class PrecompilePreambleAction : public ASTFrontendAction {
678 ASTUnit &Unit;
679
680public:
681 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
682
683 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
684 llvm::StringRef InFile) {
685 std::string Sysroot;
686 llvm::raw_ostream *OS = 0;
687 bool Chaining;
688 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
689 OS, Chaining))
690 return 0;
691
692 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
693 Sysroot.c_str() : 0;
694 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
695 isysroot, OS);
696 }
697
698 virtual bool hasCodeCompletionSupport() const { return false; }
699 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000700 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000701};
702
Daniel Dunbar764c0822009-12-01 09:51:01 +0000703}
704
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000705/// Parse the source file into a translation unit using the given compiler
706/// invocation, replacing the current translation unit.
707///
708/// \returns True if a failure occurred that causes the ASTUnit not to
709/// contain any translation-unit information, false otherwise.
Douglas Gregor6481ef12010-07-24 00:38:13 +0000710bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor96c04262010-07-27 14:52:07 +0000711 delete SavedMainFileBuffer;
712 SavedMainFileBuffer = 0;
713
Douglas Gregora0734c52010-08-19 01:33:06 +0000714 if (!Invocation.get()) {
715 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000716 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000717 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000718
Daniel Dunbar764c0822009-12-01 09:51:01 +0000719 // Create the compiler instance to use for building the AST.
Daniel Dunbar7afbb8c2009-12-02 08:43:56 +0000720 CompilerInstance Clang;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000721 Clang.setInvocation(Invocation.take());
722 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
723
Douglas Gregor8e984da2010-08-04 16:47:14 +0000724 // Set up diagnostics, capturing any diagnostics that would
725 // otherwise be dropped.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000726 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregord03e8232010-04-05 21:10:19 +0000727
Daniel Dunbar764c0822009-12-01 09:51:01 +0000728 // Create the target instance.
729 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
730 Clang.getTargetOpts()));
Douglas Gregora0734c52010-08-19 01:33:06 +0000731 if (!Clang.hasTarget()) {
732 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000733 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000734 }
735
Daniel Dunbar764c0822009-12-01 09:51:01 +0000736 // Inform the target of the language options.
737 //
738 // FIXME: We shouldn't need to do this, the target should be immutable once
739 // created. This complexity should be lifted elsewhere.
740 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000741
Daniel Dunbar764c0822009-12-01 09:51:01 +0000742 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
743 "Invocation must have exactly one source file!");
Daniel Dunbar9b491e72010-06-07 23:22:09 +0000744 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +0000745 "FIXME: AST inputs not yet supported here!");
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000746 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
747 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +0000748
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000749 // Configure the various subsystems.
750 // FIXME: Should we retain the previous file manager?
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000751 FileSystemOpts = Clang.getFileSystemOpts();
Chris Lattner5159f612010-11-23 08:35:12 +0000752 FileMgr.reset(new FileManager(Clang.getFileSystemOpts()));
753 SourceMgr.reset(new SourceManager(getDiagnostics(), *FileMgr));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000754 TheSema.reset();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000755 Ctx.reset();
756 PP.reset();
757
758 // Clear out old caches and data.
759 TopLevelDecls.clear();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000760 CleanTemporaryFiles();
761 PreprocessedEntitiesByFile.clear();
Douglas Gregord9a30af2010-08-02 20:51:39 +0000762
Douglas Gregor7b02b582010-08-20 00:02:33 +0000763 if (!OverrideMainBuffer) {
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000764 StoredDiagnostics.erase(
765 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
766 StoredDiagnostics.end());
Douglas Gregor7b02b582010-08-20 00:02:33 +0000767 TopLevelDeclsInPreamble.clear();
768 }
769
Daniel Dunbar764c0822009-12-01 09:51:01 +0000770 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000771 Clang.setFileManager(&getFileManager());
772
Daniel Dunbar764c0822009-12-01 09:51:01 +0000773 // Create the source manager.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000774 Clang.setSourceManager(&getSourceManager());
775
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000776 // If the main file has been overridden due to the use of a preamble,
777 // make that override happen and introduce the preamble.
778 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +0000779 std::string PriorImplicitPCHInclude;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000780 if (OverrideMainBuffer) {
781 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
782 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
783 PreprocessorOpts.PrecompiledPreambleBytes.second
784 = PreambleEndsAtStartOfLine;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000785 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000786 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000787 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +0000788
Douglas Gregord9a30af2010-08-02 20:51:39 +0000789 // The stored diagnostic has the old source manager in it; update
790 // the locations to refer into the new source manager. Since we've
791 // been careful to make sure that the source manager's state
792 // before and after are identical, so that we can reuse the source
793 // location itself.
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000794 for (unsigned I = NumStoredDiagnosticsFromDriver,
795 N = StoredDiagnostics.size();
796 I < N; ++I) {
Douglas Gregord9a30af2010-08-02 20:51:39 +0000797 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
798 getSourceManager());
799 StoredDiagnostics[I].setLocation(Loc);
800 }
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000801
802 // Keep track of the override buffer;
803 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregor7b02b582010-08-20 00:02:33 +0000804 } else {
805 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
806 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000807 }
808
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000809 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
810 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbar644dca02009-12-04 08:17:33 +0000811 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbar86546382010-06-07 23:23:06 +0000812 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar764c0822009-12-01 09:51:01 +0000813 goto error;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000814
Daniel Dunbar644dca02009-12-04 08:17:33 +0000815 Act->Execute();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000816
Daniel Dunbard2f8be32009-12-01 21:57:33 +0000817 // Steal the created target, context, and preprocessor, and take back the
818 // source and file managers.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000819 TheSema.reset(Clang.takeSema());
820 Consumer.reset(Clang.takeASTConsumer());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000821 Ctx.reset(Clang.takeASTContext());
822 PP.reset(Clang.takePreprocessor());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000823 Clang.takeSourceManager();
824 Clang.takeFileManager();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000825 Target.reset(Clang.takeTarget());
826
Daniel Dunbar644dca02009-12-04 08:17:33 +0000827 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000828
829 // Remove the overridden buffer we used for the preamble.
Douglas Gregor8e984da2010-08-04 16:47:14 +0000830 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000831 PreprocessorOpts.eraseRemappedFile(
832 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor8e984da2010-08-04 16:47:14 +0000833 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
834 }
835
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000836 Invocation.reset(Clang.takeInvocation());
837 return false;
838
Daniel Dunbar764c0822009-12-01 09:51:01 +0000839error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000840 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +0000841 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000842 PreprocessorOpts.eraseRemappedFile(
843 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor8e984da2010-08-04 16:47:14 +0000844 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregora0734c52010-08-19 01:33:06 +0000845 delete OverrideMainBuffer;
Douglas Gregora3d3ba12010-10-06 21:11:08 +0000846 SavedMainFileBuffer = 0;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000847 }
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000848
Douglas Gregorefc46952010-10-12 16:25:54 +0000849 StoredDiagnostics.clear();
Daniel Dunbar764c0822009-12-01 09:51:01 +0000850 Clang.takeSourceManager();
851 Clang.takeFileManager();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000852 Invocation.reset(Clang.takeInvocation());
853 return true;
854}
855
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000856/// \brief Simple function to retrieve a path for a preamble precompiled header.
857static std::string GetPreamblePCHPath() {
858 // FIXME: This is lame; sys::Path should provide this function (in particular,
859 // it should know how to find the temporary files dir).
860 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor250ab1d2010-09-11 18:05:19 +0000861 // FIXME: This is a hack so that we can override the preamble file during
862 // crash-recovery testing, which is the only case where the preamble files
863 // are not necessarily cleaned up.
864 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
865 if (TmpFile)
866 return TmpFile;
867
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000868 std::string Error;
869 const char *TmpDir = ::getenv("TMPDIR");
870 if (!TmpDir)
871 TmpDir = ::getenv("TEMP");
872 if (!TmpDir)
873 TmpDir = ::getenv("TMP");
Douglas Gregorce3449f2010-09-11 17:51:16 +0000874#ifdef LLVM_ON_WIN32
875 if (!TmpDir)
876 TmpDir = ::getenv("USERPROFILE");
877#endif
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000878 if (!TmpDir)
879 TmpDir = "/tmp";
880 llvm::sys::Path P(TmpDir);
Douglas Gregorce3449f2010-09-11 17:51:16 +0000881 P.createDirectoryOnDisk(true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000882 P.appendComponent("preamble");
Douglas Gregor20975b22010-08-11 13:06:56 +0000883 P.appendSuffix("pch");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000884 if (P.createTemporaryFileOnDisk())
885 return std::string();
886
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000887 return P.str();
888}
889
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000890/// \brief Compute the preamble for the main file, providing the source buffer
891/// that corresponds to the main file along with a pair (bytes, start-of-line)
892/// that describes the preamble.
893std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor028d3e42010-08-09 20:45:32 +0000894ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
895 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000896 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Chris Lattner5159f612010-11-23 08:35:12 +0000897 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
Douglas Gregor4dde7492010-07-23 23:58:40 +0000898 CreatedBuffer = false;
899
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000900 // Try to determine if the main file has been remapped, either from the
901 // command line (to another file) or directly through the compiler invocation
902 // (to a memory buffer).
Douglas Gregor4dde7492010-07-23 23:58:40 +0000903 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000904 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
905 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
906 // Check whether there is a file-file remapping of the main file
907 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor4dde7492010-07-23 23:58:40 +0000908 M = PreprocessorOpts.remapped_file_begin(),
909 E = PreprocessorOpts.remapped_file_end();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000910 M != E;
911 ++M) {
912 llvm::sys::PathWithStatus MPath(M->first);
913 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
914 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
915 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000916 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000917 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000918 CreatedBuffer = false;
919 }
920
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000921 Buffer = getBufferForFile(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000922 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000923 return std::make_pair((llvm::MemoryBuffer*)0,
924 std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000925 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000926 }
927 }
928 }
929
930 // Check whether there is a file-buffer remapping. It supercedes the
931 // file-file remapping.
932 for (PreprocessorOptions::remapped_file_buffer_iterator
933 M = PreprocessorOpts.remapped_file_buffer_begin(),
934 E = PreprocessorOpts.remapped_file_buffer_end();
935 M != E;
936 ++M) {
937 llvm::sys::PathWithStatus MPath(M->first);
938 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
939 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
940 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000941 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000942 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000943 CreatedBuffer = false;
944 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000945
Douglas Gregor4dde7492010-07-23 23:58:40 +0000946 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000947 }
948 }
Douglas Gregor4dde7492010-07-23 23:58:40 +0000949 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000950 }
951
952 // If the main source file was not remapped, load it now.
953 if (!Buffer) {
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000954 Buffer = getBufferForFile(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000955 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000956 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000957
958 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000959 }
960
Douglas Gregor028d3e42010-08-09 20:45:32 +0000961 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000962}
963
Douglas Gregor6481ef12010-07-24 00:38:13 +0000964static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
Douglas Gregor6481ef12010-07-24 00:38:13 +0000965 unsigned NewSize,
966 llvm::StringRef NewName) {
967 llvm::MemoryBuffer *Result
968 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
969 memcpy(const_cast<char*>(Result->getBufferStart()),
970 Old->getBufferStart(), Old->getBufferSize());
971 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000972 ' ', NewSize - Old->getBufferSize() - 1);
973 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor6481ef12010-07-24 00:38:13 +0000974
Douglas Gregor6481ef12010-07-24 00:38:13 +0000975 return Result;
976}
977
Douglas Gregor4dde7492010-07-23 23:58:40 +0000978/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
979/// the source file.
980///
981/// This routine will compute the preamble of the main source file. If a
982/// non-trivial preamble is found, it will precompile that preamble into a
983/// precompiled header so that the precompiled preamble can be used to reduce
984/// reparsing time. If a precompiled preamble has already been constructed,
985/// this routine will determine if it is still valid and, if so, avoid
986/// rebuilding the precompiled preamble.
987///
Douglas Gregor028d3e42010-08-09 20:45:32 +0000988/// \param AllowRebuild When true (the default), this routine is
989/// allowed to rebuild the precompiled preamble if it is found to be
990/// out-of-date.
991///
992/// \param MaxLines When non-zero, the maximum number of lines that
993/// can occur within the preamble.
994///
Douglas Gregor6481ef12010-07-24 00:38:13 +0000995/// \returns If the precompiled preamble can be used, returns a newly-allocated
996/// buffer that should be used in place of the main file when doing so.
997/// Otherwise, returns a NULL pointer.
Douglas Gregor028d3e42010-08-09 20:45:32 +0000998llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregorb97b6662010-08-20 00:59:43 +0000999 CompilerInvocation PreambleInvocation,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001000 bool AllowRebuild,
1001 unsigned MaxLines) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001002 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
1003 PreprocessorOptions &PreprocessorOpts
1004 = PreambleInvocation.getPreprocessorOpts();
1005
1006 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001007 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor028d3e42010-08-09 20:45:32 +00001008 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001009
Douglas Gregor3edb1672010-11-16 20:45:51 +00001010 // If ComputePreamble() Take ownership of the
1011 llvm::OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
1012 if (CreatedPreambleBuffer)
1013 OwnedPreambleBuffer.reset(NewPreamble.first);
1014
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001015 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001016 // We couldn't find a preamble in the main source. Clear out the current
1017 // preamble, if we have one. It's obviously no good any more.
1018 Preamble.clear();
1019 if (!PreambleFile.empty()) {
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001020 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001021 PreambleFile.clear();
1022 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001023
1024 // The next time we actually see a preamble, precompile it.
1025 PreambleRebuildCounter = 1;
Douglas Gregor6481ef12010-07-24 00:38:13 +00001026 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001027 }
1028
1029 if (!Preamble.empty()) {
1030 // We've previously computed a preamble. Check whether we have the same
1031 // preamble now that we did before, and that there's enough space in
1032 // the main-file buffer within the precompiled preamble to fit the
1033 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001034 if (Preamble.size() == NewPreamble.second.first &&
1035 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregorf5275a82010-07-24 00:42:07 +00001036 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor4dde7492010-07-23 23:58:40 +00001037 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001038 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001039 // The preamble has not changed. We may be able to re-use the precompiled
1040 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001041
Douglas Gregor0e119552010-07-31 00:40:00 +00001042 // Check that none of the files used by the preamble have changed.
1043 bool AnyFileChanged = false;
1044
1045 // First, make a record of those files that have been overridden via
1046 // remapping or unsaved_files.
1047 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1048 for (PreprocessorOptions::remapped_file_iterator
1049 R = PreprocessorOpts.remapped_file_begin(),
1050 REnd = PreprocessorOpts.remapped_file_end();
1051 !AnyFileChanged && R != REnd;
1052 ++R) {
1053 struct stat StatBuf;
1054 if (stat(R->second.c_str(), &StatBuf)) {
1055 // If we can't stat the file we're remapping to, assume that something
1056 // horrible happened.
1057 AnyFileChanged = true;
1058 break;
1059 }
Douglas Gregor6481ef12010-07-24 00:38:13 +00001060
Douglas Gregor0e119552010-07-31 00:40:00 +00001061 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1062 StatBuf.st_mtime);
1063 }
1064 for (PreprocessorOptions::remapped_file_buffer_iterator
1065 R = PreprocessorOpts.remapped_file_buffer_begin(),
1066 REnd = PreprocessorOpts.remapped_file_buffer_end();
1067 !AnyFileChanged && R != REnd;
1068 ++R) {
1069 // FIXME: Should we actually compare the contents of file->buffer
1070 // remappings?
1071 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1072 0);
1073 }
1074
1075 // Check whether anything has changed.
1076 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1077 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1078 !AnyFileChanged && F != FEnd;
1079 ++F) {
1080 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1081 = OverriddenFiles.find(F->first());
1082 if (Overridden != OverriddenFiles.end()) {
1083 // This file was remapped; check whether the newly-mapped file
1084 // matches up with the previous mapping.
1085 if (Overridden->second != F->second)
1086 AnyFileChanged = true;
1087 continue;
1088 }
1089
1090 // The file was not remapped; check whether it has changed on disk.
1091 struct stat StatBuf;
1092 if (stat(F->first(), &StatBuf)) {
1093 // If we can't stat the file, assume that something horrible happened.
1094 AnyFileChanged = true;
1095 } else if (StatBuf.st_size != F->second.first ||
1096 StatBuf.st_mtime != F->second.second)
1097 AnyFileChanged = true;
1098 }
1099
1100 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001101 // Okay! We can re-use the precompiled preamble.
1102
1103 // Set the state of the diagnostic object to mimic its state
1104 // after parsing the preamble.
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001105 // FIXME: This won't catch any #pragma push warning changes that
1106 // have occurred in the preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001107 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001108 ProcessWarningOptions(getDiagnostics(),
1109 PreambleInvocation.getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001110 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1111 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
1112 StoredDiagnostics.erase(
1113 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
1114 StoredDiagnostics.end());
1115
1116 // Create a version of the main file buffer that is padded to
1117 // buffer size we reserved when creating the preamble.
Douglas Gregor0e119552010-07-31 00:40:00 +00001118 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor0e119552010-07-31 00:40:00 +00001119 PreambleReservedSize,
1120 FrontendOpts.Inputs[0].second);
1121 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001122 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001123
1124 // If we aren't allowed to rebuild the precompiled preamble, just
1125 // return now.
1126 if (!AllowRebuild)
1127 return 0;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001128
Douglas Gregor4dde7492010-07-23 23:58:40 +00001129 // We can't reuse the previously-computed preamble. Build a new one.
1130 Preamble.clear();
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001131 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001132 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001133 } else if (!AllowRebuild) {
1134 // We aren't allowed to rebuild the precompiled preamble; just
1135 // return now.
1136 return 0;
1137 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001138
1139 // If the preamble rebuild counter > 1, it's because we previously
1140 // failed to build a preamble and we're not yet ready to try
1141 // again. Decrement the counter and return a failure.
1142 if (PreambleRebuildCounter > 1) {
1143 --PreambleRebuildCounter;
1144 return 0;
1145 }
1146
Douglas Gregore10f0e52010-09-11 17:56:52 +00001147 // Create a temporary file for the precompiled preamble. In rare
1148 // circumstances, this can fail.
1149 std::string PreamblePCHPath = GetPreamblePCHPath();
1150 if (PreamblePCHPath.empty()) {
1151 // Try again next time.
1152 PreambleRebuildCounter = 1;
1153 return 0;
1154 }
1155
Douglas Gregor4dde7492010-07-23 23:58:40 +00001156 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001157 SimpleTimer PreambleTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001158 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001159
1160 // Create a new buffer that stores the preamble. The buffer also contains
1161 // extra space for the original contents of the file (which will be present
1162 // when we actually parse the file) along with more room in case the file
Douglas Gregor4dde7492010-07-23 23:58:40 +00001163 // grows.
1164 PreambleReservedSize = NewPreamble.first->getBufferSize();
1165 if (PreambleReservedSize < 4096)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001166 PreambleReservedSize = 8191;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001167 else
Douglas Gregor4dde7492010-07-23 23:58:40 +00001168 PreambleReservedSize *= 2;
1169
Douglas Gregord9a30af2010-08-02 20:51:39 +00001170 // Save the preamble text for later; we'll need to compare against it for
1171 // subsequent reparses.
1172 Preamble.assign(NewPreamble.first->getBufferStart(),
1173 NewPreamble.first->getBufferStart()
1174 + NewPreamble.second.first);
1175 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1176
Douglas Gregora0734c52010-08-19 01:33:06 +00001177 delete PreambleBuffer;
1178 PreambleBuffer
Douglas Gregor4dde7492010-07-23 23:58:40 +00001179 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001180 FrontendOpts.Inputs[0].second);
1181 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor4dde7492010-07-23 23:58:40 +00001182 NewPreamble.first->getBufferStart(), Preamble.size());
1183 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001184 ' ', PreambleReservedSize - Preamble.size() - 1);
1185 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001186
1187 // Remap the main source file to the preamble buffer.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001188 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001189 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1190
1191 // Tell the compiler invocation to generate a temporary precompiled header.
1192 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor9e136b52010-10-01 01:05:22 +00001193 FrontendOpts.ChainedPCH = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001194 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001195 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001196 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1197 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001198
1199 // Create the compiler instance to use for building the precompiled preamble.
1200 CompilerInstance Clang;
1201 Clang.setInvocation(&PreambleInvocation);
1202 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1203
Douglas Gregor8e984da2010-08-04 16:47:14 +00001204 // Set up diagnostics, capturing all of the diagnostics produced.
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001205 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001206
1207 // Create the target instance.
1208 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1209 Clang.getTargetOpts()));
1210 if (!Clang.hasTarget()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001211 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1212 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001213 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001214 PreprocessorOpts.eraseRemappedFile(
1215 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001216 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001217 }
1218
1219 // Inform the target of the language options.
1220 //
1221 // FIXME: We shouldn't need to do this, the target should be immutable once
1222 // created. This complexity should be lifted elsewhere.
1223 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1224
1225 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1226 "Invocation must have exactly one source file!");
1227 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1228 "FIXME: AST inputs not yet supported here!");
1229 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1230 "IR inputs not support here!");
1231
1232 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001233 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001234 ProcessWarningOptions(getDiagnostics(), Clang.getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001235 StoredDiagnostics.erase(
1236 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1237 StoredDiagnostics.end());
Douglas Gregore9db88f2010-08-03 19:06:41 +00001238 TopLevelDecls.clear();
1239 TopLevelDeclsInPreamble.clear();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001240
1241 // Create a file manager object to provide access to and cache the filesystem.
Chris Lattner3f5a9ef2010-11-23 07:51:02 +00001242 Clang.setFileManager(new FileManager(Clang.getFileSystemOpts()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001243
1244 // Create the source manager.
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +00001245 Clang.setSourceManager(new SourceManager(getDiagnostics(),
Chris Lattner5159f612010-11-23 08:35:12 +00001246 Clang.getFileManager()));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001247
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001248 llvm::OwningPtr<PrecompilePreambleAction> Act;
1249 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001250 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1251 Clang.getFrontendOpts().Inputs[0].first)) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001252 Clang.takeInvocation();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001253 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1254 Preamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001255 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001256 PreprocessorOpts.eraseRemappedFile(
1257 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001258 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001259 }
1260
1261 Act->Execute();
1262 Act->EndSourceFile();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001263 Clang.takeInvocation();
1264
Douglas Gregore9db88f2010-08-03 19:06:41 +00001265 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001266 // There were errors parsing the preamble, so no precompiled header was
1267 // generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001268 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor4dde7492010-07-23 23:58:40 +00001269 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1270 Preamble.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001271 TopLevelDeclsInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001272 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001273 PreprocessorOpts.eraseRemappedFile(
1274 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001275 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001276 }
1277
1278 // Keep track of the preamble we precompiled.
1279 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregord9a30af2010-08-02 20:51:39 +00001280 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1281 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001282
1283 // Keep track of all of the files that the source manager knows about,
1284 // so we can verify whether they have changed or not.
1285 FilesInPreamble.clear();
1286 SourceManager &SourceMgr = Clang.getSourceManager();
1287 const llvm::MemoryBuffer *MainFileBuffer
1288 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1289 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1290 FEnd = SourceMgr.fileinfo_end();
1291 F != FEnd;
1292 ++F) {
1293 const FileEntry *File = F->second->Entry;
1294 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1295 continue;
1296
1297 FilesInPreamble[File->getName()]
1298 = std::make_pair(F->second->getSize(), File->getModificationTime());
1299 }
1300
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001301 PreambleRebuildCounter = 1;
Douglas Gregora0734c52010-08-19 01:33:06 +00001302 PreprocessorOpts.eraseRemappedFile(
1303 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001304 return CreatePaddedMainFileBuffer(NewPreamble.first,
Douglas Gregor6481ef12010-07-24 00:38:13 +00001305 PreambleReservedSize,
1306 FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001307}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001308
Douglas Gregore9db88f2010-08-03 19:06:41 +00001309void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1310 std::vector<Decl *> Resolved;
1311 Resolved.reserve(TopLevelDeclsInPreamble.size());
1312 ExternalASTSource &Source = *getASTContext().getExternalSource();
1313 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1314 // Resolve the declaration ID to an actual declaration, possibly
1315 // deserializing the declaration in the process.
1316 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1317 if (D)
1318 Resolved.push_back(D);
1319 }
1320 TopLevelDeclsInPreamble.clear();
1321 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1322}
1323
1324unsigned ASTUnit::getMaxPCHLevel() const {
1325 if (!getOnlyLocalDecls())
1326 return Decl::MaxPCHLevel;
1327
Sebastian Redl009e7f22010-10-05 16:15:19 +00001328 return 0;
Douglas Gregore9db88f2010-08-03 19:06:41 +00001329}
1330
Douglas Gregor16896c42010-10-28 15:44:59 +00001331llvm::StringRef ASTUnit::getMainFileName() const {
1332 return Invocation->getFrontendOpts().Inputs[0].second;
1333}
1334
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001335bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1336 if (!Invocation)
1337 return true;
1338
1339 // We'll manage file buffers ourselves.
1340 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1341 Invocation->getFrontendOpts().DisableFree = false;
1342
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001343 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorf5a18542010-10-27 17:24:53 +00001344 if (PrecompilePreamble) {
Douglas Gregorc6592922010-11-15 23:00:34 +00001345 PreambleRebuildCounter = 2;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001346 OverrideMainBuffer
1347 = getMainBufferWithPrecompiledPreamble(*Invocation);
1348 }
1349
Douglas Gregor16896c42010-10-28 15:44:59 +00001350 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001351 ParsingTimer.setOutput("Parsing " + getMainFileName());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001352
Douglas Gregor16896c42010-10-28 15:44:59 +00001353 return Parse(OverrideMainBuffer);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001354}
1355
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001356ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1357 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1358 bool OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001359 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001360 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001361 bool CompleteTranslationUnit,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001362 bool CacheCodeCompletionResults) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001363 // Create the AST unit.
1364 llvm::OwningPtr<ASTUnit> AST;
1365 AST.reset(new ASTUnit(false));
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001366 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001367 AST->Diagnostics = Diags;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001368 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001369 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001370 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001371 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregorc6592922010-11-15 23:00:34 +00001372 AST->CacheCodeCompletionCoolDown = 1;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001373 AST->Invocation.reset(CI);
1374
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001375 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar764c0822009-12-01 09:51:01 +00001376}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001377
1378ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1379 const char **ArgEnd,
Douglas Gregor7f95d262010-04-05 23:52:57 +00001380 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar8d4a2022009-12-13 03:46:13 +00001381 llvm::StringRef ResourceFilesPath,
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001382 bool OnlyLocalDecls,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001383 bool CaptureDiagnostics,
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001384 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001385 unsigned NumRemappedFiles,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001386 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001387 bool CompleteTranslationUnit,
Douglas Gregorf5a18542010-10-27 17:24:53 +00001388 bool CacheCodeCompletionResults,
1389 bool CXXPrecompilePreamble,
1390 bool CXXChainedPCH) {
Douglas Gregor7f95d262010-04-05 23:52:57 +00001391 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00001392 // No diagnostics engine was provided, so create our own diagnostics object
1393 // with the default options.
1394 DiagnosticOptions DiagOpts;
Douglas Gregor7f95d262010-04-05 23:52:57 +00001395 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregord03e8232010-04-05 21:10:19 +00001396 }
1397
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001398 llvm::SmallVector<const char *, 16> Args;
1399 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1400 Args.insert(Args.end(), ArgBegin, ArgEnd);
1401
1402 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1403 // also want to force it to use clang.
1404 Args.push_back("-fsyntax-only");
1405
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001406 llvm::SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1407
1408 llvm::OwningPtr<CompilerInvocation> CI;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001409
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001410 {
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001411 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001412 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001413
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001414 // FIXME: We shouldn't have to pass in the path info.
1415 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
1416 "a.out", false, false, *Diags);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001417
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001418 // Don't check that inputs exist, they have been remapped.
1419 TheDriver.setCheckInputsExist(false);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001420
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001421 llvm::OwningPtr<driver::Compilation> C(
1422 TheDriver.BuildCompilation(Args.size(), Args.data()));
1423
1424 // We expect to get back exactly one command job, if we didn't something
1425 // failed.
1426 const driver::JobList &Jobs = C->getJobs();
1427 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1428 llvm::SmallString<256> Msg;
1429 llvm::raw_svector_ostream OS(Msg);
1430 C->PrintJob(OS, C->getJobs(), "; ", true);
1431 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
1432 return 0;
1433 }
1434
1435 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1436 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
1437 Diags->Report(diag::err_fe_expected_clang_command);
1438 return 0;
1439 }
1440
1441 const driver::ArgStringList &CCArgs = Cmd->getArguments();
1442 CI.reset(new CompilerInvocation);
1443 CompilerInvocation::CreateFromArgs(*CI,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001444 const_cast<const char **>(CCArgs.data()),
1445 const_cast<const char **>(CCArgs.data()) +
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001446 CCArgs.size(),
1447 *Diags);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001448 }
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001449
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001450 // Override any files that need remapping
1451 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001452 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbar19511922010-02-16 01:55:04 +00001453 RemappedFiles[I].second);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001454
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001455 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001456 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001457
Douglas Gregorf5a18542010-10-27 17:24:53 +00001458 // Check whether we should precompile the preamble and/or use chained PCH.
1459 // FIXME: This is a temporary hack while we debug C++ chained PCH.
1460 if (CI->getLangOpts().CPlusPlus) {
1461 PrecompilePreamble = PrecompilePreamble && CXXPrecompilePreamble;
1462
1463 if (PrecompilePreamble && !CXXChainedPCH &&
1464 !CI->getPreprocessorOpts().ImplicitPCHInclude.empty())
1465 PrecompilePreamble = false;
1466 }
1467
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001468 // Create the AST unit.
1469 llvm::OwningPtr<ASTUnit> AST;
1470 AST.reset(new ASTUnit(false));
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001471 ConfigureDiags(Diags, *AST, CaptureDiagnostics);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001472 AST->Diagnostics = Diags;
Chris Lattner5159f612010-11-23 08:35:12 +00001473
1474 AST->FileMgr.reset(new FileManager(FileSystemOptions()));
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001475 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001476 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001477 AST->CompleteTranslationUnit = CompleteTranslationUnit;
1478 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregorc6592922010-11-15 23:00:34 +00001479 AST->CacheCodeCompletionCoolDown = 1;
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001480 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1481 AST->NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1482 AST->StoredDiagnostics.swap(StoredDiagnostics);
1483 AST->Invocation.reset(CI.take());
Chris Lattner5159f612010-11-23 08:35:12 +00001484 return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001485}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001486
1487bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1488 if (!Invocation.get())
1489 return true;
1490
Douglas Gregor16896c42010-10-28 15:44:59 +00001491 SimpleTimer ParsingTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001492 ParsingTimer.setOutput("Reparsing " + getMainFileName());
Douglas Gregor16896c42010-10-28 15:44:59 +00001493
Douglas Gregor0e119552010-07-31 00:40:00 +00001494 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00001495 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1496 for (PreprocessorOptions::remapped_file_buffer_iterator
1497 R = PPOpts.remapped_file_buffer_begin(),
1498 REnd = PPOpts.remapped_file_buffer_end();
1499 R != REnd;
1500 ++R) {
1501 delete R->second;
1502 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001503 Invocation->getPreprocessorOpts().clearRemappedFiles();
1504 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1505 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1506 RemappedFiles[I].second);
1507
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001508 // If we have a preamble file lying around, or if we might try to
1509 // build a precompiled preamble, do so now.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001510 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001511 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregorb97b6662010-08-20 00:59:43 +00001512 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001513
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001514 // Clear out the diagnostics state.
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001515 if (!OverrideMainBuffer) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001516 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001517 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1518 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001519
Douglas Gregor4dde7492010-07-23 23:58:40 +00001520 // Parse the sources
Douglas Gregor6481ef12010-07-24 00:38:13 +00001521 bool Result = Parse(OverrideMainBuffer);
Douglas Gregor2c8bd472010-08-17 00:40:40 +00001522
1523 if (ShouldCacheCodeCompletionResults) {
1524 if (CacheCodeCompletionCoolDown > 0)
1525 --CacheCodeCompletionCoolDown;
1526 else if (top_level_size() != NumTopLevelDeclsAtLastCompletionCache)
1527 CacheCodeCompletionResults();
1528 }
1529
Douglas Gregor4dde7492010-07-23 23:58:40 +00001530 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001531}
Douglas Gregor8e984da2010-08-04 16:47:14 +00001532
Douglas Gregorb14904c2010-08-13 22:48:40 +00001533//----------------------------------------------------------------------------//
1534// Code completion
1535//----------------------------------------------------------------------------//
1536
1537namespace {
1538 /// \brief Code completion consumer that combines the cached code-completion
1539 /// results from an ASTUnit with the code-completion results provided to it,
1540 /// then passes the result on to
1541 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1542 unsigned NormalContexts;
1543 ASTUnit &AST;
1544 CodeCompleteConsumer &Next;
1545
1546 public:
1547 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor39982192010-08-15 06:18:01 +00001548 bool IncludeMacros, bool IncludeCodePatterns,
1549 bool IncludeGlobals)
1550 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001551 Next.isOutputBinary()), AST(AST), Next(Next)
1552 {
1553 // Compute the set of contexts in which we will look when we don't have
1554 // any information about the specific context.
1555 NormalContexts
1556 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
1557 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
1558 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1559 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1560 | (1 << (CodeCompletionContext::CCC_Statement - 1))
1561 | (1 << (CodeCompletionContext::CCC_Expression - 1))
1562 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1563 | (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +00001564 | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
Douglas Gregor0ac41382010-09-23 23:01:17 +00001565 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
1566 | (1 << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor5e35d592010-09-14 23:59:36 +00001567
Douglas Gregorb14904c2010-08-13 22:48:40 +00001568 if (AST.getASTContext().getLangOptions().CPlusPlus)
1569 NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1))
1570 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
1571 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
1572 }
1573
1574 virtual void ProcessCodeCompleteResults(Sema &S,
1575 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001576 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001577 unsigned NumResults);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001578
1579 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1580 OverloadCandidate *Candidates,
1581 unsigned NumCandidates) {
1582 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1583 }
1584 };
1585}
Douglas Gregord46cf182010-08-16 20:01:48 +00001586
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001587/// \brief Helper function that computes which global names are hidden by the
1588/// local code-completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00001589static void CalculateHiddenNames(const CodeCompletionContext &Context,
1590 CodeCompletionResult *Results,
1591 unsigned NumResults,
1592 ASTContext &Ctx,
1593 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001594 bool OnlyTagNames = false;
1595 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00001596 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001597 case CodeCompletionContext::CCC_TopLevel:
1598 case CodeCompletionContext::CCC_ObjCInterface:
1599 case CodeCompletionContext::CCC_ObjCImplementation:
1600 case CodeCompletionContext::CCC_ObjCIvarList:
1601 case CodeCompletionContext::CCC_ClassStructUnion:
1602 case CodeCompletionContext::CCC_Statement:
1603 case CodeCompletionContext::CCC_Expression:
1604 case CodeCompletionContext::CCC_ObjCMessageReceiver:
1605 case CodeCompletionContext::CCC_MemberAccess:
1606 case CodeCompletionContext::CCC_Namespace:
1607 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00001608 case CodeCompletionContext::CCC_Name:
1609 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001610 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001611 break;
1612
1613 case CodeCompletionContext::CCC_EnumTag:
1614 case CodeCompletionContext::CCC_UnionTag:
1615 case CodeCompletionContext::CCC_ClassOrStructTag:
1616 OnlyTagNames = true;
1617 break;
1618
1619 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00001620 case CodeCompletionContext::CCC_MacroName:
1621 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00001622 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001623 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00001624 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00001625 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00001626 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00001627 case CodeCompletionContext::CCC_Other:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001628 // We're looking for nothing, or we're looking for names that cannot
1629 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001630 return;
1631 }
1632
John McCall276321a2010-08-25 06:19:51 +00001633 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001634 for (unsigned I = 0; I != NumResults; ++I) {
1635 if (Results[I].Kind != Result::RK_Declaration)
1636 continue;
1637
1638 unsigned IDNS
1639 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1640
1641 bool Hiding = false;
1642 if (OnlyTagNames)
1643 Hiding = (IDNS & Decl::IDNS_Tag);
1644 else {
1645 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00001646 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1647 Decl::IDNS_NonMemberOperator);
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001648 if (Ctx.getLangOptions().CPlusPlus)
1649 HiddenIDNS |= Decl::IDNS_Tag;
1650 Hiding = (IDNS & HiddenIDNS);
1651 }
1652
1653 if (!Hiding)
1654 continue;
1655
1656 DeclarationName Name = Results[I].Declaration->getDeclName();
1657 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1658 HiddenNames.insert(Identifier->getName());
1659 else
1660 HiddenNames.insert(Name.getAsString());
1661 }
1662}
1663
1664
Douglas Gregord46cf182010-08-16 20:01:48 +00001665void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1666 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001667 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001668 unsigned NumResults) {
1669 // Merge the results we were given with the results we cached.
1670 bool AddedResult = false;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001671 unsigned InContexts
Douglas Gregor0ac41382010-09-23 23:01:17 +00001672 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001673 : (1 << (Context.getKind() - 1)));
1674
1675 // Contains the set of names that are hidden by "local" completion results.
Ted Kremenek6a153372010-11-07 06:11:36 +00001676 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
Douglas Gregor12785102010-08-24 20:21:13 +00001677 llvm::SmallVector<CodeCompletionString *, 4> StringsToDestroy;
John McCall276321a2010-08-25 06:19:51 +00001678 typedef CodeCompletionResult Result;
Douglas Gregord46cf182010-08-16 20:01:48 +00001679 llvm::SmallVector<Result, 8> AllResults;
1680 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00001681 C = AST.cached_completion_begin(),
1682 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00001683 C != CEnd; ++C) {
1684 // If the context we are in matches any of the contexts we are
1685 // interested in, we'll add this result.
1686 if ((C->ShowInContexts & InContexts) == 0)
1687 continue;
1688
1689 // If we haven't added any results previously, do so now.
1690 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001691 CalculateHiddenNames(Context, Results, NumResults, S.Context,
1692 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00001693 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1694 AddedResult = true;
1695 }
1696
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001697 // Determine whether this global completion result is hidden by a local
1698 // completion result. If so, skip it.
1699 if (C->Kind != CXCursor_MacroDefinition &&
1700 HiddenNames.count(C->Completion->getTypedText()))
1701 continue;
1702
Douglas Gregord46cf182010-08-16 20:01:48 +00001703 // Adjust priority based on similar type classes.
1704 unsigned Priority = C->Priority;
Douglas Gregor8850aa32010-08-25 18:03:13 +00001705 CXCursorKind CursorKind = C->Kind;
Douglas Gregor12785102010-08-24 20:21:13 +00001706 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00001707 if (!Context.getPreferredType().isNull()) {
1708 if (C->Kind == CXCursor_MacroDefinition) {
1709 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00001710 S.getLangOptions(),
Douglas Gregor12785102010-08-24 20:21:13 +00001711 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00001712 } else if (C->Type) {
1713 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00001714 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00001715 Context.getPreferredType().getUnqualifiedType());
1716 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
1717 if (ExpectedSTC == C->TypeClass) {
1718 // We know this type is similar; check for an exact match.
1719 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00001720 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00001721 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00001722 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00001723 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
1724 Priority /= CCF_ExactTypeMatch;
1725 else
1726 Priority /= CCF_SimilarTypeMatch;
1727 }
1728 }
1729 }
1730
Douglas Gregor12785102010-08-24 20:21:13 +00001731 // Adjust the completion string, if required.
1732 if (C->Kind == CXCursor_MacroDefinition &&
1733 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
1734 // Create a new code-completion string that just contains the
1735 // macro name, without its arguments.
1736 Completion = new CodeCompletionString;
1737 Completion->AddTypedTextChunk(C->Completion->getTypedText());
1738 StringsToDestroy.push_back(Completion);
Douglas Gregor8850aa32010-08-25 18:03:13 +00001739 CursorKind = CXCursor_NotImplemented;
1740 Priority = CCP_CodePattern;
Douglas Gregor12785102010-08-24 20:21:13 +00001741 }
1742
Douglas Gregor8850aa32010-08-25 18:03:13 +00001743 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregorf757a122010-08-23 23:00:57 +00001744 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00001745 }
1746
1747 // If we did not add any cached completion results, just forward the
1748 // results we were given to the next consumer.
1749 if (!AddedResult) {
1750 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
1751 return;
1752 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00001753
Douglas Gregord46cf182010-08-16 20:01:48 +00001754 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
1755 AllResults.size());
Douglas Gregor12785102010-08-24 20:21:13 +00001756
1757 for (unsigned I = 0, N = StringsToDestroy.size(); I != N; ++I)
1758 delete StringsToDestroy[I];
Douglas Gregord46cf182010-08-16 20:01:48 +00001759}
1760
1761
1762
Douglas Gregor8e984da2010-08-04 16:47:14 +00001763void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
1764 RemappedFile *RemappedFiles,
1765 unsigned NumRemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00001766 bool IncludeMacros,
1767 bool IncludeCodePatterns,
Douglas Gregor8e984da2010-08-04 16:47:14 +00001768 CodeCompleteConsumer &Consumer,
1769 Diagnostic &Diag, LangOptions &LangOpts,
1770 SourceManager &SourceMgr, FileManager &FileMgr,
Douglas Gregorb97b6662010-08-20 00:59:43 +00001771 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
1772 llvm::SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001773 if (!Invocation.get())
1774 return;
1775
Douglas Gregor16896c42010-10-28 15:44:59 +00001776 SimpleTimer CompletionTimer(WantTiming);
Benjamin Kramerf2e5a912010-11-09 20:00:56 +00001777 CompletionTimer.setOutput("Code completion @ " + File + ":" +
1778 llvm::Twine(Line) + ":" + llvm::Twine(Column));
Douglas Gregor028d3e42010-08-09 20:45:32 +00001779
Douglas Gregor8e984da2010-08-04 16:47:14 +00001780 CompilerInvocation CCInvocation(*Invocation);
1781 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
1782 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00001783
Douglas Gregorb14904c2010-08-13 22:48:40 +00001784 FrontendOpts.ShowMacrosInCodeCompletion
1785 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorb68bc592010-08-05 09:09:23 +00001786 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor39982192010-08-15 06:18:01 +00001787 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
1788 = CachedCompletionResults.empty();
Douglas Gregor8e984da2010-08-04 16:47:14 +00001789 FrontendOpts.CodeCompletionAt.FileName = File;
1790 FrontendOpts.CodeCompletionAt.Line = Line;
1791 FrontendOpts.CodeCompletionAt.Column = Column;
1792
1793 // Set the language options appropriately.
1794 LangOpts = CCInvocation.getLangOpts();
1795
1796 CompilerInstance Clang;
1797 Clang.setInvocation(&CCInvocation);
1798 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1799
1800 // Set up diagnostics, capturing any diagnostics produced.
1801 Clang.setDiagnostics(&Diag);
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001802 ProcessWarningOptions(Diag, CCInvocation.getDiagnosticOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00001803 CaptureDroppedDiagnostics Capture(true,
Douglas Gregor44c6ee72010-11-11 00:39:14 +00001804 Clang.getDiagnostics(),
Douglas Gregor8e984da2010-08-04 16:47:14 +00001805 StoredDiagnostics);
Douglas Gregor8e984da2010-08-04 16:47:14 +00001806
1807 // Create the target instance.
1808 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1809 Clang.getTargetOpts()));
1810 if (!Clang.hasTarget()) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001811 Clang.takeInvocation();
Douglas Gregor2dd19f12010-08-18 22:29:43 +00001812 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00001813 }
1814
1815 // Inform the target of the language options.
1816 //
1817 // FIXME: We shouldn't need to do this, the target should be immutable once
1818 // created. This complexity should be lifted elsewhere.
1819 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1820
1821 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1822 "Invocation must have exactly one source file!");
1823 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1824 "FIXME: AST inputs not yet supported here!");
1825 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1826 "IR inputs not support here!");
1827
1828
1829 // Use the source and file managers that we were given.
1830 Clang.setFileManager(&FileMgr);
1831 Clang.setSourceManager(&SourceMgr);
1832
1833 // Remap files.
1834 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00001835 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregorb97b6662010-08-20 00:59:43 +00001836 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001837 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
1838 RemappedFiles[I].second);
Douglas Gregorb97b6662010-08-20 00:59:43 +00001839 OwnedBuffers.push_back(RemappedFiles[I].second);
1840 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00001841
Douglas Gregorb14904c2010-08-13 22:48:40 +00001842 // Use the code completion consumer we were given, but adding any cached
1843 // code-completion results.
1844 AugmentedCodeCompleteConsumer
1845 AugmentedConsumer(*this, Consumer, FrontendOpts.ShowMacrosInCodeCompletion,
Douglas Gregor39982192010-08-15 06:18:01 +00001846 FrontendOpts.ShowCodePatternsInCodeCompletion,
1847 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001848 Clang.setCodeCompletionConsumer(&AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00001849
Douglas Gregor028d3e42010-08-09 20:45:32 +00001850 // If we have a precompiled preamble, try to use it. We only allow
1851 // the use of the precompiled preamble if we're if the completion
1852 // point is within the main file, after the end of the precompiled
1853 // preamble.
1854 llvm::MemoryBuffer *OverrideMainBuffer = 0;
1855 if (!PreambleFile.empty()) {
1856 using llvm::sys::FileStatus;
1857 llvm::sys::PathWithStatus CompleteFilePath(File);
1858 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
1859 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
1860 if (const FileStatus *MainStatus = MainPath.getFileStatus())
1861 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
Douglas Gregorb97b6662010-08-20 00:59:43 +00001862 OverrideMainBuffer
Douglas Gregor8e817b62010-08-25 18:04:15 +00001863 = getMainBufferWithPrecompiledPreamble(CCInvocation, false,
1864 Line - 1);
Douglas Gregor028d3e42010-08-09 20:45:32 +00001865 }
1866
1867 // If the main file has been overridden due to the use of a preamble,
1868 // make that override happen and introduce the preamble.
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001869 StoredDiagnostics.insert(StoredDiagnostics.end(),
1870 this->StoredDiagnostics.begin(),
1871 this->StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver);
Douglas Gregor028d3e42010-08-09 20:45:32 +00001872 if (OverrideMainBuffer) {
1873 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1874 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1875 PreprocessorOpts.PrecompiledPreambleBytes.second
1876 = PreambleEndsAtStartOfLine;
1877 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
1878 PreprocessorOpts.DisablePCHValidation = true;
1879
1880 // The stored diagnostics have the old source manager. Copy them
1881 // to our output set of stored diagnostics, updating the source
1882 // manager to the one we were given.
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001883 for (unsigned I = NumStoredDiagnosticsFromDriver,
1884 N = this->StoredDiagnostics.size();
1885 I < N; ++I) {
Douglas Gregor028d3e42010-08-09 20:45:32 +00001886 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
1887 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
1888 StoredDiagnostics[I].setLocation(Loc);
1889 }
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001890
Douglas Gregorb97b6662010-08-20 00:59:43 +00001891 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001892 } else {
1893 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1894 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001895 }
1896
Douglas Gregor8e984da2010-08-04 16:47:14 +00001897 llvm::OwningPtr<SyntaxOnlyAction> Act;
1898 Act.reset(new SyntaxOnlyAction);
1899 if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1900 Clang.getFrontendOpts().Inputs[0].first)) {
1901 Act->Execute();
1902 Act->EndSourceFile();
1903 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001904
Douglas Gregor8e984da2010-08-04 16:47:14 +00001905 // Steal back our resources.
1906 Clang.takeFileManager();
1907 Clang.takeSourceManager();
1908 Clang.takeInvocation();
Douglas Gregor8e984da2010-08-04 16:47:14 +00001909 Clang.takeCodeCompletionConsumer();
1910}
Douglas Gregore9386682010-08-13 05:36:37 +00001911
1912bool ASTUnit::Save(llvm::StringRef File) {
1913 if (getDiagnostics().hasErrorOccurred())
1914 return true;
1915
1916 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
1917 // unconditionally create a stat cache when we parse the file?
1918 std::string ErrorInfo;
Benjamin Kramer340045b2010-08-15 16:54:31 +00001919 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo,
1920 llvm::raw_fd_ostream::F_Binary);
Douglas Gregore9386682010-08-13 05:36:37 +00001921 if (!ErrorInfo.empty() || Out.has_error())
1922 return true;
1923
1924 std::vector<unsigned char> Buffer;
1925 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redl55c0ad52010-08-18 23:56:21 +00001926 ASTWriter Writer(Stream);
1927 Writer.WriteAST(getSema(), 0, 0);
Douglas Gregore9386682010-08-13 05:36:37 +00001928
1929 // Write the generated bitstream to "Out".
Douglas Gregor2dd19f12010-08-18 22:29:43 +00001930 if (!Buffer.empty())
1931 Out.write((char *)&Buffer.front(), Buffer.size());
Douglas Gregore9386682010-08-13 05:36:37 +00001932 Out.close();
1933 return Out.has_error();
1934}