blob: 41c5dbc46060e6c16c57c28a04b300b66189257d [file] [log] [blame]
Argyrios Kyrtzidis3a08ec12009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Douglas Gregor48c8cd32010-08-03 08:14:03 +000015#include "clang/Frontend/PCHWriter.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000016#include "clang/AST/ASTContext.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000017#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000018#include "clang/AST/DeclVisitor.h"
Douglas Gregorb61c07a2010-08-16 18:08:11 +000019#include "clang/AST/TypeOrdering.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000020#include "clang/AST/StmtVisitor.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000021#include "clang/Driver/Compilation.h"
22#include "clang/Driver/Driver.h"
23#include "clang/Driver/Job.h"
24#include "clang/Driver/Tool.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000025#include "clang/Frontend/CompilerInstance.h"
26#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000027#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000028#include "clang/Frontend/FrontendOptions.h"
Douglas Gregor48c8cd32010-08-03 08:14:03 +000029#include "clang/Frontend/PCHReader.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000030#include "clang/Lex/HeaderSearch.h"
31#include "clang/Lex/Preprocessor.h"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000032#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000033#include "clang/Basic/TargetInfo.h"
34#include "clang/Basic/Diagnostic.h"
Douglas Gregoraa98ed92010-01-23 00:14:00 +000035#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000036#include "llvm/System/Host.h"
Benjamin Kramer6c839f82009-10-18 11:34:14 +000037#include "llvm/System/Path.h"
Douglas Gregor028d3e42010-08-09 20:45:32 +000038#include "llvm/Support/raw_ostream.h"
Douglas Gregor15ba0b32010-07-30 20:58:08 +000039#include "llvm/Support/Timer.h"
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000040#include <cstdlib>
Zhongxing Xu318e4032010-07-23 02:15:08 +000041#include <cstdio>
Douglas Gregor0e119552010-07-31 00:40:00 +000042#include <sys/stat.h>
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000043using namespace clang;
44
Douglas Gregorbb420ab2010-08-04 05:53:38 +000045/// \brief After failing to build a precompiled preamble (due to
46/// errors in the source that occurs in the preamble), the number of
47/// reparses during which we'll skip even trying to precompile the
48/// preamble.
49const unsigned DefaultPreambleRebuildInterval = 5;
50
Douglas Gregord03e8232010-04-05 21:10:19 +000051ASTUnit::ASTUnit(bool _MainFileIsAST)
Douglas Gregoraa21cc42010-07-19 21:46:24 +000052 : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
Douglas Gregor028d3e42010-08-09 20:45:32 +000053 CompleteTranslationUnit(true), ConcurrencyCheckValue(CheckUnlocked),
Douglas Gregorb14904c2010-08-13 22:48:40 +000054 PreambleRebuildCounter(0), SavedMainFileBuffer(0),
55 ShouldCacheCodeCompletionResults(false) {
Douglas Gregor15ba0b32010-07-30 20:58:08 +000056}
Douglas Gregord03e8232010-04-05 21:10:19 +000057
Daniel Dunbar764c0822009-12-01 09:51:01 +000058ASTUnit::~ASTUnit() {
Douglas Gregor0c7c2f82010-03-05 21:16:25 +000059 ConcurrencyCheckValue = CheckLocked;
Douglas Gregoraa21cc42010-07-19 21:46:24 +000060 CleanTemporaryFiles();
Douglas Gregor4dde7492010-07-23 23:58:40 +000061 if (!PreambleFile.empty())
Douglas Gregor15ba0b32010-07-30 20:58:08 +000062 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor3f4bea02010-07-26 21:36:20 +000063
64 // Free the buffers associated with remapped files. We are required to
65 // perform this operation here because we explicitly request that the
66 // compiler instance *not* free these buffers for each invocation of the
67 // parser.
68 if (Invocation.get()) {
69 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
70 for (PreprocessorOptions::remapped_file_buffer_iterator
71 FB = PPOpts.remapped_file_buffer_begin(),
72 FBEnd = PPOpts.remapped_file_buffer_end();
73 FB != FBEnd;
74 ++FB)
75 delete FB->second;
76 }
Douglas Gregor96c04262010-07-27 14:52:07 +000077
78 delete SavedMainFileBuffer;
Douglas Gregor15ba0b32010-07-30 20:58:08 +000079
Douglas Gregorb14904c2010-08-13 22:48:40 +000080 ClearCachedCompletionResults();
81
Douglas Gregor15ba0b32010-07-30 20:58:08 +000082 for (unsigned I = 0, N = Timers.size(); I != N; ++I)
83 delete Timers[I];
Douglas Gregoraa21cc42010-07-19 21:46:24 +000084}
85
86void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor6cb5ba42010-02-18 23:35:40 +000087 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
88 TemporaryFiles[I].eraseFromDisk();
Douglas Gregoraa21cc42010-07-19 21:46:24 +000089 TemporaryFiles.clear();
Steve Naroff44cd60e2009-10-15 22:23:48 +000090}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000091
Douglas Gregor39982192010-08-15 06:18:01 +000092/// \brief Determine the set of code-completion contexts in which this
93/// declaration should be shown.
94static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +000095 const LangOptions &LangOpts,
96 bool &IsNestedNameSpecifier) {
97 IsNestedNameSpecifier = false;
98
Douglas Gregor39982192010-08-15 06:18:01 +000099 if (isa<UsingShadowDecl>(ND))
100 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
101 if (!ND)
102 return 0;
103
104 unsigned Contexts = 0;
105 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
106 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
107 // Types can appear in these contexts.
108 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
109 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
110 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
111 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
112 | (1 << (CodeCompletionContext::CCC_Statement - 1))
113 | (1 << (CodeCompletionContext::CCC_Type - 1));
114
115 // In C++, types can appear in expressions contexts (for functional casts).
116 if (LangOpts.CPlusPlus)
117 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
118
119 // In Objective-C, message sends can send interfaces. In Objective-C++,
120 // all types are available due to functional casts.
121 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
122 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
123
124 // Deal with tag names.
125 if (isa<EnumDecl>(ND)) {
126 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
127
Douglas Gregor59cab552010-08-16 23:05:20 +0000128 // Part of the nested-name-specifier in C++0x.
Douglas Gregor39982192010-08-15 06:18:01 +0000129 if (LangOpts.CPlusPlus0x)
Douglas Gregor59cab552010-08-16 23:05:20 +0000130 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000131 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
132 if (Record->isUnion())
133 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
134 else
135 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
136
Douglas Gregor39982192010-08-15 06:18:01 +0000137 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000138 IsNestedNameSpecifier = true;
139 } else if (isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND))
140 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000141 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
142 // Values can appear in these contexts.
143 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
144 | (1 << (CodeCompletionContext::CCC_Expression - 1))
145 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
146 } else if (isa<ObjCProtocolDecl>(ND)) {
147 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
148 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregor59cab552010-08-16 23:05:20 +0000149 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000150
151 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000152 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000153 }
154
155 return Contexts;
156}
157
Douglas Gregorb14904c2010-08-13 22:48:40 +0000158void ASTUnit::CacheCodeCompletionResults() {
159 if (!TheSema)
160 return;
161
162 llvm::Timer *CachingTimer = 0;
163 if (TimerGroup.get()) {
164 CachingTimer = new llvm::Timer("Cache global code completions",
165 *TimerGroup);
166 CachingTimer->startTimer();
167 Timers.push_back(CachingTimer);
168 }
169
170 // Clear out the previous results.
171 ClearCachedCompletionResults();
172
173 // Gather the set of global code completions.
174 typedef CodeCompleteConsumer::Result Result;
175 llvm::SmallVector<Result, 8> Results;
176 TheSema->GatherGlobalCodeCompletions(Results);
177
178 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000179 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
180
Douglas Gregorb14904c2010-08-13 22:48:40 +0000181 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
182 switch (Results[I].Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000183 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000184 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000185 CachedCodeCompletionResult CachedResult;
186 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
187 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregor59cab552010-08-16 23:05:20 +0000188 Ctx->getLangOptions(),
189 IsNestedNameSpecifier);
Douglas Gregor39982192010-08-15 06:18:01 +0000190 CachedResult.Priority = Results[I].Priority;
191 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor24747402010-08-16 16:46:30 +0000192
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000193 // Keep track of the type of this completion in an ASTContext-agnostic
194 // way.
Douglas Gregor24747402010-08-16 16:46:30 +0000195 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000196 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000197 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000198 CachedResult.Type = 0;
199 } else {
200 CanQualType CanUsageType
201 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
202 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
203
204 // Determine whether we have already seen this type. If so, we save
205 // ourselves the work of formatting the type string by using the
206 // temporary, CanQualType-based hash table to find the associated value.
207 unsigned &TypeValue = CompletionTypes[CanUsageType];
208 if (TypeValue == 0) {
209 TypeValue = CompletionTypes.size();
210 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
211 = TypeValue;
212 }
213
214 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000215 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000216
Douglas Gregor39982192010-08-15 06:18:01 +0000217 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000218
219 /// Handle nested-name-specifiers in C++.
220 if (TheSema->Context.getLangOptions().CPlusPlus &&
221 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
222 // The contexts in which a nested-name-specifier can appear in C++.
223 unsigned NNSContexts
224 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
225 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
226 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
227 | (1 << (CodeCompletionContext::CCC_Statement - 1))
228 | (1 << (CodeCompletionContext::CCC_Expression - 1))
229 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
230 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
231 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
232 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
233 | (1 << (CodeCompletionContext::CCC_Type - 1));
234
235 if (isa<NamespaceDecl>(Results[I].Declaration) ||
236 isa<NamespaceAliasDecl>(Results[I].Declaration))
237 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
238
239 if (unsigned RemainingContexts
240 = NNSContexts & ~CachedResult.ShowInContexts) {
241 // If there any contexts where this completion can be a
242 // nested-name-specifier but isn't already an option, create a
243 // nested-name-specifier completion.
244 Results[I].StartsNestedNameSpecifier = true;
245 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
246 CachedResult.ShowInContexts = RemainingContexts;
247 CachedResult.Priority = CCP_NestedNameSpecifier;
248 CachedResult.TypeClass = STC_Void;
249 CachedResult.Type = 0;
250 CachedCompletionResults.push_back(CachedResult);
251 }
252 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000253 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000254 }
255
Douglas Gregorb14904c2010-08-13 22:48:40 +0000256 case Result::RK_Keyword:
257 case Result::RK_Pattern:
258 // Ignore keywords and patterns; we don't care, since they are so
259 // easily regenerated.
260 break;
261
262 case Result::RK_Macro: {
263 CachedCodeCompletionResult CachedResult;
264 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
265 CachedResult.ShowInContexts
266 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
267 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
268 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
269 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
270 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
271 | (1 << (CodeCompletionContext::CCC_Statement - 1))
272 | (1 << (CodeCompletionContext::CCC_Expression - 1))
273 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
274 CachedResult.Priority = Results[I].Priority;
275 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor6e240332010-08-16 16:18:59 +0000276 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000277 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000278 CachedCompletionResults.push_back(CachedResult);
279 break;
280 }
281 }
282 Results[I].Destroy();
283 }
284
285 if (CachingTimer)
286 CachingTimer->stopTimer();
287}
288
289void ASTUnit::ClearCachedCompletionResults() {
290 for (unsigned I = 0, N = CachedCompletionResults.size(); I != N; ++I)
291 delete CachedCompletionResults[I].Completion;
292 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000293 CachedCompletionTypes.clear();
Douglas Gregorb14904c2010-08-13 22:48:40 +0000294}
295
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000296namespace {
297
298/// \brief Gathers information from PCHReader that will be used to initialize
299/// a Preprocessor.
Benjamin Kramer16634c22009-11-28 10:07:24 +0000300class PCHInfoCollector : public PCHReaderListener {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000301 LangOptions &LangOpt;
302 HeaderSearch &HSI;
303 std::string &TargetTriple;
304 std::string &Predefines;
305 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000306
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000307 unsigned NumHeaderInfos;
Mike Stump11289f42009-09-09 15:08:12 +0000308
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000309public:
310 PCHInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
311 std::string &TargetTriple, std::string &Predefines,
312 unsigned &Counter)
313 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
314 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump11289f42009-09-09 15:08:12 +0000315
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000316 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
317 LangOpt = LangOpts;
318 return false;
319 }
Mike Stump11289f42009-09-09 15:08:12 +0000320
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000321 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000322 TargetTriple = Triple;
323 return false;
324 }
Mike Stump11289f42009-09-09 15:08:12 +0000325
Sebastian Redl8b41f302010-07-14 23:29:55 +0000326 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000327 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000328 std::string &SuggestedPredefines) {
Sebastian Redl8b41f302010-07-14 23:29:55 +0000329 Predefines = Buffers[0].Data;
330 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
331 Predefines += Buffers[I].Data;
332 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000333 return false;
334 }
Mike Stump11289f42009-09-09 15:08:12 +0000335
Douglas Gregora2f49452010-03-16 19:09:18 +0000336 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000337 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
338 }
Mike Stump11289f42009-09-09 15:08:12 +0000339
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000340 virtual void ReadCounter(unsigned Value) {
341 Counter = Value;
342 }
343};
344
Douglas Gregor33cdd812010-02-18 18:08:43 +0000345class StoredDiagnosticClient : public DiagnosticClient {
346 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
347
348public:
349 explicit StoredDiagnosticClient(
350 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
351 : StoredDiags(StoredDiags) { }
352
353 virtual void HandleDiagnostic(Diagnostic::Level Level,
354 const DiagnosticInfo &Info);
355};
356
357/// \brief RAII object that optionally captures diagnostics, if
358/// there is no diagnostic client to capture them already.
359class CaptureDroppedDiagnostics {
360 Diagnostic &Diags;
361 StoredDiagnosticClient Client;
362 DiagnosticClient *PreviousClient;
363
364public:
365 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
366 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
367 : Diags(Diags), Client(StoredDiags), PreviousClient(Diags.getClient())
368 {
369 if (RequestCapture || Diags.getClient() == 0)
370 Diags.setClient(&Client);
371 }
372
373 ~CaptureDroppedDiagnostics() {
374 Diags.setClient(PreviousClient);
375 }
376};
377
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000378} // anonymous namespace
379
Douglas Gregor33cdd812010-02-18 18:08:43 +0000380void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
381 const DiagnosticInfo &Info) {
382 StoredDiags.push_back(StoredDiagnostic(Level, Info));
383}
384
Steve Naroffc0683b92009-09-03 18:19:54 +0000385const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbara8a50932009-12-02 08:44:16 +0000386 return OriginalSourceFile;
Steve Naroffc0683b92009-09-03 18:19:54 +0000387}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000388
Steve Naroff44cd60e2009-10-15 22:23:48 +0000389const std::string &ASTUnit::getPCHFileName() {
Daniel Dunbara18f9582009-12-02 21:47:43 +0000390 assert(isMainFileAST() && "Not an ASTUnit from a PCH file!");
Benjamin Kramer2ecf8eb2010-01-30 16:23:25 +0000391 return static_cast<PCHReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroff44cd60e2009-10-15 22:23:48 +0000392}
393
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000394ASTUnit *ASTUnit::LoadFromPCHFile(const std::string &Filename,
Douglas Gregor7f95d262010-04-05 23:52:57 +0000395 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Ted Kremenek8bcb1c62009-10-17 00:34:24 +0000396 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000397 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +0000398 unsigned NumRemappedFiles,
399 bool CaptureDiagnostics) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000400 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
401
Douglas Gregor7f95d262010-04-05 23:52:57 +0000402 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000403 // No diagnostics engine was provided, so create our own diagnostics object
404 // with the default options.
405 DiagnosticOptions DiagOpts;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000406 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregord03e8232010-04-05 21:10:19 +0000407 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000408
409 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor16bef852009-10-16 20:01:17 +0000410 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000411 AST->Diagnostics = Diags;
Douglas Gregord03e8232010-04-05 21:10:19 +0000412 AST->FileMgr.reset(new FileManager);
413 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics()));
Steve Naroff505fb842009-10-19 14:34:22 +0000414 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000415
Douglas Gregor33cdd812010-02-18 18:08:43 +0000416 // If requested, capture diagnostics in the ASTUnit.
Douglas Gregord03e8232010-04-05 21:10:19 +0000417 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, AST->getDiagnostics(),
Douglas Gregora2433152010-04-05 18:10:21 +0000418 AST->StoredDiagnostics);
Douglas Gregor33cdd812010-02-18 18:08:43 +0000419
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000420 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
421 // Create the file entry for the file that we're mapping from.
422 const FileEntry *FromFile
423 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
424 RemappedFiles[I].second->getBufferSize(),
425 0);
426 if (!FromFile) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000427 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000428 << RemappedFiles[I].first;
Douglas Gregor89a56c52010-02-27 01:32:48 +0000429 delete RemappedFiles[I].second;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000430 continue;
431 }
432
433 // Override the contents of the "from" file with the contents of
434 // the "to" file.
435 AST->getSourceManager().overrideFileContents(FromFile,
436 RemappedFiles[I].second);
437 }
438
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000439 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000440
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000441 LangOptions LangInfo;
442 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
443 std::string TargetTriple;
444 std::string Predefines;
445 unsigned Counter;
446
Daniel Dunbar3a0637b2009-09-03 05:59:50 +0000447 llvm::OwningPtr<PCHReader> Reader;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000448
Ted Kremenek428c6372009-10-19 21:44:57 +0000449 Reader.reset(new PCHReader(AST->getSourceManager(), AST->getFileManager(),
Douglas Gregord03e8232010-04-05 21:10:19 +0000450 AST->getDiagnostics()));
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000451 Reader->setListener(new PCHInfoCollector(LangInfo, HeaderInfo, TargetTriple,
452 Predefines, Counter));
453
454 switch (Reader->ReadPCH(Filename)) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000455 case PCHReader::Success:
456 break;
Mike Stump11289f42009-09-09 15:08:12 +0000457
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000458 case PCHReader::Failure:
Argyrios Kyrtzidis55c34112009-06-25 18:22:30 +0000459 case PCHReader::IgnorePCH:
Douglas Gregord03e8232010-04-05 21:10:19 +0000460 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000461 return NULL;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000462 }
Mike Stump11289f42009-09-09 15:08:12 +0000463
Daniel Dunbara8a50932009-12-02 08:44:16 +0000464 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
465
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000466 // PCH loaded successfully. Now create the preprocessor.
Mike Stump11289f42009-09-09 15:08:12 +0000467
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000468 // Get information about the target being compiled for.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000469 //
470 // FIXME: This is broken, we should store the TargetOptions in the PCH.
471 TargetOptions TargetOpts;
472 TargetOpts.ABI = "";
Charles Davis95a546e2010-06-11 01:06:47 +0000473 TargetOpts.CXXABI = "itanium";
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000474 TargetOpts.CPU = "";
475 TargetOpts.Features.clear();
476 TargetOpts.Triple = TargetTriple;
Douglas Gregord03e8232010-04-05 21:10:19 +0000477 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
478 TargetOpts));
479 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
480 *AST->Target.get(),
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000481 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000482 Preprocessor &PP = *AST->PP.get();
483
Daniel Dunbarb7bbfdd2009-09-21 03:03:47 +0000484 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000485 PP.setCounterValue(Counter);
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000486 Reader->setPreprocessor(PP);
Mike Stump11289f42009-09-09 15:08:12 +0000487
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000488 // Create and initialize the ASTContext.
489
490 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000491 AST->getSourceManager(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000492 *AST->Target.get(),
493 PP.getIdentifierTable(),
494 PP.getSelectorTable(),
495 PP.getBuiltinInfo(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000496 /* size_reserve = */0));
497 ASTContext &Context = *AST->Ctx.get();
Mike Stump11289f42009-09-09 15:08:12 +0000498
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000499 Reader->InitializeContext(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000500
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000501 // Attach the PCH reader to the AST context as an external AST
502 // source, so that declarations will be deserialized from the
503 // PCH file as needed.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000504 PCHReader *ReaderPtr = Reader.get();
505 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000506 Context.setExternalSource(Source);
507
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000508 // Create an AST consumer, even though it isn't used.
509 AST->Consumer.reset(new ASTConsumer);
510
511 // Create a semantic analysis object and tell the PCH reader about it.
512 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
513 AST->TheSema->Initialize();
514 ReaderPtr->InitializeSema(*AST->TheSema);
515
Mike Stump11289f42009-09-09 15:08:12 +0000516 return AST.take();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000517}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000518
519namespace {
520
Daniel Dunbar644dca02009-12-04 08:17:33 +0000521class TopLevelDeclTrackerConsumer : public ASTConsumer {
522 ASTUnit &Unit;
523
524public:
525 TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {}
526
527 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekacc59c32010-05-03 20:16:35 +0000528 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
529 Decl *D = *it;
530 // FIXME: Currently ObjC method declarations are incorrectly being
531 // reported as top-level declarations, even though their DeclContext
532 // is the containing ObjC @interface/@implementation. This is a
533 // fundamental problem in the parser right now.
534 if (isa<ObjCMethodDecl>(D))
535 continue;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000536 Unit.addTopLevelDecl(D);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000537 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000538 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000539
540 // We're not interested in "interesting" decls.
541 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbar644dca02009-12-04 08:17:33 +0000542};
543
544class TopLevelDeclTrackerAction : public ASTFrontendAction {
545public:
546 ASTUnit &Unit;
547
Daniel Dunbar764c0822009-12-01 09:51:01 +0000548 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
549 llvm::StringRef InFile) {
Daniel Dunbar644dca02009-12-04 08:17:33 +0000550 return new TopLevelDeclTrackerConsumer(Unit);
Daniel Dunbar764c0822009-12-01 09:51:01 +0000551 }
552
553public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000554 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
555
Daniel Dunbar764c0822009-12-01 09:51:01 +0000556 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000557 virtual bool usesCompleteTranslationUnit() {
558 return Unit.isCompleteTranslationUnit();
559 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000560};
561
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000562class PrecompilePreambleConsumer : public PCHGenerator {
563 ASTUnit &Unit;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000564 std::vector<Decl *> TopLevelDecls;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000565
566public:
567 PrecompilePreambleConsumer(ASTUnit &Unit,
568 const Preprocessor &PP, bool Chaining,
569 const char *isysroot, llvm::raw_ostream *Out)
570 : PCHGenerator(PP, Chaining, isysroot, Out), Unit(Unit) { }
571
Douglas Gregore9db88f2010-08-03 19:06:41 +0000572 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000573 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
574 Decl *D = *it;
575 // FIXME: Currently ObjC method declarations are incorrectly being
576 // reported as top-level declarations, even though their DeclContext
577 // is the containing ObjC @interface/@implementation. This is a
578 // fundamental problem in the parser right now.
579 if (isa<ObjCMethodDecl>(D))
580 continue;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000581 TopLevelDecls.push_back(D);
582 }
583 }
584
585 virtual void HandleTranslationUnit(ASTContext &Ctx) {
586 PCHGenerator::HandleTranslationUnit(Ctx);
587 if (!Unit.getDiagnostics().hasErrorOccurred()) {
588 // Translate the top-level declarations we captured during
589 // parsing into declaration IDs in the precompiled
590 // preamble. This will allow us to deserialize those top-level
591 // declarations when requested.
592 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
593 Unit.addTopLevelDeclFromPreamble(
594 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000595 }
596 }
597};
598
599class PrecompilePreambleAction : public ASTFrontendAction {
600 ASTUnit &Unit;
601
602public:
603 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
604
605 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
606 llvm::StringRef InFile) {
607 std::string Sysroot;
608 llvm::raw_ostream *OS = 0;
609 bool Chaining;
610 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
611 OS, Chaining))
612 return 0;
613
614 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
615 Sysroot.c_str() : 0;
616 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
617 isysroot, OS);
618 }
619
620 virtual bool hasCodeCompletionSupport() const { return false; }
621 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000622 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000623};
624
Daniel Dunbar764c0822009-12-01 09:51:01 +0000625}
626
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000627/// Parse the source file into a translation unit using the given compiler
628/// invocation, replacing the current translation unit.
629///
630/// \returns True if a failure occurred that causes the ASTUnit not to
631/// contain any translation-unit information, false otherwise.
Douglas Gregor6481ef12010-07-24 00:38:13 +0000632bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor96c04262010-07-27 14:52:07 +0000633 delete SavedMainFileBuffer;
634 SavedMainFileBuffer = 0;
635
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000636 if (!Invocation.get())
637 return true;
638
Daniel Dunbar764c0822009-12-01 09:51:01 +0000639 // Create the compiler instance to use for building the AST.
Daniel Dunbar7afbb8c2009-12-02 08:43:56 +0000640 CompilerInstance Clang;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000641 Clang.setInvocation(Invocation.take());
642 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
643
Douglas Gregor8e984da2010-08-04 16:47:14 +0000644 // Set up diagnostics, capturing any diagnostics that would
645 // otherwise be dropped.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000646 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor8e984da2010-08-04 16:47:14 +0000647 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
648 getDiagnostics(),
649 StoredDiagnostics);
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000650 Clang.setDiagnosticClient(getDiagnostics().getClient());
Douglas Gregord03e8232010-04-05 21:10:19 +0000651
Daniel Dunbar764c0822009-12-01 09:51:01 +0000652 // Create the target instance.
653 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
654 Clang.getTargetOpts()));
Douglas Gregor33cdd812010-02-18 18:08:43 +0000655 if (!Clang.hasTarget()) {
Douglas Gregor33cdd812010-02-18 18:08:43 +0000656 Clang.takeDiagnosticClient();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000657 return true;
Douglas Gregor33cdd812010-02-18 18:08:43 +0000658 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000659
Daniel Dunbar764c0822009-12-01 09:51:01 +0000660 // Inform the target of the language options.
661 //
662 // FIXME: We shouldn't need to do this, the target should be immutable once
663 // created. This complexity should be lifted elsewhere.
664 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000665
Daniel Dunbar764c0822009-12-01 09:51:01 +0000666 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
667 "Invocation must have exactly one source file!");
Daniel Dunbar9b491e72010-06-07 23:22:09 +0000668 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +0000669 "FIXME: AST inputs not yet supported here!");
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000670 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
671 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +0000672
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000673 // Configure the various subsystems.
674 // FIXME: Should we retain the previous file manager?
675 FileMgr.reset(new FileManager);
676 SourceMgr.reset(new SourceManager(getDiagnostics()));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000677 TheSema.reset();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000678 Ctx.reset();
679 PP.reset();
680
681 // Clear out old caches and data.
682 TopLevelDecls.clear();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000683 CleanTemporaryFiles();
684 PreprocessedEntitiesByFile.clear();
Douglas Gregord9a30af2010-08-02 20:51:39 +0000685
686 if (!OverrideMainBuffer)
687 StoredDiagnostics.clear();
Douglas Gregor8e984da2010-08-04 16:47:14 +0000688
Daniel Dunbar764c0822009-12-01 09:51:01 +0000689 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000690 Clang.setFileManager(&getFileManager());
691
Daniel Dunbar764c0822009-12-01 09:51:01 +0000692 // Create the source manager.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000693 Clang.setSourceManager(&getSourceManager());
694
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000695 // If the main file has been overridden due to the use of a preamble,
696 // make that override happen and introduce the preamble.
697 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +0000698 std::string PriorImplicitPCHInclude;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000699 if (OverrideMainBuffer) {
700 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
701 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
702 PreprocessorOpts.PrecompiledPreambleBytes.second
703 = PreambleEndsAtStartOfLine;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000704 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000705 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000706 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +0000707
708 // Keep track of the override buffer;
709 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregord9a30af2010-08-02 20:51:39 +0000710
711 // The stored diagnostic has the old source manager in it; update
712 // the locations to refer into the new source manager. Since we've
713 // been careful to make sure that the source manager's state
714 // before and after are identical, so that we can reuse the source
715 // location itself.
716 for (unsigned I = 0, N = StoredDiagnostics.size(); I != N; ++I) {
717 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
718 getSourceManager());
719 StoredDiagnostics[I].setLocation(Loc);
720 }
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000721 }
722
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000723 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
724 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbar644dca02009-12-04 08:17:33 +0000725 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbar86546382010-06-07 23:23:06 +0000726 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar764c0822009-12-01 09:51:01 +0000727 goto error;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000728
Daniel Dunbar644dca02009-12-04 08:17:33 +0000729 Act->Execute();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000730
Daniel Dunbard2f8be32009-12-01 21:57:33 +0000731 // Steal the created target, context, and preprocessor, and take back the
732 // source and file managers.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000733 TheSema.reset(Clang.takeSema());
734 Consumer.reset(Clang.takeASTConsumer());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000735 Ctx.reset(Clang.takeASTContext());
736 PP.reset(Clang.takePreprocessor());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000737 Clang.takeSourceManager();
738 Clang.takeFileManager();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000739 Target.reset(Clang.takeTarget());
740
Daniel Dunbar644dca02009-12-04 08:17:33 +0000741 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000742
743 // Remove the overridden buffer we used for the preamble.
Douglas Gregor8e984da2010-08-04 16:47:14 +0000744 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000745 PreprocessorOpts.eraseRemappedFile(
746 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor8e984da2010-08-04 16:47:14 +0000747 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
748 }
749
Daniel Dunbar764c0822009-12-01 09:51:01 +0000750 Clang.takeDiagnosticClient();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000751
752 Invocation.reset(Clang.takeInvocation());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000753
754 // If we were asked to cache code-completion results and don't have any
755 // results yet, do so now.
756 if (ShouldCacheCodeCompletionResults && CachedCompletionResults.empty())
757 CacheCodeCompletionResults();
758
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000759 return false;
760
Daniel Dunbar764c0822009-12-01 09:51:01 +0000761error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000762 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +0000763 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000764 PreprocessorOpts.eraseRemappedFile(
765 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregorce3a8292010-07-27 00:27:13 +0000766 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000767 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000768 }
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000769
Daniel Dunbar764c0822009-12-01 09:51:01 +0000770 Clang.takeSourceManager();
771 Clang.takeFileManager();
772 Clang.takeDiagnosticClient();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000773 Invocation.reset(Clang.takeInvocation());
774 return true;
775}
776
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000777/// \brief Simple function to retrieve a path for a preamble precompiled header.
778static std::string GetPreamblePCHPath() {
779 // FIXME: This is lame; sys::Path should provide this function (in particular,
780 // it should know how to find the temporary files dir).
781 // FIXME: This is really lame. I copied this code from the Driver!
782 std::string Error;
783 const char *TmpDir = ::getenv("TMPDIR");
784 if (!TmpDir)
785 TmpDir = ::getenv("TEMP");
786 if (!TmpDir)
787 TmpDir = ::getenv("TMP");
788 if (!TmpDir)
789 TmpDir = "/tmp";
790 llvm::sys::Path P(TmpDir);
791 P.appendComponent("preamble");
Douglas Gregor20975b22010-08-11 13:06:56 +0000792 P.appendSuffix("pch");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000793 if (P.createTemporaryFileOnDisk())
794 return std::string();
795
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000796 return P.str();
797}
798
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000799/// \brief Compute the preamble for the main file, providing the source buffer
800/// that corresponds to the main file along with a pair (bytes, start-of-line)
801/// that describes the preamble.
802std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor028d3e42010-08-09 20:45:32 +0000803ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
804 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000805 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000806 PreprocessorOptions &PreprocessorOpts
Douglas Gregor4dde7492010-07-23 23:58:40 +0000807 = Invocation.getPreprocessorOpts();
808 CreatedBuffer = false;
809
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000810 // Try to determine if the main file has been remapped, either from the
811 // command line (to another file) or directly through the compiler invocation
812 // (to a memory buffer).
Douglas Gregor4dde7492010-07-23 23:58:40 +0000813 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000814 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
815 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
816 // Check whether there is a file-file remapping of the main file
817 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor4dde7492010-07-23 23:58:40 +0000818 M = PreprocessorOpts.remapped_file_begin(),
819 E = PreprocessorOpts.remapped_file_end();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000820 M != E;
821 ++M) {
822 llvm::sys::PathWithStatus MPath(M->first);
823 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
824 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
825 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000826 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000827 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000828 CreatedBuffer = false;
829 }
830
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000831 Buffer = llvm::MemoryBuffer::getFile(M->second);
832 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000833 return std::make_pair((llvm::MemoryBuffer*)0,
834 std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000835 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000836
Douglas Gregor4dde7492010-07-23 23:58:40 +0000837 // Remove this remapping. We've captured the buffer already.
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000838 M = PreprocessorOpts.eraseRemappedFile(M);
839 E = PreprocessorOpts.remapped_file_end();
840 }
841 }
842 }
843
844 // Check whether there is a file-buffer remapping. It supercedes the
845 // file-file remapping.
846 for (PreprocessorOptions::remapped_file_buffer_iterator
847 M = PreprocessorOpts.remapped_file_buffer_begin(),
848 E = PreprocessorOpts.remapped_file_buffer_end();
849 M != E;
850 ++M) {
851 llvm::sys::PathWithStatus MPath(M->first);
852 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
853 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
854 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000855 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000856 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000857 CreatedBuffer = false;
858 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000859
Douglas Gregor4dde7492010-07-23 23:58:40 +0000860 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
861
862 // Remove this remapping. We've captured the buffer already.
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000863 M = PreprocessorOpts.eraseRemappedFile(M);
864 E = PreprocessorOpts.remapped_file_buffer_end();
865 }
866 }
Douglas Gregor4dde7492010-07-23 23:58:40 +0000867 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000868 }
869
870 // If the main source file was not remapped, load it now.
871 if (!Buffer) {
872 Buffer = llvm::MemoryBuffer::getFile(FrontendOpts.Inputs[0].second);
873 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000874 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000875
876 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000877 }
878
Douglas Gregor028d3e42010-08-09 20:45:32 +0000879 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000880}
881
Douglas Gregor6481ef12010-07-24 00:38:13 +0000882static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
883 bool DeleteOld,
884 unsigned NewSize,
885 llvm::StringRef NewName) {
886 llvm::MemoryBuffer *Result
887 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
888 memcpy(const_cast<char*>(Result->getBufferStart()),
889 Old->getBufferStart(), Old->getBufferSize());
890 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000891 ' ', NewSize - Old->getBufferSize() - 1);
892 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor6481ef12010-07-24 00:38:13 +0000893
894 if (DeleteOld)
895 delete Old;
896
897 return Result;
898}
899
Douglas Gregor4dde7492010-07-23 23:58:40 +0000900/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
901/// the source file.
902///
903/// This routine will compute the preamble of the main source file. If a
904/// non-trivial preamble is found, it will precompile that preamble into a
905/// precompiled header so that the precompiled preamble can be used to reduce
906/// reparsing time. If a precompiled preamble has already been constructed,
907/// this routine will determine if it is still valid and, if so, avoid
908/// rebuilding the precompiled preamble.
909///
Douglas Gregor028d3e42010-08-09 20:45:32 +0000910/// \param AllowRebuild When true (the default), this routine is
911/// allowed to rebuild the precompiled preamble if it is found to be
912/// out-of-date.
913///
914/// \param MaxLines When non-zero, the maximum number of lines that
915/// can occur within the preamble.
916///
Douglas Gregor6481ef12010-07-24 00:38:13 +0000917/// \returns If the precompiled preamble can be used, returns a newly-allocated
918/// buffer that should be used in place of the main file when doing so.
919/// Otherwise, returns a NULL pointer.
Douglas Gregor028d3e42010-08-09 20:45:32 +0000920llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
921 bool AllowRebuild,
922 unsigned MaxLines) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000923 CompilerInvocation PreambleInvocation(*Invocation);
924 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
925 PreprocessorOptions &PreprocessorOpts
926 = PreambleInvocation.getPreprocessorOpts();
927
928 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000929 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor028d3e42010-08-09 20:45:32 +0000930 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +0000931
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000932 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000933 // We couldn't find a preamble in the main source. Clear out the current
934 // preamble, if we have one. It's obviously no good any more.
935 Preamble.clear();
936 if (!PreambleFile.empty()) {
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000937 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor4dde7492010-07-23 23:58:40 +0000938 PreambleFile.clear();
939 }
940 if (CreatedPreambleBuffer)
941 delete NewPreamble.first;
Douglas Gregorbb420ab2010-08-04 05:53:38 +0000942
943 // The next time we actually see a preamble, precompile it.
944 PreambleRebuildCounter = 1;
Douglas Gregor6481ef12010-07-24 00:38:13 +0000945 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000946 }
947
948 if (!Preamble.empty()) {
949 // We've previously computed a preamble. Check whether we have the same
950 // preamble now that we did before, and that there's enough space in
951 // the main-file buffer within the precompiled preamble to fit the
952 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000953 if (Preamble.size() == NewPreamble.second.first &&
954 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregorf5275a82010-07-24 00:42:07 +0000955 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor4dde7492010-07-23 23:58:40 +0000956 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000957 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000958 // The preamble has not changed. We may be able to re-use the precompiled
959 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +0000960
Douglas Gregor0e119552010-07-31 00:40:00 +0000961 // Check that none of the files used by the preamble have changed.
962 bool AnyFileChanged = false;
963
964 // First, make a record of those files that have been overridden via
965 // remapping or unsaved_files.
966 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
967 for (PreprocessorOptions::remapped_file_iterator
968 R = PreprocessorOpts.remapped_file_begin(),
969 REnd = PreprocessorOpts.remapped_file_end();
970 !AnyFileChanged && R != REnd;
971 ++R) {
972 struct stat StatBuf;
973 if (stat(R->second.c_str(), &StatBuf)) {
974 // If we can't stat the file we're remapping to, assume that something
975 // horrible happened.
976 AnyFileChanged = true;
977 break;
978 }
Douglas Gregor6481ef12010-07-24 00:38:13 +0000979
Douglas Gregor0e119552010-07-31 00:40:00 +0000980 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
981 StatBuf.st_mtime);
982 }
983 for (PreprocessorOptions::remapped_file_buffer_iterator
984 R = PreprocessorOpts.remapped_file_buffer_begin(),
985 REnd = PreprocessorOpts.remapped_file_buffer_end();
986 !AnyFileChanged && R != REnd;
987 ++R) {
988 // FIXME: Should we actually compare the contents of file->buffer
989 // remappings?
990 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
991 0);
992 }
993
994 // Check whether anything has changed.
995 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
996 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
997 !AnyFileChanged && F != FEnd;
998 ++F) {
999 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1000 = OverriddenFiles.find(F->first());
1001 if (Overridden != OverriddenFiles.end()) {
1002 // This file was remapped; check whether the newly-mapped file
1003 // matches up with the previous mapping.
1004 if (Overridden->second != F->second)
1005 AnyFileChanged = true;
1006 continue;
1007 }
1008
1009 // The file was not remapped; check whether it has changed on disk.
1010 struct stat StatBuf;
1011 if (stat(F->first(), &StatBuf)) {
1012 // If we can't stat the file, assume that something horrible happened.
1013 AnyFileChanged = true;
1014 } else if (StatBuf.st_size != F->second.first ||
1015 StatBuf.st_mtime != F->second.second)
1016 AnyFileChanged = true;
1017 }
1018
1019 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001020 // Okay! We can re-use the precompiled preamble.
1021
1022 // Set the state of the diagnostic object to mimic its state
1023 // after parsing the preamble.
1024 getDiagnostics().Reset();
1025 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1026 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
1027 StoredDiagnostics.erase(
1028 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
1029 StoredDiagnostics.end());
1030
1031 // Create a version of the main file buffer that is padded to
1032 // buffer size we reserved when creating the preamble.
Douglas Gregor0e119552010-07-31 00:40:00 +00001033 return CreatePaddedMainFileBuffer(NewPreamble.first,
1034 CreatedPreambleBuffer,
1035 PreambleReservedSize,
1036 FrontendOpts.Inputs[0].second);
1037 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001038 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001039
1040 // If we aren't allowed to rebuild the precompiled preamble, just
1041 // return now.
1042 if (!AllowRebuild)
1043 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001044
1045 // We can't reuse the previously-computed preamble. Build a new one.
1046 Preamble.clear();
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001047 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001048 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001049 } else if (!AllowRebuild) {
1050 // We aren't allowed to rebuild the precompiled preamble; just
1051 // return now.
1052 return 0;
1053 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001054
1055 // If the preamble rebuild counter > 1, it's because we previously
1056 // failed to build a preamble and we're not yet ready to try
1057 // again. Decrement the counter and return a failure.
1058 if (PreambleRebuildCounter > 1) {
1059 --PreambleRebuildCounter;
1060 return 0;
1061 }
1062
Douglas Gregor4dde7492010-07-23 23:58:40 +00001063 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001064 llvm::Timer *PreambleTimer = 0;
1065 if (TimerGroup.get()) {
1066 PreambleTimer = new llvm::Timer("Precompiling preamble", *TimerGroup);
1067 PreambleTimer->startTimer();
1068 Timers.push_back(PreambleTimer);
1069 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001070
1071 // Create a new buffer that stores the preamble. The buffer also contains
1072 // extra space for the original contents of the file (which will be present
1073 // when we actually parse the file) along with more room in case the file
Douglas Gregor4dde7492010-07-23 23:58:40 +00001074 // grows.
1075 PreambleReservedSize = NewPreamble.first->getBufferSize();
1076 if (PreambleReservedSize < 4096)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001077 PreambleReservedSize = 8191;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001078 else
Douglas Gregor4dde7492010-07-23 23:58:40 +00001079 PreambleReservedSize *= 2;
1080
Douglas Gregord9a30af2010-08-02 20:51:39 +00001081 // Save the preamble text for later; we'll need to compare against it for
1082 // subsequent reparses.
1083 Preamble.assign(NewPreamble.first->getBufferStart(),
1084 NewPreamble.first->getBufferStart()
1085 + NewPreamble.second.first);
1086 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1087
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001088 llvm::MemoryBuffer *PreambleBuffer
Douglas Gregor4dde7492010-07-23 23:58:40 +00001089 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001090 FrontendOpts.Inputs[0].second);
1091 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor4dde7492010-07-23 23:58:40 +00001092 NewPreamble.first->getBufferStart(), Preamble.size());
1093 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001094 ' ', PreambleReservedSize - Preamble.size() - 1);
1095 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001096
1097 // Remap the main source file to the preamble buffer.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001098 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001099 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1100
1101 // Tell the compiler invocation to generate a temporary precompiled header.
1102 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Sebastian Redle98428d2010-08-06 00:35:11 +00001103 // FIXME: Set ChainedPCH unconditionally, once it is ready.
1104 if (::getenv("LIBCLANG_CHAINING"))
1105 FrontendOpts.ChainedPCH = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001106 // FIXME: Generate the precompiled header into memory?
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001107 FrontendOpts.OutputFile = GetPreamblePCHPath();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001108
1109 // Create the compiler instance to use for building the precompiled preamble.
1110 CompilerInstance Clang;
1111 Clang.setInvocation(&PreambleInvocation);
1112 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1113
Douglas Gregor8e984da2010-08-04 16:47:14 +00001114 // Set up diagnostics, capturing all of the diagnostics produced.
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001115 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor8e984da2010-08-04 16:47:14 +00001116 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
1117 getDiagnostics(),
1118 StoredDiagnostics);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001119 Clang.setDiagnosticClient(getDiagnostics().getClient());
1120
1121 // Create the target instance.
1122 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1123 Clang.getTargetOpts()));
1124 if (!Clang.hasTarget()) {
1125 Clang.takeDiagnosticClient();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001126 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1127 Preamble.clear();
1128 if (CreatedPreambleBuffer)
1129 delete NewPreamble.first;
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001130 if (PreambleTimer)
1131 PreambleTimer->stopTimer();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001132 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor6481ef12010-07-24 00:38:13 +00001133 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001134 }
1135
1136 // Inform the target of the language options.
1137 //
1138 // FIXME: We shouldn't need to do this, the target should be immutable once
1139 // created. This complexity should be lifted elsewhere.
1140 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1141
1142 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1143 "Invocation must have exactly one source file!");
1144 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1145 "FIXME: AST inputs not yet supported here!");
1146 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1147 "IR inputs not support here!");
1148
1149 // Clear out old caches and data.
1150 StoredDiagnostics.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001151 TopLevelDecls.clear();
1152 TopLevelDeclsInPreamble.clear();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001153
1154 // Create a file manager object to provide access to and cache the filesystem.
1155 Clang.setFileManager(new FileManager);
1156
1157 // Create the source manager.
1158 Clang.setSourceManager(new SourceManager(getDiagnostics()));
1159
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001160 llvm::OwningPtr<PrecompilePreambleAction> Act;
1161 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001162 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1163 Clang.getFrontendOpts().Inputs[0].first)) {
1164 Clang.takeDiagnosticClient();
1165 Clang.takeInvocation();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001166 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1167 Preamble.clear();
1168 if (CreatedPreambleBuffer)
1169 delete NewPreamble.first;
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001170 if (PreambleTimer)
1171 PreambleTimer->stopTimer();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001172 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001173
Douglas Gregor6481ef12010-07-24 00:38:13 +00001174 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001175 }
1176
1177 Act->Execute();
1178 Act->EndSourceFile();
1179 Clang.takeDiagnosticClient();
1180 Clang.takeInvocation();
1181
Douglas Gregore9db88f2010-08-03 19:06:41 +00001182 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001183 // There were errors parsing the preamble, so no precompiled header was
1184 // generated. Forget that we even tried.
1185 // FIXME: Should we leave a note for ourselves to try again?
1186 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1187 Preamble.clear();
1188 if (CreatedPreambleBuffer)
1189 delete NewPreamble.first;
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001190 if (PreambleTimer)
1191 PreambleTimer->stopTimer();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001192 TopLevelDeclsInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001193 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor6481ef12010-07-24 00:38:13 +00001194 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001195 }
1196
1197 // Keep track of the preamble we precompiled.
1198 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregord9a30af2010-08-02 20:51:39 +00001199 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1200 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001201
1202 // Keep track of all of the files that the source manager knows about,
1203 // so we can verify whether they have changed or not.
1204 FilesInPreamble.clear();
1205 SourceManager &SourceMgr = Clang.getSourceManager();
1206 const llvm::MemoryBuffer *MainFileBuffer
1207 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1208 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1209 FEnd = SourceMgr.fileinfo_end();
1210 F != FEnd;
1211 ++F) {
1212 const FileEntry *File = F->second->Entry;
1213 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1214 continue;
1215
1216 FilesInPreamble[File->getName()]
1217 = std::make_pair(F->second->getSize(), File->getModificationTime());
1218 }
1219
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001220 if (PreambleTimer)
1221 PreambleTimer->stopTimer();
1222
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001223 PreambleRebuildCounter = 1;
Douglas Gregor6481ef12010-07-24 00:38:13 +00001224 return CreatePaddedMainFileBuffer(NewPreamble.first,
1225 CreatedPreambleBuffer,
1226 PreambleReservedSize,
1227 FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001228}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001229
Douglas Gregore9db88f2010-08-03 19:06:41 +00001230void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1231 std::vector<Decl *> Resolved;
1232 Resolved.reserve(TopLevelDeclsInPreamble.size());
1233 ExternalASTSource &Source = *getASTContext().getExternalSource();
1234 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1235 // Resolve the declaration ID to an actual declaration, possibly
1236 // deserializing the declaration in the process.
1237 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1238 if (D)
1239 Resolved.push_back(D);
1240 }
1241 TopLevelDeclsInPreamble.clear();
1242 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1243}
1244
1245unsigned ASTUnit::getMaxPCHLevel() const {
1246 if (!getOnlyLocalDecls())
1247 return Decl::MaxPCHLevel;
1248
1249 unsigned Result = 0;
1250 if (isMainFileAST() || SavedMainFileBuffer)
1251 ++Result;
1252 return Result;
1253}
1254
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001255ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1256 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1257 bool OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001258 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001259 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001260 bool CompleteTranslationUnit,
1261 bool CacheCodeCompletionResults) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001262 if (!Diags.getPtr()) {
1263 // No diagnostics engine was provided, so create our own diagnostics object
1264 // with the default options.
1265 DiagnosticOptions DiagOpts;
1266 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
1267 }
1268
1269 // Create the AST unit.
1270 llvm::OwningPtr<ASTUnit> AST;
1271 AST.reset(new ASTUnit(false));
1272 AST->Diagnostics = Diags;
1273 AST->CaptureDiagnostics = CaptureDiagnostics;
1274 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001275 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001276 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001277 AST->Invocation.reset(CI);
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001278 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001279
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001280 if (getenv("LIBCLANG_TIMING"))
1281 AST->TimerGroup.reset(
1282 new llvm::TimerGroup(CI->getFrontendOpts().Inputs[0].second));
1283
1284
Douglas Gregor6481ef12010-07-24 00:38:13 +00001285 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregora5fd5222010-07-28 22:12:37 +00001286 // FIXME: When C++ PCH is ready, allow use of it for a precompiled preamble.
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001287 if (PrecompilePreamble && !CI->getLangOpts().CPlusPlus) {
1288 AST->PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001289 OverrideMainBuffer = AST->getMainBufferWithPrecompiledPreamble();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001290 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001291
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001292 llvm::Timer *ParsingTimer = 0;
1293 if (AST->TimerGroup.get()) {
1294 ParsingTimer = new llvm::Timer("Initial parse", *AST->TimerGroup);
1295 ParsingTimer->startTimer();
1296 AST->Timers.push_back(ParsingTimer);
1297 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001298
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001299 bool Failed = AST->Parse(OverrideMainBuffer);
1300 if (ParsingTimer)
1301 ParsingTimer->stopTimer();
1302
1303 return Failed? 0 : AST.take();
Daniel Dunbar764c0822009-12-01 09:51:01 +00001304}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001305
1306ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1307 const char **ArgEnd,
Douglas Gregor7f95d262010-04-05 23:52:57 +00001308 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar8d4a2022009-12-13 03:46:13 +00001309 llvm::StringRef ResourceFilesPath,
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001310 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001311 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001312 unsigned NumRemappedFiles,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001313 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001314 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001315 bool CompleteTranslationUnit,
1316 bool CacheCodeCompletionResults) {
Douglas Gregor7f95d262010-04-05 23:52:57 +00001317 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00001318 // No diagnostics engine was provided, so create our own diagnostics object
1319 // with the default options.
1320 DiagnosticOptions DiagOpts;
Douglas Gregor7f95d262010-04-05 23:52:57 +00001321 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregord03e8232010-04-05 21:10:19 +00001322 }
1323
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001324 llvm::SmallVector<const char *, 16> Args;
1325 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1326 Args.insert(Args.end(), ArgBegin, ArgEnd);
1327
1328 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1329 // also want to force it to use clang.
1330 Args.push_back("-fsyntax-only");
1331
Daniel Dunbar8d4a2022009-12-13 03:46:13 +00001332 // FIXME: We shouldn't have to pass in the path info.
Daniel Dunbare38764c2010-07-19 00:44:04 +00001333 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
Douglas Gregord03e8232010-04-05 21:10:19 +00001334 "a.out", false, false, *Diags);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001335
1336 // Don't check that inputs exist, they have been remapped.
1337 TheDriver.setCheckInputsExist(false);
1338
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001339 llvm::OwningPtr<driver::Compilation> C(
1340 TheDriver.BuildCompilation(Args.size(), Args.data()));
1341
1342 // We expect to get back exactly one command job, if we didn't something
1343 // failed.
1344 const driver::JobList &Jobs = C->getJobs();
1345 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1346 llvm::SmallString<256> Msg;
1347 llvm::raw_svector_ostream OS(Msg);
1348 C->PrintJob(OS, C->getJobs(), "; ", true);
Douglas Gregord03e8232010-04-05 21:10:19 +00001349 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001350 return 0;
1351 }
1352
1353 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1354 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
Douglas Gregord03e8232010-04-05 21:10:19 +00001355 Diags->Report(diag::err_fe_expected_clang_command);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001356 return 0;
1357 }
1358
1359 const driver::ArgStringList &CCArgs = Cmd->getArguments();
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001360 llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
Dan Gohman145f3f12010-04-19 16:39:44 +00001361 CompilerInvocation::CreateFromArgs(*CI,
1362 const_cast<const char **>(CCArgs.data()),
1363 const_cast<const char **>(CCArgs.data()) +
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001364 CCArgs.size(),
Douglas Gregord03e8232010-04-05 21:10:19 +00001365 *Diags);
Daniel Dunbard6136772009-12-13 03:45:58 +00001366
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001367 // Override any files that need remapping
1368 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001369 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbar19511922010-02-16 01:55:04 +00001370 RemappedFiles[I].second);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001371
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001372 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001373 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001374
Daniel Dunbar19511922010-02-16 01:55:04 +00001375 CI->getFrontendOpts().DisableFree = true;
Douglas Gregor33cdd812010-02-18 18:08:43 +00001376 return LoadFromCompilerInvocation(CI.take(), Diags, OnlyLocalDecls,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001377 CaptureDiagnostics, PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001378 CompleteTranslationUnit,
1379 CacheCodeCompletionResults);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001380}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001381
1382bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1383 if (!Invocation.get())
1384 return true;
1385
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001386 llvm::Timer *ReparsingTimer = 0;
1387 if (TimerGroup.get()) {
1388 ReparsingTimer = new llvm::Timer("Reparse", *TimerGroup);
1389 ReparsingTimer->startTimer();
1390 Timers.push_back(ReparsingTimer);
1391 }
1392
Douglas Gregor0e119552010-07-31 00:40:00 +00001393 // Remap files.
Douglas Gregor0e119552010-07-31 00:40:00 +00001394 Invocation->getPreprocessorOpts().clearRemappedFiles();
1395 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1396 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1397 RemappedFiles[I].second);
1398
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001399 // If we have a preamble file lying around, or if we might try to
1400 // build a precompiled preamble, do so now.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001401 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001402 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregor028d3e42010-08-09 20:45:32 +00001403 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001404
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001405 // Clear out the diagnostics state.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001406 if (!OverrideMainBuffer)
1407 getDiagnostics().Reset();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001408
Douglas Gregor4dde7492010-07-23 23:58:40 +00001409 // Parse the sources
Douglas Gregor6481ef12010-07-24 00:38:13 +00001410 bool Result = Parse(OverrideMainBuffer);
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001411 if (ReparsingTimer)
1412 ReparsingTimer->stopTimer();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001413 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001414}
Douglas Gregor8e984da2010-08-04 16:47:14 +00001415
Douglas Gregorb14904c2010-08-13 22:48:40 +00001416//----------------------------------------------------------------------------//
1417// Code completion
1418//----------------------------------------------------------------------------//
1419
1420namespace {
1421 /// \brief Code completion consumer that combines the cached code-completion
1422 /// results from an ASTUnit with the code-completion results provided to it,
1423 /// then passes the result on to
1424 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1425 unsigned NormalContexts;
1426 ASTUnit &AST;
1427 CodeCompleteConsumer &Next;
1428
1429 public:
1430 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor39982192010-08-15 06:18:01 +00001431 bool IncludeMacros, bool IncludeCodePatterns,
1432 bool IncludeGlobals)
1433 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001434 Next.isOutputBinary()), AST(AST), Next(Next)
1435 {
1436 // Compute the set of contexts in which we will look when we don't have
1437 // any information about the specific context.
1438 NormalContexts
1439 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
1440 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
1441 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1442 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1443 | (1 << (CodeCompletionContext::CCC_Statement - 1))
1444 | (1 << (CodeCompletionContext::CCC_Expression - 1))
1445 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1446 | (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
1447 | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
1448
1449 if (AST.getASTContext().getLangOptions().CPlusPlus)
1450 NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1))
1451 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
1452 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
1453 }
1454
1455 virtual void ProcessCodeCompleteResults(Sema &S,
1456 CodeCompletionContext Context,
1457 Result *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001458 unsigned NumResults);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001459
1460 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1461 OverloadCandidate *Candidates,
1462 unsigned NumCandidates) {
1463 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1464 }
1465 };
1466}
Douglas Gregord46cf182010-08-16 20:01:48 +00001467
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001468/// \brief Helper function that computes which global names are hidden by the
1469/// local code-completion results.
1470void CalculateHiddenNames(const CodeCompletionContext &Context,
1471 CodeCompleteConsumer::Result *Results,
1472 unsigned NumResults,
1473 ASTContext &Ctx,
1474 llvm::StringSet<> &HiddenNames) {
1475 bool OnlyTagNames = false;
1476 switch (Context.getKind()) {
1477 case CodeCompletionContext::CCC_Other:
1478 case CodeCompletionContext::CCC_TopLevel:
1479 case CodeCompletionContext::CCC_ObjCInterface:
1480 case CodeCompletionContext::CCC_ObjCImplementation:
1481 case CodeCompletionContext::CCC_ObjCIvarList:
1482 case CodeCompletionContext::CCC_ClassStructUnion:
1483 case CodeCompletionContext::CCC_Statement:
1484 case CodeCompletionContext::CCC_Expression:
1485 case CodeCompletionContext::CCC_ObjCMessageReceiver:
1486 case CodeCompletionContext::CCC_MemberAccess:
1487 case CodeCompletionContext::CCC_Namespace:
1488 case CodeCompletionContext::CCC_Type:
1489 break;
1490
1491 case CodeCompletionContext::CCC_EnumTag:
1492 case CodeCompletionContext::CCC_UnionTag:
1493 case CodeCompletionContext::CCC_ClassOrStructTag:
1494 OnlyTagNames = true;
1495 break;
1496
1497 case CodeCompletionContext::CCC_ObjCProtocolName:
1498 // If we're just looking for protocol names, nothing can hide them.
1499 return;
1500 }
1501
1502 typedef CodeCompleteConsumer::Result Result;
1503 for (unsigned I = 0; I != NumResults; ++I) {
1504 if (Results[I].Kind != Result::RK_Declaration)
1505 continue;
1506
1507 unsigned IDNS
1508 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1509
1510 bool Hiding = false;
1511 if (OnlyTagNames)
1512 Hiding = (IDNS & Decl::IDNS_Tag);
1513 else {
1514 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00001515 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1516 Decl::IDNS_NonMemberOperator);
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001517 if (Ctx.getLangOptions().CPlusPlus)
1518 HiddenIDNS |= Decl::IDNS_Tag;
1519 Hiding = (IDNS & HiddenIDNS);
1520 }
1521
1522 if (!Hiding)
1523 continue;
1524
1525 DeclarationName Name = Results[I].Declaration->getDeclName();
1526 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1527 HiddenNames.insert(Identifier->getName());
1528 else
1529 HiddenNames.insert(Name.getAsString());
1530 }
1531}
1532
1533
Douglas Gregord46cf182010-08-16 20:01:48 +00001534void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1535 CodeCompletionContext Context,
1536 Result *Results,
1537 unsigned NumResults) {
1538 // Merge the results we were given with the results we cached.
1539 bool AddedResult = false;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001540 unsigned InContexts
1541 = (Context.getKind() == CodeCompletionContext::CCC_Other? NormalContexts
1542 : (1 << (Context.getKind() - 1)));
1543
1544 // Contains the set of names that are hidden by "local" completion results.
1545 llvm::StringSet<> HiddenNames;
1546
Douglas Gregord46cf182010-08-16 20:01:48 +00001547 typedef CodeCompleteConsumer::Result Result;
1548 llvm::SmallVector<Result, 8> AllResults;
1549 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00001550 C = AST.cached_completion_begin(),
1551 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00001552 C != CEnd; ++C) {
1553 // If the context we are in matches any of the contexts we are
1554 // interested in, we'll add this result.
1555 if ((C->ShowInContexts & InContexts) == 0)
1556 continue;
1557
1558 // If we haven't added any results previously, do so now.
1559 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001560 CalculateHiddenNames(Context, Results, NumResults, S.Context,
1561 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00001562 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1563 AddedResult = true;
1564 }
1565
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001566 // Determine whether this global completion result is hidden by a local
1567 // completion result. If so, skip it.
1568 if (C->Kind != CXCursor_MacroDefinition &&
1569 HiddenNames.count(C->Completion->getTypedText()))
1570 continue;
1571
Douglas Gregord46cf182010-08-16 20:01:48 +00001572 // Adjust priority based on similar type classes.
1573 unsigned Priority = C->Priority;
1574 if (!Context.getPreferredType().isNull()) {
1575 if (C->Kind == CXCursor_MacroDefinition) {
1576 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
1577 Context.getPreferredType()->isAnyPointerType());
1578 } else if (C->Type) {
1579 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00001580 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00001581 Context.getPreferredType().getUnqualifiedType());
1582 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
1583 if (ExpectedSTC == C->TypeClass) {
1584 // We know this type is similar; check for an exact match.
1585 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00001586 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00001587 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00001588 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00001589 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
1590 Priority /= CCF_ExactTypeMatch;
1591 else
1592 Priority /= CCF_SimilarTypeMatch;
1593 }
1594 }
1595 }
1596
1597 AllResults.push_back(Result(C->Completion, Priority, C->Kind));
1598 }
1599
1600 // If we did not add any cached completion results, just forward the
1601 // results we were given to the next consumer.
1602 if (!AddedResult) {
1603 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
1604 return;
1605 }
1606
1607 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
1608 AllResults.size());
1609}
1610
1611
1612
Douglas Gregor8e984da2010-08-04 16:47:14 +00001613void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
1614 RemappedFile *RemappedFiles,
1615 unsigned NumRemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00001616 bool IncludeMacros,
1617 bool IncludeCodePatterns,
Douglas Gregor8e984da2010-08-04 16:47:14 +00001618 CodeCompleteConsumer &Consumer,
1619 Diagnostic &Diag, LangOptions &LangOpts,
1620 SourceManager &SourceMgr, FileManager &FileMgr,
1621 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics) {
1622 if (!Invocation.get())
1623 return;
1624
Douglas Gregor028d3e42010-08-09 20:45:32 +00001625 llvm::Timer *CompletionTimer = 0;
1626 if (TimerGroup.get()) {
1627 llvm::SmallString<128> TimerName;
1628 llvm::raw_svector_ostream TimerNameOut(TimerName);
1629 TimerNameOut << "Code completion @ " << File << ":" << Line << ":"
1630 << Column;
1631 CompletionTimer = new llvm::Timer(TimerNameOut.str(), *TimerGroup);
1632 CompletionTimer->startTimer();
1633 Timers.push_back(CompletionTimer);
1634 }
1635
Douglas Gregor8e984da2010-08-04 16:47:14 +00001636 CompilerInvocation CCInvocation(*Invocation);
1637 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
1638 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00001639
Douglas Gregorb14904c2010-08-13 22:48:40 +00001640 FrontendOpts.ShowMacrosInCodeCompletion
1641 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorb68bc592010-08-05 09:09:23 +00001642 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor39982192010-08-15 06:18:01 +00001643 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
1644 = CachedCompletionResults.empty();
Douglas Gregor8e984da2010-08-04 16:47:14 +00001645 FrontendOpts.CodeCompletionAt.FileName = File;
1646 FrontendOpts.CodeCompletionAt.Line = Line;
1647 FrontendOpts.CodeCompletionAt.Column = Column;
1648
Douglas Gregorb68bc592010-08-05 09:09:23 +00001649 // Turn on spell-checking when performing code completion. It leads
1650 // to better results.
1651 unsigned SpellChecking = CCInvocation.getLangOpts().SpellChecking;
1652 CCInvocation.getLangOpts().SpellChecking = 1;
1653
Douglas Gregor8e984da2010-08-04 16:47:14 +00001654 // Set the language options appropriately.
1655 LangOpts = CCInvocation.getLangOpts();
1656
1657 CompilerInstance Clang;
1658 Clang.setInvocation(&CCInvocation);
1659 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1660
1661 // Set up diagnostics, capturing any diagnostics produced.
1662 Clang.setDiagnostics(&Diag);
1663 CaptureDroppedDiagnostics Capture(true,
1664 Clang.getDiagnostics(),
1665 StoredDiagnostics);
1666 Clang.setDiagnosticClient(Diag.getClient());
1667
1668 // Create the target instance.
1669 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1670 Clang.getTargetOpts()));
1671 if (!Clang.hasTarget()) {
1672 Clang.takeDiagnosticClient();
1673 Clang.takeInvocation();
1674 }
1675
1676 // Inform the target of the language options.
1677 //
1678 // FIXME: We shouldn't need to do this, the target should be immutable once
1679 // created. This complexity should be lifted elsewhere.
1680 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1681
1682 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1683 "Invocation must have exactly one source file!");
1684 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1685 "FIXME: AST inputs not yet supported here!");
1686 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1687 "IR inputs not support here!");
1688
1689
1690 // Use the source and file managers that we were given.
1691 Clang.setFileManager(&FileMgr);
1692 Clang.setSourceManager(&SourceMgr);
1693
1694 // Remap files.
1695 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00001696 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor8e984da2010-08-04 16:47:14 +00001697 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1698 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
1699 RemappedFiles[I].second);
1700
Douglas Gregorb14904c2010-08-13 22:48:40 +00001701 // Use the code completion consumer we were given, but adding any cached
1702 // code-completion results.
1703 AugmentedCodeCompleteConsumer
1704 AugmentedConsumer(*this, Consumer, FrontendOpts.ShowMacrosInCodeCompletion,
Douglas Gregor39982192010-08-15 06:18:01 +00001705 FrontendOpts.ShowCodePatternsInCodeCompletion,
1706 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001707 Clang.setCodeCompletionConsumer(&AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00001708
Douglas Gregor028d3e42010-08-09 20:45:32 +00001709 // If we have a precompiled preamble, try to use it. We only allow
1710 // the use of the precompiled preamble if we're if the completion
1711 // point is within the main file, after the end of the precompiled
1712 // preamble.
1713 llvm::MemoryBuffer *OverrideMainBuffer = 0;
1714 if (!PreambleFile.empty()) {
1715 using llvm::sys::FileStatus;
1716 llvm::sys::PathWithStatus CompleteFilePath(File);
1717 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
1718 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
1719 if (const FileStatus *MainStatus = MainPath.getFileStatus())
1720 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
1721 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(false,
1722 Line);
1723 }
1724
1725 // If the main file has been overridden due to the use of a preamble,
1726 // make that override happen and introduce the preamble.
1727 if (OverrideMainBuffer) {
1728 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1729 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1730 PreprocessorOpts.PrecompiledPreambleBytes.second
1731 = PreambleEndsAtStartOfLine;
1732 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
1733 PreprocessorOpts.DisablePCHValidation = true;
1734
1735 // The stored diagnostics have the old source manager. Copy them
1736 // to our output set of stored diagnostics, updating the source
1737 // manager to the one we were given.
1738 for (unsigned I = 0, N = this->StoredDiagnostics.size(); I != N; ++I) {
1739 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
1740 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
1741 StoredDiagnostics[I].setLocation(Loc);
1742 }
1743 }
1744
Douglas Gregor8e984da2010-08-04 16:47:14 +00001745 llvm::OwningPtr<SyntaxOnlyAction> Act;
1746 Act.reset(new SyntaxOnlyAction);
1747 if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1748 Clang.getFrontendOpts().Inputs[0].first)) {
1749 Act->Execute();
1750 Act->EndSourceFile();
1751 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001752
1753 if (CompletionTimer)
1754 CompletionTimer->stopTimer();
Douglas Gregor8e984da2010-08-04 16:47:14 +00001755
1756 // Steal back our resources.
Douglas Gregor028d3e42010-08-09 20:45:32 +00001757 delete OverrideMainBuffer;
Douglas Gregor8e984da2010-08-04 16:47:14 +00001758 Clang.takeFileManager();
1759 Clang.takeSourceManager();
1760 Clang.takeInvocation();
1761 Clang.takeDiagnosticClient();
1762 Clang.takeCodeCompletionConsumer();
Douglas Gregorb68bc592010-08-05 09:09:23 +00001763 CCInvocation.getLangOpts().SpellChecking = SpellChecking;
Douglas Gregor8e984da2010-08-04 16:47:14 +00001764}
Douglas Gregore9386682010-08-13 05:36:37 +00001765
1766bool ASTUnit::Save(llvm::StringRef File) {
1767 if (getDiagnostics().hasErrorOccurred())
1768 return true;
1769
1770 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
1771 // unconditionally create a stat cache when we parse the file?
1772 std::string ErrorInfo;
Benjamin Kramer340045b2010-08-15 16:54:31 +00001773 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo,
1774 llvm::raw_fd_ostream::F_Binary);
Douglas Gregore9386682010-08-13 05:36:37 +00001775 if (!ErrorInfo.empty() || Out.has_error())
1776 return true;
1777
1778 std::vector<unsigned char> Buffer;
1779 llvm::BitstreamWriter Stream(Buffer);
1780 PCHWriter Writer(Stream);
1781 Writer.WritePCH(getSema(), 0, 0);
1782
1783 // Write the generated bitstream to "Out".
1784 Out.write((char *)&Buffer.front(), Buffer.size());
Douglas Gregore9386682010-08-13 05:36:37 +00001785 Out.close();
1786 return Out.has_error();
1787}