blob: a0c9b4b40c7a32edd82e8639e80c9a270283d74b [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
55 public:
56 explicit SimpleTimer(bool WantTiming) : WantTiming(true) {
57 Start = TimeRecord::getCurrentTime();
58 }
59
60 void setOutput(llvm::StringRef Output) {
61 if (WantTiming)
62 this->Output = Output;
63 }
64
65 void setOutput(llvm::Twine Output) {
66 if (WantTiming)
67 this->Output = Output.str();
68 }
69
70 void setOutput(const char *Output) {
71 if (WantTiming)
72 this->Output = Output;
73 }
74
75 ~SimpleTimer() {
76 if (WantTiming) {
77 TimeRecord Elapsed = TimeRecord::getCurrentTime();
78 Elapsed -= Start;
79 llvm::errs() << Output << ':';
80 Elapsed.print(Elapsed, llvm::errs());
81 llvm::errs() << '\n';
82 }
83 }
84 };
85}
86
Douglas Gregorbb420ab2010-08-04 05:53:38 +000087/// \brief After failing to build a precompiled preamble (due to
88/// errors in the source that occurs in the preamble), the number of
89/// reparses during which we'll skip even trying to precompile the
90/// preamble.
91const unsigned DefaultPreambleRebuildInterval = 5;
92
Douglas Gregord03e8232010-04-05 21:10:19 +000093ASTUnit::ASTUnit(bool _MainFileIsAST)
Douglas Gregoraa21cc42010-07-19 21:46:24 +000094 : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
Douglas Gregor16896c42010-10-28 15:44:59 +000095 CompleteTranslationUnit(true), WantTiming(getenv("LIBCLANG_TIMING")),
96 NumStoredDiagnosticsFromDriver(0),
Douglas Gregor7bb8af62010-10-12 00:50:20 +000097 ConcurrencyCheckValue(CheckUnlocked),
Douglas Gregora0734c52010-08-19 01:33:06 +000098 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +000099 ShouldCacheCodeCompletionResults(false),
100 NumTopLevelDeclsAtLastCompletionCache(0),
Douglas Gregor4740c452010-08-19 00:45:44 +0000101 CacheCodeCompletionCoolDown(0),
102 UnsafeToFree(false) {
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 Gregoraa21cc42010-07-19 21:46:24 +0000129}
130
131void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor6cb5ba42010-02-18 23:35:40 +0000132 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
133 TemporaryFiles[I].eraseFromDisk();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000134 TemporaryFiles.clear();
Steve Naroff44cd60e2009-10-15 22:23:48 +0000135}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000136
Douglas Gregor39982192010-08-15 06:18:01 +0000137/// \brief Determine the set of code-completion contexts in which this
138/// declaration should be shown.
139static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000140 const LangOptions &LangOpts,
141 bool &IsNestedNameSpecifier) {
142 IsNestedNameSpecifier = false;
143
Douglas Gregor39982192010-08-15 06:18:01 +0000144 if (isa<UsingShadowDecl>(ND))
145 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
146 if (!ND)
147 return 0;
148
149 unsigned Contexts = 0;
150 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
151 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
152 // Types can appear in these contexts.
153 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
154 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
155 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
156 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
157 | (1 << (CodeCompletionContext::CCC_Statement - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000158 | (1 << (CodeCompletionContext::CCC_Type - 1))
159 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000160
161 // In C++, types can appear in expressions contexts (for functional casts).
162 if (LangOpts.CPlusPlus)
163 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
164
165 // In Objective-C, message sends can send interfaces. In Objective-C++,
166 // all types are available due to functional casts.
167 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
168 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
169
170 // Deal with tag names.
171 if (isa<EnumDecl>(ND)) {
172 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
173
Douglas Gregor59cab552010-08-16 23:05:20 +0000174 // Part of the nested-name-specifier in C++0x.
Douglas Gregor39982192010-08-15 06:18:01 +0000175 if (LangOpts.CPlusPlus0x)
Douglas Gregor59cab552010-08-16 23:05:20 +0000176 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000177 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
178 if (Record->isUnion())
179 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
180 else
181 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
182
Douglas Gregor39982192010-08-15 06:18:01 +0000183 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000184 IsNestedNameSpecifier = true;
Douglas Gregor0ac41382010-09-23 23:01:17 +0000185 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregor59cab552010-08-16 23:05:20 +0000186 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000187 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
188 // Values can appear in these contexts.
189 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
190 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000191 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor39982192010-08-15 06:18:01 +0000192 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
193 } else if (isa<ObjCProtocolDecl>(ND)) {
194 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
195 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregor59cab552010-08-16 23:05:20 +0000196 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000197
198 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000199 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000200 }
201
202 return Contexts;
203}
204
Douglas Gregorb14904c2010-08-13 22:48:40 +0000205void ASTUnit::CacheCodeCompletionResults() {
206 if (!TheSema)
207 return;
208
Douglas Gregor16896c42010-10-28 15:44:59 +0000209 SimpleTimer Timer(WantTiming);
210 if (WantTiming)
211 Timer.setOutput( "Cache global code completions for " + getMainFileName());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000212
213 // Clear out the previous results.
214 ClearCachedCompletionResults();
215
216 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000217 typedef CodeCompletionResult Result;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000218 llvm::SmallVector<Result, 8> Results;
219 TheSema->GatherGlobalCodeCompletions(Results);
220
221 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000222 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
223
Douglas Gregorb14904c2010-08-13 22:48:40 +0000224 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
225 switch (Results[I].Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000226 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000227 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000228 CachedCodeCompletionResult CachedResult;
229 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
230 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregor59cab552010-08-16 23:05:20 +0000231 Ctx->getLangOptions(),
232 IsNestedNameSpecifier);
Douglas Gregor39982192010-08-15 06:18:01 +0000233 CachedResult.Priority = Results[I].Priority;
234 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000235 CachedResult.Availability = Results[I].Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000236
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000237 // Keep track of the type of this completion in an ASTContext-agnostic
238 // way.
Douglas Gregor24747402010-08-16 16:46:30 +0000239 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000240 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000241 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000242 CachedResult.Type = 0;
243 } else {
244 CanQualType CanUsageType
245 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
246 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
247
248 // Determine whether we have already seen this type. If so, we save
249 // ourselves the work of formatting the type string by using the
250 // temporary, CanQualType-based hash table to find the associated value.
251 unsigned &TypeValue = CompletionTypes[CanUsageType];
252 if (TypeValue == 0) {
253 TypeValue = CompletionTypes.size();
254 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
255 = TypeValue;
256 }
257
258 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000259 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000260
Douglas Gregor39982192010-08-15 06:18:01 +0000261 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000262
263 /// Handle nested-name-specifiers in C++.
264 if (TheSema->Context.getLangOptions().CPlusPlus &&
265 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
266 // The contexts in which a nested-name-specifier can appear in C++.
267 unsigned NNSContexts
268 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
269 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
270 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
271 | (1 << (CodeCompletionContext::CCC_Statement - 1))
272 | (1 << (CodeCompletionContext::CCC_Expression - 1))
273 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
274 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
275 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
276 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000277 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000278 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
279 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor59cab552010-08-16 23:05:20 +0000280
281 if (isa<NamespaceDecl>(Results[I].Declaration) ||
282 isa<NamespaceAliasDecl>(Results[I].Declaration))
283 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
284
285 if (unsigned RemainingContexts
286 = NNSContexts & ~CachedResult.ShowInContexts) {
287 // If there any contexts where this completion can be a
288 // nested-name-specifier but isn't already an option, create a
289 // nested-name-specifier completion.
290 Results[I].StartsNestedNameSpecifier = true;
291 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
292 CachedResult.ShowInContexts = RemainingContexts;
293 CachedResult.Priority = CCP_NestedNameSpecifier;
294 CachedResult.TypeClass = STC_Void;
295 CachedResult.Type = 0;
296 CachedCompletionResults.push_back(CachedResult);
297 }
298 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000299 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000300 }
301
Douglas Gregorb14904c2010-08-13 22:48:40 +0000302 case Result::RK_Keyword:
303 case Result::RK_Pattern:
304 // Ignore keywords and patterns; we don't care, since they are so
305 // easily regenerated.
306 break;
307
308 case Result::RK_Macro: {
309 CachedCodeCompletionResult CachedResult;
310 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
311 CachedResult.ShowInContexts
312 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
313 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
314 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
315 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
316 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
317 | (1 << (CodeCompletionContext::CCC_Statement - 1))
318 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor12785102010-08-24 20:21:13 +0000319 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorec00a262010-08-24 22:20:20 +0000320 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +0000321 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
322 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
323
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000324
Douglas Gregorb14904c2010-08-13 22:48:40 +0000325 CachedResult.Priority = Results[I].Priority;
326 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000327 CachedResult.Availability = Results[I].Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000328 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000329 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000330 CachedCompletionResults.push_back(CachedResult);
331 break;
332 }
333 }
334 Results[I].Destroy();
335 }
336
Douglas Gregor2c8bd472010-08-17 00:40:40 +0000337 // Make a note of the state when we performed this caching.
338 NumTopLevelDeclsAtLastCompletionCache = top_level_size();
339 CacheCodeCompletionCoolDown = 15;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000340}
341
342void ASTUnit::ClearCachedCompletionResults() {
343 for (unsigned I = 0, N = CachedCompletionResults.size(); I != N; ++I)
344 delete CachedCompletionResults[I].Completion;
345 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000346 CachedCompletionTypes.clear();
Douglas Gregorb14904c2010-08-13 22:48:40 +0000347}
348
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000349namespace {
350
Sebastian Redl2c499f62010-08-18 23:56:43 +0000351/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000352/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000353class ASTInfoCollector : public ASTReaderListener {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000354 LangOptions &LangOpt;
355 HeaderSearch &HSI;
356 std::string &TargetTriple;
357 std::string &Predefines;
358 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000359
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000360 unsigned NumHeaderInfos;
Mike Stump11289f42009-09-09 15:08:12 +0000361
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000362public:
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000363 ASTInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000364 std::string &TargetTriple, std::string &Predefines,
365 unsigned &Counter)
366 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
367 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump11289f42009-09-09 15:08:12 +0000368
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000369 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
370 LangOpt = LangOpts;
371 return false;
372 }
Mike Stump11289f42009-09-09 15:08:12 +0000373
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000374 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000375 TargetTriple = Triple;
376 return false;
377 }
Mike Stump11289f42009-09-09 15:08:12 +0000378
Sebastian Redl8b41f302010-07-14 23:29:55 +0000379 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000380 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000381 std::string &SuggestedPredefines) {
Sebastian Redl8b41f302010-07-14 23:29:55 +0000382 Predefines = Buffers[0].Data;
383 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
384 Predefines += Buffers[I].Data;
385 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000386 return false;
387 }
Mike Stump11289f42009-09-09 15:08:12 +0000388
Douglas Gregora2f49452010-03-16 19:09:18 +0000389 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000390 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
391 }
Mike Stump11289f42009-09-09 15:08:12 +0000392
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000393 virtual void ReadCounter(unsigned Value) {
394 Counter = Value;
395 }
396};
397
Douglas Gregor33cdd812010-02-18 18:08:43 +0000398class StoredDiagnosticClient : public DiagnosticClient {
399 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
400
401public:
402 explicit StoredDiagnosticClient(
403 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
404 : StoredDiags(StoredDiags) { }
405
406 virtual void HandleDiagnostic(Diagnostic::Level Level,
407 const DiagnosticInfo &Info);
408};
409
410/// \brief RAII object that optionally captures diagnostics, if
411/// there is no diagnostic client to capture them already.
412class CaptureDroppedDiagnostics {
413 Diagnostic &Diags;
414 StoredDiagnosticClient Client;
415 DiagnosticClient *PreviousClient;
416
417public:
418 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
419 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000420 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000421 {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000422 if (RequestCapture || Diags.getClient() == 0) {
423 PreviousClient = Diags.takeClient();
Douglas Gregor33cdd812010-02-18 18:08:43 +0000424 Diags.setClient(&Client);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000425 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000426 }
427
428 ~CaptureDroppedDiagnostics() {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000429 if (Diags.getClient() == &Client) {
430 Diags.takeClient();
431 Diags.setClient(PreviousClient);
432 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000433 }
434};
435
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000436} // anonymous namespace
437
Douglas Gregor33cdd812010-02-18 18:08:43 +0000438void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
439 const DiagnosticInfo &Info) {
440 StoredDiags.push_back(StoredDiagnostic(Level, Info));
441}
442
Steve Naroffc0683b92009-09-03 18:19:54 +0000443const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbara8a50932009-12-02 08:44:16 +0000444 return OriginalSourceFile;
Steve Naroffc0683b92009-09-03 18:19:54 +0000445}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000446
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000447const std::string &ASTUnit::getASTFileName() {
448 assert(isMainFileAST() && "Not an ASTUnit from an AST file!");
Sebastian Redl2c499f62010-08-18 23:56:43 +0000449 return static_cast<ASTReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroff44cd60e2009-10-15 22:23:48 +0000450}
451
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000452ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Douglas Gregor7f95d262010-04-05 23:52:57 +0000453 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Ted Kremenek8bcb1c62009-10-17 00:34:24 +0000454 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000455 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +0000456 unsigned NumRemappedFiles,
457 bool CaptureDiagnostics) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000458 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
459
Douglas Gregor7f95d262010-04-05 23:52:57 +0000460 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000461 // No diagnostics engine was provided, so create our own diagnostics object
462 // with the default options.
463 DiagnosticOptions DiagOpts;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000464 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregord03e8232010-04-05 21:10:19 +0000465 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000466
467 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor16bef852009-10-16 20:01:17 +0000468 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000469 AST->Diagnostics = Diags;
Douglas Gregord03e8232010-04-05 21:10:19 +0000470 AST->FileMgr.reset(new FileManager);
471 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics()));
Steve Naroff505fb842009-10-19 14:34:22 +0000472 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000473
Douglas Gregor33cdd812010-02-18 18:08:43 +0000474 // If requested, capture diagnostics in the ASTUnit.
Douglas Gregord03e8232010-04-05 21:10:19 +0000475 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, AST->getDiagnostics(),
Douglas Gregora2433152010-04-05 18:10:21 +0000476 AST->StoredDiagnostics);
Douglas Gregor33cdd812010-02-18 18:08:43 +0000477
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000478 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
479 // Create the file entry for the file that we're mapping from.
480 const FileEntry *FromFile
481 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
482 RemappedFiles[I].second->getBufferSize(),
483 0);
484 if (!FromFile) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000485 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000486 << RemappedFiles[I].first;
Douglas Gregor89a56c52010-02-27 01:32:48 +0000487 delete RemappedFiles[I].second;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000488 continue;
489 }
490
491 // Override the contents of the "from" file with the contents of
492 // the "to" file.
493 AST->getSourceManager().overrideFileContents(FromFile,
494 RemappedFiles[I].second);
495 }
496
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000497 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000498
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000499 LangOptions LangInfo;
500 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
501 std::string TargetTriple;
502 std::string Predefines;
503 unsigned Counter;
504
Sebastian Redl2c499f62010-08-18 23:56:43 +0000505 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000506
Sebastian Redl2c499f62010-08-18 23:56:43 +0000507 Reader.reset(new ASTReader(AST->getSourceManager(), AST->getFileManager(),
Douglas Gregord03e8232010-04-05 21:10:19 +0000508 AST->getDiagnostics()));
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000509 Reader->setListener(new ASTInfoCollector(LangInfo, HeaderInfo, TargetTriple,
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000510 Predefines, Counter));
511
Sebastian Redl009e7f22010-10-05 16:15:19 +0000512 switch (Reader->ReadAST(Filename, ASTReader::MainFile)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000513 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000514 break;
Mike Stump11289f42009-09-09 15:08:12 +0000515
Sebastian Redl2c499f62010-08-18 23:56:43 +0000516 case ASTReader::Failure:
517 case ASTReader::IgnorePCH:
Douglas Gregord03e8232010-04-05 21:10:19 +0000518 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000519 return NULL;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000520 }
Mike Stump11289f42009-09-09 15:08:12 +0000521
Daniel Dunbara8a50932009-12-02 08:44:16 +0000522 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
523
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000524 // AST file loaded successfully. Now create the preprocessor.
Mike Stump11289f42009-09-09 15:08:12 +0000525
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000526 // Get information about the target being compiled for.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000527 //
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000528 // FIXME: This is broken, we should store the TargetOptions in the AST file.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000529 TargetOptions TargetOpts;
530 TargetOpts.ABI = "";
John McCall1c456c82010-08-22 06:43:33 +0000531 TargetOpts.CXXABI = "";
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000532 TargetOpts.CPU = "";
533 TargetOpts.Features.clear();
534 TargetOpts.Triple = TargetTriple;
Douglas Gregord03e8232010-04-05 21:10:19 +0000535 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
536 TargetOpts));
537 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
538 *AST->Target.get(),
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000539 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000540 Preprocessor &PP = *AST->PP.get();
541
Daniel Dunbarb7bbfdd2009-09-21 03:03:47 +0000542 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000543 PP.setCounterValue(Counter);
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000544 Reader->setPreprocessor(PP);
Mike Stump11289f42009-09-09 15:08:12 +0000545
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000546 // Create and initialize the ASTContext.
547
548 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000549 AST->getSourceManager(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000550 *AST->Target.get(),
551 PP.getIdentifierTable(),
552 PP.getSelectorTable(),
553 PP.getBuiltinInfo(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000554 /* size_reserve = */0));
555 ASTContext &Context = *AST->Ctx.get();
Mike Stump11289f42009-09-09 15:08:12 +0000556
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000557 Reader->InitializeContext(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000558
Sebastian Redl2c499f62010-08-18 23:56:43 +0000559 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000560 // source, so that declarations will be deserialized from the
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000561 // AST file as needed.
Sebastian Redl2c499f62010-08-18 23:56:43 +0000562 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000563 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000564 Context.setExternalSource(Source);
565
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000566 // Create an AST consumer, even though it isn't used.
567 AST->Consumer.reset(new ASTConsumer);
568
Sebastian Redl2c499f62010-08-18 23:56:43 +0000569 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000570 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
571 AST->TheSema->Initialize();
572 ReaderPtr->InitializeSema(*AST->TheSema);
573
Mike Stump11289f42009-09-09 15:08:12 +0000574 return AST.take();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000575}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000576
577namespace {
578
Daniel Dunbar644dca02009-12-04 08:17:33 +0000579class TopLevelDeclTrackerConsumer : public ASTConsumer {
580 ASTUnit &Unit;
581
582public:
583 TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {}
584
585 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekacc59c32010-05-03 20:16:35 +0000586 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
587 Decl *D = *it;
588 // FIXME: Currently ObjC method declarations are incorrectly being
589 // reported as top-level declarations, even though their DeclContext
590 // is the containing ObjC @interface/@implementation. This is a
591 // fundamental problem in the parser right now.
592 if (isa<ObjCMethodDecl>(D))
593 continue;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000594 Unit.addTopLevelDecl(D);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000595 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000596 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000597
598 // We're not interested in "interesting" decls.
599 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbar644dca02009-12-04 08:17:33 +0000600};
601
602class TopLevelDeclTrackerAction : public ASTFrontendAction {
603public:
604 ASTUnit &Unit;
605
Daniel Dunbar764c0822009-12-01 09:51:01 +0000606 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
607 llvm::StringRef InFile) {
Daniel Dunbar644dca02009-12-04 08:17:33 +0000608 return new TopLevelDeclTrackerConsumer(Unit);
Daniel Dunbar764c0822009-12-01 09:51:01 +0000609 }
610
611public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000612 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
613
Daniel Dunbar764c0822009-12-01 09:51:01 +0000614 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000615 virtual bool usesCompleteTranslationUnit() {
616 return Unit.isCompleteTranslationUnit();
617 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000618};
619
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000620class PrecompilePreambleConsumer : public PCHGenerator {
621 ASTUnit &Unit;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000622 std::vector<Decl *> TopLevelDecls;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000623
624public:
625 PrecompilePreambleConsumer(ASTUnit &Unit,
626 const Preprocessor &PP, bool Chaining,
627 const char *isysroot, llvm::raw_ostream *Out)
628 : PCHGenerator(PP, Chaining, isysroot, Out), Unit(Unit) { }
629
Douglas Gregore9db88f2010-08-03 19:06:41 +0000630 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000631 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
632 Decl *D = *it;
633 // FIXME: Currently ObjC method declarations are incorrectly being
634 // reported as top-level declarations, even though their DeclContext
635 // is the containing ObjC @interface/@implementation. This is a
636 // fundamental problem in the parser right now.
637 if (isa<ObjCMethodDecl>(D))
638 continue;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000639 TopLevelDecls.push_back(D);
640 }
641 }
642
643 virtual void HandleTranslationUnit(ASTContext &Ctx) {
644 PCHGenerator::HandleTranslationUnit(Ctx);
645 if (!Unit.getDiagnostics().hasErrorOccurred()) {
646 // Translate the top-level declarations we captured during
647 // parsing into declaration IDs in the precompiled
648 // preamble. This will allow us to deserialize those top-level
649 // declarations when requested.
650 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
651 Unit.addTopLevelDeclFromPreamble(
652 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000653 }
654 }
655};
656
657class PrecompilePreambleAction : public ASTFrontendAction {
658 ASTUnit &Unit;
659
660public:
661 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
662
663 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
664 llvm::StringRef InFile) {
665 std::string Sysroot;
666 llvm::raw_ostream *OS = 0;
667 bool Chaining;
668 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
669 OS, Chaining))
670 return 0;
671
672 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
673 Sysroot.c_str() : 0;
674 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
675 isysroot, OS);
676 }
677
678 virtual bool hasCodeCompletionSupport() const { return false; }
679 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000680 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000681};
682
Daniel Dunbar764c0822009-12-01 09:51:01 +0000683}
684
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000685/// Parse the source file into a translation unit using the given compiler
686/// invocation, replacing the current translation unit.
687///
688/// \returns True if a failure occurred that causes the ASTUnit not to
689/// contain any translation-unit information, false otherwise.
Douglas Gregor6481ef12010-07-24 00:38:13 +0000690bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor96c04262010-07-27 14:52:07 +0000691 delete SavedMainFileBuffer;
692 SavedMainFileBuffer = 0;
693
Douglas Gregora0734c52010-08-19 01:33:06 +0000694 if (!Invocation.get()) {
695 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000696 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000697 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000698
Daniel Dunbar764c0822009-12-01 09:51:01 +0000699 // Create the compiler instance to use for building the AST.
Daniel Dunbar7afbb8c2009-12-02 08:43:56 +0000700 CompilerInstance Clang;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000701 Clang.setInvocation(Invocation.take());
702 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
703
Douglas Gregor8e984da2010-08-04 16:47:14 +0000704 // Set up diagnostics, capturing any diagnostics that would
705 // otherwise be dropped.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000706 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor8e984da2010-08-04 16:47:14 +0000707 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
708 getDiagnostics(),
709 StoredDiagnostics);
Douglas Gregord03e8232010-04-05 21:10:19 +0000710
Daniel Dunbar764c0822009-12-01 09:51:01 +0000711 // Create the target instance.
712 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
713 Clang.getTargetOpts()));
Douglas Gregora0734c52010-08-19 01:33:06 +0000714 if (!Clang.hasTarget()) {
715 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000716 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000717 }
718
Daniel Dunbar764c0822009-12-01 09:51:01 +0000719 // Inform the target of the language options.
720 //
721 // FIXME: We shouldn't need to do this, the target should be immutable once
722 // created. This complexity should be lifted elsewhere.
723 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000724
Daniel Dunbar764c0822009-12-01 09:51:01 +0000725 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
726 "Invocation must have exactly one source file!");
Daniel Dunbar9b491e72010-06-07 23:22:09 +0000727 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +0000728 "FIXME: AST inputs not yet supported here!");
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000729 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
730 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +0000731
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000732 // Configure the various subsystems.
733 // FIXME: Should we retain the previous file manager?
734 FileMgr.reset(new FileManager);
735 SourceMgr.reset(new SourceManager(getDiagnostics()));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000736 TheSema.reset();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000737 Ctx.reset();
738 PP.reset();
739
740 // Clear out old caches and data.
741 TopLevelDecls.clear();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000742 CleanTemporaryFiles();
743 PreprocessedEntitiesByFile.clear();
Douglas Gregord9a30af2010-08-02 20:51:39 +0000744
Douglas Gregor7b02b582010-08-20 00:02:33 +0000745 if (!OverrideMainBuffer) {
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000746 StoredDiagnostics.erase(
747 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
748 StoredDiagnostics.end());
Douglas Gregor7b02b582010-08-20 00:02:33 +0000749 TopLevelDeclsInPreamble.clear();
750 }
751
Daniel Dunbar764c0822009-12-01 09:51:01 +0000752 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000753 Clang.setFileManager(&getFileManager());
754
Daniel Dunbar764c0822009-12-01 09:51:01 +0000755 // Create the source manager.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000756 Clang.setSourceManager(&getSourceManager());
757
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000758 // If the main file has been overridden due to the use of a preamble,
759 // make that override happen and introduce the preamble.
760 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +0000761 std::string PriorImplicitPCHInclude;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000762 if (OverrideMainBuffer) {
763 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
764 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
765 PreprocessorOpts.PrecompiledPreambleBytes.second
766 = PreambleEndsAtStartOfLine;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000767 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000768 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000769 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +0000770
Douglas Gregord9a30af2010-08-02 20:51:39 +0000771 // The stored diagnostic has the old source manager in it; update
772 // the locations to refer into the new source manager. Since we've
773 // been careful to make sure that the source manager's state
774 // before and after are identical, so that we can reuse the source
775 // location itself.
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000776 for (unsigned I = NumStoredDiagnosticsFromDriver,
777 N = StoredDiagnostics.size();
778 I < N; ++I) {
Douglas Gregord9a30af2010-08-02 20:51:39 +0000779 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
780 getSourceManager());
781 StoredDiagnostics[I].setLocation(Loc);
782 }
Douglas Gregor7bb8af62010-10-12 00:50:20 +0000783
784 // Keep track of the override buffer;
785 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregor7b02b582010-08-20 00:02:33 +0000786 } else {
787 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
788 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000789 }
790
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000791 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
792 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbar644dca02009-12-04 08:17:33 +0000793 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbar86546382010-06-07 23:23:06 +0000794 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar764c0822009-12-01 09:51:01 +0000795 goto error;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000796
Daniel Dunbar644dca02009-12-04 08:17:33 +0000797 Act->Execute();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000798
Daniel Dunbard2f8be32009-12-01 21:57:33 +0000799 // Steal the created target, context, and preprocessor, and take back the
800 // source and file managers.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000801 TheSema.reset(Clang.takeSema());
802 Consumer.reset(Clang.takeASTConsumer());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000803 Ctx.reset(Clang.takeASTContext());
804 PP.reset(Clang.takePreprocessor());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000805 Clang.takeSourceManager();
806 Clang.takeFileManager();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000807 Target.reset(Clang.takeTarget());
808
Daniel Dunbar644dca02009-12-04 08:17:33 +0000809 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000810
811 // Remove the overridden buffer we used for the preamble.
Douglas Gregor8e984da2010-08-04 16:47:14 +0000812 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000813 PreprocessorOpts.eraseRemappedFile(
814 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor8e984da2010-08-04 16:47:14 +0000815 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
816 }
817
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000818 Invocation.reset(Clang.takeInvocation());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000819
820 // If we were asked to cache code-completion results and don't have any
821 // results yet, do so now.
822 if (ShouldCacheCodeCompletionResults && CachedCompletionResults.empty())
823 CacheCodeCompletionResults();
Douglas Gregorbb6a8812010-10-08 04:03:57 +0000824
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000825 return false;
826
Daniel Dunbar764c0822009-12-01 09:51:01 +0000827error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000828 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +0000829 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000830 PreprocessorOpts.eraseRemappedFile(
831 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregorce3a8292010-07-27 00:27:13 +0000832 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000833 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregora0734c52010-08-19 01:33:06 +0000834 delete OverrideMainBuffer;
Douglas Gregora3d3ba12010-10-06 21:11:08 +0000835 SavedMainFileBuffer = 0;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000836 }
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000837
Douglas Gregorefc46952010-10-12 16:25:54 +0000838 StoredDiagnostics.clear();
Daniel Dunbar764c0822009-12-01 09:51:01 +0000839 Clang.takeSourceManager();
840 Clang.takeFileManager();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000841 Invocation.reset(Clang.takeInvocation());
842 return true;
843}
844
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000845/// \brief Simple function to retrieve a path for a preamble precompiled header.
846static std::string GetPreamblePCHPath() {
847 // FIXME: This is lame; sys::Path should provide this function (in particular,
848 // it should know how to find the temporary files dir).
849 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor250ab1d2010-09-11 18:05:19 +0000850 // FIXME: This is a hack so that we can override the preamble file during
851 // crash-recovery testing, which is the only case where the preamble files
852 // are not necessarily cleaned up.
853 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
854 if (TmpFile)
855 return TmpFile;
856
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000857 std::string Error;
858 const char *TmpDir = ::getenv("TMPDIR");
859 if (!TmpDir)
860 TmpDir = ::getenv("TEMP");
861 if (!TmpDir)
862 TmpDir = ::getenv("TMP");
Douglas Gregorce3449f2010-09-11 17:51:16 +0000863#ifdef LLVM_ON_WIN32
864 if (!TmpDir)
865 TmpDir = ::getenv("USERPROFILE");
866#endif
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000867 if (!TmpDir)
868 TmpDir = "/tmp";
869 llvm::sys::Path P(TmpDir);
Douglas Gregorce3449f2010-09-11 17:51:16 +0000870 P.createDirectoryOnDisk(true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000871 P.appendComponent("preamble");
Douglas Gregor20975b22010-08-11 13:06:56 +0000872 P.appendSuffix("pch");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000873 if (P.createTemporaryFileOnDisk())
874 return std::string();
875
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000876 return P.str();
877}
878
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000879/// \brief Compute the preamble for the main file, providing the source buffer
880/// that corresponds to the main file along with a pair (bytes, start-of-line)
881/// that describes the preamble.
882std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor028d3e42010-08-09 20:45:32 +0000883ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
884 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000885 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000886 PreprocessorOptions &PreprocessorOpts
Douglas Gregor4dde7492010-07-23 23:58:40 +0000887 = Invocation.getPreprocessorOpts();
888 CreatedBuffer = false;
889
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000890 // Try to determine if the main file has been remapped, either from the
891 // command line (to another file) or directly through the compiler invocation
892 // (to a memory buffer).
Douglas Gregor4dde7492010-07-23 23:58:40 +0000893 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000894 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
895 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
896 // Check whether there is a file-file remapping of the main file
897 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor4dde7492010-07-23 23:58:40 +0000898 M = PreprocessorOpts.remapped_file_begin(),
899 E = PreprocessorOpts.remapped_file_end();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000900 M != E;
901 ++M) {
902 llvm::sys::PathWithStatus MPath(M->first);
903 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
904 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
905 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000906 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000907 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000908 CreatedBuffer = false;
909 }
910
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000911 Buffer = llvm::MemoryBuffer::getFile(M->second);
912 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000913 return std::make_pair((llvm::MemoryBuffer*)0,
914 std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000915 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000916 }
917 }
918 }
919
920 // Check whether there is a file-buffer remapping. It supercedes the
921 // file-file remapping.
922 for (PreprocessorOptions::remapped_file_buffer_iterator
923 M = PreprocessorOpts.remapped_file_buffer_begin(),
924 E = PreprocessorOpts.remapped_file_buffer_end();
925 M != E;
926 ++M) {
927 llvm::sys::PathWithStatus MPath(M->first);
928 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
929 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
930 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000931 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000932 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000933 CreatedBuffer = false;
934 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000935
Douglas Gregor4dde7492010-07-23 23:58:40 +0000936 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000937 }
938 }
Douglas Gregor4dde7492010-07-23 23:58:40 +0000939 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000940 }
941
942 // If the main source file was not remapped, load it now.
943 if (!Buffer) {
944 Buffer = llvm::MemoryBuffer::getFile(FrontendOpts.Inputs[0].second);
945 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000946 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000947
948 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000949 }
950
Douglas Gregor028d3e42010-08-09 20:45:32 +0000951 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000952}
953
Douglas Gregor6481ef12010-07-24 00:38:13 +0000954static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
955 bool DeleteOld,
956 unsigned NewSize,
957 llvm::StringRef NewName) {
958 llvm::MemoryBuffer *Result
959 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
960 memcpy(const_cast<char*>(Result->getBufferStart()),
961 Old->getBufferStart(), Old->getBufferSize());
962 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000963 ' ', NewSize - Old->getBufferSize() - 1);
964 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor6481ef12010-07-24 00:38:13 +0000965
966 if (DeleteOld)
967 delete Old;
968
969 return Result;
970}
971
Douglas Gregor4dde7492010-07-23 23:58:40 +0000972/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
973/// the source file.
974///
975/// This routine will compute the preamble of the main source file. If a
976/// non-trivial preamble is found, it will precompile that preamble into a
977/// precompiled header so that the precompiled preamble can be used to reduce
978/// reparsing time. If a precompiled preamble has already been constructed,
979/// this routine will determine if it is still valid and, if so, avoid
980/// rebuilding the precompiled preamble.
981///
Douglas Gregor028d3e42010-08-09 20:45:32 +0000982/// \param AllowRebuild When true (the default), this routine is
983/// allowed to rebuild the precompiled preamble if it is found to be
984/// out-of-date.
985///
986/// \param MaxLines When non-zero, the maximum number of lines that
987/// can occur within the preamble.
988///
Douglas Gregor6481ef12010-07-24 00:38:13 +0000989/// \returns If the precompiled preamble can be used, returns a newly-allocated
990/// buffer that should be used in place of the main file when doing so.
991/// Otherwise, returns a NULL pointer.
Douglas Gregor028d3e42010-08-09 20:45:32 +0000992llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregorb97b6662010-08-20 00:59:43 +0000993 CompilerInvocation PreambleInvocation,
Douglas Gregor028d3e42010-08-09 20:45:32 +0000994 bool AllowRebuild,
995 unsigned MaxLines) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000996 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
997 PreprocessorOptions &PreprocessorOpts
998 = PreambleInvocation.getPreprocessorOpts();
999
1000 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001001 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor028d3e42010-08-09 20:45:32 +00001002 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001003
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001004 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001005 // We couldn't find a preamble in the main source. Clear out the current
1006 // preamble, if we have one. It's obviously no good any more.
1007 Preamble.clear();
1008 if (!PreambleFile.empty()) {
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001009 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001010 PreambleFile.clear();
1011 }
1012 if (CreatedPreambleBuffer)
1013 delete NewPreamble.first;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001014
1015 // The next time we actually see a preamble, precompile it.
1016 PreambleRebuildCounter = 1;
Douglas Gregor6481ef12010-07-24 00:38:13 +00001017 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001018 }
1019
1020 if (!Preamble.empty()) {
1021 // We've previously computed a preamble. Check whether we have the same
1022 // preamble now that we did before, and that there's enough space in
1023 // the main-file buffer within the precompiled preamble to fit the
1024 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001025 if (Preamble.size() == NewPreamble.second.first &&
1026 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregorf5275a82010-07-24 00:42:07 +00001027 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor4dde7492010-07-23 23:58:40 +00001028 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001029 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001030 // The preamble has not changed. We may be able to re-use the precompiled
1031 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001032
Douglas Gregor0e119552010-07-31 00:40:00 +00001033 // Check that none of the files used by the preamble have changed.
1034 bool AnyFileChanged = false;
1035
1036 // First, make a record of those files that have been overridden via
1037 // remapping or unsaved_files.
1038 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1039 for (PreprocessorOptions::remapped_file_iterator
1040 R = PreprocessorOpts.remapped_file_begin(),
1041 REnd = PreprocessorOpts.remapped_file_end();
1042 !AnyFileChanged && R != REnd;
1043 ++R) {
1044 struct stat StatBuf;
1045 if (stat(R->second.c_str(), &StatBuf)) {
1046 // If we can't stat the file we're remapping to, assume that something
1047 // horrible happened.
1048 AnyFileChanged = true;
1049 break;
1050 }
Douglas Gregor6481ef12010-07-24 00:38:13 +00001051
Douglas Gregor0e119552010-07-31 00:40:00 +00001052 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1053 StatBuf.st_mtime);
1054 }
1055 for (PreprocessorOptions::remapped_file_buffer_iterator
1056 R = PreprocessorOpts.remapped_file_buffer_begin(),
1057 REnd = PreprocessorOpts.remapped_file_buffer_end();
1058 !AnyFileChanged && R != REnd;
1059 ++R) {
1060 // FIXME: Should we actually compare the contents of file->buffer
1061 // remappings?
1062 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1063 0);
1064 }
1065
1066 // Check whether anything has changed.
1067 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1068 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1069 !AnyFileChanged && F != FEnd;
1070 ++F) {
1071 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1072 = OverriddenFiles.find(F->first());
1073 if (Overridden != OverriddenFiles.end()) {
1074 // This file was remapped; check whether the newly-mapped file
1075 // matches up with the previous mapping.
1076 if (Overridden->second != F->second)
1077 AnyFileChanged = true;
1078 continue;
1079 }
1080
1081 // The file was not remapped; check whether it has changed on disk.
1082 struct stat StatBuf;
1083 if (stat(F->first(), &StatBuf)) {
1084 // If we can't stat the file, assume that something horrible happened.
1085 AnyFileChanged = true;
1086 } else if (StatBuf.st_size != F->second.first ||
1087 StatBuf.st_mtime != F->second.second)
1088 AnyFileChanged = true;
1089 }
1090
1091 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001092 // Okay! We can re-use the precompiled preamble.
1093
1094 // Set the state of the diagnostic object to mimic its state
1095 // after parsing the preamble.
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001096 // FIXME: This won't catch any #pragma push warning changes that
1097 // have occurred in the preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001098 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001099 ProcessWarningOptions(getDiagnostics(),
1100 PreambleInvocation.getDiagnosticOpts());
Douglas Gregord9a30af2010-08-02 20:51:39 +00001101 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1102 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
1103 StoredDiagnostics.erase(
1104 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
1105 StoredDiagnostics.end());
1106
1107 // Create a version of the main file buffer that is padded to
1108 // buffer size we reserved when creating the preamble.
Douglas Gregor0e119552010-07-31 00:40:00 +00001109 return CreatePaddedMainFileBuffer(NewPreamble.first,
1110 CreatedPreambleBuffer,
1111 PreambleReservedSize,
1112 FrontendOpts.Inputs[0].second);
1113 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001114 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001115
1116 // If we aren't allowed to rebuild the precompiled preamble, just
1117 // return now.
1118 if (!AllowRebuild)
1119 return 0;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001120
Douglas Gregor4dde7492010-07-23 23:58:40 +00001121 // We can't reuse the previously-computed preamble. Build a new one.
1122 Preamble.clear();
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001123 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001124 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001125 } else if (!AllowRebuild) {
1126 // We aren't allowed to rebuild the precompiled preamble; just
1127 // return now.
1128 return 0;
1129 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001130
1131 // If the preamble rebuild counter > 1, it's because we previously
1132 // failed to build a preamble and we're not yet ready to try
1133 // again. Decrement the counter and return a failure.
1134 if (PreambleRebuildCounter > 1) {
1135 --PreambleRebuildCounter;
1136 return 0;
1137 }
1138
Douglas Gregore10f0e52010-09-11 17:56:52 +00001139 // Create a temporary file for the precompiled preamble. In rare
1140 // circumstances, this can fail.
1141 std::string PreamblePCHPath = GetPreamblePCHPath();
1142 if (PreamblePCHPath.empty()) {
1143 // Try again next time.
1144 PreambleRebuildCounter = 1;
1145 return 0;
1146 }
1147
Douglas Gregor4dde7492010-07-23 23:58:40 +00001148 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor16896c42010-10-28 15:44:59 +00001149 SimpleTimer PreambleTimer(WantTiming);
1150 if (WantTiming)
1151 PreambleTimer.setOutput("Precompiling preamble");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001152
1153 // Create a new buffer that stores the preamble. The buffer also contains
1154 // extra space for the original contents of the file (which will be present
1155 // when we actually parse the file) along with more room in case the file
Douglas Gregor4dde7492010-07-23 23:58:40 +00001156 // grows.
1157 PreambleReservedSize = NewPreamble.first->getBufferSize();
1158 if (PreambleReservedSize < 4096)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001159 PreambleReservedSize = 8191;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001160 else
Douglas Gregor4dde7492010-07-23 23:58:40 +00001161 PreambleReservedSize *= 2;
1162
Douglas Gregord9a30af2010-08-02 20:51:39 +00001163 // Save the preamble text for later; we'll need to compare against it for
1164 // subsequent reparses.
1165 Preamble.assign(NewPreamble.first->getBufferStart(),
1166 NewPreamble.first->getBufferStart()
1167 + NewPreamble.second.first);
1168 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1169
Douglas Gregora0734c52010-08-19 01:33:06 +00001170 delete PreambleBuffer;
1171 PreambleBuffer
Douglas Gregor4dde7492010-07-23 23:58:40 +00001172 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001173 FrontendOpts.Inputs[0].second);
1174 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor4dde7492010-07-23 23:58:40 +00001175 NewPreamble.first->getBufferStart(), Preamble.size());
1176 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001177 ' ', PreambleReservedSize - Preamble.size() - 1);
1178 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001179
1180 // Remap the main source file to the preamble buffer.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001181 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001182 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1183
1184 // Tell the compiler invocation to generate a temporary precompiled header.
1185 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor9e136b52010-10-01 01:05:22 +00001186 FrontendOpts.ChainedPCH = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001187 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001188 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001189 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1190 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001191
1192 // Create the compiler instance to use for building the precompiled preamble.
1193 CompilerInstance Clang;
1194 Clang.setInvocation(&PreambleInvocation);
1195 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1196
Douglas Gregor8e984da2010-08-04 16:47:14 +00001197 // Set up diagnostics, capturing all of the diagnostics produced.
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001198 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor8e984da2010-08-04 16:47:14 +00001199 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
1200 getDiagnostics(),
1201 StoredDiagnostics);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001202
1203 // Create the target instance.
1204 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1205 Clang.getTargetOpts()));
1206 if (!Clang.hasTarget()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001207 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1208 Preamble.clear();
1209 if (CreatedPreambleBuffer)
1210 delete NewPreamble.first;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001211 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001212 PreprocessorOpts.eraseRemappedFile(
1213 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001214 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001215 }
1216
1217 // Inform the target of the language options.
1218 //
1219 // FIXME: We shouldn't need to do this, the target should be immutable once
1220 // created. This complexity should be lifted elsewhere.
1221 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1222
1223 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1224 "Invocation must have exactly one source file!");
1225 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1226 "FIXME: AST inputs not yet supported here!");
1227 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1228 "IR inputs not support here!");
1229
1230 // Clear out old caches and data.
Douglas Gregorbb6a8812010-10-08 04:03:57 +00001231 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001232 ProcessWarningOptions(getDiagnostics(), Clang.getDiagnosticOpts());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001233 StoredDiagnostics.erase(
1234 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1235 StoredDiagnostics.end());
Douglas Gregore9db88f2010-08-03 19:06:41 +00001236 TopLevelDecls.clear();
1237 TopLevelDeclsInPreamble.clear();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001238
1239 // Create a file manager object to provide access to and cache the filesystem.
1240 Clang.setFileManager(new FileManager);
1241
1242 // Create the source manager.
1243 Clang.setSourceManager(new SourceManager(getDiagnostics()));
1244
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001245 llvm::OwningPtr<PrecompilePreambleAction> Act;
1246 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001247 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1248 Clang.getFrontendOpts().Inputs[0].first)) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001249 Clang.takeInvocation();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001250 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1251 Preamble.clear();
1252 if (CreatedPreambleBuffer)
1253 delete NewPreamble.first;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001254 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001255 PreprocessorOpts.eraseRemappedFile(
1256 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001257 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001258 }
1259
1260 Act->Execute();
1261 Act->EndSourceFile();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001262 Clang.takeInvocation();
1263
Douglas Gregore9db88f2010-08-03 19:06:41 +00001264 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001265 // There were errors parsing the preamble, so no precompiled header was
1266 // generated. Forget that we even tried.
Douglas Gregora6f74e22010-09-27 16:43:25 +00001267 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor4dde7492010-07-23 23:58:40 +00001268 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1269 Preamble.clear();
1270 if (CreatedPreambleBuffer)
1271 delete NewPreamble.first;
Douglas Gregore9db88f2010-08-03 19:06:41 +00001272 TopLevelDeclsInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001273 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001274 PreprocessorOpts.eraseRemappedFile(
1275 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001276 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001277 }
1278
1279 // Keep track of the preamble we precompiled.
1280 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregord9a30af2010-08-02 20:51:39 +00001281 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1282 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001283
1284 // Keep track of all of the files that the source manager knows about,
1285 // so we can verify whether they have changed or not.
1286 FilesInPreamble.clear();
1287 SourceManager &SourceMgr = Clang.getSourceManager();
1288 const llvm::MemoryBuffer *MainFileBuffer
1289 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1290 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1291 FEnd = SourceMgr.fileinfo_end();
1292 F != FEnd;
1293 ++F) {
1294 const FileEntry *File = F->second->Entry;
1295 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1296 continue;
1297
1298 FilesInPreamble[File->getName()]
1299 = std::make_pair(F->second->getSize(), File->getModificationTime());
1300 }
1301
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001302 PreambleRebuildCounter = 1;
Douglas Gregora0734c52010-08-19 01:33:06 +00001303 PreprocessorOpts.eraseRemappedFile(
1304 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001305 return CreatePaddedMainFileBuffer(NewPreamble.first,
1306 CreatedPreambleBuffer,
1307 PreambleReservedSize,
1308 FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001309}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001310
Douglas Gregore9db88f2010-08-03 19:06:41 +00001311void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1312 std::vector<Decl *> Resolved;
1313 Resolved.reserve(TopLevelDeclsInPreamble.size());
1314 ExternalASTSource &Source = *getASTContext().getExternalSource();
1315 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1316 // Resolve the declaration ID to an actual declaration, possibly
1317 // deserializing the declaration in the process.
1318 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1319 if (D)
1320 Resolved.push_back(D);
1321 }
1322 TopLevelDeclsInPreamble.clear();
1323 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1324}
1325
1326unsigned ASTUnit::getMaxPCHLevel() const {
1327 if (!getOnlyLocalDecls())
1328 return Decl::MaxPCHLevel;
1329
Sebastian Redl009e7f22010-10-05 16:15:19 +00001330 return 0;
Douglas Gregore9db88f2010-08-03 19:06:41 +00001331}
1332
Douglas Gregor16896c42010-10-28 15:44:59 +00001333llvm::StringRef ASTUnit::getMainFileName() const {
1334 return Invocation->getFrontendOpts().Inputs[0].second;
1335}
1336
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001337bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1338 if (!Invocation)
1339 return true;
1340
1341 // We'll manage file buffers ourselves.
1342 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1343 Invocation->getFrontendOpts().DisableFree = false;
1344
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001345 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorf5a18542010-10-27 17:24:53 +00001346 if (PrecompilePreamble) {
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001347 PreambleRebuildCounter = 1;
1348 OverrideMainBuffer
1349 = getMainBufferWithPrecompiledPreamble(*Invocation);
1350 }
1351
Douglas Gregor16896c42010-10-28 15:44:59 +00001352 SimpleTimer ParsingTimer(WantTiming);
1353 if (WantTiming)
1354 ParsingTimer.setOutput( "Parsing " + getMainFileName());
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001355
Douglas Gregor16896c42010-10-28 15:44:59 +00001356 return Parse(OverrideMainBuffer);
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001357}
1358
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001359ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1360 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1361 bool OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001362 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001363 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001364 bool CompleteTranslationUnit,
1365 bool CacheCodeCompletionResults) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001366 if (!Diags.getPtr()) {
1367 // No diagnostics engine was provided, so create our own diagnostics object
1368 // with the default options.
1369 DiagnosticOptions DiagOpts;
1370 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
1371 }
1372
1373 // Create the AST unit.
1374 llvm::OwningPtr<ASTUnit> AST;
1375 AST.reset(new ASTUnit(false));
1376 AST->Diagnostics = Diags;
1377 AST->CaptureDiagnostics = CaptureDiagnostics;
1378 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001379 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001380 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001381 AST->Invocation.reset(CI);
1382
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001383 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar764c0822009-12-01 09:51:01 +00001384}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001385
1386ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1387 const char **ArgEnd,
Douglas Gregor7f95d262010-04-05 23:52:57 +00001388 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar8d4a2022009-12-13 03:46:13 +00001389 llvm::StringRef ResourceFilesPath,
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001390 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001391 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001392 unsigned NumRemappedFiles,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001393 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001394 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001395 bool CompleteTranslationUnit,
Douglas Gregorf5a18542010-10-27 17:24:53 +00001396 bool CacheCodeCompletionResults,
1397 bool CXXPrecompilePreamble,
1398 bool CXXChainedPCH) {
Douglas Gregor2dd19f12010-08-18 22:29:43 +00001399 bool CreatedDiagnosticsObject = false;
1400
Douglas Gregor7f95d262010-04-05 23:52:57 +00001401 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00001402 // No diagnostics engine was provided, so create our own diagnostics object
1403 // with the default options.
1404 DiagnosticOptions DiagOpts;
Douglas Gregor7f95d262010-04-05 23:52:57 +00001405 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00001406 CreatedDiagnosticsObject = true;
Douglas Gregord03e8232010-04-05 21:10:19 +00001407 }
1408
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001409 llvm::SmallVector<const char *, 16> Args;
1410 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1411 Args.insert(Args.end(), ArgBegin, ArgEnd);
1412
1413 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1414 // also want to force it to use clang.
1415 Args.push_back("-fsyntax-only");
1416
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001417 llvm::SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1418
1419 llvm::OwningPtr<CompilerInvocation> CI;
1420 {
1421 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
1422 *Diags,
1423 StoredDiagnostics);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001424
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001425 // FIXME: We shouldn't have to pass in the path info.
1426 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
1427 "a.out", false, false, *Diags);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001428
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001429 // Don't check that inputs exist, they have been remapped.
1430 TheDriver.setCheckInputsExist(false);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001431
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001432 llvm::OwningPtr<driver::Compilation> C(
1433 TheDriver.BuildCompilation(Args.size(), Args.data()));
1434
1435 // We expect to get back exactly one command job, if we didn't something
1436 // failed.
1437 const driver::JobList &Jobs = C->getJobs();
1438 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1439 llvm::SmallString<256> Msg;
1440 llvm::raw_svector_ostream OS(Msg);
1441 C->PrintJob(OS, C->getJobs(), "; ", true);
1442 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
1443 return 0;
1444 }
1445
1446 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1447 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
1448 Diags->Report(diag::err_fe_expected_clang_command);
1449 return 0;
1450 }
1451
1452 const driver::ArgStringList &CCArgs = Cmd->getArguments();
1453 CI.reset(new CompilerInvocation);
1454 CompilerInvocation::CreateFromArgs(*CI,
1455 const_cast<const char **>(CCArgs.data()),
1456 const_cast<const char **>(CCArgs.data()) +
1457 CCArgs.size(),
1458 *Diags);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001459 }
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001460
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001461 // Override any files that need remapping
1462 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001463 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbar19511922010-02-16 01:55:04 +00001464 RemappedFiles[I].second);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001465
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001466 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001467 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001468
Douglas Gregorf5a18542010-10-27 17:24:53 +00001469 // Check whether we should precompile the preamble and/or use chained PCH.
1470 // FIXME: This is a temporary hack while we debug C++ chained PCH.
1471 if (CI->getLangOpts().CPlusPlus) {
1472 PrecompilePreamble = PrecompilePreamble && CXXPrecompilePreamble;
1473
1474 if (PrecompilePreamble && !CXXChainedPCH &&
1475 !CI->getPreprocessorOpts().ImplicitPCHInclude.empty())
1476 PrecompilePreamble = false;
1477 }
1478
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001479 // Create the AST unit.
1480 llvm::OwningPtr<ASTUnit> AST;
1481 AST.reset(new ASTUnit(false));
1482 AST->Diagnostics = Diags;
1483 AST->CaptureDiagnostics = CaptureDiagnostics;
1484 AST->OnlyLocalDecls = OnlyLocalDecls;
1485 AST->CompleteTranslationUnit = CompleteTranslationUnit;
1486 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1487 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1488 AST->NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1489 AST->StoredDiagnostics.swap(StoredDiagnostics);
1490 AST->Invocation.reset(CI.take());
1491 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001492}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001493
1494bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1495 if (!Invocation.get())
1496 return true;
1497
Douglas Gregor16896c42010-10-28 15:44:59 +00001498 SimpleTimer ParsingTimer(WantTiming);
1499 if (WantTiming)
1500 ParsingTimer.setOutput( "Reparsing " + getMainFileName());
1501
Douglas Gregor0e119552010-07-31 00:40:00 +00001502 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00001503 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1504 for (PreprocessorOptions::remapped_file_buffer_iterator
1505 R = PPOpts.remapped_file_buffer_begin(),
1506 REnd = PPOpts.remapped_file_buffer_end();
1507 R != REnd;
1508 ++R) {
1509 delete R->second;
1510 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001511 Invocation->getPreprocessorOpts().clearRemappedFiles();
1512 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1513 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1514 RemappedFiles[I].second);
1515
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001516 // If we have a preamble file lying around, or if we might try to
1517 // build a precompiled preamble, do so now.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001518 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001519 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregorb97b6662010-08-20 00:59:43 +00001520 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001521
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001522 // Clear out the diagnostics state.
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001523 if (!OverrideMainBuffer) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001524 getDiagnostics().Reset();
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001525 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1526 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001527
Douglas Gregor4dde7492010-07-23 23:58:40 +00001528 // Parse the sources
Douglas Gregor6481ef12010-07-24 00:38:13 +00001529 bool Result = Parse(OverrideMainBuffer);
Douglas Gregor2c8bd472010-08-17 00:40:40 +00001530
1531 if (ShouldCacheCodeCompletionResults) {
1532 if (CacheCodeCompletionCoolDown > 0)
1533 --CacheCodeCompletionCoolDown;
1534 else if (top_level_size() != NumTopLevelDeclsAtLastCompletionCache)
1535 CacheCodeCompletionResults();
1536 }
1537
Douglas Gregor4dde7492010-07-23 23:58:40 +00001538 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001539}
Douglas Gregor8e984da2010-08-04 16:47:14 +00001540
Douglas Gregorb14904c2010-08-13 22:48:40 +00001541//----------------------------------------------------------------------------//
1542// Code completion
1543//----------------------------------------------------------------------------//
1544
1545namespace {
1546 /// \brief Code completion consumer that combines the cached code-completion
1547 /// results from an ASTUnit with the code-completion results provided to it,
1548 /// then passes the result on to
1549 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1550 unsigned NormalContexts;
1551 ASTUnit &AST;
1552 CodeCompleteConsumer &Next;
1553
1554 public:
1555 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor39982192010-08-15 06:18:01 +00001556 bool IncludeMacros, bool IncludeCodePatterns,
1557 bool IncludeGlobals)
1558 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001559 Next.isOutputBinary()), AST(AST), Next(Next)
1560 {
1561 // Compute the set of contexts in which we will look when we don't have
1562 // any information about the specific context.
1563 NormalContexts
1564 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
1565 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
1566 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1567 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1568 | (1 << (CodeCompletionContext::CCC_Statement - 1))
1569 | (1 << (CodeCompletionContext::CCC_Expression - 1))
1570 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1571 | (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
Douglas Gregor5e35d592010-09-14 23:59:36 +00001572 | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
Douglas Gregor0ac41382010-09-23 23:01:17 +00001573 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
1574 | (1 << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor5e35d592010-09-14 23:59:36 +00001575
Douglas Gregorb14904c2010-08-13 22:48:40 +00001576 if (AST.getASTContext().getLangOptions().CPlusPlus)
1577 NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1))
1578 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
1579 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
1580 }
1581
1582 virtual void ProcessCodeCompleteResults(Sema &S,
1583 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001584 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001585 unsigned NumResults);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001586
1587 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1588 OverloadCandidate *Candidates,
1589 unsigned NumCandidates) {
1590 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1591 }
1592 };
1593}
Douglas Gregord46cf182010-08-16 20:01:48 +00001594
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001595/// \brief Helper function that computes which global names are hidden by the
1596/// local code-completion results.
1597void CalculateHiddenNames(const CodeCompletionContext &Context,
John McCall276321a2010-08-25 06:19:51 +00001598 CodeCompletionResult *Results,
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001599 unsigned NumResults,
1600 ASTContext &Ctx,
1601 llvm::StringSet<> &HiddenNames) {
1602 bool OnlyTagNames = false;
1603 switch (Context.getKind()) {
Douglas Gregor0ac41382010-09-23 23:01:17 +00001604 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001605 case CodeCompletionContext::CCC_TopLevel:
1606 case CodeCompletionContext::CCC_ObjCInterface:
1607 case CodeCompletionContext::CCC_ObjCImplementation:
1608 case CodeCompletionContext::CCC_ObjCIvarList:
1609 case CodeCompletionContext::CCC_ClassStructUnion:
1610 case CodeCompletionContext::CCC_Statement:
1611 case CodeCompletionContext::CCC_Expression:
1612 case CodeCompletionContext::CCC_ObjCMessageReceiver:
1613 case CodeCompletionContext::CCC_MemberAccess:
1614 case CodeCompletionContext::CCC_Namespace:
1615 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00001616 case CodeCompletionContext::CCC_Name:
1617 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor5e35d592010-09-14 23:59:36 +00001618 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001619 break;
1620
1621 case CodeCompletionContext::CCC_EnumTag:
1622 case CodeCompletionContext::CCC_UnionTag:
1623 case CodeCompletionContext::CCC_ClassOrStructTag:
1624 OnlyTagNames = true;
1625 break;
1626
1627 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00001628 case CodeCompletionContext::CCC_MacroName:
1629 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00001630 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001631 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00001632 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00001633 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00001634 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +00001635 case CodeCompletionContext::CCC_Other:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001636 // We're looking for nothing, or we're looking for names that cannot
1637 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001638 return;
1639 }
1640
John McCall276321a2010-08-25 06:19:51 +00001641 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001642 for (unsigned I = 0; I != NumResults; ++I) {
1643 if (Results[I].Kind != Result::RK_Declaration)
1644 continue;
1645
1646 unsigned IDNS
1647 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1648
1649 bool Hiding = false;
1650 if (OnlyTagNames)
1651 Hiding = (IDNS & Decl::IDNS_Tag);
1652 else {
1653 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00001654 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1655 Decl::IDNS_NonMemberOperator);
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001656 if (Ctx.getLangOptions().CPlusPlus)
1657 HiddenIDNS |= Decl::IDNS_Tag;
1658 Hiding = (IDNS & HiddenIDNS);
1659 }
1660
1661 if (!Hiding)
1662 continue;
1663
1664 DeclarationName Name = Results[I].Declaration->getDeclName();
1665 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1666 HiddenNames.insert(Identifier->getName());
1667 else
1668 HiddenNames.insert(Name.getAsString());
1669 }
1670}
1671
1672
Douglas Gregord46cf182010-08-16 20:01:48 +00001673void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1674 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001675 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001676 unsigned NumResults) {
1677 // Merge the results we were given with the results we cached.
1678 bool AddedResult = false;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001679 unsigned InContexts
Douglas Gregor0ac41382010-09-23 23:01:17 +00001680 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001681 : (1 << (Context.getKind() - 1)));
1682
1683 // Contains the set of names that are hidden by "local" completion results.
1684 llvm::StringSet<> HiddenNames;
Douglas Gregor12785102010-08-24 20:21:13 +00001685 llvm::SmallVector<CodeCompletionString *, 4> StringsToDestroy;
John McCall276321a2010-08-25 06:19:51 +00001686 typedef CodeCompletionResult Result;
Douglas Gregord46cf182010-08-16 20:01:48 +00001687 llvm::SmallVector<Result, 8> AllResults;
1688 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00001689 C = AST.cached_completion_begin(),
1690 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00001691 C != CEnd; ++C) {
1692 // If the context we are in matches any of the contexts we are
1693 // interested in, we'll add this result.
1694 if ((C->ShowInContexts & InContexts) == 0)
1695 continue;
1696
1697 // If we haven't added any results previously, do so now.
1698 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001699 CalculateHiddenNames(Context, Results, NumResults, S.Context,
1700 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00001701 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1702 AddedResult = true;
1703 }
1704
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001705 // Determine whether this global completion result is hidden by a local
1706 // completion result. If so, skip it.
1707 if (C->Kind != CXCursor_MacroDefinition &&
1708 HiddenNames.count(C->Completion->getTypedText()))
1709 continue;
1710
Douglas Gregord46cf182010-08-16 20:01:48 +00001711 // Adjust priority based on similar type classes.
1712 unsigned Priority = C->Priority;
Douglas Gregor8850aa32010-08-25 18:03:13 +00001713 CXCursorKind CursorKind = C->Kind;
Douglas Gregor12785102010-08-24 20:21:13 +00001714 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00001715 if (!Context.getPreferredType().isNull()) {
1716 if (C->Kind == CXCursor_MacroDefinition) {
1717 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregor9dcf58a2010-09-20 21:11:48 +00001718 S.getLangOptions(),
Douglas Gregor12785102010-08-24 20:21:13 +00001719 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00001720 } else if (C->Type) {
1721 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00001722 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00001723 Context.getPreferredType().getUnqualifiedType());
1724 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
1725 if (ExpectedSTC == C->TypeClass) {
1726 // We know this type is similar; check for an exact match.
1727 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00001728 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00001729 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00001730 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00001731 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
1732 Priority /= CCF_ExactTypeMatch;
1733 else
1734 Priority /= CCF_SimilarTypeMatch;
1735 }
1736 }
1737 }
1738
Douglas Gregor12785102010-08-24 20:21:13 +00001739 // Adjust the completion string, if required.
1740 if (C->Kind == CXCursor_MacroDefinition &&
1741 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
1742 // Create a new code-completion string that just contains the
1743 // macro name, without its arguments.
1744 Completion = new CodeCompletionString;
1745 Completion->AddTypedTextChunk(C->Completion->getTypedText());
1746 StringsToDestroy.push_back(Completion);
Douglas Gregor8850aa32010-08-25 18:03:13 +00001747 CursorKind = CXCursor_NotImplemented;
1748 Priority = CCP_CodePattern;
Douglas Gregor12785102010-08-24 20:21:13 +00001749 }
1750
Douglas Gregor8850aa32010-08-25 18:03:13 +00001751 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregorf757a122010-08-23 23:00:57 +00001752 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00001753 }
1754
1755 // If we did not add any cached completion results, just forward the
1756 // results we were given to the next consumer.
1757 if (!AddedResult) {
1758 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
1759 return;
1760 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00001761
Douglas Gregord46cf182010-08-16 20:01:48 +00001762 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
1763 AllResults.size());
Douglas Gregor12785102010-08-24 20:21:13 +00001764
1765 for (unsigned I = 0, N = StringsToDestroy.size(); I != N; ++I)
1766 delete StringsToDestroy[I];
Douglas Gregord46cf182010-08-16 20:01:48 +00001767}
1768
1769
1770
Douglas Gregor8e984da2010-08-04 16:47:14 +00001771void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
1772 RemappedFile *RemappedFiles,
1773 unsigned NumRemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00001774 bool IncludeMacros,
1775 bool IncludeCodePatterns,
Douglas Gregor8e984da2010-08-04 16:47:14 +00001776 CodeCompleteConsumer &Consumer,
1777 Diagnostic &Diag, LangOptions &LangOpts,
1778 SourceManager &SourceMgr, FileManager &FileMgr,
Douglas Gregorb97b6662010-08-20 00:59:43 +00001779 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
1780 llvm::SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001781 if (!Invocation.get())
1782 return;
1783
Douglas Gregor16896c42010-10-28 15:44:59 +00001784 SimpleTimer CompletionTimer(WantTiming);
1785 if (WantTiming) {
Douglas Gregor028d3e42010-08-09 20:45:32 +00001786 llvm::SmallString<128> TimerName;
1787 llvm::raw_svector_ostream TimerNameOut(TimerName);
1788 TimerNameOut << "Code completion @ " << File << ":" << Line << ":"
1789 << Column;
Douglas Gregor16896c42010-10-28 15:44:59 +00001790 CompletionTimer.setOutput(TimerNameOut.str());
Douglas Gregor028d3e42010-08-09 20:45:32 +00001791 }
1792
Douglas Gregor8e984da2010-08-04 16:47:14 +00001793 CompilerInvocation CCInvocation(*Invocation);
1794 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
1795 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00001796
Douglas Gregorb14904c2010-08-13 22:48:40 +00001797 FrontendOpts.ShowMacrosInCodeCompletion
1798 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorb68bc592010-08-05 09:09:23 +00001799 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor39982192010-08-15 06:18:01 +00001800 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
1801 = CachedCompletionResults.empty();
Douglas Gregor8e984da2010-08-04 16:47:14 +00001802 FrontendOpts.CodeCompletionAt.FileName = File;
1803 FrontendOpts.CodeCompletionAt.Line = Line;
1804 FrontendOpts.CodeCompletionAt.Column = Column;
1805
1806 // Set the language options appropriately.
1807 LangOpts = CCInvocation.getLangOpts();
1808
1809 CompilerInstance Clang;
1810 Clang.setInvocation(&CCInvocation);
1811 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1812
1813 // Set up diagnostics, capturing any diagnostics produced.
1814 Clang.setDiagnostics(&Diag);
Douglas Gregor36e3b5c2010-10-11 21:37:58 +00001815 ProcessWarningOptions(Diag, CCInvocation.getDiagnosticOpts());
Douglas Gregor8e984da2010-08-04 16:47:14 +00001816 CaptureDroppedDiagnostics Capture(true,
1817 Clang.getDiagnostics(),
1818 StoredDiagnostics);
Douglas Gregor8e984da2010-08-04 16:47:14 +00001819
1820 // Create the target instance.
1821 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1822 Clang.getTargetOpts()));
1823 if (!Clang.hasTarget()) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001824 Clang.takeInvocation();
Douglas Gregor2dd19f12010-08-18 22:29:43 +00001825 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00001826 }
1827
1828 // Inform the target of the language options.
1829 //
1830 // FIXME: We shouldn't need to do this, the target should be immutable once
1831 // created. This complexity should be lifted elsewhere.
1832 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1833
1834 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1835 "Invocation must have exactly one source file!");
1836 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1837 "FIXME: AST inputs not yet supported here!");
1838 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1839 "IR inputs not support here!");
1840
1841
1842 // Use the source and file managers that we were given.
1843 Clang.setFileManager(&FileMgr);
1844 Clang.setSourceManager(&SourceMgr);
1845
1846 // Remap files.
1847 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00001848 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregorb97b6662010-08-20 00:59:43 +00001849 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001850 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
1851 RemappedFiles[I].second);
Douglas Gregorb97b6662010-08-20 00:59:43 +00001852 OwnedBuffers.push_back(RemappedFiles[I].second);
1853 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00001854
Douglas Gregorb14904c2010-08-13 22:48:40 +00001855 // Use the code completion consumer we were given, but adding any cached
1856 // code-completion results.
1857 AugmentedCodeCompleteConsumer
1858 AugmentedConsumer(*this, Consumer, FrontendOpts.ShowMacrosInCodeCompletion,
Douglas Gregor39982192010-08-15 06:18:01 +00001859 FrontendOpts.ShowCodePatternsInCodeCompletion,
1860 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001861 Clang.setCodeCompletionConsumer(&AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00001862
Douglas Gregor028d3e42010-08-09 20:45:32 +00001863 // If we have a precompiled preamble, try to use it. We only allow
1864 // the use of the precompiled preamble if we're if the completion
1865 // point is within the main file, after the end of the precompiled
1866 // preamble.
1867 llvm::MemoryBuffer *OverrideMainBuffer = 0;
1868 if (!PreambleFile.empty()) {
1869 using llvm::sys::FileStatus;
1870 llvm::sys::PathWithStatus CompleteFilePath(File);
1871 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
1872 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
1873 if (const FileStatus *MainStatus = MainPath.getFileStatus())
1874 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
Douglas Gregorb97b6662010-08-20 00:59:43 +00001875 OverrideMainBuffer
Douglas Gregor8e817b62010-08-25 18:04:15 +00001876 = getMainBufferWithPrecompiledPreamble(CCInvocation, false,
1877 Line - 1);
Douglas Gregor028d3e42010-08-09 20:45:32 +00001878 }
1879
1880 // If the main file has been overridden due to the use of a preamble,
1881 // make that override happen and introduce the preamble.
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001882 StoredDiagnostics.insert(StoredDiagnostics.end(),
1883 this->StoredDiagnostics.begin(),
1884 this->StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver);
Douglas Gregor028d3e42010-08-09 20:45:32 +00001885 if (OverrideMainBuffer) {
1886 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1887 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1888 PreprocessorOpts.PrecompiledPreambleBytes.second
1889 = PreambleEndsAtStartOfLine;
1890 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
1891 PreprocessorOpts.DisablePCHValidation = true;
1892
1893 // The stored diagnostics have the old source manager. Copy them
1894 // to our output set of stored diagnostics, updating the source
1895 // manager to the one we were given.
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001896 for (unsigned I = NumStoredDiagnosticsFromDriver,
1897 N = this->StoredDiagnostics.size();
1898 I < N; ++I) {
Douglas Gregor028d3e42010-08-09 20:45:32 +00001899 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
1900 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
1901 StoredDiagnostics[I].setLocation(Loc);
1902 }
Douglas Gregor7bb8af62010-10-12 00:50:20 +00001903
Douglas Gregorb97b6662010-08-20 00:59:43 +00001904 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001905 } else {
1906 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1907 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001908 }
1909
Douglas Gregor8e984da2010-08-04 16:47:14 +00001910 llvm::OwningPtr<SyntaxOnlyAction> Act;
1911 Act.reset(new SyntaxOnlyAction);
1912 if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1913 Clang.getFrontendOpts().Inputs[0].first)) {
1914 Act->Execute();
1915 Act->EndSourceFile();
1916 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001917
Douglas Gregor8e984da2010-08-04 16:47:14 +00001918 // Steal back our resources.
1919 Clang.takeFileManager();
1920 Clang.takeSourceManager();
1921 Clang.takeInvocation();
Douglas Gregor8e984da2010-08-04 16:47:14 +00001922 Clang.takeCodeCompletionConsumer();
1923}
Douglas Gregore9386682010-08-13 05:36:37 +00001924
1925bool ASTUnit::Save(llvm::StringRef File) {
1926 if (getDiagnostics().hasErrorOccurred())
1927 return true;
1928
1929 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
1930 // unconditionally create a stat cache when we parse the file?
1931 std::string ErrorInfo;
Benjamin Kramer340045b2010-08-15 16:54:31 +00001932 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo,
1933 llvm::raw_fd_ostream::F_Binary);
Douglas Gregore9386682010-08-13 05:36:37 +00001934 if (!ErrorInfo.empty() || Out.has_error())
1935 return true;
1936
1937 std::vector<unsigned char> Buffer;
1938 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redl55c0ad52010-08-18 23:56:21 +00001939 ASTWriter Writer(Stream);
1940 Writer.WriteAST(getSema(), 0, 0);
Douglas Gregore9386682010-08-13 05:36:37 +00001941
1942 // Write the generated bitstream to "Out".
Douglas Gregor2dd19f12010-08-18 22:29:43 +00001943 if (!Buffer.empty())
1944 Out.write((char *)&Buffer.front(), Buffer.size());
Douglas Gregore9386682010-08-13 05:36:37 +00001945 Out.close();
1946 return Out.has_error();
1947}