blob: f68940446099385f03e7089ac56955d63754fab3 [file] [log] [blame]
Argyrios Kyrtzidis4b562cf2009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000015#include "clang/AST/ASTContext.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000016#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
Douglas Gregorf5586f62010-08-16 18:08:11 +000018#include "clang/AST/TypeOrdering.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000019#include "clang/AST/StmtVisitor.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000020#include "clang/Driver/Compilation.h"
21#include "clang/Driver/Driver.h"
22#include "clang/Driver/Job.h"
23#include "clang/Driver/Tool.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000024#include "clang/Frontend/CompilerInstance.h"
25#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000026#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000027#include "clang/Frontend/FrontendOptions.h"
Sebastian Redl85728132010-08-17 20:43:28 +000028#include "clang/Serialization/PCHReader.h"
29#include "clang/Serialization/PCHWriter.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000030#include "clang/Lex/HeaderSearch.h"
31#include "clang/Lex/Preprocessor.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000032#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000033#include "clang/Basic/TargetInfo.h"
34#include "clang/Basic/Diagnostic.h"
Douglas Gregor349d38c2010-08-16 23:08:34 +000035#include "llvm/ADT/StringSet.h"
Douglas Gregor4db64a42010-01-23 00:14:00 +000036#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000037#include "llvm/System/Host.h"
Benjamin Kramer4a630d32009-10-18 11:34:14 +000038#include "llvm/System/Path.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000039#include "llvm/Support/raw_ostream.h"
Douglas Gregor385103b2010-07-30 20:58:08 +000040#include "llvm/Support/Timer.h"
Douglas Gregor44c181a2010-07-23 00:33:23 +000041#include <cstdlib>
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000042#include <cstdio>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000043#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000044using namespace clang;
45
Douglas Gregoreababfb2010-08-04 05:53:38 +000046/// \brief After failing to build a precompiled preamble (due to
47/// errors in the source that occurs in the preamble), the number of
48/// reparses during which we'll skip even trying to precompile the
49/// preamble.
50const unsigned DefaultPreambleRebuildInterval = 5;
51
Douglas Gregor3687e9d2010-04-05 21:10:19 +000052ASTUnit::ASTUnit(bool _MainFileIsAST)
Douglas Gregorabc563f2010-07-19 21:46:24 +000053 : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
Douglas Gregordf95a132010-08-09 20:45:32 +000054 CompleteTranslationUnit(true), ConcurrencyCheckValue(CheckUnlocked),
Douglas Gregor87c08a52010-08-13 22:48:40 +000055 PreambleRebuildCounter(0), SavedMainFileBuffer(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +000056 ShouldCacheCodeCompletionResults(false),
57 NumTopLevelDeclsAtLastCompletionCache(0),
58 CacheCodeCompletionCoolDown(0) {
Douglas Gregor385103b2010-07-30 20:58:08 +000059}
Douglas Gregor3687e9d2010-04-05 21:10:19 +000060
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000061ASTUnit::~ASTUnit() {
Douglas Gregorbdf60622010-03-05 21:16:25 +000062 ConcurrencyCheckValue = CheckLocked;
Douglas Gregorabc563f2010-07-19 21:46:24 +000063 CleanTemporaryFiles();
Douglas Gregor175c4a92010-07-23 23:58:40 +000064 if (!PreambleFile.empty())
Douglas Gregor385103b2010-07-30 20:58:08 +000065 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000066
67 // Free the buffers associated with remapped files. We are required to
68 // perform this operation here because we explicitly request that the
69 // compiler instance *not* free these buffers for each invocation of the
70 // parser.
71 if (Invocation.get()) {
72 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
73 for (PreprocessorOptions::remapped_file_buffer_iterator
74 FB = PPOpts.remapped_file_buffer_begin(),
75 FBEnd = PPOpts.remapped_file_buffer_end();
76 FB != FBEnd;
77 ++FB)
78 delete FB->second;
79 }
Douglas Gregor28233422010-07-27 14:52:07 +000080
81 delete SavedMainFileBuffer;
Douglas Gregor385103b2010-07-30 20:58:08 +000082
Douglas Gregor87c08a52010-08-13 22:48:40 +000083 ClearCachedCompletionResults();
84
Douglas Gregor385103b2010-07-30 20:58:08 +000085 for (unsigned I = 0, N = Timers.size(); I != N; ++I)
86 delete Timers[I];
Douglas Gregorabc563f2010-07-19 21:46:24 +000087}
88
89void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor313e26c2010-02-18 23:35:40 +000090 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
91 TemporaryFiles[I].eraseFromDisk();
Douglas Gregorabc563f2010-07-19 21:46:24 +000092 TemporaryFiles.clear();
Steve Naroffe19944c2009-10-15 22:23:48 +000093}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000094
Douglas Gregor8071e422010-08-15 06:18:01 +000095/// \brief Determine the set of code-completion contexts in which this
96/// declaration should be shown.
97static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +000098 const LangOptions &LangOpts,
99 bool &IsNestedNameSpecifier) {
100 IsNestedNameSpecifier = false;
101
Douglas Gregor8071e422010-08-15 06:18:01 +0000102 if (isa<UsingShadowDecl>(ND))
103 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
104 if (!ND)
105 return 0;
106
107 unsigned Contexts = 0;
108 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
109 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
110 // Types can appear in these contexts.
111 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
112 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
113 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
114 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
115 | (1 << (CodeCompletionContext::CCC_Statement - 1))
116 | (1 << (CodeCompletionContext::CCC_Type - 1));
117
118 // In C++, types can appear in expressions contexts (for functional casts).
119 if (LangOpts.CPlusPlus)
120 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
121
122 // In Objective-C, message sends can send interfaces. In Objective-C++,
123 // all types are available due to functional casts.
124 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
125 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
126
127 // Deal with tag names.
128 if (isa<EnumDecl>(ND)) {
129 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
130
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000131 // Part of the nested-name-specifier in C++0x.
Douglas Gregor8071e422010-08-15 06:18:01 +0000132 if (LangOpts.CPlusPlus0x)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000133 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000134 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
135 if (Record->isUnion())
136 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
137 else
138 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
139
Douglas Gregor8071e422010-08-15 06:18:01 +0000140 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000141 IsNestedNameSpecifier = true;
142 } else if (isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND))
143 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000144 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
145 // Values can appear in these contexts.
146 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
147 | (1 << (CodeCompletionContext::CCC_Expression - 1))
148 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
149 } else if (isa<ObjCProtocolDecl>(ND)) {
150 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
151 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000152 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000153
154 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000155 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000156 }
157
158 return Contexts;
159}
160
Douglas Gregor87c08a52010-08-13 22:48:40 +0000161void ASTUnit::CacheCodeCompletionResults() {
162 if (!TheSema)
163 return;
164
165 llvm::Timer *CachingTimer = 0;
166 if (TimerGroup.get()) {
167 CachingTimer = new llvm::Timer("Cache global code completions",
168 *TimerGroup);
169 CachingTimer->startTimer();
170 Timers.push_back(CachingTimer);
171 }
172
173 // Clear out the previous results.
174 ClearCachedCompletionResults();
175
176 // Gather the set of global code completions.
177 typedef CodeCompleteConsumer::Result Result;
178 llvm::SmallVector<Result, 8> Results;
179 TheSema->GatherGlobalCodeCompletions(Results);
180
181 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000182 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
183
Douglas Gregor87c08a52010-08-13 22:48:40 +0000184 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
185 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000186 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000187 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000188 CachedCodeCompletionResult CachedResult;
189 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
190 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000191 Ctx->getLangOptions(),
192 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000193 CachedResult.Priority = Results[I].Priority;
194 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000195
Douglas Gregorf5586f62010-08-16 18:08:11 +0000196 // Keep track of the type of this completion in an ASTContext-agnostic
197 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000198 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000199 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000200 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000201 CachedResult.Type = 0;
202 } else {
203 CanQualType CanUsageType
204 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
205 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
206
207 // Determine whether we have already seen this type. If so, we save
208 // ourselves the work of formatting the type string by using the
209 // temporary, CanQualType-based hash table to find the associated value.
210 unsigned &TypeValue = CompletionTypes[CanUsageType];
211 if (TypeValue == 0) {
212 TypeValue = CompletionTypes.size();
213 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
214 = TypeValue;
215 }
216
217 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000218 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000219
Douglas Gregor8071e422010-08-15 06:18:01 +0000220 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000221
222 /// Handle nested-name-specifiers in C++.
223 if (TheSema->Context.getLangOptions().CPlusPlus &&
224 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
225 // The contexts in which a nested-name-specifier can appear in C++.
226 unsigned NNSContexts
227 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
228 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
229 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
230 | (1 << (CodeCompletionContext::CCC_Statement - 1))
231 | (1 << (CodeCompletionContext::CCC_Expression - 1))
232 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
233 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
234 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
235 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
236 | (1 << (CodeCompletionContext::CCC_Type - 1));
237
238 if (isa<NamespaceDecl>(Results[I].Declaration) ||
239 isa<NamespaceAliasDecl>(Results[I].Declaration))
240 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
241
242 if (unsigned RemainingContexts
243 = NNSContexts & ~CachedResult.ShowInContexts) {
244 // If there any contexts where this completion can be a
245 // nested-name-specifier but isn't already an option, create a
246 // nested-name-specifier completion.
247 Results[I].StartsNestedNameSpecifier = true;
248 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
249 CachedResult.ShowInContexts = RemainingContexts;
250 CachedResult.Priority = CCP_NestedNameSpecifier;
251 CachedResult.TypeClass = STC_Void;
252 CachedResult.Type = 0;
253 CachedCompletionResults.push_back(CachedResult);
254 }
255 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000256 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000257 }
258
Douglas Gregor87c08a52010-08-13 22:48:40 +0000259 case Result::RK_Keyword:
260 case Result::RK_Pattern:
261 // Ignore keywords and patterns; we don't care, since they are so
262 // easily regenerated.
263 break;
264
265 case Result::RK_Macro: {
266 CachedCodeCompletionResult CachedResult;
267 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
268 CachedResult.ShowInContexts
269 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
270 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
271 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
272 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
273 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
274 | (1 << (CodeCompletionContext::CCC_Statement - 1))
275 | (1 << (CodeCompletionContext::CCC_Expression - 1))
276 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
277 CachedResult.Priority = Results[I].Priority;
278 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor1827e102010-08-16 16:18:59 +0000279 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000280 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000281 CachedCompletionResults.push_back(CachedResult);
282 break;
283 }
284 }
285 Results[I].Destroy();
286 }
287
288 if (CachingTimer)
289 CachingTimer->stopTimer();
Douglas Gregor727d93e2010-08-17 00:40:40 +0000290
291 // Make a note of the state when we performed this caching.
292 NumTopLevelDeclsAtLastCompletionCache = top_level_size();
293 CacheCodeCompletionCoolDown = 15;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000294}
295
296void ASTUnit::ClearCachedCompletionResults() {
297 for (unsigned I = 0, N = CachedCompletionResults.size(); I != N; ++I)
298 delete CachedCompletionResults[I].Completion;
299 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000300 CachedCompletionTypes.clear();
Douglas Gregor87c08a52010-08-13 22:48:40 +0000301}
302
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000303namespace {
304
305/// \brief Gathers information from PCHReader that will be used to initialize
306/// a Preprocessor.
Benjamin Kramerbd218282009-11-28 10:07:24 +0000307class PCHInfoCollector : public PCHReaderListener {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000308 LangOptions &LangOpt;
309 HeaderSearch &HSI;
310 std::string &TargetTriple;
311 std::string &Predefines;
312 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000313
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000314 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000315
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000316public:
317 PCHInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
318 std::string &TargetTriple, std::string &Predefines,
319 unsigned &Counter)
320 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
321 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000322
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000323 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
324 LangOpt = LangOpts;
325 return false;
326 }
Mike Stump1eb44332009-09-09 15:08:12 +0000327
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000328 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000329 TargetTriple = Triple;
330 return false;
331 }
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000333 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000334 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000335 std::string &SuggestedPredefines) {
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000336 Predefines = Buffers[0].Data;
337 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
338 Predefines += Buffers[I].Data;
339 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000340 return false;
341 }
Mike Stump1eb44332009-09-09 15:08:12 +0000342
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000343 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000344 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
345 }
Mike Stump1eb44332009-09-09 15:08:12 +0000346
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000347 virtual void ReadCounter(unsigned Value) {
348 Counter = Value;
349 }
350};
351
Douglas Gregora88084b2010-02-18 18:08:43 +0000352class StoredDiagnosticClient : public DiagnosticClient {
353 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
354
355public:
356 explicit StoredDiagnosticClient(
357 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
358 : StoredDiags(StoredDiags) { }
359
360 virtual void HandleDiagnostic(Diagnostic::Level Level,
361 const DiagnosticInfo &Info);
362};
363
364/// \brief RAII object that optionally captures diagnostics, if
365/// there is no diagnostic client to capture them already.
366class CaptureDroppedDiagnostics {
367 Diagnostic &Diags;
368 StoredDiagnosticClient Client;
369 DiagnosticClient *PreviousClient;
370
371public:
372 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
373 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000374 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000375 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000376 if (RequestCapture || Diags.getClient() == 0) {
377 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000378 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000379 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000380 }
381
382 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000383 if (Diags.getClient() == &Client) {
384 Diags.takeClient();
385 Diags.setClient(PreviousClient);
386 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000387 }
388};
389
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000390} // anonymous namespace
391
Douglas Gregora88084b2010-02-18 18:08:43 +0000392void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
393 const DiagnosticInfo &Info) {
394 StoredDiags.push_back(StoredDiagnostic(Level, Info));
395}
396
Steve Naroff77accc12009-09-03 18:19:54 +0000397const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000398 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000399}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000400
Steve Naroffe19944c2009-10-15 22:23:48 +0000401const std::string &ASTUnit::getPCHFileName() {
Daniel Dunbarc7822db2009-12-02 21:47:43 +0000402 assert(isMainFileAST() && "Not an ASTUnit from a PCH file!");
Benjamin Kramer7297c182010-01-30 16:23:25 +0000403 return static_cast<PCHReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroffe19944c2009-10-15 22:23:48 +0000404}
405
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000406ASTUnit *ASTUnit::LoadFromPCHFile(const std::string &Filename,
Douglas Gregor28019772010-04-05 23:52:57 +0000407 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000408 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000409 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000410 unsigned NumRemappedFiles,
411 bool CaptureDiagnostics) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000412 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
413
Douglas Gregor28019772010-04-05 23:52:57 +0000414 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000415 // No diagnostics engine was provided, so create our own diagnostics object
416 // with the default options.
417 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +0000418 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000419 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000420
421 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000422 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor28019772010-04-05 23:52:57 +0000423 AST->Diagnostics = Diags;
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000424 AST->FileMgr.reset(new FileManager);
425 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics()));
Steve Naroff36c44642009-10-19 14:34:22 +0000426 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000427
Douglas Gregora88084b2010-02-18 18:08:43 +0000428 // If requested, capture diagnostics in the ASTUnit.
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000429 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, AST->getDiagnostics(),
Douglas Gregor405634b2010-04-05 18:10:21 +0000430 AST->StoredDiagnostics);
Douglas Gregora88084b2010-02-18 18:08:43 +0000431
Douglas Gregor4db64a42010-01-23 00:14:00 +0000432 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
433 // Create the file entry for the file that we're mapping from.
434 const FileEntry *FromFile
435 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
436 RemappedFiles[I].second->getBufferSize(),
437 0);
438 if (!FromFile) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000439 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregor4db64a42010-01-23 00:14:00 +0000440 << RemappedFiles[I].first;
Douglas Gregorc8dfe5e2010-02-27 01:32:48 +0000441 delete RemappedFiles[I].second;
Douglas Gregor4db64a42010-01-23 00:14:00 +0000442 continue;
443 }
444
445 // Override the contents of the "from" file with the contents of
446 // the "to" file.
447 AST->getSourceManager().overrideFileContents(FromFile,
448 RemappedFiles[I].second);
449 }
450
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000451 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000452
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000453 LangOptions LangInfo;
454 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
455 std::string TargetTriple;
456 std::string Predefines;
457 unsigned Counter;
458
Daniel Dunbarbce6f622009-09-03 05:59:50 +0000459 llvm::OwningPtr<PCHReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000460
Ted Kremenekfc062212009-10-19 21:44:57 +0000461 Reader.reset(new PCHReader(AST->getSourceManager(), AST->getFileManager(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000462 AST->getDiagnostics()));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000463 Reader->setListener(new PCHInfoCollector(LangInfo, HeaderInfo, TargetTriple,
464 Predefines, Counter));
465
466 switch (Reader->ReadPCH(Filename)) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000467 case PCHReader::Success:
468 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000469
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000470 case PCHReader::Failure:
Argyrios Kyrtzidis106c9982009-06-25 18:22:30 +0000471 case PCHReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000472 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000473 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000474 }
Mike Stump1eb44332009-09-09 15:08:12 +0000475
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000476 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
477
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000478 // PCH loaded successfully. Now create the preprocessor.
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000480 // Get information about the target being compiled for.
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000481 //
482 // FIXME: This is broken, we should store the TargetOptions in the PCH.
483 TargetOptions TargetOpts;
484 TargetOpts.ABI = "";
Charles Davis98b7c5c2010-06-11 01:06:47 +0000485 TargetOpts.CXXABI = "itanium";
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000486 TargetOpts.CPU = "";
487 TargetOpts.Features.clear();
488 TargetOpts.Triple = TargetTriple;
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000489 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
490 TargetOpts));
491 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
492 *AST->Target.get(),
Daniel Dunbar31b87d82009-09-21 03:03:39 +0000493 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000494 Preprocessor &PP = *AST->PP.get();
495
Daniel Dunbard5b61262009-09-21 03:03:47 +0000496 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000497 PP.setCounterValue(Counter);
Daniel Dunbarcc318932009-09-03 05:59:35 +0000498 Reader->setPreprocessor(PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000499
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000500 // Create and initialize the ASTContext.
501
502 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar31b87d82009-09-21 03:03:39 +0000503 AST->getSourceManager(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000504 *AST->Target.get(),
505 PP.getIdentifierTable(),
506 PP.getSelectorTable(),
507 PP.getBuiltinInfo(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000508 /* size_reserve = */0));
509 ASTContext &Context = *AST->Ctx.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Daniel Dunbarcc318932009-09-03 05:59:35 +0000511 Reader->InitializeContext(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000513 // Attach the PCH reader to the AST context as an external AST
514 // source, so that declarations will be deserialized from the
515 // PCH file as needed.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000516 PCHReader *ReaderPtr = Reader.get();
517 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000518 Context.setExternalSource(Source);
519
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000520 // Create an AST consumer, even though it isn't used.
521 AST->Consumer.reset(new ASTConsumer);
522
523 // Create a semantic analysis object and tell the PCH reader about it.
524 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
525 AST->TheSema->Initialize();
526 ReaderPtr->InitializeSema(*AST->TheSema);
527
Mike Stump1eb44332009-09-09 15:08:12 +0000528 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000529}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000530
531namespace {
532
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000533class TopLevelDeclTrackerConsumer : public ASTConsumer {
534 ASTUnit &Unit;
535
536public:
537 TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {}
538
539 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekda5a4282010-05-03 20:16:35 +0000540 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
541 Decl *D = *it;
542 // FIXME: Currently ObjC method declarations are incorrectly being
543 // reported as top-level declarations, even though their DeclContext
544 // is the containing ObjC @interface/@implementation. This is a
545 // fundamental problem in the parser right now.
546 if (isa<ObjCMethodDecl>(D))
547 continue;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000548 Unit.addTopLevelDecl(D);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000549 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000550 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000551
552 // We're not interested in "interesting" decls.
553 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000554};
555
556class TopLevelDeclTrackerAction : public ASTFrontendAction {
557public:
558 ASTUnit &Unit;
559
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000560 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
561 llvm::StringRef InFile) {
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000562 return new TopLevelDeclTrackerConsumer(Unit);
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000563 }
564
565public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000566 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
567
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000568 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000569 virtual bool usesCompleteTranslationUnit() {
570 return Unit.isCompleteTranslationUnit();
571 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000572};
573
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000574class PrecompilePreambleConsumer : public PCHGenerator {
575 ASTUnit &Unit;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000576 std::vector<Decl *> TopLevelDecls;
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000577
578public:
579 PrecompilePreambleConsumer(ASTUnit &Unit,
580 const Preprocessor &PP, bool Chaining,
581 const char *isysroot, llvm::raw_ostream *Out)
582 : PCHGenerator(PP, Chaining, isysroot, Out), Unit(Unit) { }
583
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000584 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000585 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
586 Decl *D = *it;
587 // FIXME: Currently ObjC method declarations are incorrectly being
588 // reported as top-level declarations, even though their DeclContext
589 // is the containing ObjC @interface/@implementation. This is a
590 // fundamental problem in the parser right now.
591 if (isa<ObjCMethodDecl>(D))
592 continue;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000593 TopLevelDecls.push_back(D);
594 }
595 }
596
597 virtual void HandleTranslationUnit(ASTContext &Ctx) {
598 PCHGenerator::HandleTranslationUnit(Ctx);
599 if (!Unit.getDiagnostics().hasErrorOccurred()) {
600 // Translate the top-level declarations we captured during
601 // parsing into declaration IDs in the precompiled
602 // preamble. This will allow us to deserialize those top-level
603 // declarations when requested.
604 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
605 Unit.addTopLevelDeclFromPreamble(
606 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000607 }
608 }
609};
610
611class PrecompilePreambleAction : public ASTFrontendAction {
612 ASTUnit &Unit;
613
614public:
615 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
616
617 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
618 llvm::StringRef InFile) {
619 std::string Sysroot;
620 llvm::raw_ostream *OS = 0;
621 bool Chaining;
622 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
623 OS, Chaining))
624 return 0;
625
626 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
627 Sysroot.c_str() : 0;
628 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
629 isysroot, OS);
630 }
631
632 virtual bool hasCodeCompletionSupport() const { return false; }
633 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000634 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000635};
636
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000637}
638
Douglas Gregorabc563f2010-07-19 21:46:24 +0000639/// Parse the source file into a translation unit using the given compiler
640/// invocation, replacing the current translation unit.
641///
642/// \returns True if a failure occurred that causes the ASTUnit not to
643/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +0000644bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +0000645 delete SavedMainFileBuffer;
646 SavedMainFileBuffer = 0;
647
Douglas Gregorabc563f2010-07-19 21:46:24 +0000648 if (!Invocation.get())
649 return true;
650
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000651 // Create the compiler instance to use for building the AST.
Daniel Dunbarcb6dda12009-12-02 08:43:56 +0000652 CompilerInstance Clang;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000653 Clang.setInvocation(Invocation.take());
654 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
655
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000656 // Set up diagnostics, capturing any diagnostics that would
657 // otherwise be dropped.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000658 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000659 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
660 getDiagnostics(),
661 StoredDiagnostics);
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000662
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000663 // Create the target instance.
664 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
665 Clang.getTargetOpts()));
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000666 if (!Clang.hasTarget())
Douglas Gregorabc563f2010-07-19 21:46:24 +0000667 return true;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000668
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000669 // Inform the target of the language options.
670 //
671 // FIXME: We shouldn't need to do this, the target should be immutable once
672 // created. This complexity should be lifted elsewhere.
673 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000674
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000675 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
676 "Invocation must have exactly one source file!");
Daniel Dunbarc34ce3f2010-06-07 23:22:09 +0000677 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000678 "FIXME: AST inputs not yet supported here!");
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +0000679 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
680 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000681
Douglas Gregorabc563f2010-07-19 21:46:24 +0000682 // Configure the various subsystems.
683 // FIXME: Should we retain the previous file manager?
684 FileMgr.reset(new FileManager);
685 SourceMgr.reset(new SourceManager(getDiagnostics()));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000686 TheSema.reset();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000687 Ctx.reset();
688 PP.reset();
689
690 // Clear out old caches and data.
691 TopLevelDecls.clear();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000692 CleanTemporaryFiles();
693 PreprocessedEntitiesByFile.clear();
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000694
695 if (!OverrideMainBuffer)
696 StoredDiagnostics.clear();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000697
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000698 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000699 Clang.setFileManager(&getFileManager());
700
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000701 // Create the source manager.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000702 Clang.setSourceManager(&getSourceManager());
703
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000704 // If the main file has been overridden due to the use of a preamble,
705 // make that override happen and introduce the preamble.
706 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000707 std::string PriorImplicitPCHInclude;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000708 if (OverrideMainBuffer) {
709 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
710 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
711 PreprocessorOpts.PrecompiledPreambleBytes.second
712 = PreambleEndsAtStartOfLine;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000713 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor385103b2010-07-30 20:58:08 +0000714 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000715 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +0000716
717 // Keep track of the override buffer;
718 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000719
720 // The stored diagnostic has the old source manager in it; update
721 // the locations to refer into the new source manager. Since we've
722 // been careful to make sure that the source manager's state
723 // before and after are identical, so that we can reuse the source
724 // location itself.
725 for (unsigned I = 0, N = StoredDiagnostics.size(); I != N; ++I) {
726 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
727 getSourceManager());
728 StoredDiagnostics[I].setLocation(Loc);
729 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000730 }
731
Douglas Gregorabc563f2010-07-19 21:46:24 +0000732 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
733 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000734 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbard3598a62010-06-07 23:23:06 +0000735 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000736 goto error;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000737
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000738 Act->Execute();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000739
Daniel Dunbar64a32ba2009-12-01 21:57:33 +0000740 // Steal the created target, context, and preprocessor, and take back the
741 // source and file managers.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000742 TheSema.reset(Clang.takeSema());
743 Consumer.reset(Clang.takeASTConsumer());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000744 Ctx.reset(Clang.takeASTContext());
745 PP.reset(Clang.takePreprocessor());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000746 Clang.takeSourceManager();
747 Clang.takeFileManager();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000748 Target.reset(Clang.takeTarget());
749
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000750 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000751
752 // Remove the overridden buffer we used for the preamble.
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000753 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000754 PreprocessorOpts.eraseRemappedFile(
755 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000756 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
757 }
758
Douglas Gregorabc563f2010-07-19 21:46:24 +0000759 Invocation.reset(Clang.takeInvocation());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000760
761 // If we were asked to cache code-completion results and don't have any
762 // results yet, do so now.
763 if (ShouldCacheCodeCompletionResults && CachedCompletionResults.empty())
764 CacheCodeCompletionResults();
765
Douglas Gregorabc563f2010-07-19 21:46:24 +0000766 return false;
767
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000768error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000769 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000770 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000771 PreprocessorOpts.eraseRemappedFile(
772 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000773 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000774 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000775 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000776
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000777 Clang.takeSourceManager();
778 Clang.takeFileManager();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000779 Invocation.reset(Clang.takeInvocation());
780 return true;
781}
782
Douglas Gregor44c181a2010-07-23 00:33:23 +0000783/// \brief Simple function to retrieve a path for a preamble precompiled header.
784static std::string GetPreamblePCHPath() {
785 // FIXME: This is lame; sys::Path should provide this function (in particular,
786 // it should know how to find the temporary files dir).
787 // FIXME: This is really lame. I copied this code from the Driver!
788 std::string Error;
789 const char *TmpDir = ::getenv("TMPDIR");
790 if (!TmpDir)
791 TmpDir = ::getenv("TEMP");
792 if (!TmpDir)
793 TmpDir = ::getenv("TMP");
794 if (!TmpDir)
795 TmpDir = "/tmp";
796 llvm::sys::Path P(TmpDir);
797 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +0000798 P.appendSuffix("pch");
Douglas Gregor44c181a2010-07-23 00:33:23 +0000799 if (P.createTemporaryFileOnDisk())
800 return std::string();
801
Douglas Gregor44c181a2010-07-23 00:33:23 +0000802 return P.str();
803}
804
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000805/// \brief Compute the preamble for the main file, providing the source buffer
806/// that corresponds to the main file along with a pair (bytes, start-of-line)
807/// that describes the preamble.
808std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +0000809ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
810 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000811 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000812 PreprocessorOptions &PreprocessorOpts
Douglas Gregor175c4a92010-07-23 23:58:40 +0000813 = Invocation.getPreprocessorOpts();
814 CreatedBuffer = false;
815
Douglas Gregor44c181a2010-07-23 00:33:23 +0000816 // Try to determine if the main file has been remapped, either from the
817 // command line (to another file) or directly through the compiler invocation
818 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +0000819 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000820 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
821 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
822 // Check whether there is a file-file remapping of the main file
823 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +0000824 M = PreprocessorOpts.remapped_file_begin(),
825 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000826 M != E;
827 ++M) {
828 llvm::sys::PathWithStatus MPath(M->first);
829 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
830 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
831 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000832 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000833 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000834 CreatedBuffer = false;
835 }
836
Douglas Gregor44c181a2010-07-23 00:33:23 +0000837 Buffer = llvm::MemoryBuffer::getFile(M->second);
838 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000839 return std::make_pair((llvm::MemoryBuffer*)0,
840 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000841 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000842
Douglas Gregor175c4a92010-07-23 23:58:40 +0000843 // Remove this remapping. We've captured the buffer already.
Douglas Gregor44c181a2010-07-23 00:33:23 +0000844 M = PreprocessorOpts.eraseRemappedFile(M);
845 E = PreprocessorOpts.remapped_file_end();
846 }
847 }
848 }
849
850 // Check whether there is a file-buffer remapping. It supercedes the
851 // file-file remapping.
852 for (PreprocessorOptions::remapped_file_buffer_iterator
853 M = PreprocessorOpts.remapped_file_buffer_begin(),
854 E = PreprocessorOpts.remapped_file_buffer_end();
855 M != E;
856 ++M) {
857 llvm::sys::PathWithStatus MPath(M->first);
858 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
859 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
860 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000861 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000862 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000863 CreatedBuffer = false;
864 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000865
Douglas Gregor175c4a92010-07-23 23:58:40 +0000866 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
867
868 // Remove this remapping. We've captured the buffer already.
Douglas Gregor44c181a2010-07-23 00:33:23 +0000869 M = PreprocessorOpts.eraseRemappedFile(M);
870 E = PreprocessorOpts.remapped_file_buffer_end();
871 }
872 }
Douglas Gregor175c4a92010-07-23 23:58:40 +0000873 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000874 }
875
876 // If the main source file was not remapped, load it now.
877 if (!Buffer) {
878 Buffer = llvm::MemoryBuffer::getFile(FrontendOpts.Inputs[0].second);
879 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000880 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000881
882 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000883 }
884
Douglas Gregordf95a132010-08-09 20:45:32 +0000885 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000886}
887
Douglas Gregor754f3492010-07-24 00:38:13 +0000888static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
889 bool DeleteOld,
890 unsigned NewSize,
891 llvm::StringRef NewName) {
892 llvm::MemoryBuffer *Result
893 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
894 memcpy(const_cast<char*>(Result->getBufferStart()),
895 Old->getBufferStart(), Old->getBufferSize());
896 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000897 ' ', NewSize - Old->getBufferSize() - 1);
898 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +0000899
900 if (DeleteOld)
901 delete Old;
902
903 return Result;
904}
905
Douglas Gregor175c4a92010-07-23 23:58:40 +0000906/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
907/// the source file.
908///
909/// This routine will compute the preamble of the main source file. If a
910/// non-trivial preamble is found, it will precompile that preamble into a
911/// precompiled header so that the precompiled preamble can be used to reduce
912/// reparsing time. If a precompiled preamble has already been constructed,
913/// this routine will determine if it is still valid and, if so, avoid
914/// rebuilding the precompiled preamble.
915///
Douglas Gregordf95a132010-08-09 20:45:32 +0000916/// \param AllowRebuild When true (the default), this routine is
917/// allowed to rebuild the precompiled preamble if it is found to be
918/// out-of-date.
919///
920/// \param MaxLines When non-zero, the maximum number of lines that
921/// can occur within the preamble.
922///
Douglas Gregor754f3492010-07-24 00:38:13 +0000923/// \returns If the precompiled preamble can be used, returns a newly-allocated
924/// buffer that should be used in place of the main file when doing so.
925/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +0000926llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
927 bool AllowRebuild,
928 unsigned MaxLines) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000929 CompilerInvocation PreambleInvocation(*Invocation);
930 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
931 PreprocessorOptions &PreprocessorOpts
932 = PreambleInvocation.getPreprocessorOpts();
933
934 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000935 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregordf95a132010-08-09 20:45:32 +0000936 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +0000937
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000938 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000939 // We couldn't find a preamble in the main source. Clear out the current
940 // preamble, if we have one. It's obviously no good any more.
941 Preamble.clear();
942 if (!PreambleFile.empty()) {
Douglas Gregor385103b2010-07-30 20:58:08 +0000943 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000944 PreambleFile.clear();
945 }
946 if (CreatedPreambleBuffer)
947 delete NewPreamble.first;
Douglas Gregoreababfb2010-08-04 05:53:38 +0000948
949 // The next time we actually see a preamble, precompile it.
950 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +0000951 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000952 }
953
954 if (!Preamble.empty()) {
955 // We've previously computed a preamble. Check whether we have the same
956 // preamble now that we did before, and that there's enough space in
957 // the main-file buffer within the precompiled preamble to fit the
958 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000959 if (Preamble.size() == NewPreamble.second.first &&
960 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +0000961 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor175c4a92010-07-23 23:58:40 +0000962 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000963 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000964 // The preamble has not changed. We may be able to re-use the precompiled
965 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000966
Douglas Gregorcc5888d2010-07-31 00:40:00 +0000967 // Check that none of the files used by the preamble have changed.
968 bool AnyFileChanged = false;
969
970 // First, make a record of those files that have been overridden via
971 // remapping or unsaved_files.
972 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
973 for (PreprocessorOptions::remapped_file_iterator
974 R = PreprocessorOpts.remapped_file_begin(),
975 REnd = PreprocessorOpts.remapped_file_end();
976 !AnyFileChanged && R != REnd;
977 ++R) {
978 struct stat StatBuf;
979 if (stat(R->second.c_str(), &StatBuf)) {
980 // If we can't stat the file we're remapping to, assume that something
981 // horrible happened.
982 AnyFileChanged = true;
983 break;
984 }
Douglas Gregor754f3492010-07-24 00:38:13 +0000985
Douglas Gregorcc5888d2010-07-31 00:40:00 +0000986 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
987 StatBuf.st_mtime);
988 }
989 for (PreprocessorOptions::remapped_file_buffer_iterator
990 R = PreprocessorOpts.remapped_file_buffer_begin(),
991 REnd = PreprocessorOpts.remapped_file_buffer_end();
992 !AnyFileChanged && R != REnd;
993 ++R) {
994 // FIXME: Should we actually compare the contents of file->buffer
995 // remappings?
996 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
997 0);
998 }
999
1000 // Check whether anything has changed.
1001 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1002 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1003 !AnyFileChanged && F != FEnd;
1004 ++F) {
1005 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1006 = OverriddenFiles.find(F->first());
1007 if (Overridden != OverriddenFiles.end()) {
1008 // This file was remapped; check whether the newly-mapped file
1009 // matches up with the previous mapping.
1010 if (Overridden->second != F->second)
1011 AnyFileChanged = true;
1012 continue;
1013 }
1014
1015 // The file was not remapped; check whether it has changed on disk.
1016 struct stat StatBuf;
1017 if (stat(F->first(), &StatBuf)) {
1018 // If we can't stat the file, assume that something horrible happened.
1019 AnyFileChanged = true;
1020 } else if (StatBuf.st_size != F->second.first ||
1021 StatBuf.st_mtime != F->second.second)
1022 AnyFileChanged = true;
1023 }
1024
1025 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001026 // Okay! We can re-use the precompiled preamble.
1027
1028 // Set the state of the diagnostic object to mimic its state
1029 // after parsing the preamble.
1030 getDiagnostics().Reset();
1031 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1032 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
1033 StoredDiagnostics.erase(
1034 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
1035 StoredDiagnostics.end());
1036
1037 // Create a version of the main file buffer that is padded to
1038 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001039 return CreatePaddedMainFileBuffer(NewPreamble.first,
1040 CreatedPreambleBuffer,
1041 PreambleReservedSize,
1042 FrontendOpts.Inputs[0].second);
1043 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001044 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001045
1046 // If we aren't allowed to rebuild the precompiled preamble, just
1047 // return now.
1048 if (!AllowRebuild)
1049 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001050
1051 // We can't reuse the previously-computed preamble. Build a new one.
1052 Preamble.clear();
Douglas Gregor385103b2010-07-30 20:58:08 +00001053 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001054 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001055 } else if (!AllowRebuild) {
1056 // We aren't allowed to rebuild the precompiled preamble; just
1057 // return now.
1058 return 0;
1059 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001060
1061 // If the preamble rebuild counter > 1, it's because we previously
1062 // failed to build a preamble and we're not yet ready to try
1063 // again. Decrement the counter and return a failure.
1064 if (PreambleRebuildCounter > 1) {
1065 --PreambleRebuildCounter;
1066 return 0;
1067 }
1068
Douglas Gregor175c4a92010-07-23 23:58:40 +00001069 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor385103b2010-07-30 20:58:08 +00001070 llvm::Timer *PreambleTimer = 0;
1071 if (TimerGroup.get()) {
1072 PreambleTimer = new llvm::Timer("Precompiling preamble", *TimerGroup);
1073 PreambleTimer->startTimer();
1074 Timers.push_back(PreambleTimer);
1075 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001076
1077 // Create a new buffer that stores the preamble. The buffer also contains
1078 // extra space for the original contents of the file (which will be present
1079 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001080 // grows.
1081 PreambleReservedSize = NewPreamble.first->getBufferSize();
1082 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001083 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001084 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001085 PreambleReservedSize *= 2;
1086
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001087 // Save the preamble text for later; we'll need to compare against it for
1088 // subsequent reparses.
1089 Preamble.assign(NewPreamble.first->getBufferStart(),
1090 NewPreamble.first->getBufferStart()
1091 + NewPreamble.second.first);
1092 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1093
Douglas Gregor44c181a2010-07-23 00:33:23 +00001094 llvm::MemoryBuffer *PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001095 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001096 FrontendOpts.Inputs[0].second);
1097 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001098 NewPreamble.first->getBufferStart(), Preamble.size());
1099 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001100 ' ', PreambleReservedSize - Preamble.size() - 1);
1101 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001102
1103 // Remap the main source file to the preamble buffer.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001104 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001105 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1106
1107 // Tell the compiler invocation to generate a temporary precompiled header.
1108 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Sebastian Redlf65339e2010-08-06 00:35:11 +00001109 // FIXME: Set ChainedPCH unconditionally, once it is ready.
1110 if (::getenv("LIBCLANG_CHAINING"))
1111 FrontendOpts.ChainedPCH = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001112 // FIXME: Generate the precompiled header into memory?
Douglas Gregor385103b2010-07-30 20:58:08 +00001113 FrontendOpts.OutputFile = GetPreamblePCHPath();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001114
1115 // Create the compiler instance to use for building the precompiled preamble.
1116 CompilerInstance Clang;
1117 Clang.setInvocation(&PreambleInvocation);
1118 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1119
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001120 // Set up diagnostics, capturing all of the diagnostics produced.
Douglas Gregor44c181a2010-07-23 00:33:23 +00001121 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001122 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
1123 getDiagnostics(),
1124 StoredDiagnostics);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001125
1126 // Create the target instance.
1127 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1128 Clang.getTargetOpts()));
1129 if (!Clang.hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001130 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1131 Preamble.clear();
1132 if (CreatedPreambleBuffer)
1133 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +00001134 if (PreambleTimer)
1135 PreambleTimer->stopTimer();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001136 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor754f3492010-07-24 00:38:13 +00001137 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001138 }
1139
1140 // Inform the target of the language options.
1141 //
1142 // FIXME: We shouldn't need to do this, the target should be immutable once
1143 // created. This complexity should be lifted elsewhere.
1144 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1145
1146 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1147 "Invocation must have exactly one source file!");
1148 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1149 "FIXME: AST inputs not yet supported here!");
1150 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1151 "IR inputs not support here!");
1152
1153 // Clear out old caches and data.
1154 StoredDiagnostics.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001155 TopLevelDecls.clear();
1156 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001157
1158 // Create a file manager object to provide access to and cache the filesystem.
1159 Clang.setFileManager(new FileManager);
1160
1161 // Create the source manager.
1162 Clang.setSourceManager(new SourceManager(getDiagnostics()));
1163
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001164 llvm::OwningPtr<PrecompilePreambleAction> Act;
1165 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001166 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1167 Clang.getFrontendOpts().Inputs[0].first)) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001168 Clang.takeInvocation();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001169 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1170 Preamble.clear();
1171 if (CreatedPreambleBuffer)
1172 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +00001173 if (PreambleTimer)
1174 PreambleTimer->stopTimer();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001175 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor385103b2010-07-30 20:58:08 +00001176
Douglas Gregor754f3492010-07-24 00:38:13 +00001177 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001178 }
1179
1180 Act->Execute();
1181 Act->EndSourceFile();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001182 Clang.takeInvocation();
1183
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001184 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001185 // There were errors parsing the preamble, so no precompiled header was
1186 // generated. Forget that we even tried.
1187 // FIXME: Should we leave a note for ourselves to try again?
1188 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1189 Preamble.clear();
1190 if (CreatedPreambleBuffer)
1191 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +00001192 if (PreambleTimer)
1193 PreambleTimer->stopTimer();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001194 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001195 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor754f3492010-07-24 00:38:13 +00001196 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001197 }
1198
1199 // Keep track of the preamble we precompiled.
1200 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001201 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1202 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001203
1204 // Keep track of all of the files that the source manager knows about,
1205 // so we can verify whether they have changed or not.
1206 FilesInPreamble.clear();
1207 SourceManager &SourceMgr = Clang.getSourceManager();
1208 const llvm::MemoryBuffer *MainFileBuffer
1209 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1210 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1211 FEnd = SourceMgr.fileinfo_end();
1212 F != FEnd;
1213 ++F) {
1214 const FileEntry *File = F->second->Entry;
1215 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1216 continue;
1217
1218 FilesInPreamble[File->getName()]
1219 = std::make_pair(F->second->getSize(), File->getModificationTime());
1220 }
1221
Douglas Gregor385103b2010-07-30 20:58:08 +00001222 if (PreambleTimer)
1223 PreambleTimer->stopTimer();
1224
Douglas Gregoreababfb2010-08-04 05:53:38 +00001225 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001226 return CreatePaddedMainFileBuffer(NewPreamble.first,
1227 CreatedPreambleBuffer,
1228 PreambleReservedSize,
1229 FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001230}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001231
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001232void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1233 std::vector<Decl *> Resolved;
1234 Resolved.reserve(TopLevelDeclsInPreamble.size());
1235 ExternalASTSource &Source = *getASTContext().getExternalSource();
1236 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1237 // Resolve the declaration ID to an actual declaration, possibly
1238 // deserializing the declaration in the process.
1239 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1240 if (D)
1241 Resolved.push_back(D);
1242 }
1243 TopLevelDeclsInPreamble.clear();
1244 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1245}
1246
1247unsigned ASTUnit::getMaxPCHLevel() const {
1248 if (!getOnlyLocalDecls())
1249 return Decl::MaxPCHLevel;
1250
1251 unsigned Result = 0;
1252 if (isMainFileAST() || SavedMainFileBuffer)
1253 ++Result;
1254 return Result;
1255}
1256
Douglas Gregorabc563f2010-07-19 21:46:24 +00001257ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1258 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1259 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001260 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001261 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001262 bool CompleteTranslationUnit,
1263 bool CacheCodeCompletionResults) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001264 if (!Diags.getPtr()) {
1265 // No diagnostics engine was provided, so create our own diagnostics object
1266 // with the default options.
1267 DiagnosticOptions DiagOpts;
1268 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
1269 }
1270
1271 // Create the AST unit.
1272 llvm::OwningPtr<ASTUnit> AST;
1273 AST.reset(new ASTUnit(false));
1274 AST->Diagnostics = Diags;
1275 AST->CaptureDiagnostics = CaptureDiagnostics;
1276 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregordf95a132010-08-09 20:45:32 +00001277 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001278 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001279 AST->Invocation.reset(CI);
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001280 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001281
Douglas Gregor385103b2010-07-30 20:58:08 +00001282 if (getenv("LIBCLANG_TIMING"))
1283 AST->TimerGroup.reset(
1284 new llvm::TimerGroup(CI->getFrontendOpts().Inputs[0].second));
1285
1286
Douglas Gregor754f3492010-07-24 00:38:13 +00001287 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorfd0b8702010-07-28 22:12:37 +00001288 // FIXME: When C++ PCH is ready, allow use of it for a precompiled preamble.
Douglas Gregoreababfb2010-08-04 05:53:38 +00001289 if (PrecompilePreamble && !CI->getLangOpts().CPlusPlus) {
1290 AST->PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001291 OverrideMainBuffer = AST->getMainBufferWithPrecompiledPreamble();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001292 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001293
Douglas Gregor385103b2010-07-30 20:58:08 +00001294 llvm::Timer *ParsingTimer = 0;
1295 if (AST->TimerGroup.get()) {
1296 ParsingTimer = new llvm::Timer("Initial parse", *AST->TimerGroup);
1297 ParsingTimer->startTimer();
1298 AST->Timers.push_back(ParsingTimer);
1299 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001300
Douglas Gregor385103b2010-07-30 20:58:08 +00001301 bool Failed = AST->Parse(OverrideMainBuffer);
1302 if (ParsingTimer)
1303 ParsingTimer->stopTimer();
1304
1305 return Failed? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001306}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001307
1308ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1309 const char **ArgEnd,
Douglas Gregor28019772010-04-05 23:52:57 +00001310 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001311 llvm::StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001312 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001313 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001314 unsigned NumRemappedFiles,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001315 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001316 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001317 bool CompleteTranslationUnit,
1318 bool CacheCodeCompletionResults) {
Douglas Gregorbdbb0042010-08-18 22:29:43 +00001319 bool CreatedDiagnosticsObject = false;
1320
Douglas Gregor28019772010-04-05 23:52:57 +00001321 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001322 // No diagnostics engine was provided, so create our own diagnostics object
1323 // with the default options.
1324 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001325 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00001326 CreatedDiagnosticsObject = true;
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001327 }
1328
Daniel Dunbar7b556682009-12-02 03:23:45 +00001329 llvm::SmallVector<const char *, 16> Args;
1330 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1331 Args.insert(Args.end(), ArgBegin, ArgEnd);
1332
1333 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1334 // also want to force it to use clang.
1335 Args.push_back("-fsyntax-only");
1336
Daniel Dunbar869824e2009-12-13 03:46:13 +00001337 // FIXME: We shouldn't have to pass in the path info.
Daniel Dunbar0bbad512010-07-19 00:44:04 +00001338 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001339 "a.out", false, false, *Diags);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001340
1341 // Don't check that inputs exist, they have been remapped.
1342 TheDriver.setCheckInputsExist(false);
1343
Daniel Dunbar7b556682009-12-02 03:23:45 +00001344 llvm::OwningPtr<driver::Compilation> C(
1345 TheDriver.BuildCompilation(Args.size(), Args.data()));
1346
1347 // We expect to get back exactly one command job, if we didn't something
1348 // failed.
1349 const driver::JobList &Jobs = C->getJobs();
1350 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1351 llvm::SmallString<256> Msg;
1352 llvm::raw_svector_ostream OS(Msg);
1353 C->PrintJob(OS, C->getJobs(), "; ", true);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001354 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001355 return 0;
1356 }
1357
1358 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1359 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001360 Diags->Report(diag::err_fe_expected_clang_command);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001361 return 0;
1362 }
1363
1364 const driver::ArgStringList &CCArgs = Cmd->getArguments();
Daniel Dunbar807b0612010-01-30 21:47:16 +00001365 llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
Dan Gohmancb421fa2010-04-19 16:39:44 +00001366 CompilerInvocation::CreateFromArgs(*CI,
1367 const_cast<const char **>(CCArgs.data()),
1368 const_cast<const char **>(CCArgs.data()) +
Douglas Gregor44c181a2010-07-23 00:33:23 +00001369 CCArgs.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001370 *Diags);
Daniel Dunbar1e69fe32009-12-13 03:45:58 +00001371
Douglas Gregor4db64a42010-01-23 00:14:00 +00001372 // Override any files that need remapping
1373 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar807b0612010-01-30 21:47:16 +00001374 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbarb26d4832010-02-16 01:55:04 +00001375 RemappedFiles[I].second);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001376
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001377 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001378 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001379
Douglas Gregorf4210892010-08-18 23:38:21 +00001380 CI->getFrontendOpts().DisableFree = false;
Douglas Gregora88084b2010-02-18 18:08:43 +00001381 return LoadFromCompilerInvocation(CI.take(), Diags, OnlyLocalDecls,
Douglas Gregordf95a132010-08-09 20:45:32 +00001382 CaptureDiagnostics, PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001383 CompleteTranslationUnit,
1384 CacheCodeCompletionResults);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001385}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001386
1387bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1388 if (!Invocation.get())
1389 return true;
1390
Douglas Gregor385103b2010-07-30 20:58:08 +00001391 llvm::Timer *ReparsingTimer = 0;
1392 if (TimerGroup.get()) {
1393 ReparsingTimer = new llvm::Timer("Reparse", *TimerGroup);
1394 ReparsingTimer->startTimer();
1395 Timers.push_back(ReparsingTimer);
1396 }
1397
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001398 // Remap files.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001399 Invocation->getPreprocessorOpts().clearRemappedFiles();
1400 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1401 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1402 RemappedFiles[I].second);
1403
Douglas Gregoreababfb2010-08-04 05:53:38 +00001404 // If we have a preamble file lying around, or if we might try to
1405 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00001406 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregoreababfb2010-08-04 05:53:38 +00001407 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregordf95a132010-08-09 20:45:32 +00001408 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001409
Douglas Gregorabc563f2010-07-19 21:46:24 +00001410 // Clear out the diagnostics state.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001411 if (!OverrideMainBuffer)
1412 getDiagnostics().Reset();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001413
Douglas Gregor175c4a92010-07-23 23:58:40 +00001414 // Parse the sources
Douglas Gregor754f3492010-07-24 00:38:13 +00001415 bool Result = Parse(OverrideMainBuffer);
Douglas Gregor385103b2010-07-30 20:58:08 +00001416 if (ReparsingTimer)
1417 ReparsingTimer->stopTimer();
Douglas Gregor727d93e2010-08-17 00:40:40 +00001418
1419 if (ShouldCacheCodeCompletionResults) {
1420 if (CacheCodeCompletionCoolDown > 0)
1421 --CacheCodeCompletionCoolDown;
1422 else if (top_level_size() != NumTopLevelDeclsAtLastCompletionCache)
1423 CacheCodeCompletionResults();
1424 }
1425
Douglas Gregor175c4a92010-07-23 23:58:40 +00001426 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001427}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001428
Douglas Gregor87c08a52010-08-13 22:48:40 +00001429//----------------------------------------------------------------------------//
1430// Code completion
1431//----------------------------------------------------------------------------//
1432
1433namespace {
1434 /// \brief Code completion consumer that combines the cached code-completion
1435 /// results from an ASTUnit with the code-completion results provided to it,
1436 /// then passes the result on to
1437 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1438 unsigned NormalContexts;
1439 ASTUnit &AST;
1440 CodeCompleteConsumer &Next;
1441
1442 public:
1443 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor8071e422010-08-15 06:18:01 +00001444 bool IncludeMacros, bool IncludeCodePatterns,
1445 bool IncludeGlobals)
1446 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001447 Next.isOutputBinary()), AST(AST), Next(Next)
1448 {
1449 // Compute the set of contexts in which we will look when we don't have
1450 // any information about the specific context.
1451 NormalContexts
1452 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
1453 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
1454 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1455 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1456 | (1 << (CodeCompletionContext::CCC_Statement - 1))
1457 | (1 << (CodeCompletionContext::CCC_Expression - 1))
1458 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1459 | (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
1460 | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
1461
1462 if (AST.getASTContext().getLangOptions().CPlusPlus)
1463 NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1))
1464 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
1465 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
1466 }
1467
1468 virtual void ProcessCodeCompleteResults(Sema &S,
1469 CodeCompletionContext Context,
1470 Result *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001471 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001472
1473 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1474 OverloadCandidate *Candidates,
1475 unsigned NumCandidates) {
1476 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1477 }
1478 };
1479}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001480
Douglas Gregor5f808c22010-08-16 21:18:39 +00001481/// \brief Helper function that computes which global names are hidden by the
1482/// local code-completion results.
1483void CalculateHiddenNames(const CodeCompletionContext &Context,
1484 CodeCompleteConsumer::Result *Results,
1485 unsigned NumResults,
1486 ASTContext &Ctx,
1487 llvm::StringSet<> &HiddenNames) {
1488 bool OnlyTagNames = false;
1489 switch (Context.getKind()) {
1490 case CodeCompletionContext::CCC_Other:
1491 case CodeCompletionContext::CCC_TopLevel:
1492 case CodeCompletionContext::CCC_ObjCInterface:
1493 case CodeCompletionContext::CCC_ObjCImplementation:
1494 case CodeCompletionContext::CCC_ObjCIvarList:
1495 case CodeCompletionContext::CCC_ClassStructUnion:
1496 case CodeCompletionContext::CCC_Statement:
1497 case CodeCompletionContext::CCC_Expression:
1498 case CodeCompletionContext::CCC_ObjCMessageReceiver:
1499 case CodeCompletionContext::CCC_MemberAccess:
1500 case CodeCompletionContext::CCC_Namespace:
1501 case CodeCompletionContext::CCC_Type:
1502 break;
1503
1504 case CodeCompletionContext::CCC_EnumTag:
1505 case CodeCompletionContext::CCC_UnionTag:
1506 case CodeCompletionContext::CCC_ClassOrStructTag:
1507 OnlyTagNames = true;
1508 break;
1509
1510 case CodeCompletionContext::CCC_ObjCProtocolName:
1511 // If we're just looking for protocol names, nothing can hide them.
1512 return;
1513 }
1514
1515 typedef CodeCompleteConsumer::Result Result;
1516 for (unsigned I = 0; I != NumResults; ++I) {
1517 if (Results[I].Kind != Result::RK_Declaration)
1518 continue;
1519
1520 unsigned IDNS
1521 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1522
1523 bool Hiding = false;
1524 if (OnlyTagNames)
1525 Hiding = (IDNS & Decl::IDNS_Tag);
1526 else {
1527 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00001528 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1529 Decl::IDNS_NonMemberOperator);
Douglas Gregor5f808c22010-08-16 21:18:39 +00001530 if (Ctx.getLangOptions().CPlusPlus)
1531 HiddenIDNS |= Decl::IDNS_Tag;
1532 Hiding = (IDNS & HiddenIDNS);
1533 }
1534
1535 if (!Hiding)
1536 continue;
1537
1538 DeclarationName Name = Results[I].Declaration->getDeclName();
1539 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1540 HiddenNames.insert(Identifier->getName());
1541 else
1542 HiddenNames.insert(Name.getAsString());
1543 }
1544}
1545
1546
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001547void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1548 CodeCompletionContext Context,
1549 Result *Results,
1550 unsigned NumResults) {
1551 // Merge the results we were given with the results we cached.
1552 bool AddedResult = false;
Douglas Gregor5f808c22010-08-16 21:18:39 +00001553 unsigned InContexts
1554 = (Context.getKind() == CodeCompletionContext::CCC_Other? NormalContexts
1555 : (1 << (Context.getKind() - 1)));
1556
1557 // Contains the set of names that are hidden by "local" completion results.
1558 llvm::StringSet<> HiddenNames;
1559
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001560 typedef CodeCompleteConsumer::Result Result;
1561 llvm::SmallVector<Result, 8> AllResults;
1562 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00001563 C = AST.cached_completion_begin(),
1564 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001565 C != CEnd; ++C) {
1566 // If the context we are in matches any of the contexts we are
1567 // interested in, we'll add this result.
1568 if ((C->ShowInContexts & InContexts) == 0)
1569 continue;
1570
1571 // If we haven't added any results previously, do so now.
1572 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00001573 CalculateHiddenNames(Context, Results, NumResults, S.Context,
1574 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001575 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1576 AddedResult = true;
1577 }
1578
Douglas Gregor5f808c22010-08-16 21:18:39 +00001579 // Determine whether this global completion result is hidden by a local
1580 // completion result. If so, skip it.
1581 if (C->Kind != CXCursor_MacroDefinition &&
1582 HiddenNames.count(C->Completion->getTypedText()))
1583 continue;
1584
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001585 // Adjust priority based on similar type classes.
1586 unsigned Priority = C->Priority;
1587 if (!Context.getPreferredType().isNull()) {
1588 if (C->Kind == CXCursor_MacroDefinition) {
1589 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
1590 Context.getPreferredType()->isAnyPointerType());
1591 } else if (C->Type) {
1592 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00001593 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001594 Context.getPreferredType().getUnqualifiedType());
1595 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
1596 if (ExpectedSTC == C->TypeClass) {
1597 // We know this type is similar; check for an exact match.
1598 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00001599 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001600 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00001601 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001602 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
1603 Priority /= CCF_ExactTypeMatch;
1604 else
1605 Priority /= CCF_SimilarTypeMatch;
1606 }
1607 }
1608 }
1609
1610 AllResults.push_back(Result(C->Completion, Priority, C->Kind));
1611 }
1612
1613 // If we did not add any cached completion results, just forward the
1614 // results we were given to the next consumer.
1615 if (!AddedResult) {
1616 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
1617 return;
1618 }
1619
1620 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
1621 AllResults.size());
1622}
1623
1624
1625
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001626void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
1627 RemappedFile *RemappedFiles,
1628 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00001629 bool IncludeMacros,
1630 bool IncludeCodePatterns,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001631 CodeCompleteConsumer &Consumer,
1632 Diagnostic &Diag, LangOptions &LangOpts,
1633 SourceManager &SourceMgr, FileManager &FileMgr,
1634 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics) {
1635 if (!Invocation.get())
1636 return;
1637
Douglas Gregordf95a132010-08-09 20:45:32 +00001638 llvm::Timer *CompletionTimer = 0;
1639 if (TimerGroup.get()) {
1640 llvm::SmallString<128> TimerName;
1641 llvm::raw_svector_ostream TimerNameOut(TimerName);
1642 TimerNameOut << "Code completion @ " << File << ":" << Line << ":"
1643 << Column;
1644 CompletionTimer = new llvm::Timer(TimerNameOut.str(), *TimerGroup);
1645 CompletionTimer->startTimer();
1646 Timers.push_back(CompletionTimer);
1647 }
1648
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001649 CompilerInvocation CCInvocation(*Invocation);
1650 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
1651 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001652
Douglas Gregor87c08a52010-08-13 22:48:40 +00001653 FrontendOpts.ShowMacrosInCodeCompletion
1654 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001655 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor8071e422010-08-15 06:18:01 +00001656 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
1657 = CachedCompletionResults.empty();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001658 FrontendOpts.CodeCompletionAt.FileName = File;
1659 FrontendOpts.CodeCompletionAt.Line = Line;
1660 FrontendOpts.CodeCompletionAt.Column = Column;
1661
Douglas Gregorcee235c2010-08-05 09:09:23 +00001662 // Turn on spell-checking when performing code completion. It leads
1663 // to better results.
1664 unsigned SpellChecking = CCInvocation.getLangOpts().SpellChecking;
1665 CCInvocation.getLangOpts().SpellChecking = 1;
1666
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001667 // Set the language options appropriately.
1668 LangOpts = CCInvocation.getLangOpts();
1669
1670 CompilerInstance Clang;
1671 Clang.setInvocation(&CCInvocation);
1672 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1673
1674 // Set up diagnostics, capturing any diagnostics produced.
1675 Clang.setDiagnostics(&Diag);
1676 CaptureDroppedDiagnostics Capture(true,
1677 Clang.getDiagnostics(),
1678 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001679
1680 // Create the target instance.
1681 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1682 Clang.getTargetOpts()));
1683 if (!Clang.hasTarget()) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001684 Clang.takeInvocation();
Douglas Gregorbdbb0042010-08-18 22:29:43 +00001685 CCInvocation.getLangOpts().SpellChecking = SpellChecking;
1686 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001687 }
1688
1689 // Inform the target of the language options.
1690 //
1691 // FIXME: We shouldn't need to do this, the target should be immutable once
1692 // created. This complexity should be lifted elsewhere.
1693 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1694
1695 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1696 "Invocation must have exactly one source file!");
1697 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1698 "FIXME: AST inputs not yet supported here!");
1699 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1700 "IR inputs not support here!");
1701
1702
1703 // Use the source and file managers that we were given.
1704 Clang.setFileManager(&FileMgr);
1705 Clang.setSourceManager(&SourceMgr);
1706
1707 // Remap files.
1708 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00001709 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001710 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1711 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
1712 RemappedFiles[I].second);
1713
Douglas Gregor87c08a52010-08-13 22:48:40 +00001714 // Use the code completion consumer we were given, but adding any cached
1715 // code-completion results.
1716 AugmentedCodeCompleteConsumer
1717 AugmentedConsumer(*this, Consumer, FrontendOpts.ShowMacrosInCodeCompletion,
Douglas Gregor8071e422010-08-15 06:18:01 +00001718 FrontendOpts.ShowCodePatternsInCodeCompletion,
1719 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001720 Clang.setCodeCompletionConsumer(&AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001721
Douglas Gregordf95a132010-08-09 20:45:32 +00001722 // If we have a precompiled preamble, try to use it. We only allow
1723 // the use of the precompiled preamble if we're if the completion
1724 // point is within the main file, after the end of the precompiled
1725 // preamble.
1726 llvm::MemoryBuffer *OverrideMainBuffer = 0;
1727 if (!PreambleFile.empty()) {
1728 using llvm::sys::FileStatus;
1729 llvm::sys::PathWithStatus CompleteFilePath(File);
1730 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
1731 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
1732 if (const FileStatus *MainStatus = MainPath.getFileStatus())
1733 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
1734 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(false,
1735 Line);
1736 }
1737
1738 // If the main file has been overridden due to the use of a preamble,
1739 // make that override happen and introduce the preamble.
1740 if (OverrideMainBuffer) {
1741 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1742 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1743 PreprocessorOpts.PrecompiledPreambleBytes.second
1744 = PreambleEndsAtStartOfLine;
1745 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
1746 PreprocessorOpts.DisablePCHValidation = true;
1747
1748 // The stored diagnostics have the old source manager. Copy them
1749 // to our output set of stored diagnostics, updating the source
1750 // manager to the one we were given.
1751 for (unsigned I = 0, N = this->StoredDiagnostics.size(); I != N; ++I) {
1752 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
1753 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
1754 StoredDiagnostics[I].setLocation(Loc);
1755 }
1756 }
1757
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001758 llvm::OwningPtr<SyntaxOnlyAction> Act;
1759 Act.reset(new SyntaxOnlyAction);
1760 if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1761 Clang.getFrontendOpts().Inputs[0].first)) {
1762 Act->Execute();
1763 Act->EndSourceFile();
1764 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001765
1766 if (CompletionTimer)
1767 CompletionTimer->stopTimer();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001768
1769 // Steal back our resources.
Douglas Gregordf95a132010-08-09 20:45:32 +00001770 delete OverrideMainBuffer;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001771 Clang.takeFileManager();
1772 Clang.takeSourceManager();
1773 Clang.takeInvocation();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001774 Clang.takeCodeCompletionConsumer();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001775 CCInvocation.getLangOpts().SpellChecking = SpellChecking;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001776}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001777
1778bool ASTUnit::Save(llvm::StringRef File) {
1779 if (getDiagnostics().hasErrorOccurred())
1780 return true;
1781
1782 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
1783 // unconditionally create a stat cache when we parse the file?
1784 std::string ErrorInfo;
Benjamin Kramer1395c5d2010-08-15 16:54:31 +00001785 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo,
1786 llvm::raw_fd_ostream::F_Binary);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001787 if (!ErrorInfo.empty() || Out.has_error())
1788 return true;
1789
1790 std::vector<unsigned char> Buffer;
1791 llvm::BitstreamWriter Stream(Buffer);
1792 PCHWriter Writer(Stream);
1793 Writer.WritePCH(getSema(), 0, 0);
1794
1795 // Write the generated bitstream to "Out".
Douglas Gregorbdbb0042010-08-18 22:29:43 +00001796 if (!Buffer.empty())
1797 Out.write((char *)&Buffer.front(), Buffer.size());
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001798 Out.close();
1799 return Out.has_error();
1800}