blob: 4395246f49324c213ed9222803cf00e11056d18a [file] [log] [blame]
Argyrios Kyrtzidis3a08ec12009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000015#include "clang/AST/ASTContext.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000016#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
Douglas Gregorb61c07a2010-08-16 18:08:11 +000018#include "clang/AST/TypeOrdering.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000019#include "clang/AST/StmtVisitor.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000020#include "clang/Driver/Compilation.h"
21#include "clang/Driver/Driver.h"
22#include "clang/Driver/Job.h"
23#include "clang/Driver/Tool.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000024#include "clang/Frontend/CompilerInstance.h"
25#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000026#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000027#include "clang/Frontend/FrontendOptions.h"
Sebastian Redlf5b13462010-08-18 23:57:17 +000028#include "clang/Serialization/ASTReader.h"
Sebastian Redl1914c6f2010-08-18 23:56:37 +000029#include "clang/Serialization/ASTWriter.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 Gregor40a5a7d2010-08-16 23:08:34 +000035#include "llvm/ADT/StringSet.h"
Douglas Gregoraa98ed92010-01-23 00:14:00 +000036#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000037#include "llvm/System/Host.h"
Benjamin Kramer6c839f82009-10-18 11:34:14 +000038#include "llvm/System/Path.h"
Douglas Gregor028d3e42010-08-09 20:45:32 +000039#include "llvm/Support/raw_ostream.h"
Douglas Gregor15ba0b32010-07-30 20:58:08 +000040#include "llvm/Support/Timer.h"
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000041#include <cstdlib>
Zhongxing Xu318e4032010-07-23 02:15:08 +000042#include <cstdio>
Douglas Gregor0e119552010-07-31 00:40:00 +000043#include <sys/stat.h>
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000044using namespace clang;
45
Douglas Gregorbb420ab2010-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 Gregord03e8232010-04-05 21:10:19 +000052ASTUnit::ASTUnit(bool _MainFileIsAST)
Douglas Gregoraa21cc42010-07-19 21:46:24 +000053 : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
Douglas Gregor028d3e42010-08-09 20:45:32 +000054 CompleteTranslationUnit(true), ConcurrencyCheckValue(CheckUnlocked),
Douglas Gregora0734c52010-08-19 01:33:06 +000055 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +000056 ShouldCacheCodeCompletionResults(false),
57 NumTopLevelDeclsAtLastCompletionCache(0),
Douglas Gregor4740c452010-08-19 00:45:44 +000058 CacheCodeCompletionCoolDown(0),
59 UnsafeToFree(false) {
Douglas Gregor15ba0b32010-07-30 20:58:08 +000060}
Douglas Gregord03e8232010-04-05 21:10:19 +000061
Daniel Dunbar764c0822009-12-01 09:51:01 +000062ASTUnit::~ASTUnit() {
Douglas Gregor0c7c2f82010-03-05 21:16:25 +000063 ConcurrencyCheckValue = CheckLocked;
Douglas Gregoraa21cc42010-07-19 21:46:24 +000064 CleanTemporaryFiles();
Douglas Gregor4dde7492010-07-23 23:58:40 +000065 if (!PreambleFile.empty())
Douglas Gregor15ba0b32010-07-30 20:58:08 +000066 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor3f4bea02010-07-26 21:36:20 +000067
68 // Free the buffers associated with remapped files. We are required to
69 // perform this operation here because we explicitly request that the
70 // compiler instance *not* free these buffers for each invocation of the
71 // parser.
72 if (Invocation.get()) {
73 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
74 for (PreprocessorOptions::remapped_file_buffer_iterator
75 FB = PPOpts.remapped_file_buffer_begin(),
76 FBEnd = PPOpts.remapped_file_buffer_end();
77 FB != FBEnd;
78 ++FB)
79 delete FB->second;
80 }
Douglas Gregor96c04262010-07-27 14:52:07 +000081
82 delete SavedMainFileBuffer;
Douglas Gregora0734c52010-08-19 01:33:06 +000083 delete PreambleBuffer;
84
Douglas Gregorb14904c2010-08-13 22:48:40 +000085 ClearCachedCompletionResults();
86
Douglas Gregor15ba0b32010-07-30 20:58:08 +000087 for (unsigned I = 0, N = Timers.size(); I != N; ++I)
88 delete Timers[I];
Douglas Gregoraa21cc42010-07-19 21:46:24 +000089}
90
91void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor6cb5ba42010-02-18 23:35:40 +000092 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
93 TemporaryFiles[I].eraseFromDisk();
Douglas Gregoraa21cc42010-07-19 21:46:24 +000094 TemporaryFiles.clear();
Steve Naroff44cd60e2009-10-15 22:23:48 +000095}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000096
Douglas Gregor39982192010-08-15 06:18:01 +000097/// \brief Determine the set of code-completion contexts in which this
98/// declaration should be shown.
99static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000100 const LangOptions &LangOpts,
101 bool &IsNestedNameSpecifier) {
102 IsNestedNameSpecifier = false;
103
Douglas Gregor39982192010-08-15 06:18:01 +0000104 if (isa<UsingShadowDecl>(ND))
105 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
106 if (!ND)
107 return 0;
108
109 unsigned Contexts = 0;
110 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
111 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
112 // Types can appear in these contexts.
113 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
114 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
115 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
116 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
117 | (1 << (CodeCompletionContext::CCC_Statement - 1))
118 | (1 << (CodeCompletionContext::CCC_Type - 1));
119
120 // In C++, types can appear in expressions contexts (for functional casts).
121 if (LangOpts.CPlusPlus)
122 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
123
124 // In Objective-C, message sends can send interfaces. In Objective-C++,
125 // all types are available due to functional casts.
126 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
127 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
128
129 // Deal with tag names.
130 if (isa<EnumDecl>(ND)) {
131 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
132
Douglas Gregor59cab552010-08-16 23:05:20 +0000133 // Part of the nested-name-specifier in C++0x.
Douglas Gregor39982192010-08-15 06:18:01 +0000134 if (LangOpts.CPlusPlus0x)
Douglas Gregor59cab552010-08-16 23:05:20 +0000135 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000136 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
137 if (Record->isUnion())
138 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
139 else
140 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
141
Douglas Gregor39982192010-08-15 06:18:01 +0000142 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000143 IsNestedNameSpecifier = true;
144 } else if (isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND))
145 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000146 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
147 // Values can appear in these contexts.
148 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
149 | (1 << (CodeCompletionContext::CCC_Expression - 1))
150 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
151 } else if (isa<ObjCProtocolDecl>(ND)) {
152 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
153 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregor59cab552010-08-16 23:05:20 +0000154 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000155
156 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000157 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000158 }
159
160 return Contexts;
161}
162
Douglas Gregorb14904c2010-08-13 22:48:40 +0000163void ASTUnit::CacheCodeCompletionResults() {
164 if (!TheSema)
165 return;
166
167 llvm::Timer *CachingTimer = 0;
168 if (TimerGroup.get()) {
169 CachingTimer = new llvm::Timer("Cache global code completions",
170 *TimerGroup);
171 CachingTimer->startTimer();
172 Timers.push_back(CachingTimer);
173 }
174
175 // Clear out the previous results.
176 ClearCachedCompletionResults();
177
178 // Gather the set of global code completions.
179 typedef CodeCompleteConsumer::Result Result;
180 llvm::SmallVector<Result, 8> Results;
181 TheSema->GatherGlobalCodeCompletions(Results);
182
183 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000184 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
185
Douglas Gregorb14904c2010-08-13 22:48:40 +0000186 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
187 switch (Results[I].Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000188 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000189 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000190 CachedCodeCompletionResult CachedResult;
191 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
192 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregor59cab552010-08-16 23:05:20 +0000193 Ctx->getLangOptions(),
194 IsNestedNameSpecifier);
Douglas Gregor39982192010-08-15 06:18:01 +0000195 CachedResult.Priority = Results[I].Priority;
196 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor24747402010-08-16 16:46:30 +0000197
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000198 // Keep track of the type of this completion in an ASTContext-agnostic
199 // way.
Douglas Gregor24747402010-08-16 16:46:30 +0000200 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000201 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000202 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000203 CachedResult.Type = 0;
204 } else {
205 CanQualType CanUsageType
206 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
207 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
208
209 // Determine whether we have already seen this type. If so, we save
210 // ourselves the work of formatting the type string by using the
211 // temporary, CanQualType-based hash table to find the associated value.
212 unsigned &TypeValue = CompletionTypes[CanUsageType];
213 if (TypeValue == 0) {
214 TypeValue = CompletionTypes.size();
215 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
216 = TypeValue;
217 }
218
219 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000220 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000221
Douglas Gregor39982192010-08-15 06:18:01 +0000222 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000223
224 /// Handle nested-name-specifiers in C++.
225 if (TheSema->Context.getLangOptions().CPlusPlus &&
226 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
227 // The contexts in which a nested-name-specifier can appear in C++.
228 unsigned NNSContexts
229 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
230 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
231 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
232 | (1 << (CodeCompletionContext::CCC_Statement - 1))
233 | (1 << (CodeCompletionContext::CCC_Expression - 1))
234 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
235 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
236 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
237 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
238 | (1 << (CodeCompletionContext::CCC_Type - 1));
239
240 if (isa<NamespaceDecl>(Results[I].Declaration) ||
241 isa<NamespaceAliasDecl>(Results[I].Declaration))
242 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
243
244 if (unsigned RemainingContexts
245 = NNSContexts & ~CachedResult.ShowInContexts) {
246 // If there any contexts where this completion can be a
247 // nested-name-specifier but isn't already an option, create a
248 // nested-name-specifier completion.
249 Results[I].StartsNestedNameSpecifier = true;
250 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
251 CachedResult.ShowInContexts = RemainingContexts;
252 CachedResult.Priority = CCP_NestedNameSpecifier;
253 CachedResult.TypeClass = STC_Void;
254 CachedResult.Type = 0;
255 CachedCompletionResults.push_back(CachedResult);
256 }
257 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000258 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000259 }
260
Douglas Gregorb14904c2010-08-13 22:48:40 +0000261 case Result::RK_Keyword:
262 case Result::RK_Pattern:
263 // Ignore keywords and patterns; we don't care, since they are so
264 // easily regenerated.
265 break;
266
267 case Result::RK_Macro: {
268 CachedCodeCompletionResult CachedResult;
269 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
270 CachedResult.ShowInContexts
271 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
272 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
273 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
274 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
275 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
276 | (1 << (CodeCompletionContext::CCC_Statement - 1))
277 | (1 << (CodeCompletionContext::CCC_Expression - 1))
278 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
279 CachedResult.Priority = Results[I].Priority;
280 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor6e240332010-08-16 16:18:59 +0000281 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000282 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000283 CachedCompletionResults.push_back(CachedResult);
284 break;
285 }
286 }
287 Results[I].Destroy();
288 }
289
290 if (CachingTimer)
291 CachingTimer->stopTimer();
Douglas Gregor2c8bd472010-08-17 00:40:40 +0000292
293 // Make a note of the state when we performed this caching.
294 NumTopLevelDeclsAtLastCompletionCache = top_level_size();
295 CacheCodeCompletionCoolDown = 15;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000296}
297
298void ASTUnit::ClearCachedCompletionResults() {
299 for (unsigned I = 0, N = CachedCompletionResults.size(); I != N; ++I)
300 delete CachedCompletionResults[I].Completion;
301 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000302 CachedCompletionTypes.clear();
Douglas Gregorb14904c2010-08-13 22:48:40 +0000303}
304
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000305namespace {
306
Sebastian Redl2c499f62010-08-18 23:56:43 +0000307/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000308/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000309class ASTInfoCollector : public ASTReaderListener {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000310 LangOptions &LangOpt;
311 HeaderSearch &HSI;
312 std::string &TargetTriple;
313 std::string &Predefines;
314 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000315
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000316 unsigned NumHeaderInfos;
Mike Stump11289f42009-09-09 15:08:12 +0000317
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000318public:
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000319 ASTInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000320 std::string &TargetTriple, std::string &Predefines,
321 unsigned &Counter)
322 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
323 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump11289f42009-09-09 15:08:12 +0000324
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000325 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
326 LangOpt = LangOpts;
327 return false;
328 }
Mike Stump11289f42009-09-09 15:08:12 +0000329
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000330 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000331 TargetTriple = Triple;
332 return false;
333 }
Mike Stump11289f42009-09-09 15:08:12 +0000334
Sebastian Redl8b41f302010-07-14 23:29:55 +0000335 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000336 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000337 std::string &SuggestedPredefines) {
Sebastian Redl8b41f302010-07-14 23:29:55 +0000338 Predefines = Buffers[0].Data;
339 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
340 Predefines += Buffers[I].Data;
341 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000342 return false;
343 }
Mike Stump11289f42009-09-09 15:08:12 +0000344
Douglas Gregora2f49452010-03-16 19:09:18 +0000345 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000346 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
347 }
Mike Stump11289f42009-09-09 15:08:12 +0000348
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000349 virtual void ReadCounter(unsigned Value) {
350 Counter = Value;
351 }
352};
353
Douglas Gregor33cdd812010-02-18 18:08:43 +0000354class StoredDiagnosticClient : public DiagnosticClient {
355 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
356
357public:
358 explicit StoredDiagnosticClient(
359 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
360 : StoredDiags(StoredDiags) { }
361
362 virtual void HandleDiagnostic(Diagnostic::Level Level,
363 const DiagnosticInfo &Info);
364};
365
366/// \brief RAII object that optionally captures diagnostics, if
367/// there is no diagnostic client to capture them already.
368class CaptureDroppedDiagnostics {
369 Diagnostic &Diags;
370 StoredDiagnosticClient Client;
371 DiagnosticClient *PreviousClient;
372
373public:
374 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
375 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000376 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000377 {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000378 if (RequestCapture || Diags.getClient() == 0) {
379 PreviousClient = Diags.takeClient();
Douglas Gregor33cdd812010-02-18 18:08:43 +0000380 Diags.setClient(&Client);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000381 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000382 }
383
384 ~CaptureDroppedDiagnostics() {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000385 if (Diags.getClient() == &Client) {
386 Diags.takeClient();
387 Diags.setClient(PreviousClient);
388 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000389 }
390};
391
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000392} // anonymous namespace
393
Douglas Gregor33cdd812010-02-18 18:08:43 +0000394void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
395 const DiagnosticInfo &Info) {
396 StoredDiags.push_back(StoredDiagnostic(Level, Info));
397}
398
Steve Naroffc0683b92009-09-03 18:19:54 +0000399const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbara8a50932009-12-02 08:44:16 +0000400 return OriginalSourceFile;
Steve Naroffc0683b92009-09-03 18:19:54 +0000401}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000402
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000403const std::string &ASTUnit::getASTFileName() {
404 assert(isMainFileAST() && "Not an ASTUnit from an AST file!");
Sebastian Redl2c499f62010-08-18 23:56:43 +0000405 return static_cast<ASTReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroff44cd60e2009-10-15 22:23:48 +0000406}
407
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000408ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Douglas Gregor7f95d262010-04-05 23:52:57 +0000409 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Ted Kremenek8bcb1c62009-10-17 00:34:24 +0000410 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000411 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +0000412 unsigned NumRemappedFiles,
413 bool CaptureDiagnostics) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000414 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
415
Douglas Gregor7f95d262010-04-05 23:52:57 +0000416 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000417 // No diagnostics engine was provided, so create our own diagnostics object
418 // with the default options.
419 DiagnosticOptions DiagOpts;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000420 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregord03e8232010-04-05 21:10:19 +0000421 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000422
423 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor16bef852009-10-16 20:01:17 +0000424 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000425 AST->Diagnostics = Diags;
Douglas Gregord03e8232010-04-05 21:10:19 +0000426 AST->FileMgr.reset(new FileManager);
427 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics()));
Steve Naroff505fb842009-10-19 14:34:22 +0000428 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000429
Douglas Gregor33cdd812010-02-18 18:08:43 +0000430 // If requested, capture diagnostics in the ASTUnit.
Douglas Gregord03e8232010-04-05 21:10:19 +0000431 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, AST->getDiagnostics(),
Douglas Gregora2433152010-04-05 18:10:21 +0000432 AST->StoredDiagnostics);
Douglas Gregor33cdd812010-02-18 18:08:43 +0000433
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000434 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
435 // Create the file entry for the file that we're mapping from.
436 const FileEntry *FromFile
437 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
438 RemappedFiles[I].second->getBufferSize(),
439 0);
440 if (!FromFile) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000441 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000442 << RemappedFiles[I].first;
Douglas Gregor89a56c52010-02-27 01:32:48 +0000443 delete RemappedFiles[I].second;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000444 continue;
445 }
446
447 // Override the contents of the "from" file with the contents of
448 // the "to" file.
449 AST->getSourceManager().overrideFileContents(FromFile,
450 RemappedFiles[I].second);
451 }
452
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000453 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000454
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000455 LangOptions LangInfo;
456 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
457 std::string TargetTriple;
458 std::string Predefines;
459 unsigned Counter;
460
Sebastian Redl2c499f62010-08-18 23:56:43 +0000461 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000462
Sebastian Redl2c499f62010-08-18 23:56:43 +0000463 Reader.reset(new ASTReader(AST->getSourceManager(), AST->getFileManager(),
Douglas Gregord03e8232010-04-05 21:10:19 +0000464 AST->getDiagnostics()));
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000465 Reader->setListener(new ASTInfoCollector(LangInfo, HeaderInfo, TargetTriple,
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000466 Predefines, Counter));
467
Sebastian Redl3e31c722010-08-18 23:56:56 +0000468 switch (Reader->ReadAST(Filename)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000469 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000470 break;
Mike Stump11289f42009-09-09 15:08:12 +0000471
Sebastian Redl2c499f62010-08-18 23:56:43 +0000472 case ASTReader::Failure:
473 case ASTReader::IgnorePCH:
Douglas Gregord03e8232010-04-05 21:10:19 +0000474 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000475 return NULL;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000476 }
Mike Stump11289f42009-09-09 15:08:12 +0000477
Daniel Dunbara8a50932009-12-02 08:44:16 +0000478 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
479
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000480 // AST file loaded successfully. Now create the preprocessor.
Mike Stump11289f42009-09-09 15:08:12 +0000481
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000482 // Get information about the target being compiled for.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000483 //
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000484 // FIXME: This is broken, we should store the TargetOptions in the AST file.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000485 TargetOptions TargetOpts;
486 TargetOpts.ABI = "";
Charles Davis95a546e2010-06-11 01:06:47 +0000487 TargetOpts.CXXABI = "itanium";
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000488 TargetOpts.CPU = "";
489 TargetOpts.Features.clear();
490 TargetOpts.Triple = TargetTriple;
Douglas Gregord03e8232010-04-05 21:10:19 +0000491 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
492 TargetOpts));
493 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
494 *AST->Target.get(),
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000495 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000496 Preprocessor &PP = *AST->PP.get();
497
Daniel Dunbarb7bbfdd2009-09-21 03:03:47 +0000498 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000499 PP.setCounterValue(Counter);
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000500 Reader->setPreprocessor(PP);
Mike Stump11289f42009-09-09 15:08:12 +0000501
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000502 // Create and initialize the ASTContext.
503
504 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000505 AST->getSourceManager(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000506 *AST->Target.get(),
507 PP.getIdentifierTable(),
508 PP.getSelectorTable(),
509 PP.getBuiltinInfo(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000510 /* size_reserve = */0));
511 ASTContext &Context = *AST->Ctx.get();
Mike Stump11289f42009-09-09 15:08:12 +0000512
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000513 Reader->InitializeContext(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000514
Sebastian Redl2c499f62010-08-18 23:56:43 +0000515 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000516 // source, so that declarations will be deserialized from the
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000517 // AST file as needed.
Sebastian Redl2c499f62010-08-18 23:56:43 +0000518 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000519 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000520 Context.setExternalSource(Source);
521
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000522 // Create an AST consumer, even though it isn't used.
523 AST->Consumer.reset(new ASTConsumer);
524
Sebastian Redl2c499f62010-08-18 23:56:43 +0000525 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000526 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
527 AST->TheSema->Initialize();
528 ReaderPtr->InitializeSema(*AST->TheSema);
529
Mike Stump11289f42009-09-09 15:08:12 +0000530 return AST.take();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000531}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000532
533namespace {
534
Daniel Dunbar644dca02009-12-04 08:17:33 +0000535class TopLevelDeclTrackerConsumer : public ASTConsumer {
536 ASTUnit &Unit;
537
538public:
539 TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {}
540
541 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekacc59c32010-05-03 20:16:35 +0000542 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
543 Decl *D = *it;
544 // FIXME: Currently ObjC method declarations are incorrectly being
545 // reported as top-level declarations, even though their DeclContext
546 // is the containing ObjC @interface/@implementation. This is a
547 // fundamental problem in the parser right now.
548 if (isa<ObjCMethodDecl>(D))
549 continue;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000550 Unit.addTopLevelDecl(D);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000551 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000552 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000553
554 // We're not interested in "interesting" decls.
555 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbar644dca02009-12-04 08:17:33 +0000556};
557
558class TopLevelDeclTrackerAction : public ASTFrontendAction {
559public:
560 ASTUnit &Unit;
561
Daniel Dunbar764c0822009-12-01 09:51:01 +0000562 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
563 llvm::StringRef InFile) {
Daniel Dunbar644dca02009-12-04 08:17:33 +0000564 return new TopLevelDeclTrackerConsumer(Unit);
Daniel Dunbar764c0822009-12-01 09:51:01 +0000565 }
566
567public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000568 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
569
Daniel Dunbar764c0822009-12-01 09:51:01 +0000570 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000571 virtual bool usesCompleteTranslationUnit() {
572 return Unit.isCompleteTranslationUnit();
573 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000574};
575
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000576class PrecompilePreambleConsumer : public PCHGenerator {
577 ASTUnit &Unit;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000578 std::vector<Decl *> TopLevelDecls;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000579
580public:
581 PrecompilePreambleConsumer(ASTUnit &Unit,
582 const Preprocessor &PP, bool Chaining,
583 const char *isysroot, llvm::raw_ostream *Out)
584 : PCHGenerator(PP, Chaining, isysroot, Out), Unit(Unit) { }
585
Douglas Gregore9db88f2010-08-03 19:06:41 +0000586 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000587 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
588 Decl *D = *it;
589 // FIXME: Currently ObjC method declarations are incorrectly being
590 // reported as top-level declarations, even though their DeclContext
591 // is the containing ObjC @interface/@implementation. This is a
592 // fundamental problem in the parser right now.
593 if (isa<ObjCMethodDecl>(D))
594 continue;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000595 TopLevelDecls.push_back(D);
596 }
597 }
598
599 virtual void HandleTranslationUnit(ASTContext &Ctx) {
600 PCHGenerator::HandleTranslationUnit(Ctx);
601 if (!Unit.getDiagnostics().hasErrorOccurred()) {
602 // Translate the top-level declarations we captured during
603 // parsing into declaration IDs in the precompiled
604 // preamble. This will allow us to deserialize those top-level
605 // declarations when requested.
606 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
607 Unit.addTopLevelDeclFromPreamble(
608 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000609 }
610 }
611};
612
613class PrecompilePreambleAction : public ASTFrontendAction {
614 ASTUnit &Unit;
615
616public:
617 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
618
619 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
620 llvm::StringRef InFile) {
621 std::string Sysroot;
622 llvm::raw_ostream *OS = 0;
623 bool Chaining;
624 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
625 OS, Chaining))
626 return 0;
627
628 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
629 Sysroot.c_str() : 0;
630 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
631 isysroot, OS);
632 }
633
634 virtual bool hasCodeCompletionSupport() const { return false; }
635 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000636 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000637};
638
Daniel Dunbar764c0822009-12-01 09:51:01 +0000639}
640
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000641/// Parse the source file into a translation unit using the given compiler
642/// invocation, replacing the current translation unit.
643///
644/// \returns True if a failure occurred that causes the ASTUnit not to
645/// contain any translation-unit information, false otherwise.
Douglas Gregor6481ef12010-07-24 00:38:13 +0000646bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor96c04262010-07-27 14:52:07 +0000647 delete SavedMainFileBuffer;
648 SavedMainFileBuffer = 0;
649
Douglas Gregora0734c52010-08-19 01:33:06 +0000650 if (!Invocation.get()) {
651 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000652 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000653 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000654
Daniel Dunbar764c0822009-12-01 09:51:01 +0000655 // Create the compiler instance to use for building the AST.
Daniel Dunbar7afbb8c2009-12-02 08:43:56 +0000656 CompilerInstance Clang;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000657 Clang.setInvocation(Invocation.take());
658 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
659
Douglas Gregor8e984da2010-08-04 16:47:14 +0000660 // Set up diagnostics, capturing any diagnostics that would
661 // otherwise be dropped.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000662 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor8e984da2010-08-04 16:47:14 +0000663 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
664 getDiagnostics(),
665 StoredDiagnostics);
Douglas Gregord03e8232010-04-05 21:10:19 +0000666
Daniel Dunbar764c0822009-12-01 09:51:01 +0000667 // Create the target instance.
668 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
669 Clang.getTargetOpts()));
Douglas Gregora0734c52010-08-19 01:33:06 +0000670 if (!Clang.hasTarget()) {
671 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000672 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000673 }
674
Daniel Dunbar764c0822009-12-01 09:51:01 +0000675 // Inform the target of the language options.
676 //
677 // FIXME: We shouldn't need to do this, the target should be immutable once
678 // created. This complexity should be lifted elsewhere.
679 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000680
Daniel Dunbar764c0822009-12-01 09:51:01 +0000681 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
682 "Invocation must have exactly one source file!");
Daniel Dunbar9b491e72010-06-07 23:22:09 +0000683 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +0000684 "FIXME: AST inputs not yet supported here!");
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000685 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
686 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +0000687
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000688 // Configure the various subsystems.
689 // FIXME: Should we retain the previous file manager?
690 FileMgr.reset(new FileManager);
691 SourceMgr.reset(new SourceManager(getDiagnostics()));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000692 TheSema.reset();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000693 Ctx.reset();
694 PP.reset();
695
696 // Clear out old caches and data.
697 TopLevelDecls.clear();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000698 CleanTemporaryFiles();
699 PreprocessedEntitiesByFile.clear();
Douglas Gregord9a30af2010-08-02 20:51:39 +0000700
701 if (!OverrideMainBuffer)
702 StoredDiagnostics.clear();
Douglas Gregor8e984da2010-08-04 16:47:14 +0000703
Daniel Dunbar764c0822009-12-01 09:51:01 +0000704 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000705 Clang.setFileManager(&getFileManager());
706
Daniel Dunbar764c0822009-12-01 09:51:01 +0000707 // Create the source manager.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000708 Clang.setSourceManager(&getSourceManager());
709
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000710 // If the main file has been overridden due to the use of a preamble,
711 // make that override happen and introduce the preamble.
712 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +0000713 std::string PriorImplicitPCHInclude;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000714 if (OverrideMainBuffer) {
715 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
716 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
717 PreprocessorOpts.PrecompiledPreambleBytes.second
718 = PreambleEndsAtStartOfLine;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000719 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000720 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000721 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +0000722
723 // Keep track of the override buffer;
724 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregord9a30af2010-08-02 20:51:39 +0000725
726 // The stored diagnostic has the old source manager in it; update
727 // the locations to refer into the new source manager. Since we've
728 // been careful to make sure that the source manager's state
729 // before and after are identical, so that we can reuse the source
730 // location itself.
731 for (unsigned I = 0, N = StoredDiagnostics.size(); I != N; ++I) {
732 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
733 getSourceManager());
734 StoredDiagnostics[I].setLocation(Loc);
735 }
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000736 }
737
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000738 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
739 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbar644dca02009-12-04 08:17:33 +0000740 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbar86546382010-06-07 23:23:06 +0000741 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar764c0822009-12-01 09:51:01 +0000742 goto error;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000743
Daniel Dunbar644dca02009-12-04 08:17:33 +0000744 Act->Execute();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000745
Daniel Dunbard2f8be32009-12-01 21:57:33 +0000746 // Steal the created target, context, and preprocessor, and take back the
747 // source and file managers.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000748 TheSema.reset(Clang.takeSema());
749 Consumer.reset(Clang.takeASTConsumer());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000750 Ctx.reset(Clang.takeASTContext());
751 PP.reset(Clang.takePreprocessor());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000752 Clang.takeSourceManager();
753 Clang.takeFileManager();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000754 Target.reset(Clang.takeTarget());
755
Daniel Dunbar644dca02009-12-04 08:17:33 +0000756 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000757
758 // Remove the overridden buffer we used for the preamble.
Douglas Gregor8e984da2010-08-04 16:47:14 +0000759 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000760 PreprocessorOpts.eraseRemappedFile(
761 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor8e984da2010-08-04 16:47:14 +0000762 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
763 }
764
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000765 Invocation.reset(Clang.takeInvocation());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000766
767 // If we were asked to cache code-completion results and don't have any
768 // results yet, do so now.
769 if (ShouldCacheCodeCompletionResults && CachedCompletionResults.empty())
770 CacheCodeCompletionResults();
771
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000772 return false;
773
Daniel Dunbar764c0822009-12-01 09:51:01 +0000774error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000775 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +0000776 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000777 PreprocessorOpts.eraseRemappedFile(
778 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregorce3a8292010-07-27 00:27:13 +0000779 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000780 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregora0734c52010-08-19 01:33:06 +0000781 delete OverrideMainBuffer;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000782 }
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000783
Daniel Dunbar764c0822009-12-01 09:51:01 +0000784 Clang.takeSourceManager();
785 Clang.takeFileManager();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000786 Invocation.reset(Clang.takeInvocation());
787 return true;
788}
789
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000790/// \brief Simple function to retrieve a path for a preamble precompiled header.
791static std::string GetPreamblePCHPath() {
792 // FIXME: This is lame; sys::Path should provide this function (in particular,
793 // it should know how to find the temporary files dir).
794 // FIXME: This is really lame. I copied this code from the Driver!
795 std::string Error;
796 const char *TmpDir = ::getenv("TMPDIR");
797 if (!TmpDir)
798 TmpDir = ::getenv("TEMP");
799 if (!TmpDir)
800 TmpDir = ::getenv("TMP");
801 if (!TmpDir)
802 TmpDir = "/tmp";
803 llvm::sys::Path P(TmpDir);
804 P.appendComponent("preamble");
Douglas Gregor20975b22010-08-11 13:06:56 +0000805 P.appendSuffix("pch");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000806 if (P.createTemporaryFileOnDisk())
807 return std::string();
808
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000809 return P.str();
810}
811
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000812/// \brief Compute the preamble for the main file, providing the source buffer
813/// that corresponds to the main file along with a pair (bytes, start-of-line)
814/// that describes the preamble.
815std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor028d3e42010-08-09 20:45:32 +0000816ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
817 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000818 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000819 PreprocessorOptions &PreprocessorOpts
Douglas Gregor4dde7492010-07-23 23:58:40 +0000820 = Invocation.getPreprocessorOpts();
821 CreatedBuffer = false;
822
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000823 // Try to determine if the main file has been remapped, either from the
824 // command line (to another file) or directly through the compiler invocation
825 // (to a memory buffer).
Douglas Gregor4dde7492010-07-23 23:58:40 +0000826 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000827 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
828 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
829 // Check whether there is a file-file remapping of the main file
830 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor4dde7492010-07-23 23:58:40 +0000831 M = PreprocessorOpts.remapped_file_begin(),
832 E = PreprocessorOpts.remapped_file_end();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000833 M != E;
834 ++M) {
835 llvm::sys::PathWithStatus MPath(M->first);
836 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
837 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
838 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000839 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000840 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000841 CreatedBuffer = false;
842 }
843
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000844 Buffer = llvm::MemoryBuffer::getFile(M->second);
845 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000846 return std::make_pair((llvm::MemoryBuffer*)0,
847 std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000848 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000849
Douglas Gregor4dde7492010-07-23 23:58:40 +0000850 // Remove this remapping. We've captured the buffer already.
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000851 M = PreprocessorOpts.eraseRemappedFile(M);
852 E = PreprocessorOpts.remapped_file_end();
Daniel Dunbar438c7722010-08-19 19:40:40 +0000853 if (M == E)
854 break;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000855 }
856 }
857 }
858
859 // Check whether there is a file-buffer remapping. It supercedes the
860 // file-file remapping.
861 for (PreprocessorOptions::remapped_file_buffer_iterator
862 M = PreprocessorOpts.remapped_file_buffer_begin(),
863 E = PreprocessorOpts.remapped_file_buffer_end();
864 M != E;
865 ++M) {
866 llvm::sys::PathWithStatus MPath(M->first);
867 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
868 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
869 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000870 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000871 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000872 CreatedBuffer = false;
873 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000874
Douglas Gregor4dde7492010-07-23 23:58:40 +0000875 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
876
877 // Remove this remapping. We've captured the buffer already.
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000878 M = PreprocessorOpts.eraseRemappedFile(M);
879 E = PreprocessorOpts.remapped_file_buffer_end();
Daniel Dunbar438c7722010-08-19 19:40:40 +0000880 if (M == E)
881 break;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000882 }
883 }
Douglas Gregor4dde7492010-07-23 23:58:40 +0000884 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000885 }
886
887 // If the main source file was not remapped, load it now.
888 if (!Buffer) {
889 Buffer = llvm::MemoryBuffer::getFile(FrontendOpts.Inputs[0].second);
890 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000891 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000892
893 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000894 }
895
Douglas Gregor028d3e42010-08-09 20:45:32 +0000896 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000897}
898
Douglas Gregor6481ef12010-07-24 00:38:13 +0000899static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
900 bool DeleteOld,
901 unsigned NewSize,
902 llvm::StringRef NewName) {
903 llvm::MemoryBuffer *Result
904 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
905 memcpy(const_cast<char*>(Result->getBufferStart()),
906 Old->getBufferStart(), Old->getBufferSize());
907 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000908 ' ', NewSize - Old->getBufferSize() - 1);
909 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor6481ef12010-07-24 00:38:13 +0000910
911 if (DeleteOld)
912 delete Old;
913
914 return Result;
915}
916
Douglas Gregor4dde7492010-07-23 23:58:40 +0000917/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
918/// the source file.
919///
920/// This routine will compute the preamble of the main source file. If a
921/// non-trivial preamble is found, it will precompile that preamble into a
922/// precompiled header so that the precompiled preamble can be used to reduce
923/// reparsing time. If a precompiled preamble has already been constructed,
924/// this routine will determine if it is still valid and, if so, avoid
925/// rebuilding the precompiled preamble.
926///
Douglas Gregor028d3e42010-08-09 20:45:32 +0000927/// \param AllowRebuild When true (the default), this routine is
928/// allowed to rebuild the precompiled preamble if it is found to be
929/// out-of-date.
930///
931/// \param MaxLines When non-zero, the maximum number of lines that
932/// can occur within the preamble.
933///
Douglas Gregor6481ef12010-07-24 00:38:13 +0000934/// \returns If the precompiled preamble can be used, returns a newly-allocated
935/// buffer that should be used in place of the main file when doing so.
936/// Otherwise, returns a NULL pointer.
Douglas Gregor028d3e42010-08-09 20:45:32 +0000937llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
938 bool AllowRebuild,
939 unsigned MaxLines) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000940 CompilerInvocation PreambleInvocation(*Invocation);
941 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
942 PreprocessorOptions &PreprocessorOpts
943 = PreambleInvocation.getPreprocessorOpts();
944
945 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000946 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor028d3e42010-08-09 20:45:32 +0000947 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +0000948
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000949 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000950 // We couldn't find a preamble in the main source. Clear out the current
951 // preamble, if we have one. It's obviously no good any more.
952 Preamble.clear();
953 if (!PreambleFile.empty()) {
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000954 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor4dde7492010-07-23 23:58:40 +0000955 PreambleFile.clear();
956 }
957 if (CreatedPreambleBuffer)
958 delete NewPreamble.first;
Douglas Gregorbb420ab2010-08-04 05:53:38 +0000959
960 // The next time we actually see a preamble, precompile it.
961 PreambleRebuildCounter = 1;
Douglas Gregor6481ef12010-07-24 00:38:13 +0000962 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000963 }
964
965 if (!Preamble.empty()) {
966 // We've previously computed a preamble. Check whether we have the same
967 // preamble now that we did before, and that there's enough space in
968 // the main-file buffer within the precompiled preamble to fit the
969 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000970 if (Preamble.size() == NewPreamble.second.first &&
971 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregorf5275a82010-07-24 00:42:07 +0000972 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor4dde7492010-07-23 23:58:40 +0000973 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000974 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000975 // The preamble has not changed. We may be able to re-use the precompiled
976 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +0000977
Douglas Gregor0e119552010-07-31 00:40:00 +0000978 // Check that none of the files used by the preamble have changed.
979 bool AnyFileChanged = false;
980
981 // First, make a record of those files that have been overridden via
982 // remapping or unsaved_files.
983 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
984 for (PreprocessorOptions::remapped_file_iterator
985 R = PreprocessorOpts.remapped_file_begin(),
986 REnd = PreprocessorOpts.remapped_file_end();
987 !AnyFileChanged && R != REnd;
988 ++R) {
989 struct stat StatBuf;
990 if (stat(R->second.c_str(), &StatBuf)) {
991 // If we can't stat the file we're remapping to, assume that something
992 // horrible happened.
993 AnyFileChanged = true;
994 break;
995 }
Douglas Gregor6481ef12010-07-24 00:38:13 +0000996
Douglas Gregor0e119552010-07-31 00:40:00 +0000997 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
998 StatBuf.st_mtime);
999 }
1000 for (PreprocessorOptions::remapped_file_buffer_iterator
1001 R = PreprocessorOpts.remapped_file_buffer_begin(),
1002 REnd = PreprocessorOpts.remapped_file_buffer_end();
1003 !AnyFileChanged && R != REnd;
1004 ++R) {
1005 // FIXME: Should we actually compare the contents of file->buffer
1006 // remappings?
1007 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1008 0);
1009 }
1010
1011 // Check whether anything has changed.
1012 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1013 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1014 !AnyFileChanged && F != FEnd;
1015 ++F) {
1016 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1017 = OverriddenFiles.find(F->first());
1018 if (Overridden != OverriddenFiles.end()) {
1019 // This file was remapped; check whether the newly-mapped file
1020 // matches up with the previous mapping.
1021 if (Overridden->second != F->second)
1022 AnyFileChanged = true;
1023 continue;
1024 }
1025
1026 // The file was not remapped; check whether it has changed on disk.
1027 struct stat StatBuf;
1028 if (stat(F->first(), &StatBuf)) {
1029 // If we can't stat the file, assume that something horrible happened.
1030 AnyFileChanged = true;
1031 } else if (StatBuf.st_size != F->second.first ||
1032 StatBuf.st_mtime != F->second.second)
1033 AnyFileChanged = true;
1034 }
1035
1036 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001037 // Okay! We can re-use the precompiled preamble.
1038
1039 // Set the state of the diagnostic object to mimic its state
1040 // after parsing the preamble.
1041 getDiagnostics().Reset();
1042 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1043 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
1044 StoredDiagnostics.erase(
1045 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
1046 StoredDiagnostics.end());
1047
1048 // Create a version of the main file buffer that is padded to
1049 // buffer size we reserved when creating the preamble.
Douglas Gregor0e119552010-07-31 00:40:00 +00001050 return CreatePaddedMainFileBuffer(NewPreamble.first,
1051 CreatedPreambleBuffer,
1052 PreambleReservedSize,
1053 FrontendOpts.Inputs[0].second);
1054 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001055 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001056
1057 // If we aren't allowed to rebuild the precompiled preamble, just
1058 // return now.
1059 if (!AllowRebuild)
1060 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001061
1062 // We can't reuse the previously-computed preamble. Build a new one.
1063 Preamble.clear();
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001064 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001065 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001066 } else if (!AllowRebuild) {
1067 // We aren't allowed to rebuild the precompiled preamble; just
1068 // return now.
1069 return 0;
1070 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001071
1072 // If the preamble rebuild counter > 1, it's because we previously
1073 // failed to build a preamble and we're not yet ready to try
1074 // again. Decrement the counter and return a failure.
1075 if (PreambleRebuildCounter > 1) {
1076 --PreambleRebuildCounter;
1077 return 0;
1078 }
1079
Douglas Gregor4dde7492010-07-23 23:58:40 +00001080 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001081 llvm::Timer *PreambleTimer = 0;
1082 if (TimerGroup.get()) {
1083 PreambleTimer = new llvm::Timer("Precompiling preamble", *TimerGroup);
1084 PreambleTimer->startTimer();
1085 Timers.push_back(PreambleTimer);
1086 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001087
1088 // Create a new buffer that stores the preamble. The buffer also contains
1089 // extra space for the original contents of the file (which will be present
1090 // when we actually parse the file) along with more room in case the file
Douglas Gregor4dde7492010-07-23 23:58:40 +00001091 // grows.
1092 PreambleReservedSize = NewPreamble.first->getBufferSize();
1093 if (PreambleReservedSize < 4096)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001094 PreambleReservedSize = 8191;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001095 else
Douglas Gregor4dde7492010-07-23 23:58:40 +00001096 PreambleReservedSize *= 2;
1097
Douglas Gregord9a30af2010-08-02 20:51:39 +00001098 // Save the preamble text for later; we'll need to compare against it for
1099 // subsequent reparses.
1100 Preamble.assign(NewPreamble.first->getBufferStart(),
1101 NewPreamble.first->getBufferStart()
1102 + NewPreamble.second.first);
1103 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1104
Douglas Gregora0734c52010-08-19 01:33:06 +00001105 delete PreambleBuffer;
1106 PreambleBuffer
Douglas Gregor4dde7492010-07-23 23:58:40 +00001107 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001108 FrontendOpts.Inputs[0].second);
1109 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor4dde7492010-07-23 23:58:40 +00001110 NewPreamble.first->getBufferStart(), Preamble.size());
1111 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001112 ' ', PreambleReservedSize - Preamble.size() - 1);
1113 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001114
1115 // Remap the main source file to the preamble buffer.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001116 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001117 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1118
1119 // Tell the compiler invocation to generate a temporary precompiled header.
1120 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Sebastian Redle98428d2010-08-06 00:35:11 +00001121 // FIXME: Set ChainedPCH unconditionally, once it is ready.
1122 if (::getenv("LIBCLANG_CHAINING"))
1123 FrontendOpts.ChainedPCH = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001124 // FIXME: Generate the precompiled header into memory?
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001125 FrontendOpts.OutputFile = GetPreamblePCHPath();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001126
1127 // Create the compiler instance to use for building the precompiled preamble.
1128 CompilerInstance Clang;
1129 Clang.setInvocation(&PreambleInvocation);
1130 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1131
Douglas Gregor8e984da2010-08-04 16:47:14 +00001132 // Set up diagnostics, capturing all of the diagnostics produced.
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001133 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor8e984da2010-08-04 16:47:14 +00001134 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
1135 getDiagnostics(),
1136 StoredDiagnostics);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001137
1138 // Create the target instance.
1139 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1140 Clang.getTargetOpts()));
1141 if (!Clang.hasTarget()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001142 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1143 Preamble.clear();
1144 if (CreatedPreambleBuffer)
1145 delete NewPreamble.first;
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001146 if (PreambleTimer)
1147 PreambleTimer->stopTimer();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001148 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001149 PreprocessorOpts.eraseRemappedFile(
1150 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001151 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001152 }
1153
1154 // Inform the target of the language options.
1155 //
1156 // FIXME: We shouldn't need to do this, the target should be immutable once
1157 // created. This complexity should be lifted elsewhere.
1158 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1159
1160 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1161 "Invocation must have exactly one source file!");
1162 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1163 "FIXME: AST inputs not yet supported here!");
1164 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1165 "IR inputs not support here!");
1166
1167 // Clear out old caches and data.
1168 StoredDiagnostics.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001169 TopLevelDecls.clear();
1170 TopLevelDeclsInPreamble.clear();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001171
1172 // Create a file manager object to provide access to and cache the filesystem.
1173 Clang.setFileManager(new FileManager);
1174
1175 // Create the source manager.
1176 Clang.setSourceManager(new SourceManager(getDiagnostics()));
1177
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001178 llvm::OwningPtr<PrecompilePreambleAction> Act;
1179 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001180 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1181 Clang.getFrontendOpts().Inputs[0].first)) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001182 Clang.takeInvocation();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001183 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1184 Preamble.clear();
1185 if (CreatedPreambleBuffer)
1186 delete NewPreamble.first;
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001187 if (PreambleTimer)
1188 PreambleTimer->stopTimer();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001189 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001190 PreprocessorOpts.eraseRemappedFile(
1191 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001192 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001193 }
1194
1195 Act->Execute();
1196 Act->EndSourceFile();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001197 Clang.takeInvocation();
1198
Douglas Gregore9db88f2010-08-03 19:06:41 +00001199 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001200 // There were errors parsing the preamble, so no precompiled header was
1201 // generated. Forget that we even tried.
1202 // FIXME: Should we leave a note for ourselves to try again?
1203 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1204 Preamble.clear();
1205 if (CreatedPreambleBuffer)
1206 delete NewPreamble.first;
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001207 if (PreambleTimer)
1208 PreambleTimer->stopTimer();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001209 TopLevelDeclsInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001210 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001211 PreprocessorOpts.eraseRemappedFile(
1212 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001213 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001214 }
1215
1216 // Keep track of the preamble we precompiled.
1217 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregord9a30af2010-08-02 20:51:39 +00001218 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1219 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001220
1221 // Keep track of all of the files that the source manager knows about,
1222 // so we can verify whether they have changed or not.
1223 FilesInPreamble.clear();
1224 SourceManager &SourceMgr = Clang.getSourceManager();
1225 const llvm::MemoryBuffer *MainFileBuffer
1226 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1227 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1228 FEnd = SourceMgr.fileinfo_end();
1229 F != FEnd;
1230 ++F) {
1231 const FileEntry *File = F->second->Entry;
1232 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1233 continue;
1234
1235 FilesInPreamble[File->getName()]
1236 = std::make_pair(F->second->getSize(), File->getModificationTime());
1237 }
1238
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001239 if (PreambleTimer)
1240 PreambleTimer->stopTimer();
1241
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001242 PreambleRebuildCounter = 1;
Douglas Gregora0734c52010-08-19 01:33:06 +00001243 PreprocessorOpts.eraseRemappedFile(
1244 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001245 return CreatePaddedMainFileBuffer(NewPreamble.first,
1246 CreatedPreambleBuffer,
1247 PreambleReservedSize,
1248 FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001249}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001250
Douglas Gregore9db88f2010-08-03 19:06:41 +00001251void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1252 std::vector<Decl *> Resolved;
1253 Resolved.reserve(TopLevelDeclsInPreamble.size());
1254 ExternalASTSource &Source = *getASTContext().getExternalSource();
1255 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1256 // Resolve the declaration ID to an actual declaration, possibly
1257 // deserializing the declaration in the process.
1258 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1259 if (D)
1260 Resolved.push_back(D);
1261 }
1262 TopLevelDeclsInPreamble.clear();
1263 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1264}
1265
1266unsigned ASTUnit::getMaxPCHLevel() const {
1267 if (!getOnlyLocalDecls())
1268 return Decl::MaxPCHLevel;
1269
1270 unsigned Result = 0;
1271 if (isMainFileAST() || SavedMainFileBuffer)
1272 ++Result;
1273 return Result;
1274}
1275
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001276ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1277 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1278 bool OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001279 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001280 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001281 bool CompleteTranslationUnit,
1282 bool CacheCodeCompletionResults) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001283 if (!Diags.getPtr()) {
1284 // No diagnostics engine was provided, so create our own diagnostics object
1285 // with the default options.
1286 DiagnosticOptions DiagOpts;
1287 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
1288 }
1289
1290 // Create the AST unit.
1291 llvm::OwningPtr<ASTUnit> AST;
1292 AST.reset(new ASTUnit(false));
1293 AST->Diagnostics = Diags;
1294 AST->CaptureDiagnostics = CaptureDiagnostics;
1295 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001296 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001297 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001298 AST->Invocation.reset(CI);
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001299 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001300
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001301 if (getenv("LIBCLANG_TIMING"))
1302 AST->TimerGroup.reset(
1303 new llvm::TimerGroup(CI->getFrontendOpts().Inputs[0].second));
1304
1305
Douglas Gregor6481ef12010-07-24 00:38:13 +00001306 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregora5fd5222010-07-28 22:12:37 +00001307 // FIXME: When C++ PCH is ready, allow use of it for a precompiled preamble.
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001308 if (PrecompilePreamble && !CI->getLangOpts().CPlusPlus) {
1309 AST->PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001310 OverrideMainBuffer = AST->getMainBufferWithPrecompiledPreamble();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001311 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001312
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001313 llvm::Timer *ParsingTimer = 0;
1314 if (AST->TimerGroup.get()) {
1315 ParsingTimer = new llvm::Timer("Initial parse", *AST->TimerGroup);
1316 ParsingTimer->startTimer();
1317 AST->Timers.push_back(ParsingTimer);
1318 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001319
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001320 bool Failed = AST->Parse(OverrideMainBuffer);
1321 if (ParsingTimer)
1322 ParsingTimer->stopTimer();
1323
1324 return Failed? 0 : AST.take();
Daniel Dunbar764c0822009-12-01 09:51:01 +00001325}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001326
1327ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1328 const char **ArgEnd,
Douglas Gregor7f95d262010-04-05 23:52:57 +00001329 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar8d4a2022009-12-13 03:46:13 +00001330 llvm::StringRef ResourceFilesPath,
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001331 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001332 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001333 unsigned NumRemappedFiles,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001334 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001335 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001336 bool CompleteTranslationUnit,
1337 bool CacheCodeCompletionResults) {
Douglas Gregor2dd19f12010-08-18 22:29:43 +00001338 bool CreatedDiagnosticsObject = false;
1339
Douglas Gregor7f95d262010-04-05 23:52:57 +00001340 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00001341 // No diagnostics engine was provided, so create our own diagnostics object
1342 // with the default options.
1343 DiagnosticOptions DiagOpts;
Douglas Gregor7f95d262010-04-05 23:52:57 +00001344 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00001345 CreatedDiagnosticsObject = true;
Douglas Gregord03e8232010-04-05 21:10:19 +00001346 }
1347
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001348 llvm::SmallVector<const char *, 16> Args;
1349 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1350 Args.insert(Args.end(), ArgBegin, ArgEnd);
1351
1352 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1353 // also want to force it to use clang.
1354 Args.push_back("-fsyntax-only");
1355
Daniel Dunbar8d4a2022009-12-13 03:46:13 +00001356 // FIXME: We shouldn't have to pass in the path info.
Daniel Dunbare38764c2010-07-19 00:44:04 +00001357 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
Douglas Gregord03e8232010-04-05 21:10:19 +00001358 "a.out", false, false, *Diags);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001359
1360 // Don't check that inputs exist, they have been remapped.
1361 TheDriver.setCheckInputsExist(false);
1362
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001363 llvm::OwningPtr<driver::Compilation> C(
1364 TheDriver.BuildCompilation(Args.size(), Args.data()));
1365
1366 // We expect to get back exactly one command job, if we didn't something
1367 // failed.
1368 const driver::JobList &Jobs = C->getJobs();
1369 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1370 llvm::SmallString<256> Msg;
1371 llvm::raw_svector_ostream OS(Msg);
1372 C->PrintJob(OS, C->getJobs(), "; ", true);
Douglas Gregord03e8232010-04-05 21:10:19 +00001373 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001374 return 0;
1375 }
1376
1377 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1378 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
Douglas Gregord03e8232010-04-05 21:10:19 +00001379 Diags->Report(diag::err_fe_expected_clang_command);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001380 return 0;
1381 }
1382
1383 const driver::ArgStringList &CCArgs = Cmd->getArguments();
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001384 llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
Dan Gohman145f3f12010-04-19 16:39:44 +00001385 CompilerInvocation::CreateFromArgs(*CI,
1386 const_cast<const char **>(CCArgs.data()),
1387 const_cast<const char **>(CCArgs.data()) +
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001388 CCArgs.size(),
Douglas Gregord03e8232010-04-05 21:10:19 +00001389 *Diags);
Daniel Dunbard6136772009-12-13 03:45:58 +00001390
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001391 // Override any files that need remapping
1392 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001393 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbar19511922010-02-16 01:55:04 +00001394 RemappedFiles[I].second);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001395
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001396 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001397 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001398
Douglas Gregor4c6ed902010-08-18 23:38:21 +00001399 CI->getFrontendOpts().DisableFree = false;
Douglas Gregor33cdd812010-02-18 18:08:43 +00001400 return LoadFromCompilerInvocation(CI.take(), Diags, OnlyLocalDecls,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001401 CaptureDiagnostics, PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001402 CompleteTranslationUnit,
1403 CacheCodeCompletionResults);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001404}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001405
1406bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1407 if (!Invocation.get())
1408 return true;
1409
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001410 llvm::Timer *ReparsingTimer = 0;
1411 if (TimerGroup.get()) {
1412 ReparsingTimer = new llvm::Timer("Reparse", *TimerGroup);
1413 ReparsingTimer->startTimer();
1414 Timers.push_back(ReparsingTimer);
1415 }
1416
Douglas Gregor0e119552010-07-31 00:40:00 +00001417 // Remap files.
Douglas Gregor0e119552010-07-31 00:40:00 +00001418 Invocation->getPreprocessorOpts().clearRemappedFiles();
1419 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1420 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1421 RemappedFiles[I].second);
1422
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001423 // If we have a preamble file lying around, or if we might try to
1424 // build a precompiled preamble, do so now.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001425 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001426 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregor028d3e42010-08-09 20:45:32 +00001427 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001428
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001429 // Clear out the diagnostics state.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001430 if (!OverrideMainBuffer)
1431 getDiagnostics().Reset();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001432
Douglas Gregor4dde7492010-07-23 23:58:40 +00001433 // Parse the sources
Douglas Gregor6481ef12010-07-24 00:38:13 +00001434 bool Result = Parse(OverrideMainBuffer);
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001435 if (ReparsingTimer)
1436 ReparsingTimer->stopTimer();
Douglas Gregor2c8bd472010-08-17 00:40:40 +00001437
1438 if (ShouldCacheCodeCompletionResults) {
1439 if (CacheCodeCompletionCoolDown > 0)
1440 --CacheCodeCompletionCoolDown;
1441 else if (top_level_size() != NumTopLevelDeclsAtLastCompletionCache)
1442 CacheCodeCompletionResults();
1443 }
1444
Douglas Gregor4dde7492010-07-23 23:58:40 +00001445 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001446}
Douglas Gregor8e984da2010-08-04 16:47:14 +00001447
Douglas Gregorb14904c2010-08-13 22:48:40 +00001448//----------------------------------------------------------------------------//
1449// Code completion
1450//----------------------------------------------------------------------------//
1451
1452namespace {
1453 /// \brief Code completion consumer that combines the cached code-completion
1454 /// results from an ASTUnit with the code-completion results provided to it,
1455 /// then passes the result on to
1456 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1457 unsigned NormalContexts;
1458 ASTUnit &AST;
1459 CodeCompleteConsumer &Next;
1460
1461 public:
1462 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor39982192010-08-15 06:18:01 +00001463 bool IncludeMacros, bool IncludeCodePatterns,
1464 bool IncludeGlobals)
1465 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001466 Next.isOutputBinary()), AST(AST), Next(Next)
1467 {
1468 // Compute the set of contexts in which we will look when we don't have
1469 // any information about the specific context.
1470 NormalContexts
1471 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
1472 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
1473 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1474 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1475 | (1 << (CodeCompletionContext::CCC_Statement - 1))
1476 | (1 << (CodeCompletionContext::CCC_Expression - 1))
1477 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1478 | (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
1479 | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
1480
1481 if (AST.getASTContext().getLangOptions().CPlusPlus)
1482 NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1))
1483 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
1484 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
1485 }
1486
1487 virtual void ProcessCodeCompleteResults(Sema &S,
1488 CodeCompletionContext Context,
1489 Result *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001490 unsigned NumResults);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001491
1492 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1493 OverloadCandidate *Candidates,
1494 unsigned NumCandidates) {
1495 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1496 }
1497 };
1498}
Douglas Gregord46cf182010-08-16 20:01:48 +00001499
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001500/// \brief Helper function that computes which global names are hidden by the
1501/// local code-completion results.
1502void CalculateHiddenNames(const CodeCompletionContext &Context,
1503 CodeCompleteConsumer::Result *Results,
1504 unsigned NumResults,
1505 ASTContext &Ctx,
1506 llvm::StringSet<> &HiddenNames) {
1507 bool OnlyTagNames = false;
1508 switch (Context.getKind()) {
1509 case CodeCompletionContext::CCC_Other:
1510 case CodeCompletionContext::CCC_TopLevel:
1511 case CodeCompletionContext::CCC_ObjCInterface:
1512 case CodeCompletionContext::CCC_ObjCImplementation:
1513 case CodeCompletionContext::CCC_ObjCIvarList:
1514 case CodeCompletionContext::CCC_ClassStructUnion:
1515 case CodeCompletionContext::CCC_Statement:
1516 case CodeCompletionContext::CCC_Expression:
1517 case CodeCompletionContext::CCC_ObjCMessageReceiver:
1518 case CodeCompletionContext::CCC_MemberAccess:
1519 case CodeCompletionContext::CCC_Namespace:
1520 case CodeCompletionContext::CCC_Type:
1521 break;
1522
1523 case CodeCompletionContext::CCC_EnumTag:
1524 case CodeCompletionContext::CCC_UnionTag:
1525 case CodeCompletionContext::CCC_ClassOrStructTag:
1526 OnlyTagNames = true;
1527 break;
1528
1529 case CodeCompletionContext::CCC_ObjCProtocolName:
1530 // If we're just looking for protocol names, nothing can hide them.
1531 return;
1532 }
1533
1534 typedef CodeCompleteConsumer::Result Result;
1535 for (unsigned I = 0; I != NumResults; ++I) {
1536 if (Results[I].Kind != Result::RK_Declaration)
1537 continue;
1538
1539 unsigned IDNS
1540 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1541
1542 bool Hiding = false;
1543 if (OnlyTagNames)
1544 Hiding = (IDNS & Decl::IDNS_Tag);
1545 else {
1546 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00001547 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1548 Decl::IDNS_NonMemberOperator);
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001549 if (Ctx.getLangOptions().CPlusPlus)
1550 HiddenIDNS |= Decl::IDNS_Tag;
1551 Hiding = (IDNS & HiddenIDNS);
1552 }
1553
1554 if (!Hiding)
1555 continue;
1556
1557 DeclarationName Name = Results[I].Declaration->getDeclName();
1558 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1559 HiddenNames.insert(Identifier->getName());
1560 else
1561 HiddenNames.insert(Name.getAsString());
1562 }
1563}
1564
1565
Douglas Gregord46cf182010-08-16 20:01:48 +00001566void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1567 CodeCompletionContext Context,
1568 Result *Results,
1569 unsigned NumResults) {
1570 // Merge the results we were given with the results we cached.
1571 bool AddedResult = false;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001572 unsigned InContexts
1573 = (Context.getKind() == CodeCompletionContext::CCC_Other? NormalContexts
1574 : (1 << (Context.getKind() - 1)));
1575
1576 // Contains the set of names that are hidden by "local" completion results.
1577 llvm::StringSet<> HiddenNames;
1578
Douglas Gregord46cf182010-08-16 20:01:48 +00001579 typedef CodeCompleteConsumer::Result Result;
1580 llvm::SmallVector<Result, 8> AllResults;
1581 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00001582 C = AST.cached_completion_begin(),
1583 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00001584 C != CEnd; ++C) {
1585 // If the context we are in matches any of the contexts we are
1586 // interested in, we'll add this result.
1587 if ((C->ShowInContexts & InContexts) == 0)
1588 continue;
1589
1590 // If we haven't added any results previously, do so now.
1591 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001592 CalculateHiddenNames(Context, Results, NumResults, S.Context,
1593 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00001594 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1595 AddedResult = true;
1596 }
1597
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001598 // Determine whether this global completion result is hidden by a local
1599 // completion result. If so, skip it.
1600 if (C->Kind != CXCursor_MacroDefinition &&
1601 HiddenNames.count(C->Completion->getTypedText()))
1602 continue;
1603
Douglas Gregord46cf182010-08-16 20:01:48 +00001604 // Adjust priority based on similar type classes.
1605 unsigned Priority = C->Priority;
1606 if (!Context.getPreferredType().isNull()) {
1607 if (C->Kind == CXCursor_MacroDefinition) {
1608 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
1609 Context.getPreferredType()->isAnyPointerType());
1610 } else if (C->Type) {
1611 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00001612 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00001613 Context.getPreferredType().getUnqualifiedType());
1614 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
1615 if (ExpectedSTC == C->TypeClass) {
1616 // We know this type is similar; check for an exact match.
1617 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00001618 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00001619 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00001620 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00001621 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
1622 Priority /= CCF_ExactTypeMatch;
1623 else
1624 Priority /= CCF_SimilarTypeMatch;
1625 }
1626 }
1627 }
1628
1629 AllResults.push_back(Result(C->Completion, Priority, C->Kind));
1630 }
1631
1632 // If we did not add any cached completion results, just forward the
1633 // results we were given to the next consumer.
1634 if (!AddedResult) {
1635 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
1636 return;
1637 }
1638
1639 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
1640 AllResults.size());
1641}
1642
1643
1644
Douglas Gregor8e984da2010-08-04 16:47:14 +00001645void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
1646 RemappedFile *RemappedFiles,
1647 unsigned NumRemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00001648 bool IncludeMacros,
1649 bool IncludeCodePatterns,
Douglas Gregor8e984da2010-08-04 16:47:14 +00001650 CodeCompleteConsumer &Consumer,
1651 Diagnostic &Diag, LangOptions &LangOpts,
1652 SourceManager &SourceMgr, FileManager &FileMgr,
1653 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics) {
1654 if (!Invocation.get())
1655 return;
1656
Douglas Gregor028d3e42010-08-09 20:45:32 +00001657 llvm::Timer *CompletionTimer = 0;
1658 if (TimerGroup.get()) {
1659 llvm::SmallString<128> TimerName;
1660 llvm::raw_svector_ostream TimerNameOut(TimerName);
1661 TimerNameOut << "Code completion @ " << File << ":" << Line << ":"
1662 << Column;
1663 CompletionTimer = new llvm::Timer(TimerNameOut.str(), *TimerGroup);
1664 CompletionTimer->startTimer();
1665 Timers.push_back(CompletionTimer);
1666 }
1667
Douglas Gregor8e984da2010-08-04 16:47:14 +00001668 CompilerInvocation CCInvocation(*Invocation);
1669 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
1670 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00001671
Douglas Gregorb14904c2010-08-13 22:48:40 +00001672 FrontendOpts.ShowMacrosInCodeCompletion
1673 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorb68bc592010-08-05 09:09:23 +00001674 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor39982192010-08-15 06:18:01 +00001675 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
1676 = CachedCompletionResults.empty();
Douglas Gregor8e984da2010-08-04 16:47:14 +00001677 FrontendOpts.CodeCompletionAt.FileName = File;
1678 FrontendOpts.CodeCompletionAt.Line = Line;
1679 FrontendOpts.CodeCompletionAt.Column = Column;
1680
Douglas Gregorb68bc592010-08-05 09:09:23 +00001681 // Turn on spell-checking when performing code completion. It leads
1682 // to better results.
1683 unsigned SpellChecking = CCInvocation.getLangOpts().SpellChecking;
1684 CCInvocation.getLangOpts().SpellChecking = 1;
1685
Douglas Gregor8e984da2010-08-04 16:47:14 +00001686 // Set the language options appropriately.
1687 LangOpts = CCInvocation.getLangOpts();
1688
1689 CompilerInstance Clang;
1690 Clang.setInvocation(&CCInvocation);
1691 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1692
1693 // Set up diagnostics, capturing any diagnostics produced.
1694 Clang.setDiagnostics(&Diag);
1695 CaptureDroppedDiagnostics Capture(true,
1696 Clang.getDiagnostics(),
1697 StoredDiagnostics);
Douglas Gregor8e984da2010-08-04 16:47:14 +00001698
1699 // Create the target instance.
1700 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1701 Clang.getTargetOpts()));
1702 if (!Clang.hasTarget()) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001703 Clang.takeInvocation();
Douglas Gregor2dd19f12010-08-18 22:29:43 +00001704 CCInvocation.getLangOpts().SpellChecking = SpellChecking;
1705 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00001706 }
1707
1708 // Inform the target of the language options.
1709 //
1710 // FIXME: We shouldn't need to do this, the target should be immutable once
1711 // created. This complexity should be lifted elsewhere.
1712 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1713
1714 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1715 "Invocation must have exactly one source file!");
1716 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1717 "FIXME: AST inputs not yet supported here!");
1718 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1719 "IR inputs not support here!");
1720
1721
1722 // Use the source and file managers that we were given.
1723 Clang.setFileManager(&FileMgr);
1724 Clang.setSourceManager(&SourceMgr);
1725
1726 // Remap files.
1727 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00001728 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor8e984da2010-08-04 16:47:14 +00001729 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1730 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
1731 RemappedFiles[I].second);
1732
Douglas Gregorb14904c2010-08-13 22:48:40 +00001733 // Use the code completion consumer we were given, but adding any cached
1734 // code-completion results.
1735 AugmentedCodeCompleteConsumer
1736 AugmentedConsumer(*this, Consumer, FrontendOpts.ShowMacrosInCodeCompletion,
Douglas Gregor39982192010-08-15 06:18:01 +00001737 FrontendOpts.ShowCodePatternsInCodeCompletion,
1738 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001739 Clang.setCodeCompletionConsumer(&AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00001740
Douglas Gregor028d3e42010-08-09 20:45:32 +00001741 // If we have a precompiled preamble, try to use it. We only allow
1742 // the use of the precompiled preamble if we're if the completion
1743 // point is within the main file, after the end of the precompiled
1744 // preamble.
1745 llvm::MemoryBuffer *OverrideMainBuffer = 0;
1746 if (!PreambleFile.empty()) {
1747 using llvm::sys::FileStatus;
1748 llvm::sys::PathWithStatus CompleteFilePath(File);
1749 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
1750 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
1751 if (const FileStatus *MainStatus = MainPath.getFileStatus())
1752 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
1753 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(false,
1754 Line);
1755 }
1756
1757 // If the main file has been overridden due to the use of a preamble,
1758 // make that override happen and introduce the preamble.
1759 if (OverrideMainBuffer) {
1760 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1761 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1762 PreprocessorOpts.PrecompiledPreambleBytes.second
1763 = PreambleEndsAtStartOfLine;
1764 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
1765 PreprocessorOpts.DisablePCHValidation = true;
1766
1767 // The stored diagnostics have the old source manager. Copy them
1768 // to our output set of stored diagnostics, updating the source
1769 // manager to the one we were given.
1770 for (unsigned I = 0, N = this->StoredDiagnostics.size(); I != N; ++I) {
1771 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
1772 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
1773 StoredDiagnostics[I].setLocation(Loc);
1774 }
1775 }
1776
Douglas Gregor8e984da2010-08-04 16:47:14 +00001777 llvm::OwningPtr<SyntaxOnlyAction> Act;
1778 Act.reset(new SyntaxOnlyAction);
1779 if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1780 Clang.getFrontendOpts().Inputs[0].first)) {
1781 Act->Execute();
1782 Act->EndSourceFile();
1783 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001784
1785 if (CompletionTimer)
1786 CompletionTimer->stopTimer();
Douglas Gregor8e984da2010-08-04 16:47:14 +00001787
1788 // Steal back our resources.
Douglas Gregor028d3e42010-08-09 20:45:32 +00001789 delete OverrideMainBuffer;
Douglas Gregor8e984da2010-08-04 16:47:14 +00001790 Clang.takeFileManager();
1791 Clang.takeSourceManager();
1792 Clang.takeInvocation();
Douglas Gregor8e984da2010-08-04 16:47:14 +00001793 Clang.takeCodeCompletionConsumer();
Douglas Gregorb68bc592010-08-05 09:09:23 +00001794 CCInvocation.getLangOpts().SpellChecking = SpellChecking;
Douglas Gregor8e984da2010-08-04 16:47:14 +00001795}
Douglas Gregore9386682010-08-13 05:36:37 +00001796
1797bool ASTUnit::Save(llvm::StringRef File) {
1798 if (getDiagnostics().hasErrorOccurred())
1799 return true;
1800
1801 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
1802 // unconditionally create a stat cache when we parse the file?
1803 std::string ErrorInfo;
Benjamin Kramer340045b2010-08-15 16:54:31 +00001804 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo,
1805 llvm::raw_fd_ostream::F_Binary);
Douglas Gregore9386682010-08-13 05:36:37 +00001806 if (!ErrorInfo.empty() || Out.has_error())
1807 return true;
1808
1809 std::vector<unsigned char> Buffer;
1810 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redl55c0ad52010-08-18 23:56:21 +00001811 ASTWriter Writer(Stream);
1812 Writer.WriteAST(getSema(), 0, 0);
Douglas Gregore9386682010-08-13 05:36:37 +00001813
1814 // Write the generated bitstream to "Out".
Douglas Gregor2dd19f12010-08-18 22:29:43 +00001815 if (!Buffer.empty())
1816 Out.write((char *)&Buffer.front(), Buffer.size());
Douglas Gregore9386682010-08-13 05:36:37 +00001817 Out.close();
1818 return Out.has_error();
1819}