blob: 523b8d0a6c2165f47459ff6c03548829d7874791 [file] [log] [blame]
Argyrios Kyrtzidis4b562cf2009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000015#include "clang/AST/ASTContext.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000016#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
Douglas Gregorf5586f62010-08-16 18:08:11 +000018#include "clang/AST/TypeOrdering.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000019#include "clang/AST/StmtVisitor.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000020#include "clang/Driver/Compilation.h"
21#include "clang/Driver/Driver.h"
22#include "clang/Driver/Job.h"
23#include "clang/Driver/Tool.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000024#include "clang/Frontend/CompilerInstance.h"
25#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000026#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000027#include "clang/Frontend/FrontendOptions.h"
Sebastian Redl6ab7cd82010-08-18 23:57:17 +000028#include "clang/Serialization/ASTReader.h"
Sebastian Redl7faa2ec2010-08-18 23:56:37 +000029#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000030#include "clang/Lex/HeaderSearch.h"
31#include "clang/Lex/Preprocessor.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000032#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000033#include "clang/Basic/TargetInfo.h"
34#include "clang/Basic/Diagnostic.h"
Douglas Gregor349d38c2010-08-16 23:08:34 +000035#include "llvm/ADT/StringSet.h"
Douglas Gregor4db64a42010-01-23 00:14:00 +000036#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000037#include "llvm/System/Host.h"
Benjamin Kramer4a630d32009-10-18 11:34:14 +000038#include "llvm/System/Path.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000039#include "llvm/Support/raw_ostream.h"
Douglas Gregor385103b2010-07-30 20:58:08 +000040#include "llvm/Support/Timer.h"
Douglas Gregor44c181a2010-07-23 00:33:23 +000041#include <cstdlib>
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000042#include <cstdio>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000043#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000044using namespace clang;
45
Douglas Gregoreababfb2010-08-04 05:53:38 +000046/// \brief After failing to build a precompiled preamble (due to
47/// errors in the source that occurs in the preamble), the number of
48/// reparses during which we'll skip even trying to precompile the
49/// preamble.
50const unsigned DefaultPreambleRebuildInterval = 5;
51
Douglas Gregor3687e9d2010-04-05 21:10:19 +000052ASTUnit::ASTUnit(bool _MainFileIsAST)
Douglas Gregorabc563f2010-07-19 21:46:24 +000053 : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
Douglas Gregordf95a132010-08-09 20:45:32 +000054 CompleteTranslationUnit(true), ConcurrencyCheckValue(CheckUnlocked),
Douglas Gregor671947b2010-08-19 01:33:06 +000055 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +000056 ShouldCacheCodeCompletionResults(false),
57 NumTopLevelDeclsAtLastCompletionCache(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +000058 CacheCodeCompletionCoolDown(0),
59 UnsafeToFree(false) {
Douglas Gregor385103b2010-07-30 20:58:08 +000060}
Douglas Gregor3687e9d2010-04-05 21:10:19 +000061
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000062ASTUnit::~ASTUnit() {
Douglas Gregorbdf60622010-03-05 21:16:25 +000063 ConcurrencyCheckValue = CheckLocked;
Douglas Gregorabc563f2010-07-19 21:46:24 +000064 CleanTemporaryFiles();
Douglas Gregor175c4a92010-07-23 23:58:40 +000065 if (!PreambleFile.empty())
Douglas Gregor385103b2010-07-30 20:58:08 +000066 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorf4f6c9d2010-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 Gregor28233422010-07-27 14:52:07 +000081
82 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +000083 delete PreambleBuffer;
84
Douglas Gregor87c08a52010-08-13 22:48:40 +000085 ClearCachedCompletionResults();
86
Douglas Gregor385103b2010-07-30 20:58:08 +000087 for (unsigned I = 0, N = Timers.size(); I != N; ++I)
88 delete Timers[I];
Douglas Gregorabc563f2010-07-19 21:46:24 +000089}
90
91void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor313e26c2010-02-18 23:35:40 +000092 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
93 TemporaryFiles[I].eraseFromDisk();
Douglas Gregorabc563f2010-07-19 21:46:24 +000094 TemporaryFiles.clear();
Steve Naroffe19944c2009-10-15 22:23:48 +000095}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000096
Douglas Gregor8071e422010-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 Gregora5fb7c32010-08-16 23:05:20 +0000100 const LangOptions &LangOpts,
101 bool &IsNestedNameSpecifier) {
102 IsNestedNameSpecifier = false;
103
Douglas Gregor8071e422010-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 Gregora5fb7c32010-08-16 23:05:20 +0000133 // Part of the nested-name-specifier in C++0x.
Douglas Gregor8071e422010-08-15 06:18:01 +0000134 if (LangOpts.CPlusPlus0x)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000135 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-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 Gregor8071e422010-08-15 06:18:01 +0000142 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000143 IsNestedNameSpecifier = true;
144 } else if (isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND))
145 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-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 Gregora5fb7c32010-08-16 23:05:20 +0000154 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000155
156 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000157 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000158 }
159
160 return Contexts;
161}
162
Douglas Gregor87c08a52010-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 Gregorf5586f62010-08-16 18:08:11 +0000184 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
185
Douglas Gregor87c08a52010-08-13 22:48:40 +0000186 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
187 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000188 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000189 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000190 CachedCodeCompletionResult CachedResult;
191 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
192 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000193 Ctx->getLangOptions(),
194 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000195 CachedResult.Priority = Results[I].Priority;
196 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000197
Douglas Gregorf5586f62010-08-16 18:08:11 +0000198 // Keep track of the type of this completion in an ASTContext-agnostic
199 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000200 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000201 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000202 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-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 Gregorc4421e92010-08-16 16:46:30 +0000220 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000221
Douglas Gregor8071e422010-08-15 06:18:01 +0000222 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-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 Gregor87c08a52010-08-13 22:48:40 +0000258 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000259 }
260
Douglas Gregor87c08a52010-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 Gregor1827e102010-08-16 16:18:59 +0000281 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000282 CachedResult.Type = 0;
Douglas Gregor87c08a52010-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 Gregor727d93e2010-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 Gregor87c08a52010-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 Gregorf5586f62010-08-16 18:08:11 +0000302 CachedCompletionTypes.clear();
Douglas Gregor87c08a52010-08-13 22:48:40 +0000303}
304
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000305namespace {
306
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000307/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000308/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000309class ASTInfoCollector : public ASTReaderListener {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000310 LangOptions &LangOpt;
311 HeaderSearch &HSI;
312 std::string &TargetTriple;
313 std::string &Predefines;
314 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000315
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000316 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000317
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000318public:
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000319 ASTInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
Argyrios Kyrtzidis0853a022009-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 Stump1eb44332009-09-09 15:08:12 +0000324
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000325 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
326 LangOpt = LangOpts;
327 return false;
328 }
Mike Stump1eb44332009-09-09 15:08:12 +0000329
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000330 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000331 TargetTriple = Triple;
332 return false;
333 }
Mike Stump1eb44332009-09-09 15:08:12 +0000334
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000335 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000336 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000337 std::string &SuggestedPredefines) {
Sebastian Redlcb481aa2010-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 Kyrtzidis0853a022009-06-20 08:08:23 +0000342 return false;
343 }
Mike Stump1eb44332009-09-09 15:08:12 +0000344
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000345 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000346 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
347 }
Mike Stump1eb44332009-09-09 15:08:12 +0000348
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000349 virtual void ReadCounter(unsigned Value) {
350 Counter = Value;
351 }
352};
353
Douglas Gregora88084b2010-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 Gregorbdbb0042010-08-18 22:29:43 +0000376 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000377 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000378 if (RequestCapture || Diags.getClient() == 0) {
379 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000380 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000381 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000382 }
383
384 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000385 if (Diags.getClient() == &Client) {
386 Diags.takeClient();
387 Diags.setClient(PreviousClient);
388 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000389 }
390};
391
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000392} // anonymous namespace
393
Douglas Gregora88084b2010-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 Naroff77accc12009-09-03 18:19:54 +0000399const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000400 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000401}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000402
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000403const std::string &ASTUnit::getASTFileName() {
404 assert(isMainFileAST() && "Not an ASTUnit from an AST file!");
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000405 return static_cast<ASTReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroffe19944c2009-10-15 22:23:48 +0000406}
407
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000408ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Douglas Gregor28019772010-04-05 23:52:57 +0000409 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000410 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000411 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000412 unsigned NumRemappedFiles,
413 bool CaptureDiagnostics) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000414 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
415
Douglas Gregor28019772010-04-05 23:52:57 +0000416 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-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 Gregor28019772010-04-05 23:52:57 +0000420 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000421 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000422
423 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000424 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor28019772010-04-05 23:52:57 +0000425 AST->Diagnostics = Diags;
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000426 AST->FileMgr.reset(new FileManager);
427 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics()));
Steve Naroff36c44642009-10-19 14:34:22 +0000428 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000429
Douglas Gregora88084b2010-02-18 18:08:43 +0000430 // If requested, capture diagnostics in the ASTUnit.
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000431 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, AST->getDiagnostics(),
Douglas Gregor405634b2010-04-05 18:10:21 +0000432 AST->StoredDiagnostics);
Douglas Gregora88084b2010-02-18 18:08:43 +0000433
Douglas Gregor4db64a42010-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 Gregor3687e9d2010-04-05 21:10:19 +0000441 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregor4db64a42010-01-23 00:14:00 +0000442 << RemappedFiles[I].first;
Douglas Gregorc8dfe5e2010-02-27 01:32:48 +0000443 delete RemappedFiles[I].second;
Douglas Gregor4db64a42010-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 Kyrtzidis0853a022009-06-20 08:08:23 +0000453 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000454
Argyrios Kyrtzidis0853a022009-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 Redlc43b54c2010-08-18 23:56:43 +0000461 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000462
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000463 Reader.reset(new ASTReader(AST->getSourceManager(), AST->getFileManager(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000464 AST->getDiagnostics()));
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000465 Reader->setListener(new ASTInfoCollector(LangInfo, HeaderInfo, TargetTriple,
Daniel Dunbarcc318932009-09-03 05:59:35 +0000466 Predefines, Counter));
467
Sebastian Redl571db7f2010-08-18 23:56:56 +0000468 switch (Reader->ReadAST(Filename)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000469 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000470 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000471
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000472 case ASTReader::Failure:
473 case ASTReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000474 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000475 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000476 }
Mike Stump1eb44332009-09-09 15:08:12 +0000477
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000478 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
479
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000480 // AST file loaded successfully. Now create the preprocessor.
Mike Stump1eb44332009-09-09 15:08:12 +0000481
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000482 // Get information about the target being compiled for.
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000483 //
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000484 // FIXME: This is broken, we should store the TargetOptions in the AST file.
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000485 TargetOptions TargetOpts;
486 TargetOpts.ABI = "";
Charles Davis98b7c5c2010-06-11 01:06:47 +0000487 TargetOpts.CXXABI = "itanium";
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000488 TargetOpts.CPU = "";
489 TargetOpts.Features.clear();
490 TargetOpts.Triple = TargetTriple;
Douglas Gregor3687e9d2010-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 Dunbar31b87d82009-09-21 03:03:39 +0000495 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000496 Preprocessor &PP = *AST->PP.get();
497
Daniel Dunbard5b61262009-09-21 03:03:47 +0000498 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000499 PP.setCounterValue(Counter);
Daniel Dunbarcc318932009-09-03 05:59:35 +0000500 Reader->setPreprocessor(PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000501
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000502 // Create and initialize the ASTContext.
503
504 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar31b87d82009-09-21 03:03:39 +0000505 AST->getSourceManager(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000506 *AST->Target.get(),
507 PP.getIdentifierTable(),
508 PP.getSelectorTable(),
509 PP.getBuiltinInfo(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000510 /* size_reserve = */0));
511 ASTContext &Context = *AST->Ctx.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Daniel Dunbarcc318932009-09-03 05:59:35 +0000513 Reader->InitializeContext(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000514
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000515 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000516 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000517 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000518 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000519 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000520 Context.setExternalSource(Source);
521
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000522 // Create an AST consumer, even though it isn't used.
523 AST->Consumer.reset(new ASTConsumer);
524
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000525 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-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 Stump1eb44332009-09-09 15:08:12 +0000530 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000531}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000532
533namespace {
534
Daniel Dunbarf772d1e2009-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 Kremenekda5a4282010-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 Gregoreb8837b2010-08-03 19:06:41 +0000550 Unit.addTopLevelDecl(D);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000551 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000552 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000553
554 // We're not interested in "interesting" decls.
555 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000556};
557
558class TopLevelDeclTrackerAction : public ASTFrontendAction {
559public:
560 ASTUnit &Unit;
561
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000562 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
563 llvm::StringRef InFile) {
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000564 return new TopLevelDeclTrackerConsumer(Unit);
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000565 }
566
567public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000568 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
569
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000570 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000571 virtual bool usesCompleteTranslationUnit() {
572 return Unit.isCompleteTranslationUnit();
573 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000574};
575
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000576class PrecompilePreambleConsumer : public PCHGenerator {
577 ASTUnit &Unit;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000578 std::vector<Decl *> TopLevelDecls;
Douglas Gregor1d715ac2010-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 Gregoreb8837b2010-08-03 19:06:41 +0000586 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-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 Gregoreb8837b2010-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 Gregor1d715ac2010-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 Gregordf95a132010-08-09 20:45:32 +0000636 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000637};
638
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000639}
640
Douglas Gregorabc563f2010-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 Gregor754f3492010-07-24 00:38:13 +0000646bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +0000647 delete SavedMainFileBuffer;
648 SavedMainFileBuffer = 0;
649
Douglas Gregor671947b2010-08-19 01:33:06 +0000650 if (!Invocation.get()) {
651 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000652 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +0000653 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000654
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000655 // Create the compiler instance to use for building the AST.
Daniel Dunbarcb6dda12009-12-02 08:43:56 +0000656 CompilerInstance Clang;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000657 Clang.setInvocation(Invocation.take());
658 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
659
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000660 // Set up diagnostics, capturing any diagnostics that would
661 // otherwise be dropped.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000662 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000663 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
664 getDiagnostics(),
665 StoredDiagnostics);
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000666
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000667 // Create the target instance.
668 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
669 Clang.getTargetOpts()));
Douglas Gregor671947b2010-08-19 01:33:06 +0000670 if (!Clang.hasTarget()) {
671 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000672 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +0000673 }
674
Daniel Dunbar521bf9c2009-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 Gregorabc563f2010-07-19 21:46:24 +0000680
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000681 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
682 "Invocation must have exactly one source file!");
Daniel Dunbarc34ce3f2010-06-07 23:22:09 +0000683 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000684 "FIXME: AST inputs not yet supported here!");
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +0000685 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
686 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000687
Douglas Gregorabc563f2010-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 Gregor914ed9d2010-08-13 03:15:25 +0000692 TheSema.reset();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000693 Ctx.reset();
694 PP.reset();
695
696 // Clear out old caches and data.
697 TopLevelDecls.clear();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000698 CleanTemporaryFiles();
699 PreprocessedEntitiesByFile.clear();
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000700
701 if (!OverrideMainBuffer)
702 StoredDiagnostics.clear();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000703
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000704 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000705 Clang.setFileManager(&getFileManager());
706
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000707 // Create the source manager.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000708 Clang.setSourceManager(&getSourceManager());
709
Douglas Gregorf4f6c9d2010-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 Gregor1abc6bc2010-08-04 16:47:14 +0000713 std::string PriorImplicitPCHInclude;
Douglas Gregorf4f6c9d2010-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 Gregor1abc6bc2010-08-04 16:47:14 +0000719 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor385103b2010-07-30 20:58:08 +0000720 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000721 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +0000722
723 // Keep track of the override buffer;
724 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorc0659ec2010-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 Gregorf4f6c9d2010-07-26 21:36:20 +0000736 }
737
Douglas Gregorabc563f2010-07-19 21:46:24 +0000738 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
739 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000740 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbard3598a62010-06-07 23:23:06 +0000741 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000742 goto error;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000743
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000744 Act->Execute();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000745
Daniel Dunbar64a32ba2009-12-01 21:57:33 +0000746 // Steal the created target, context, and preprocessor, and take back the
747 // source and file managers.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000748 TheSema.reset(Clang.takeSema());
749 Consumer.reset(Clang.takeASTConsumer());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000750 Ctx.reset(Clang.takeASTContext());
751 PP.reset(Clang.takePreprocessor());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000752 Clang.takeSourceManager();
753 Clang.takeFileManager();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000754 Target.reset(Clang.takeTarget());
755
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000756 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000757
758 // Remove the overridden buffer we used for the preamble.
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000759 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000760 PreprocessorOpts.eraseRemappedFile(
761 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000762 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
763 }
764
Douglas Gregorabc563f2010-07-19 21:46:24 +0000765 Invocation.reset(Clang.takeInvocation());
Douglas Gregor87c08a52010-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 Gregorabc563f2010-07-19 21:46:24 +0000772 return false;
773
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000774error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000775 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000776 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000777 PreprocessorOpts.eraseRemappedFile(
778 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000779 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000780 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregor671947b2010-08-19 01:33:06 +0000781 delete OverrideMainBuffer;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000782 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000783
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000784 Clang.takeSourceManager();
785 Clang.takeFileManager();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000786 Invocation.reset(Clang.takeInvocation());
787 return true;
788}
789
Douglas Gregor44c181a2010-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 Gregor6bf18302010-08-11 13:06:56 +0000805 P.appendSuffix("pch");
Douglas Gregor44c181a2010-07-23 00:33:23 +0000806 if (P.createTemporaryFileOnDisk())
807 return std::string();
808
Douglas Gregor44c181a2010-07-23 00:33:23 +0000809 return P.str();
810}
811
Douglas Gregorf4f6c9d2010-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 Gregordf95a132010-08-09 20:45:32 +0000816ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
817 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000818 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000819 PreprocessorOptions &PreprocessorOpts
Douglas Gregor175c4a92010-07-23 23:58:40 +0000820 = Invocation.getPreprocessorOpts();
821 CreatedBuffer = false;
822
Douglas Gregor44c181a2010-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 Gregor175c4a92010-07-23 23:58:40 +0000826 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor44c181a2010-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 Gregor175c4a92010-07-23 23:58:40 +0000831 M = PreprocessorOpts.remapped_file_begin(),
832 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-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 Gregor175c4a92010-07-23 23:58:40 +0000839 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000840 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000841 CreatedBuffer = false;
842 }
843
Douglas Gregor44c181a2010-07-23 00:33:23 +0000844 Buffer = llvm::MemoryBuffer::getFile(M->second);
845 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000846 return std::make_pair((llvm::MemoryBuffer*)0,
847 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000848 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000849
Douglas Gregor175c4a92010-07-23 23:58:40 +0000850 // Remove this remapping. We've captured the buffer already.
Douglas Gregor44c181a2010-07-23 00:33:23 +0000851 M = PreprocessorOpts.eraseRemappedFile(M);
852 E = PreprocessorOpts.remapped_file_end();
853 }
854 }
855 }
856
857 // Check whether there is a file-buffer remapping. It supercedes the
858 // file-file remapping.
859 for (PreprocessorOptions::remapped_file_buffer_iterator
860 M = PreprocessorOpts.remapped_file_buffer_begin(),
861 E = PreprocessorOpts.remapped_file_buffer_end();
862 M != E;
863 ++M) {
864 llvm::sys::PathWithStatus MPath(M->first);
865 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
866 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
867 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000868 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000869 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000870 CreatedBuffer = false;
871 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000872
Douglas Gregor175c4a92010-07-23 23:58:40 +0000873 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
874
875 // Remove this remapping. We've captured the buffer already.
Douglas Gregor44c181a2010-07-23 00:33:23 +0000876 M = PreprocessorOpts.eraseRemappedFile(M);
877 E = PreprocessorOpts.remapped_file_buffer_end();
878 }
879 }
Douglas Gregor175c4a92010-07-23 23:58:40 +0000880 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000881 }
882
883 // If the main source file was not remapped, load it now.
884 if (!Buffer) {
885 Buffer = llvm::MemoryBuffer::getFile(FrontendOpts.Inputs[0].second);
886 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000887 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000888
889 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000890 }
891
Douglas Gregordf95a132010-08-09 20:45:32 +0000892 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000893}
894
Douglas Gregor754f3492010-07-24 00:38:13 +0000895static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
896 bool DeleteOld,
897 unsigned NewSize,
898 llvm::StringRef NewName) {
899 llvm::MemoryBuffer *Result
900 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
901 memcpy(const_cast<char*>(Result->getBufferStart()),
902 Old->getBufferStart(), Old->getBufferSize());
903 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000904 ' ', NewSize - Old->getBufferSize() - 1);
905 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +0000906
907 if (DeleteOld)
908 delete Old;
909
910 return Result;
911}
912
Douglas Gregor175c4a92010-07-23 23:58:40 +0000913/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
914/// the source file.
915///
916/// This routine will compute the preamble of the main source file. If a
917/// non-trivial preamble is found, it will precompile that preamble into a
918/// precompiled header so that the precompiled preamble can be used to reduce
919/// reparsing time. If a precompiled preamble has already been constructed,
920/// this routine will determine if it is still valid and, if so, avoid
921/// rebuilding the precompiled preamble.
922///
Douglas Gregordf95a132010-08-09 20:45:32 +0000923/// \param AllowRebuild When true (the default), this routine is
924/// allowed to rebuild the precompiled preamble if it is found to be
925/// out-of-date.
926///
927/// \param MaxLines When non-zero, the maximum number of lines that
928/// can occur within the preamble.
929///
Douglas Gregor754f3492010-07-24 00:38:13 +0000930/// \returns If the precompiled preamble can be used, returns a newly-allocated
931/// buffer that should be used in place of the main file when doing so.
932/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +0000933llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
934 bool AllowRebuild,
935 unsigned MaxLines) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000936 CompilerInvocation PreambleInvocation(*Invocation);
937 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
938 PreprocessorOptions &PreprocessorOpts
939 = PreambleInvocation.getPreprocessorOpts();
940
941 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000942 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregordf95a132010-08-09 20:45:32 +0000943 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +0000944
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000945 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000946 // We couldn't find a preamble in the main source. Clear out the current
947 // preamble, if we have one. It's obviously no good any more.
948 Preamble.clear();
949 if (!PreambleFile.empty()) {
Douglas Gregor385103b2010-07-30 20:58:08 +0000950 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000951 PreambleFile.clear();
952 }
953 if (CreatedPreambleBuffer)
954 delete NewPreamble.first;
Douglas Gregoreababfb2010-08-04 05:53:38 +0000955
956 // The next time we actually see a preamble, precompile it.
957 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +0000958 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000959 }
960
961 if (!Preamble.empty()) {
962 // We've previously computed a preamble. Check whether we have the same
963 // preamble now that we did before, and that there's enough space in
964 // the main-file buffer within the precompiled preamble to fit the
965 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000966 if (Preamble.size() == NewPreamble.second.first &&
967 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +0000968 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor175c4a92010-07-23 23:58:40 +0000969 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000970 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000971 // The preamble has not changed. We may be able to re-use the precompiled
972 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000973
Douglas Gregorcc5888d2010-07-31 00:40:00 +0000974 // Check that none of the files used by the preamble have changed.
975 bool AnyFileChanged = false;
976
977 // First, make a record of those files that have been overridden via
978 // remapping or unsaved_files.
979 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
980 for (PreprocessorOptions::remapped_file_iterator
981 R = PreprocessorOpts.remapped_file_begin(),
982 REnd = PreprocessorOpts.remapped_file_end();
983 !AnyFileChanged && R != REnd;
984 ++R) {
985 struct stat StatBuf;
986 if (stat(R->second.c_str(), &StatBuf)) {
987 // If we can't stat the file we're remapping to, assume that something
988 // horrible happened.
989 AnyFileChanged = true;
990 break;
991 }
Douglas Gregor754f3492010-07-24 00:38:13 +0000992
Douglas Gregorcc5888d2010-07-31 00:40:00 +0000993 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
994 StatBuf.st_mtime);
995 }
996 for (PreprocessorOptions::remapped_file_buffer_iterator
997 R = PreprocessorOpts.remapped_file_buffer_begin(),
998 REnd = PreprocessorOpts.remapped_file_buffer_end();
999 !AnyFileChanged && R != REnd;
1000 ++R) {
1001 // FIXME: Should we actually compare the contents of file->buffer
1002 // remappings?
1003 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1004 0);
1005 }
1006
1007 // Check whether anything has changed.
1008 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1009 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1010 !AnyFileChanged && F != FEnd;
1011 ++F) {
1012 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1013 = OverriddenFiles.find(F->first());
1014 if (Overridden != OverriddenFiles.end()) {
1015 // This file was remapped; check whether the newly-mapped file
1016 // matches up with the previous mapping.
1017 if (Overridden->second != F->second)
1018 AnyFileChanged = true;
1019 continue;
1020 }
1021
1022 // The file was not remapped; check whether it has changed on disk.
1023 struct stat StatBuf;
1024 if (stat(F->first(), &StatBuf)) {
1025 // If we can't stat the file, assume that something horrible happened.
1026 AnyFileChanged = true;
1027 } else if (StatBuf.st_size != F->second.first ||
1028 StatBuf.st_mtime != F->second.second)
1029 AnyFileChanged = true;
1030 }
1031
1032 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001033 // Okay! We can re-use the precompiled preamble.
1034
1035 // Set the state of the diagnostic object to mimic its state
1036 // after parsing the preamble.
1037 getDiagnostics().Reset();
1038 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1039 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
1040 StoredDiagnostics.erase(
1041 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
1042 StoredDiagnostics.end());
1043
1044 // Create a version of the main file buffer that is padded to
1045 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001046 return CreatePaddedMainFileBuffer(NewPreamble.first,
1047 CreatedPreambleBuffer,
1048 PreambleReservedSize,
1049 FrontendOpts.Inputs[0].second);
1050 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001051 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001052
1053 // If we aren't allowed to rebuild the precompiled preamble, just
1054 // return now.
1055 if (!AllowRebuild)
1056 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001057
1058 // We can't reuse the previously-computed preamble. Build a new one.
1059 Preamble.clear();
Douglas Gregor385103b2010-07-30 20:58:08 +00001060 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001061 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001062 } else if (!AllowRebuild) {
1063 // We aren't allowed to rebuild the precompiled preamble; just
1064 // return now.
1065 return 0;
1066 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001067
1068 // If the preamble rebuild counter > 1, it's because we previously
1069 // failed to build a preamble and we're not yet ready to try
1070 // again. Decrement the counter and return a failure.
1071 if (PreambleRebuildCounter > 1) {
1072 --PreambleRebuildCounter;
1073 return 0;
1074 }
1075
Douglas Gregor175c4a92010-07-23 23:58:40 +00001076 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor385103b2010-07-30 20:58:08 +00001077 llvm::Timer *PreambleTimer = 0;
1078 if (TimerGroup.get()) {
1079 PreambleTimer = new llvm::Timer("Precompiling preamble", *TimerGroup);
1080 PreambleTimer->startTimer();
1081 Timers.push_back(PreambleTimer);
1082 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001083
1084 // Create a new buffer that stores the preamble. The buffer also contains
1085 // extra space for the original contents of the file (which will be present
1086 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001087 // grows.
1088 PreambleReservedSize = NewPreamble.first->getBufferSize();
1089 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001090 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001091 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001092 PreambleReservedSize *= 2;
1093
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001094 // Save the preamble text for later; we'll need to compare against it for
1095 // subsequent reparses.
1096 Preamble.assign(NewPreamble.first->getBufferStart(),
1097 NewPreamble.first->getBufferStart()
1098 + NewPreamble.second.first);
1099 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1100
Douglas Gregor671947b2010-08-19 01:33:06 +00001101 delete PreambleBuffer;
1102 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001103 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001104 FrontendOpts.Inputs[0].second);
1105 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001106 NewPreamble.first->getBufferStart(), Preamble.size());
1107 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001108 ' ', PreambleReservedSize - Preamble.size() - 1);
1109 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001110
1111 // Remap the main source file to the preamble buffer.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001112 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001113 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1114
1115 // Tell the compiler invocation to generate a temporary precompiled header.
1116 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Sebastian Redlf65339e2010-08-06 00:35:11 +00001117 // FIXME: Set ChainedPCH unconditionally, once it is ready.
1118 if (::getenv("LIBCLANG_CHAINING"))
1119 FrontendOpts.ChainedPCH = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001120 // FIXME: Generate the precompiled header into memory?
Douglas Gregor385103b2010-07-30 20:58:08 +00001121 FrontendOpts.OutputFile = GetPreamblePCHPath();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001122
1123 // Create the compiler instance to use for building the precompiled preamble.
1124 CompilerInstance Clang;
1125 Clang.setInvocation(&PreambleInvocation);
1126 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1127
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001128 // Set up diagnostics, capturing all of the diagnostics produced.
Douglas Gregor44c181a2010-07-23 00:33:23 +00001129 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001130 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
1131 getDiagnostics(),
1132 StoredDiagnostics);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001133
1134 // Create the target instance.
1135 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1136 Clang.getTargetOpts()));
1137 if (!Clang.hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001138 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1139 Preamble.clear();
1140 if (CreatedPreambleBuffer)
1141 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +00001142 if (PreambleTimer)
1143 PreambleTimer->stopTimer();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001144 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001145 PreprocessorOpts.eraseRemappedFile(
1146 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001147 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001148 }
1149
1150 // Inform the target of the language options.
1151 //
1152 // FIXME: We shouldn't need to do this, the target should be immutable once
1153 // created. This complexity should be lifted elsewhere.
1154 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1155
1156 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1157 "Invocation must have exactly one source file!");
1158 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1159 "FIXME: AST inputs not yet supported here!");
1160 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1161 "IR inputs not support here!");
1162
1163 // Clear out old caches and data.
1164 StoredDiagnostics.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001165 TopLevelDecls.clear();
1166 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001167
1168 // Create a file manager object to provide access to and cache the filesystem.
1169 Clang.setFileManager(new FileManager);
1170
1171 // Create the source manager.
1172 Clang.setSourceManager(new SourceManager(getDiagnostics()));
1173
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001174 llvm::OwningPtr<PrecompilePreambleAction> Act;
1175 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001176 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1177 Clang.getFrontendOpts().Inputs[0].first)) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001178 Clang.takeInvocation();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001179 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1180 Preamble.clear();
1181 if (CreatedPreambleBuffer)
1182 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +00001183 if (PreambleTimer)
1184 PreambleTimer->stopTimer();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001185 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001186 PreprocessorOpts.eraseRemappedFile(
1187 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001188 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001189 }
1190
1191 Act->Execute();
1192 Act->EndSourceFile();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001193 Clang.takeInvocation();
1194
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001195 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001196 // There were errors parsing the preamble, so no precompiled header was
1197 // generated. Forget that we even tried.
1198 // FIXME: Should we leave a note for ourselves to try again?
1199 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1200 Preamble.clear();
1201 if (CreatedPreambleBuffer)
1202 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +00001203 if (PreambleTimer)
1204 PreambleTimer->stopTimer();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001205 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001206 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001207 PreprocessorOpts.eraseRemappedFile(
1208 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001209 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001210 }
1211
1212 // Keep track of the preamble we precompiled.
1213 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001214 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1215 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001216
1217 // Keep track of all of the files that the source manager knows about,
1218 // so we can verify whether they have changed or not.
1219 FilesInPreamble.clear();
1220 SourceManager &SourceMgr = Clang.getSourceManager();
1221 const llvm::MemoryBuffer *MainFileBuffer
1222 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1223 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1224 FEnd = SourceMgr.fileinfo_end();
1225 F != FEnd;
1226 ++F) {
1227 const FileEntry *File = F->second->Entry;
1228 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1229 continue;
1230
1231 FilesInPreamble[File->getName()]
1232 = std::make_pair(F->second->getSize(), File->getModificationTime());
1233 }
1234
Douglas Gregor385103b2010-07-30 20:58:08 +00001235 if (PreambleTimer)
1236 PreambleTimer->stopTimer();
1237
Douglas Gregoreababfb2010-08-04 05:53:38 +00001238 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001239 PreprocessorOpts.eraseRemappedFile(
1240 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001241 return CreatePaddedMainFileBuffer(NewPreamble.first,
1242 CreatedPreambleBuffer,
1243 PreambleReservedSize,
1244 FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001245}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001246
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001247void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1248 std::vector<Decl *> Resolved;
1249 Resolved.reserve(TopLevelDeclsInPreamble.size());
1250 ExternalASTSource &Source = *getASTContext().getExternalSource();
1251 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1252 // Resolve the declaration ID to an actual declaration, possibly
1253 // deserializing the declaration in the process.
1254 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1255 if (D)
1256 Resolved.push_back(D);
1257 }
1258 TopLevelDeclsInPreamble.clear();
1259 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1260}
1261
1262unsigned ASTUnit::getMaxPCHLevel() const {
1263 if (!getOnlyLocalDecls())
1264 return Decl::MaxPCHLevel;
1265
1266 unsigned Result = 0;
1267 if (isMainFileAST() || SavedMainFileBuffer)
1268 ++Result;
1269 return Result;
1270}
1271
Douglas Gregorabc563f2010-07-19 21:46:24 +00001272ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1273 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1274 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001275 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001276 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001277 bool CompleteTranslationUnit,
1278 bool CacheCodeCompletionResults) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001279 if (!Diags.getPtr()) {
1280 // No diagnostics engine was provided, so create our own diagnostics object
1281 // with the default options.
1282 DiagnosticOptions DiagOpts;
1283 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
1284 }
1285
1286 // Create the AST unit.
1287 llvm::OwningPtr<ASTUnit> AST;
1288 AST.reset(new ASTUnit(false));
1289 AST->Diagnostics = Diags;
1290 AST->CaptureDiagnostics = CaptureDiagnostics;
1291 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregordf95a132010-08-09 20:45:32 +00001292 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001293 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001294 AST->Invocation.reset(CI);
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001295 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001296
Douglas Gregor385103b2010-07-30 20:58:08 +00001297 if (getenv("LIBCLANG_TIMING"))
1298 AST->TimerGroup.reset(
1299 new llvm::TimerGroup(CI->getFrontendOpts().Inputs[0].second));
1300
1301
Douglas Gregor754f3492010-07-24 00:38:13 +00001302 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorfd0b8702010-07-28 22:12:37 +00001303 // FIXME: When C++ PCH is ready, allow use of it for a precompiled preamble.
Douglas Gregoreababfb2010-08-04 05:53:38 +00001304 if (PrecompilePreamble && !CI->getLangOpts().CPlusPlus) {
1305 AST->PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001306 OverrideMainBuffer = AST->getMainBufferWithPrecompiledPreamble();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001307 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001308
Douglas Gregor385103b2010-07-30 20:58:08 +00001309 llvm::Timer *ParsingTimer = 0;
1310 if (AST->TimerGroup.get()) {
1311 ParsingTimer = new llvm::Timer("Initial parse", *AST->TimerGroup);
1312 ParsingTimer->startTimer();
1313 AST->Timers.push_back(ParsingTimer);
1314 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001315
Douglas Gregor385103b2010-07-30 20:58:08 +00001316 bool Failed = AST->Parse(OverrideMainBuffer);
1317 if (ParsingTimer)
1318 ParsingTimer->stopTimer();
1319
1320 return Failed? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001321}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001322
1323ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1324 const char **ArgEnd,
Douglas Gregor28019772010-04-05 23:52:57 +00001325 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001326 llvm::StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001327 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001328 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001329 unsigned NumRemappedFiles,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001330 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001331 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001332 bool CompleteTranslationUnit,
1333 bool CacheCodeCompletionResults) {
Douglas Gregorbdbb0042010-08-18 22:29:43 +00001334 bool CreatedDiagnosticsObject = false;
1335
Douglas Gregor28019772010-04-05 23:52:57 +00001336 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001337 // No diagnostics engine was provided, so create our own diagnostics object
1338 // with the default options.
1339 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001340 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00001341 CreatedDiagnosticsObject = true;
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001342 }
1343
Daniel Dunbar7b556682009-12-02 03:23:45 +00001344 llvm::SmallVector<const char *, 16> Args;
1345 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1346 Args.insert(Args.end(), ArgBegin, ArgEnd);
1347
1348 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1349 // also want to force it to use clang.
1350 Args.push_back("-fsyntax-only");
1351
Daniel Dunbar869824e2009-12-13 03:46:13 +00001352 // FIXME: We shouldn't have to pass in the path info.
Daniel Dunbar0bbad512010-07-19 00:44:04 +00001353 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001354 "a.out", false, false, *Diags);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001355
1356 // Don't check that inputs exist, they have been remapped.
1357 TheDriver.setCheckInputsExist(false);
1358
Daniel Dunbar7b556682009-12-02 03:23:45 +00001359 llvm::OwningPtr<driver::Compilation> C(
1360 TheDriver.BuildCompilation(Args.size(), Args.data()));
1361
1362 // We expect to get back exactly one command job, if we didn't something
1363 // failed.
1364 const driver::JobList &Jobs = C->getJobs();
1365 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1366 llvm::SmallString<256> Msg;
1367 llvm::raw_svector_ostream OS(Msg);
1368 C->PrintJob(OS, C->getJobs(), "; ", true);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001369 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001370 return 0;
1371 }
1372
1373 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1374 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001375 Diags->Report(diag::err_fe_expected_clang_command);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001376 return 0;
1377 }
1378
1379 const driver::ArgStringList &CCArgs = Cmd->getArguments();
Daniel Dunbar807b0612010-01-30 21:47:16 +00001380 llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
Dan Gohmancb421fa2010-04-19 16:39:44 +00001381 CompilerInvocation::CreateFromArgs(*CI,
1382 const_cast<const char **>(CCArgs.data()),
1383 const_cast<const char **>(CCArgs.data()) +
Douglas Gregor44c181a2010-07-23 00:33:23 +00001384 CCArgs.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001385 *Diags);
Daniel Dunbar1e69fe32009-12-13 03:45:58 +00001386
Douglas Gregor4db64a42010-01-23 00:14:00 +00001387 // Override any files that need remapping
1388 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar807b0612010-01-30 21:47:16 +00001389 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbarb26d4832010-02-16 01:55:04 +00001390 RemappedFiles[I].second);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001391
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001392 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001393 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001394
Douglas Gregorf4210892010-08-18 23:38:21 +00001395 CI->getFrontendOpts().DisableFree = false;
Douglas Gregora88084b2010-02-18 18:08:43 +00001396 return LoadFromCompilerInvocation(CI.take(), Diags, OnlyLocalDecls,
Douglas Gregordf95a132010-08-09 20:45:32 +00001397 CaptureDiagnostics, PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001398 CompleteTranslationUnit,
1399 CacheCodeCompletionResults);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001400}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001401
1402bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1403 if (!Invocation.get())
1404 return true;
1405
Douglas Gregor385103b2010-07-30 20:58:08 +00001406 llvm::Timer *ReparsingTimer = 0;
1407 if (TimerGroup.get()) {
1408 ReparsingTimer = new llvm::Timer("Reparse", *TimerGroup);
1409 ReparsingTimer->startTimer();
1410 Timers.push_back(ReparsingTimer);
1411 }
1412
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001413 // Remap files.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001414 Invocation->getPreprocessorOpts().clearRemappedFiles();
1415 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1416 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1417 RemappedFiles[I].second);
1418
Douglas Gregoreababfb2010-08-04 05:53:38 +00001419 // If we have a preamble file lying around, or if we might try to
1420 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00001421 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregoreababfb2010-08-04 05:53:38 +00001422 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregordf95a132010-08-09 20:45:32 +00001423 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001424
Douglas Gregorabc563f2010-07-19 21:46:24 +00001425 // Clear out the diagnostics state.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001426 if (!OverrideMainBuffer)
1427 getDiagnostics().Reset();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001428
Douglas Gregor175c4a92010-07-23 23:58:40 +00001429 // Parse the sources
Douglas Gregor754f3492010-07-24 00:38:13 +00001430 bool Result = Parse(OverrideMainBuffer);
Douglas Gregor385103b2010-07-30 20:58:08 +00001431 if (ReparsingTimer)
1432 ReparsingTimer->stopTimer();
Douglas Gregor727d93e2010-08-17 00:40:40 +00001433
1434 if (ShouldCacheCodeCompletionResults) {
1435 if (CacheCodeCompletionCoolDown > 0)
1436 --CacheCodeCompletionCoolDown;
1437 else if (top_level_size() != NumTopLevelDeclsAtLastCompletionCache)
1438 CacheCodeCompletionResults();
1439 }
1440
Douglas Gregor175c4a92010-07-23 23:58:40 +00001441 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001442}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001443
Douglas Gregor87c08a52010-08-13 22:48:40 +00001444//----------------------------------------------------------------------------//
1445// Code completion
1446//----------------------------------------------------------------------------//
1447
1448namespace {
1449 /// \brief Code completion consumer that combines the cached code-completion
1450 /// results from an ASTUnit with the code-completion results provided to it,
1451 /// then passes the result on to
1452 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1453 unsigned NormalContexts;
1454 ASTUnit &AST;
1455 CodeCompleteConsumer &Next;
1456
1457 public:
1458 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor8071e422010-08-15 06:18:01 +00001459 bool IncludeMacros, bool IncludeCodePatterns,
1460 bool IncludeGlobals)
1461 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001462 Next.isOutputBinary()), AST(AST), Next(Next)
1463 {
1464 // Compute the set of contexts in which we will look when we don't have
1465 // any information about the specific context.
1466 NormalContexts
1467 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
1468 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
1469 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1470 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1471 | (1 << (CodeCompletionContext::CCC_Statement - 1))
1472 | (1 << (CodeCompletionContext::CCC_Expression - 1))
1473 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1474 | (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
1475 | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
1476
1477 if (AST.getASTContext().getLangOptions().CPlusPlus)
1478 NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1))
1479 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
1480 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
1481 }
1482
1483 virtual void ProcessCodeCompleteResults(Sema &S,
1484 CodeCompletionContext Context,
1485 Result *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001486 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001487
1488 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1489 OverloadCandidate *Candidates,
1490 unsigned NumCandidates) {
1491 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1492 }
1493 };
1494}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001495
Douglas Gregor5f808c22010-08-16 21:18:39 +00001496/// \brief Helper function that computes which global names are hidden by the
1497/// local code-completion results.
1498void CalculateHiddenNames(const CodeCompletionContext &Context,
1499 CodeCompleteConsumer::Result *Results,
1500 unsigned NumResults,
1501 ASTContext &Ctx,
1502 llvm::StringSet<> &HiddenNames) {
1503 bool OnlyTagNames = false;
1504 switch (Context.getKind()) {
1505 case CodeCompletionContext::CCC_Other:
1506 case CodeCompletionContext::CCC_TopLevel:
1507 case CodeCompletionContext::CCC_ObjCInterface:
1508 case CodeCompletionContext::CCC_ObjCImplementation:
1509 case CodeCompletionContext::CCC_ObjCIvarList:
1510 case CodeCompletionContext::CCC_ClassStructUnion:
1511 case CodeCompletionContext::CCC_Statement:
1512 case CodeCompletionContext::CCC_Expression:
1513 case CodeCompletionContext::CCC_ObjCMessageReceiver:
1514 case CodeCompletionContext::CCC_MemberAccess:
1515 case CodeCompletionContext::CCC_Namespace:
1516 case CodeCompletionContext::CCC_Type:
1517 break;
1518
1519 case CodeCompletionContext::CCC_EnumTag:
1520 case CodeCompletionContext::CCC_UnionTag:
1521 case CodeCompletionContext::CCC_ClassOrStructTag:
1522 OnlyTagNames = true;
1523 break;
1524
1525 case CodeCompletionContext::CCC_ObjCProtocolName:
1526 // If we're just looking for protocol names, nothing can hide them.
1527 return;
1528 }
1529
1530 typedef CodeCompleteConsumer::Result Result;
1531 for (unsigned I = 0; I != NumResults; ++I) {
1532 if (Results[I].Kind != Result::RK_Declaration)
1533 continue;
1534
1535 unsigned IDNS
1536 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1537
1538 bool Hiding = false;
1539 if (OnlyTagNames)
1540 Hiding = (IDNS & Decl::IDNS_Tag);
1541 else {
1542 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00001543 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1544 Decl::IDNS_NonMemberOperator);
Douglas Gregor5f808c22010-08-16 21:18:39 +00001545 if (Ctx.getLangOptions().CPlusPlus)
1546 HiddenIDNS |= Decl::IDNS_Tag;
1547 Hiding = (IDNS & HiddenIDNS);
1548 }
1549
1550 if (!Hiding)
1551 continue;
1552
1553 DeclarationName Name = Results[I].Declaration->getDeclName();
1554 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1555 HiddenNames.insert(Identifier->getName());
1556 else
1557 HiddenNames.insert(Name.getAsString());
1558 }
1559}
1560
1561
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001562void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1563 CodeCompletionContext Context,
1564 Result *Results,
1565 unsigned NumResults) {
1566 // Merge the results we were given with the results we cached.
1567 bool AddedResult = false;
Douglas Gregor5f808c22010-08-16 21:18:39 +00001568 unsigned InContexts
1569 = (Context.getKind() == CodeCompletionContext::CCC_Other? NormalContexts
1570 : (1 << (Context.getKind() - 1)));
1571
1572 // Contains the set of names that are hidden by "local" completion results.
1573 llvm::StringSet<> HiddenNames;
1574
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001575 typedef CodeCompleteConsumer::Result Result;
1576 llvm::SmallVector<Result, 8> AllResults;
1577 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00001578 C = AST.cached_completion_begin(),
1579 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001580 C != CEnd; ++C) {
1581 // If the context we are in matches any of the contexts we are
1582 // interested in, we'll add this result.
1583 if ((C->ShowInContexts & InContexts) == 0)
1584 continue;
1585
1586 // If we haven't added any results previously, do so now.
1587 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00001588 CalculateHiddenNames(Context, Results, NumResults, S.Context,
1589 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001590 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1591 AddedResult = true;
1592 }
1593
Douglas Gregor5f808c22010-08-16 21:18:39 +00001594 // Determine whether this global completion result is hidden by a local
1595 // completion result. If so, skip it.
1596 if (C->Kind != CXCursor_MacroDefinition &&
1597 HiddenNames.count(C->Completion->getTypedText()))
1598 continue;
1599
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001600 // Adjust priority based on similar type classes.
1601 unsigned Priority = C->Priority;
1602 if (!Context.getPreferredType().isNull()) {
1603 if (C->Kind == CXCursor_MacroDefinition) {
1604 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
1605 Context.getPreferredType()->isAnyPointerType());
1606 } else if (C->Type) {
1607 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00001608 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001609 Context.getPreferredType().getUnqualifiedType());
1610 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
1611 if (ExpectedSTC == C->TypeClass) {
1612 // We know this type is similar; check for an exact match.
1613 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00001614 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001615 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00001616 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001617 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
1618 Priority /= CCF_ExactTypeMatch;
1619 else
1620 Priority /= CCF_SimilarTypeMatch;
1621 }
1622 }
1623 }
1624
1625 AllResults.push_back(Result(C->Completion, Priority, C->Kind));
1626 }
1627
1628 // If we did not add any cached completion results, just forward the
1629 // results we were given to the next consumer.
1630 if (!AddedResult) {
1631 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
1632 return;
1633 }
1634
1635 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
1636 AllResults.size());
1637}
1638
1639
1640
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001641void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
1642 RemappedFile *RemappedFiles,
1643 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00001644 bool IncludeMacros,
1645 bool IncludeCodePatterns,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001646 CodeCompleteConsumer &Consumer,
1647 Diagnostic &Diag, LangOptions &LangOpts,
1648 SourceManager &SourceMgr, FileManager &FileMgr,
1649 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics) {
1650 if (!Invocation.get())
1651 return;
1652
Douglas Gregordf95a132010-08-09 20:45:32 +00001653 llvm::Timer *CompletionTimer = 0;
1654 if (TimerGroup.get()) {
1655 llvm::SmallString<128> TimerName;
1656 llvm::raw_svector_ostream TimerNameOut(TimerName);
1657 TimerNameOut << "Code completion @ " << File << ":" << Line << ":"
1658 << Column;
1659 CompletionTimer = new llvm::Timer(TimerNameOut.str(), *TimerGroup);
1660 CompletionTimer->startTimer();
1661 Timers.push_back(CompletionTimer);
1662 }
1663
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001664 CompilerInvocation CCInvocation(*Invocation);
1665 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
1666 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001667
Douglas Gregor87c08a52010-08-13 22:48:40 +00001668 FrontendOpts.ShowMacrosInCodeCompletion
1669 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001670 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor8071e422010-08-15 06:18:01 +00001671 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
1672 = CachedCompletionResults.empty();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001673 FrontendOpts.CodeCompletionAt.FileName = File;
1674 FrontendOpts.CodeCompletionAt.Line = Line;
1675 FrontendOpts.CodeCompletionAt.Column = Column;
1676
Douglas Gregorcee235c2010-08-05 09:09:23 +00001677 // Turn on spell-checking when performing code completion. It leads
1678 // to better results.
1679 unsigned SpellChecking = CCInvocation.getLangOpts().SpellChecking;
1680 CCInvocation.getLangOpts().SpellChecking = 1;
1681
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001682 // Set the language options appropriately.
1683 LangOpts = CCInvocation.getLangOpts();
1684
1685 CompilerInstance Clang;
1686 Clang.setInvocation(&CCInvocation);
1687 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1688
1689 // Set up diagnostics, capturing any diagnostics produced.
1690 Clang.setDiagnostics(&Diag);
1691 CaptureDroppedDiagnostics Capture(true,
1692 Clang.getDiagnostics(),
1693 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001694
1695 // Create the target instance.
1696 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1697 Clang.getTargetOpts()));
1698 if (!Clang.hasTarget()) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001699 Clang.takeInvocation();
Douglas Gregorbdbb0042010-08-18 22:29:43 +00001700 CCInvocation.getLangOpts().SpellChecking = SpellChecking;
1701 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001702 }
1703
1704 // Inform the target of the language options.
1705 //
1706 // FIXME: We shouldn't need to do this, the target should be immutable once
1707 // created. This complexity should be lifted elsewhere.
1708 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1709
1710 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1711 "Invocation must have exactly one source file!");
1712 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1713 "FIXME: AST inputs not yet supported here!");
1714 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1715 "IR inputs not support here!");
1716
1717
1718 // Use the source and file managers that we were given.
1719 Clang.setFileManager(&FileMgr);
1720 Clang.setSourceManager(&SourceMgr);
1721
1722 // Remap files.
1723 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00001724 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001725 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1726 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
1727 RemappedFiles[I].second);
1728
Douglas Gregor87c08a52010-08-13 22:48:40 +00001729 // Use the code completion consumer we were given, but adding any cached
1730 // code-completion results.
1731 AugmentedCodeCompleteConsumer
1732 AugmentedConsumer(*this, Consumer, FrontendOpts.ShowMacrosInCodeCompletion,
Douglas Gregor8071e422010-08-15 06:18:01 +00001733 FrontendOpts.ShowCodePatternsInCodeCompletion,
1734 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001735 Clang.setCodeCompletionConsumer(&AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001736
Douglas Gregordf95a132010-08-09 20:45:32 +00001737 // If we have a precompiled preamble, try to use it. We only allow
1738 // the use of the precompiled preamble if we're if the completion
1739 // point is within the main file, after the end of the precompiled
1740 // preamble.
1741 llvm::MemoryBuffer *OverrideMainBuffer = 0;
1742 if (!PreambleFile.empty()) {
1743 using llvm::sys::FileStatus;
1744 llvm::sys::PathWithStatus CompleteFilePath(File);
1745 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
1746 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
1747 if (const FileStatus *MainStatus = MainPath.getFileStatus())
1748 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
1749 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(false,
1750 Line);
1751 }
1752
1753 // If the main file has been overridden due to the use of a preamble,
1754 // make that override happen and introduce the preamble.
1755 if (OverrideMainBuffer) {
1756 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1757 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1758 PreprocessorOpts.PrecompiledPreambleBytes.second
1759 = PreambleEndsAtStartOfLine;
1760 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
1761 PreprocessorOpts.DisablePCHValidation = true;
1762
1763 // The stored diagnostics have the old source manager. Copy them
1764 // to our output set of stored diagnostics, updating the source
1765 // manager to the one we were given.
1766 for (unsigned I = 0, N = this->StoredDiagnostics.size(); I != N; ++I) {
1767 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
1768 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
1769 StoredDiagnostics[I].setLocation(Loc);
1770 }
1771 }
1772
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001773 llvm::OwningPtr<SyntaxOnlyAction> Act;
1774 Act.reset(new SyntaxOnlyAction);
1775 if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1776 Clang.getFrontendOpts().Inputs[0].first)) {
1777 Act->Execute();
1778 Act->EndSourceFile();
1779 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001780
1781 if (CompletionTimer)
1782 CompletionTimer->stopTimer();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001783
1784 // Steal back our resources.
Douglas Gregordf95a132010-08-09 20:45:32 +00001785 delete OverrideMainBuffer;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001786 Clang.takeFileManager();
1787 Clang.takeSourceManager();
1788 Clang.takeInvocation();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001789 Clang.takeCodeCompletionConsumer();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001790 CCInvocation.getLangOpts().SpellChecking = SpellChecking;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001791}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001792
1793bool ASTUnit::Save(llvm::StringRef File) {
1794 if (getDiagnostics().hasErrorOccurred())
1795 return true;
1796
1797 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
1798 // unconditionally create a stat cache when we parse the file?
1799 std::string ErrorInfo;
Benjamin Kramer1395c5d2010-08-15 16:54:31 +00001800 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo,
1801 llvm::raw_fd_ostream::F_Binary);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001802 if (!ErrorInfo.empty() || Out.has_error())
1803 return true;
1804
1805 std::vector<unsigned char> Buffer;
1806 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00001807 ASTWriter Writer(Stream);
1808 Writer.WriteAST(getSema(), 0, 0);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001809
1810 // Write the generated bitstream to "Out".
Douglas Gregorbdbb0042010-08-18 22:29:43 +00001811 if (!Buffer.empty())
1812 Out.write((char *)&Buffer.front(), Buffer.size());
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001813 Out.close();
1814 return Out.has_error();
1815}