blob: e8e80647b4080eb25dcda08745914a909100caca [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"
Douglas Gregor32be4a52010-10-11 21:37:58 +000028#include "clang/Frontend/Utils.h"
Sebastian Redl6ab7cd82010-08-18 23:57:17 +000029#include "clang/Serialization/ASTReader.h"
Sebastian Redl7faa2ec2010-08-18 23:56:37 +000030#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000031#include "clang/Lex/HeaderSearch.h"
32#include "clang/Lex/Preprocessor.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000033#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000034#include "clang/Basic/TargetInfo.h"
35#include "clang/Basic/Diagnostic.h"
Douglas Gregor349d38c2010-08-16 23:08:34 +000036#include "llvm/ADT/StringSet.h"
Douglas Gregor4db64a42010-01-23 00:14:00 +000037#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000038#include "llvm/System/Host.h"
Benjamin Kramer4a630d32009-10-18 11:34:14 +000039#include "llvm/System/Path.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000040#include "llvm/Support/raw_ostream.h"
Douglas Gregor385103b2010-07-30 20:58:08 +000041#include "llvm/Support/Timer.h"
Douglas Gregor44c181a2010-07-23 00:33:23 +000042#include <cstdlib>
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000043#include <cstdio>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000044#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000045using namespace clang;
46
Douglas Gregoreababfb2010-08-04 05:53:38 +000047/// \brief After failing to build a precompiled preamble (due to
48/// errors in the source that occurs in the preamble), the number of
49/// reparses during which we'll skip even trying to precompile the
50/// preamble.
51const unsigned DefaultPreambleRebuildInterval = 5;
52
Douglas Gregor3687e9d2010-04-05 21:10:19 +000053ASTUnit::ASTUnit(bool _MainFileIsAST)
Douglas Gregorabc563f2010-07-19 21:46:24 +000054 : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
Douglas Gregor4cd912a2010-10-12 00:50:20 +000055 CompleteTranslationUnit(true), NumStoredDiagnosticsFromDriver(0),
56 ConcurrencyCheckValue(CheckUnlocked),
Douglas Gregor671947b2010-08-19 01:33:06 +000057 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +000058 ShouldCacheCodeCompletionResults(false),
59 NumTopLevelDeclsAtLastCompletionCache(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +000060 CacheCodeCompletionCoolDown(0),
61 UnsafeToFree(false) {
Douglas Gregor385103b2010-07-30 20:58:08 +000062}
Douglas Gregor3687e9d2010-04-05 21:10:19 +000063
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000064ASTUnit::~ASTUnit() {
Douglas Gregorbdf60622010-03-05 21:16:25 +000065 ConcurrencyCheckValue = CheckLocked;
Douglas Gregorabc563f2010-07-19 21:46:24 +000066 CleanTemporaryFiles();
Douglas Gregor175c4a92010-07-23 23:58:40 +000067 if (!PreambleFile.empty())
Douglas Gregor385103b2010-07-30 20:58:08 +000068 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000069
70 // Free the buffers associated with remapped files. We are required to
71 // perform this operation here because we explicitly request that the
72 // compiler instance *not* free these buffers for each invocation of the
73 // parser.
74 if (Invocation.get()) {
75 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
76 for (PreprocessorOptions::remapped_file_buffer_iterator
77 FB = PPOpts.remapped_file_buffer_begin(),
78 FBEnd = PPOpts.remapped_file_buffer_end();
79 FB != FBEnd;
80 ++FB)
81 delete FB->second;
82 }
Douglas Gregor28233422010-07-27 14:52:07 +000083
84 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +000085 delete PreambleBuffer;
86
Douglas Gregor87c08a52010-08-13 22:48:40 +000087 ClearCachedCompletionResults();
88
Douglas Gregor8c8d5412010-09-24 21:18:36 +000089 if (TimerGroup)
90 TimerGroup->printAll(llvm::errs());
91
Douglas Gregor385103b2010-07-30 20:58:08 +000092 for (unsigned I = 0, N = Timers.size(); I != N; ++I)
93 delete Timers[I];
Douglas Gregorabc563f2010-07-19 21:46:24 +000094}
95
96void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor313e26c2010-02-18 23:35:40 +000097 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
98 TemporaryFiles[I].eraseFromDisk();
Douglas Gregorabc563f2010-07-19 21:46:24 +000099 TemporaryFiles.clear();
Steve Naroffe19944c2009-10-15 22:23:48 +0000100}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000101
Douglas Gregor8071e422010-08-15 06:18:01 +0000102/// \brief Determine the set of code-completion contexts in which this
103/// declaration should be shown.
104static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000105 const LangOptions &LangOpts,
106 bool &IsNestedNameSpecifier) {
107 IsNestedNameSpecifier = false;
108
Douglas Gregor8071e422010-08-15 06:18:01 +0000109 if (isa<UsingShadowDecl>(ND))
110 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
111 if (!ND)
112 return 0;
113
114 unsigned Contexts = 0;
115 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
116 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
117 // Types can appear in these contexts.
118 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
119 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
120 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
121 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
122 | (1 << (CodeCompletionContext::CCC_Statement - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000123 | (1 << (CodeCompletionContext::CCC_Type - 1))
124 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000125
126 // In C++, types can appear in expressions contexts (for functional casts).
127 if (LangOpts.CPlusPlus)
128 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
129
130 // In Objective-C, message sends can send interfaces. In Objective-C++,
131 // all types are available due to functional casts.
132 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
133 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
134
135 // Deal with tag names.
136 if (isa<EnumDecl>(ND)) {
137 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
138
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000139 // Part of the nested-name-specifier in C++0x.
Douglas Gregor8071e422010-08-15 06:18:01 +0000140 if (LangOpts.CPlusPlus0x)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000141 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000142 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
143 if (Record->isUnion())
144 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
145 else
146 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
147
Douglas Gregor8071e422010-08-15 06:18:01 +0000148 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000149 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000150 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000151 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000152 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
153 // Values can appear in these contexts.
154 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
155 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000156 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor8071e422010-08-15 06:18:01 +0000157 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
158 } else if (isa<ObjCProtocolDecl>(ND)) {
159 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
160 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000161 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000162
163 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000164 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000165 }
166
167 return Contexts;
168}
169
Douglas Gregor87c08a52010-08-13 22:48:40 +0000170void ASTUnit::CacheCodeCompletionResults() {
171 if (!TheSema)
172 return;
173
174 llvm::Timer *CachingTimer = 0;
175 if (TimerGroup.get()) {
176 CachingTimer = new llvm::Timer("Cache global code completions",
177 *TimerGroup);
178 CachingTimer->startTimer();
179 Timers.push_back(CachingTimer);
180 }
181
182 // Clear out the previous results.
183 ClearCachedCompletionResults();
184
185 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000186 typedef CodeCompletionResult Result;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000187 llvm::SmallVector<Result, 8> Results;
188 TheSema->GatherGlobalCodeCompletions(Results);
189
190 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000191 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
192
Douglas Gregor87c08a52010-08-13 22:48:40 +0000193 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
194 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000195 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000196 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000197 CachedCodeCompletionResult CachedResult;
198 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
199 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000200 Ctx->getLangOptions(),
201 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000202 CachedResult.Priority = Results[I].Priority;
203 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000204 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000205
Douglas Gregorf5586f62010-08-16 18:08:11 +0000206 // Keep track of the type of this completion in an ASTContext-agnostic
207 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000208 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000209 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000210 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000211 CachedResult.Type = 0;
212 } else {
213 CanQualType CanUsageType
214 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
215 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
216
217 // Determine whether we have already seen this type. If so, we save
218 // ourselves the work of formatting the type string by using the
219 // temporary, CanQualType-based hash table to find the associated value.
220 unsigned &TypeValue = CompletionTypes[CanUsageType];
221 if (TypeValue == 0) {
222 TypeValue = CompletionTypes.size();
223 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
224 = TypeValue;
225 }
226
227 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000228 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000229
Douglas Gregor8071e422010-08-15 06:18:01 +0000230 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000231
232 /// Handle nested-name-specifiers in C++.
233 if (TheSema->Context.getLangOptions().CPlusPlus &&
234 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
235 // The contexts in which a nested-name-specifier can appear in C++.
236 unsigned NNSContexts
237 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
238 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
239 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
240 | (1 << (CodeCompletionContext::CCC_Statement - 1))
241 | (1 << (CodeCompletionContext::CCC_Expression - 1))
242 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
243 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
244 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
245 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000246 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000247 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
248 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000249
250 if (isa<NamespaceDecl>(Results[I].Declaration) ||
251 isa<NamespaceAliasDecl>(Results[I].Declaration))
252 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
253
254 if (unsigned RemainingContexts
255 = NNSContexts & ~CachedResult.ShowInContexts) {
256 // If there any contexts where this completion can be a
257 // nested-name-specifier but isn't already an option, create a
258 // nested-name-specifier completion.
259 Results[I].StartsNestedNameSpecifier = true;
260 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
261 CachedResult.ShowInContexts = RemainingContexts;
262 CachedResult.Priority = CCP_NestedNameSpecifier;
263 CachedResult.TypeClass = STC_Void;
264 CachedResult.Type = 0;
265 CachedCompletionResults.push_back(CachedResult);
266 }
267 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000268 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000269 }
270
Douglas Gregor87c08a52010-08-13 22:48:40 +0000271 case Result::RK_Keyword:
272 case Result::RK_Pattern:
273 // Ignore keywords and patterns; we don't care, since they are so
274 // easily regenerated.
275 break;
276
277 case Result::RK_Macro: {
278 CachedCodeCompletionResult CachedResult;
279 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
280 CachedResult.ShowInContexts
281 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
282 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
283 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
284 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
285 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
286 | (1 << (CodeCompletionContext::CCC_Statement - 1))
287 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000288 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorf29c5232010-08-24 22:20:20 +0000289 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000290 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
291 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
292
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000293
Douglas Gregor87c08a52010-08-13 22:48:40 +0000294 CachedResult.Priority = Results[I].Priority;
295 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000296 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000297 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000298 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000299 CachedCompletionResults.push_back(CachedResult);
300 break;
301 }
302 }
303 Results[I].Destroy();
304 }
305
306 if (CachingTimer)
307 CachingTimer->stopTimer();
Douglas Gregor727d93e2010-08-17 00:40:40 +0000308
309 // Make a note of the state when we performed this caching.
310 NumTopLevelDeclsAtLastCompletionCache = top_level_size();
311 CacheCodeCompletionCoolDown = 15;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000312}
313
314void ASTUnit::ClearCachedCompletionResults() {
315 for (unsigned I = 0, N = CachedCompletionResults.size(); I != N; ++I)
316 delete CachedCompletionResults[I].Completion;
317 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000318 CachedCompletionTypes.clear();
Douglas Gregor87c08a52010-08-13 22:48:40 +0000319}
320
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000321namespace {
322
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000323/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000324/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000325class ASTInfoCollector : public ASTReaderListener {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000326 LangOptions &LangOpt;
327 HeaderSearch &HSI;
328 std::string &TargetTriple;
329 std::string &Predefines;
330 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000331
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000332 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000334public:
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000335 ASTInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000336 std::string &TargetTriple, std::string &Predefines,
337 unsigned &Counter)
338 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
339 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000340
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000341 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
342 LangOpt = LangOpts;
343 return false;
344 }
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000346 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000347 TargetTriple = Triple;
348 return false;
349 }
Mike Stump1eb44332009-09-09 15:08:12 +0000350
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000351 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000352 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000353 std::string &SuggestedPredefines) {
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000354 Predefines = Buffers[0].Data;
355 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
356 Predefines += Buffers[I].Data;
357 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000358 return false;
359 }
Mike Stump1eb44332009-09-09 15:08:12 +0000360
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000361 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000362 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
363 }
Mike Stump1eb44332009-09-09 15:08:12 +0000364
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000365 virtual void ReadCounter(unsigned Value) {
366 Counter = Value;
367 }
368};
369
Douglas Gregora88084b2010-02-18 18:08:43 +0000370class StoredDiagnosticClient : public DiagnosticClient {
371 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
372
373public:
374 explicit StoredDiagnosticClient(
375 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
376 : StoredDiags(StoredDiags) { }
377
378 virtual void HandleDiagnostic(Diagnostic::Level Level,
379 const DiagnosticInfo &Info);
380};
381
382/// \brief RAII object that optionally captures diagnostics, if
383/// there is no diagnostic client to capture them already.
384class CaptureDroppedDiagnostics {
385 Diagnostic &Diags;
386 StoredDiagnosticClient Client;
387 DiagnosticClient *PreviousClient;
388
389public:
390 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
391 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000392 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000393 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000394 if (RequestCapture || Diags.getClient() == 0) {
395 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000396 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000397 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000398 }
399
400 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000401 if (Diags.getClient() == &Client) {
402 Diags.takeClient();
403 Diags.setClient(PreviousClient);
404 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000405 }
406};
407
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000408} // anonymous namespace
409
Douglas Gregora88084b2010-02-18 18:08:43 +0000410void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
411 const DiagnosticInfo &Info) {
412 StoredDiags.push_back(StoredDiagnostic(Level, Info));
413}
414
Steve Naroff77accc12009-09-03 18:19:54 +0000415const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000416 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000417}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000418
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000419const std::string &ASTUnit::getASTFileName() {
420 assert(isMainFileAST() && "Not an ASTUnit from an AST file!");
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000421 return static_cast<ASTReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroffe19944c2009-10-15 22:23:48 +0000422}
423
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000424ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Douglas Gregor28019772010-04-05 23:52:57 +0000425 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000426 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000427 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000428 unsigned NumRemappedFiles,
429 bool CaptureDiagnostics) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000430 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
431
Douglas Gregor28019772010-04-05 23:52:57 +0000432 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000433 // No diagnostics engine was provided, so create our own diagnostics object
434 // with the default options.
435 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +0000436 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000437 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000438
439 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000440 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor28019772010-04-05 23:52:57 +0000441 AST->Diagnostics = Diags;
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000442 AST->FileMgr.reset(new FileManager);
443 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics()));
Steve Naroff36c44642009-10-19 14:34:22 +0000444 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000445
Douglas Gregora88084b2010-02-18 18:08:43 +0000446 // If requested, capture diagnostics in the ASTUnit.
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000447 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, AST->getDiagnostics(),
Douglas Gregor405634b2010-04-05 18:10:21 +0000448 AST->StoredDiagnostics);
Douglas Gregora88084b2010-02-18 18:08:43 +0000449
Douglas Gregor4db64a42010-01-23 00:14:00 +0000450 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
451 // Create the file entry for the file that we're mapping from.
452 const FileEntry *FromFile
453 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
454 RemappedFiles[I].second->getBufferSize(),
455 0);
456 if (!FromFile) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000457 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregor4db64a42010-01-23 00:14:00 +0000458 << RemappedFiles[I].first;
Douglas Gregorc8dfe5e2010-02-27 01:32:48 +0000459 delete RemappedFiles[I].second;
Douglas Gregor4db64a42010-01-23 00:14:00 +0000460 continue;
461 }
462
463 // Override the contents of the "from" file with the contents of
464 // the "to" file.
465 AST->getSourceManager().overrideFileContents(FromFile,
466 RemappedFiles[I].second);
467 }
468
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000469 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000470
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000471 LangOptions LangInfo;
472 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
473 std::string TargetTriple;
474 std::string Predefines;
475 unsigned Counter;
476
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000477 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000478
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000479 Reader.reset(new ASTReader(AST->getSourceManager(), AST->getFileManager(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000480 AST->getDiagnostics()));
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000481 Reader->setListener(new ASTInfoCollector(LangInfo, HeaderInfo, TargetTriple,
Daniel Dunbarcc318932009-09-03 05:59:35 +0000482 Predefines, Counter));
483
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +0000484 switch (Reader->ReadAST(Filename, ASTReader::MainFile)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000485 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000486 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000487
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000488 case ASTReader::Failure:
489 case ASTReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000490 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000491 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000492 }
Mike Stump1eb44332009-09-09 15:08:12 +0000493
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000494 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
495
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000496 // AST file loaded successfully. Now create the preprocessor.
Mike Stump1eb44332009-09-09 15:08:12 +0000497
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000498 // Get information about the target being compiled for.
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000499 //
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000500 // FIXME: This is broken, we should store the TargetOptions in the AST file.
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000501 TargetOptions TargetOpts;
502 TargetOpts.ABI = "";
John McCall875ab102010-08-22 06:43:33 +0000503 TargetOpts.CXXABI = "";
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000504 TargetOpts.CPU = "";
505 TargetOpts.Features.clear();
506 TargetOpts.Triple = TargetTriple;
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000507 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
508 TargetOpts));
509 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
510 *AST->Target.get(),
Daniel Dunbar31b87d82009-09-21 03:03:39 +0000511 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000512 Preprocessor &PP = *AST->PP.get();
513
Daniel Dunbard5b61262009-09-21 03:03:47 +0000514 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000515 PP.setCounterValue(Counter);
Daniel Dunbarcc318932009-09-03 05:59:35 +0000516 Reader->setPreprocessor(PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000517
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000518 // Create and initialize the ASTContext.
519
520 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar31b87d82009-09-21 03:03:39 +0000521 AST->getSourceManager(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000522 *AST->Target.get(),
523 PP.getIdentifierTable(),
524 PP.getSelectorTable(),
525 PP.getBuiltinInfo(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000526 /* size_reserve = */0));
527 ASTContext &Context = *AST->Ctx.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000528
Daniel Dunbarcc318932009-09-03 05:59:35 +0000529 Reader->InitializeContext(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000531 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000532 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000533 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000534 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000535 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000536 Context.setExternalSource(Source);
537
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000538 // Create an AST consumer, even though it isn't used.
539 AST->Consumer.reset(new ASTConsumer);
540
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000541 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000542 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
543 AST->TheSema->Initialize();
544 ReaderPtr->InitializeSema(*AST->TheSema);
545
Mike Stump1eb44332009-09-09 15:08:12 +0000546 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000547}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000548
549namespace {
550
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000551class TopLevelDeclTrackerConsumer : public ASTConsumer {
552 ASTUnit &Unit;
553
554public:
555 TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {}
556
557 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekda5a4282010-05-03 20:16:35 +0000558 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
559 Decl *D = *it;
560 // FIXME: Currently ObjC method declarations are incorrectly being
561 // reported as top-level declarations, even though their DeclContext
562 // is the containing ObjC @interface/@implementation. This is a
563 // fundamental problem in the parser right now.
564 if (isa<ObjCMethodDecl>(D))
565 continue;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000566 Unit.addTopLevelDecl(D);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000567 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000568 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000569
570 // We're not interested in "interesting" decls.
571 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000572};
573
574class TopLevelDeclTrackerAction : public ASTFrontendAction {
575public:
576 ASTUnit &Unit;
577
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000578 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
579 llvm::StringRef InFile) {
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000580 return new TopLevelDeclTrackerConsumer(Unit);
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000581 }
582
583public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000584 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
585
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000586 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000587 virtual bool usesCompleteTranslationUnit() {
588 return Unit.isCompleteTranslationUnit();
589 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000590};
591
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000592class PrecompilePreambleConsumer : public PCHGenerator {
593 ASTUnit &Unit;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000594 std::vector<Decl *> TopLevelDecls;
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000595
596public:
597 PrecompilePreambleConsumer(ASTUnit &Unit,
598 const Preprocessor &PP, bool Chaining,
599 const char *isysroot, llvm::raw_ostream *Out)
600 : PCHGenerator(PP, Chaining, isysroot, Out), Unit(Unit) { }
601
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000602 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000603 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
604 Decl *D = *it;
605 // FIXME: Currently ObjC method declarations are incorrectly being
606 // reported as top-level declarations, even though their DeclContext
607 // is the containing ObjC @interface/@implementation. This is a
608 // fundamental problem in the parser right now.
609 if (isa<ObjCMethodDecl>(D))
610 continue;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000611 TopLevelDecls.push_back(D);
612 }
613 }
614
615 virtual void HandleTranslationUnit(ASTContext &Ctx) {
616 PCHGenerator::HandleTranslationUnit(Ctx);
617 if (!Unit.getDiagnostics().hasErrorOccurred()) {
618 // Translate the top-level declarations we captured during
619 // parsing into declaration IDs in the precompiled
620 // preamble. This will allow us to deserialize those top-level
621 // declarations when requested.
622 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
623 Unit.addTopLevelDeclFromPreamble(
624 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000625 }
626 }
627};
628
629class PrecompilePreambleAction : public ASTFrontendAction {
630 ASTUnit &Unit;
631
632public:
633 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
634
635 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
636 llvm::StringRef InFile) {
637 std::string Sysroot;
638 llvm::raw_ostream *OS = 0;
639 bool Chaining;
640 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
641 OS, Chaining))
642 return 0;
643
644 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
645 Sysroot.c_str() : 0;
646 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
647 isysroot, OS);
648 }
649
650 virtual bool hasCodeCompletionSupport() const { return false; }
651 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000652 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000653};
654
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000655}
656
Douglas Gregorabc563f2010-07-19 21:46:24 +0000657/// Parse the source file into a translation unit using the given compiler
658/// invocation, replacing the current translation unit.
659///
660/// \returns True if a failure occurred that causes the ASTUnit not to
661/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +0000662bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +0000663 delete SavedMainFileBuffer;
664 SavedMainFileBuffer = 0;
665
Douglas Gregor671947b2010-08-19 01:33:06 +0000666 if (!Invocation.get()) {
667 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000668 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +0000669 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000670
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000671 // Create the compiler instance to use for building the AST.
Daniel Dunbarcb6dda12009-12-02 08:43:56 +0000672 CompilerInstance Clang;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000673 Clang.setInvocation(Invocation.take());
674 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
675
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000676 // Set up diagnostics, capturing any diagnostics that would
677 // otherwise be dropped.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000678 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000679 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
680 getDiagnostics(),
681 StoredDiagnostics);
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000682
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000683 // Create the target instance.
684 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
685 Clang.getTargetOpts()));
Douglas Gregor671947b2010-08-19 01:33:06 +0000686 if (!Clang.hasTarget()) {
687 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000688 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +0000689 }
690
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000691 // Inform the target of the language options.
692 //
693 // FIXME: We shouldn't need to do this, the target should be immutable once
694 // created. This complexity should be lifted elsewhere.
695 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000696
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000697 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
698 "Invocation must have exactly one source file!");
Daniel Dunbarc34ce3f2010-06-07 23:22:09 +0000699 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000700 "FIXME: AST inputs not yet supported here!");
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +0000701 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
702 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000703
Douglas Gregorabc563f2010-07-19 21:46:24 +0000704 // Configure the various subsystems.
705 // FIXME: Should we retain the previous file manager?
706 FileMgr.reset(new FileManager);
707 SourceMgr.reset(new SourceManager(getDiagnostics()));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000708 TheSema.reset();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000709 Ctx.reset();
710 PP.reset();
711
712 // Clear out old caches and data.
713 TopLevelDecls.clear();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000714 CleanTemporaryFiles();
715 PreprocessedEntitiesByFile.clear();
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000716
Douglas Gregorf128fed2010-08-20 00:02:33 +0000717 if (!OverrideMainBuffer) {
Douglas Gregor4cd912a2010-10-12 00:50:20 +0000718 StoredDiagnostics.erase(
719 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
720 StoredDiagnostics.end());
Douglas Gregorf128fed2010-08-20 00:02:33 +0000721 TopLevelDeclsInPreamble.clear();
722 }
723
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000724 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000725 Clang.setFileManager(&getFileManager());
726
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000727 // Create the source manager.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000728 Clang.setSourceManager(&getSourceManager());
729
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000730 // If the main file has been overridden due to the use of a preamble,
731 // make that override happen and introduce the preamble.
732 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000733 std::string PriorImplicitPCHInclude;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000734 if (OverrideMainBuffer) {
735 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
736 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
737 PreprocessorOpts.PrecompiledPreambleBytes.second
738 = PreambleEndsAtStartOfLine;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000739 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor385103b2010-07-30 20:58:08 +0000740 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000741 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +0000742
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000743 // The stored diagnostic has the old source manager in it; update
744 // the locations to refer into the new source manager. Since we've
745 // been careful to make sure that the source manager's state
746 // before and after are identical, so that we can reuse the source
747 // location itself.
Douglas Gregor4cd912a2010-10-12 00:50:20 +0000748 for (unsigned I = NumStoredDiagnosticsFromDriver,
749 N = StoredDiagnostics.size();
750 I < N; ++I) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000751 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
752 getSourceManager());
753 StoredDiagnostics[I].setLocation(Loc);
754 }
Douglas Gregor4cd912a2010-10-12 00:50:20 +0000755
756 // Keep track of the override buffer;
757 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorf128fed2010-08-20 00:02:33 +0000758 } else {
759 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
760 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000761 }
762
Douglas Gregorabc563f2010-07-19 21:46:24 +0000763 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
764 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000765 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbard3598a62010-06-07 23:23:06 +0000766 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000767 goto error;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000768
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000769 Act->Execute();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000770
Daniel Dunbar64a32ba2009-12-01 21:57:33 +0000771 // Steal the created target, context, and preprocessor, and take back the
772 // source and file managers.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000773 TheSema.reset(Clang.takeSema());
774 Consumer.reset(Clang.takeASTConsumer());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000775 Ctx.reset(Clang.takeASTContext());
776 PP.reset(Clang.takePreprocessor());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000777 Clang.takeSourceManager();
778 Clang.takeFileManager();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000779 Target.reset(Clang.takeTarget());
780
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000781 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000782
783 // Remove the overridden buffer we used for the preamble.
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000784 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000785 PreprocessorOpts.eraseRemappedFile(
786 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000787 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
788 }
789
Douglas Gregorabc563f2010-07-19 21:46:24 +0000790 Invocation.reset(Clang.takeInvocation());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000791
792 // If we were asked to cache code-completion results and don't have any
793 // results yet, do so now.
794 if (ShouldCacheCodeCompletionResults && CachedCompletionResults.empty())
795 CacheCodeCompletionResults();
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +0000796
Douglas Gregorabc563f2010-07-19 21:46:24 +0000797 return false;
798
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000799error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000800 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000801 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000802 PreprocessorOpts.eraseRemappedFile(
803 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000804 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000805 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregor671947b2010-08-19 01:33:06 +0000806 delete OverrideMainBuffer;
Douglas Gregor37cf6632010-10-06 21:11:08 +0000807 SavedMainFileBuffer = 0;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000808 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000809
Douglas Gregord54eb442010-10-12 16:25:54 +0000810 StoredDiagnostics.clear();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000811 Clang.takeSourceManager();
812 Clang.takeFileManager();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000813 Invocation.reset(Clang.takeInvocation());
814 return true;
815}
816
Douglas Gregor44c181a2010-07-23 00:33:23 +0000817/// \brief Simple function to retrieve a path for a preamble precompiled header.
818static std::string GetPreamblePCHPath() {
819 // FIXME: This is lame; sys::Path should provide this function (in particular,
820 // it should know how to find the temporary files dir).
821 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +0000822 // FIXME: This is a hack so that we can override the preamble file during
823 // crash-recovery testing, which is the only case where the preamble files
824 // are not necessarily cleaned up.
825 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
826 if (TmpFile)
827 return TmpFile;
828
Douglas Gregor44c181a2010-07-23 00:33:23 +0000829 std::string Error;
830 const char *TmpDir = ::getenv("TMPDIR");
831 if (!TmpDir)
832 TmpDir = ::getenv("TEMP");
833 if (!TmpDir)
834 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +0000835#ifdef LLVM_ON_WIN32
836 if (!TmpDir)
837 TmpDir = ::getenv("USERPROFILE");
838#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +0000839 if (!TmpDir)
840 TmpDir = "/tmp";
841 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +0000842 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +0000843 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +0000844 P.appendSuffix("pch");
Douglas Gregor44c181a2010-07-23 00:33:23 +0000845 if (P.createTemporaryFileOnDisk())
846 return std::string();
847
Douglas Gregor44c181a2010-07-23 00:33:23 +0000848 return P.str();
849}
850
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000851/// \brief Compute the preamble for the main file, providing the source buffer
852/// that corresponds to the main file along with a pair (bytes, start-of-line)
853/// that describes the preamble.
854std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +0000855ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
856 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000857 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000858 PreprocessorOptions &PreprocessorOpts
Douglas Gregor175c4a92010-07-23 23:58:40 +0000859 = Invocation.getPreprocessorOpts();
860 CreatedBuffer = false;
861
Douglas Gregor44c181a2010-07-23 00:33:23 +0000862 // Try to determine if the main file has been remapped, either from the
863 // command line (to another file) or directly through the compiler invocation
864 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +0000865 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000866 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
867 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
868 // Check whether there is a file-file remapping of the main file
869 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +0000870 M = PreprocessorOpts.remapped_file_begin(),
871 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000872 M != E;
873 ++M) {
874 llvm::sys::PathWithStatus MPath(M->first);
875 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
876 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
877 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000878 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000879 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000880 CreatedBuffer = false;
881 }
882
Douglas Gregor44c181a2010-07-23 00:33:23 +0000883 Buffer = llvm::MemoryBuffer::getFile(M->second);
884 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000885 return std::make_pair((llvm::MemoryBuffer*)0,
886 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000887 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000888 }
889 }
890 }
891
892 // Check whether there is a file-buffer remapping. It supercedes the
893 // file-file remapping.
894 for (PreprocessorOptions::remapped_file_buffer_iterator
895 M = PreprocessorOpts.remapped_file_buffer_begin(),
896 E = PreprocessorOpts.remapped_file_buffer_end();
897 M != E;
898 ++M) {
899 llvm::sys::PathWithStatus MPath(M->first);
900 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
901 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
902 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000903 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000904 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000905 CreatedBuffer = false;
906 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000907
Douglas Gregor175c4a92010-07-23 23:58:40 +0000908 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
Douglas Gregor44c181a2010-07-23 00:33:23 +0000909 }
910 }
Douglas Gregor175c4a92010-07-23 23:58:40 +0000911 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000912 }
913
914 // If the main source file was not remapped, load it now.
915 if (!Buffer) {
916 Buffer = llvm::MemoryBuffer::getFile(FrontendOpts.Inputs[0].second);
917 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000918 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000919
920 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000921 }
922
Douglas Gregordf95a132010-08-09 20:45:32 +0000923 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000924}
925
Douglas Gregor754f3492010-07-24 00:38:13 +0000926static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
927 bool DeleteOld,
928 unsigned NewSize,
929 llvm::StringRef NewName) {
930 llvm::MemoryBuffer *Result
931 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
932 memcpy(const_cast<char*>(Result->getBufferStart()),
933 Old->getBufferStart(), Old->getBufferSize());
934 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000935 ' ', NewSize - Old->getBufferSize() - 1);
936 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +0000937
938 if (DeleteOld)
939 delete Old;
940
941 return Result;
942}
943
Douglas Gregor175c4a92010-07-23 23:58:40 +0000944/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
945/// the source file.
946///
947/// This routine will compute the preamble of the main source file. If a
948/// non-trivial preamble is found, it will precompile that preamble into a
949/// precompiled header so that the precompiled preamble can be used to reduce
950/// reparsing time. If a precompiled preamble has already been constructed,
951/// this routine will determine if it is still valid and, if so, avoid
952/// rebuilding the precompiled preamble.
953///
Douglas Gregordf95a132010-08-09 20:45:32 +0000954/// \param AllowRebuild When true (the default), this routine is
955/// allowed to rebuild the precompiled preamble if it is found to be
956/// out-of-date.
957///
958/// \param MaxLines When non-zero, the maximum number of lines that
959/// can occur within the preamble.
960///
Douglas Gregor754f3492010-07-24 00:38:13 +0000961/// \returns If the precompiled preamble can be used, returns a newly-allocated
962/// buffer that should be used in place of the main file when doing so.
963/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +0000964llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor2283d792010-08-20 00:59:43 +0000965 CompilerInvocation PreambleInvocation,
Douglas Gregordf95a132010-08-09 20:45:32 +0000966 bool AllowRebuild,
967 unsigned MaxLines) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000968 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
969 PreprocessorOptions &PreprocessorOpts
970 = PreambleInvocation.getPreprocessorOpts();
971
972 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000973 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregordf95a132010-08-09 20:45:32 +0000974 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +0000975
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000976 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000977 // We couldn't find a preamble in the main source. Clear out the current
978 // preamble, if we have one. It's obviously no good any more.
979 Preamble.clear();
980 if (!PreambleFile.empty()) {
Douglas Gregor385103b2010-07-30 20:58:08 +0000981 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000982 PreambleFile.clear();
983 }
984 if (CreatedPreambleBuffer)
985 delete NewPreamble.first;
Douglas Gregoreababfb2010-08-04 05:53:38 +0000986
987 // The next time we actually see a preamble, precompile it.
988 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +0000989 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000990 }
991
992 if (!Preamble.empty()) {
993 // We've previously computed a preamble. Check whether we have the same
994 // preamble now that we did before, and that there's enough space in
995 // the main-file buffer within the precompiled preamble to fit the
996 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000997 if (Preamble.size() == NewPreamble.second.first &&
998 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +0000999 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor175c4a92010-07-23 23:58:40 +00001000 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001001 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001002 // The preamble has not changed. We may be able to re-use the precompiled
1003 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001004
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001005 // Check that none of the files used by the preamble have changed.
1006 bool AnyFileChanged = false;
1007
1008 // First, make a record of those files that have been overridden via
1009 // remapping or unsaved_files.
1010 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1011 for (PreprocessorOptions::remapped_file_iterator
1012 R = PreprocessorOpts.remapped_file_begin(),
1013 REnd = PreprocessorOpts.remapped_file_end();
1014 !AnyFileChanged && R != REnd;
1015 ++R) {
1016 struct stat StatBuf;
1017 if (stat(R->second.c_str(), &StatBuf)) {
1018 // If we can't stat the file we're remapping to, assume that something
1019 // horrible happened.
1020 AnyFileChanged = true;
1021 break;
1022 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001023
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001024 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1025 StatBuf.st_mtime);
1026 }
1027 for (PreprocessorOptions::remapped_file_buffer_iterator
1028 R = PreprocessorOpts.remapped_file_buffer_begin(),
1029 REnd = PreprocessorOpts.remapped_file_buffer_end();
1030 !AnyFileChanged && R != REnd;
1031 ++R) {
1032 // FIXME: Should we actually compare the contents of file->buffer
1033 // remappings?
1034 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1035 0);
1036 }
1037
1038 // Check whether anything has changed.
1039 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1040 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1041 !AnyFileChanged && F != FEnd;
1042 ++F) {
1043 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1044 = OverriddenFiles.find(F->first());
1045 if (Overridden != OverriddenFiles.end()) {
1046 // This file was remapped; check whether the newly-mapped file
1047 // matches up with the previous mapping.
1048 if (Overridden->second != F->second)
1049 AnyFileChanged = true;
1050 continue;
1051 }
1052
1053 // The file was not remapped; check whether it has changed on disk.
1054 struct stat StatBuf;
1055 if (stat(F->first(), &StatBuf)) {
1056 // If we can't stat the file, assume that something horrible happened.
1057 AnyFileChanged = true;
1058 } else if (StatBuf.st_size != F->second.first ||
1059 StatBuf.st_mtime != F->second.second)
1060 AnyFileChanged = true;
1061 }
1062
1063 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001064 // Okay! We can re-use the precompiled preamble.
1065
1066 // Set the state of the diagnostic object to mimic its state
1067 // after parsing the preamble.
Douglas Gregor32be4a52010-10-11 21:37:58 +00001068 // FIXME: This won't catch any #pragma push warning changes that
1069 // have occurred in the preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001070 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001071 ProcessWarningOptions(getDiagnostics(),
1072 PreambleInvocation.getDiagnosticOpts());
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001073 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1074 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
1075 StoredDiagnostics.erase(
1076 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
1077 StoredDiagnostics.end());
1078
1079 // Create a version of the main file buffer that is padded to
1080 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001081 return CreatePaddedMainFileBuffer(NewPreamble.first,
1082 CreatedPreambleBuffer,
1083 PreambleReservedSize,
1084 FrontendOpts.Inputs[0].second);
1085 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001086 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001087
1088 // If we aren't allowed to rebuild the precompiled preamble, just
1089 // return now.
1090 if (!AllowRebuild)
1091 return 0;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001092
Douglas Gregor175c4a92010-07-23 23:58:40 +00001093 // We can't reuse the previously-computed preamble. Build a new one.
1094 Preamble.clear();
Douglas Gregor385103b2010-07-30 20:58:08 +00001095 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001096 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001097 } else if (!AllowRebuild) {
1098 // We aren't allowed to rebuild the precompiled preamble; just
1099 // return now.
1100 return 0;
1101 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001102
1103 // If the preamble rebuild counter > 1, it's because we previously
1104 // failed to build a preamble and we're not yet ready to try
1105 // again. Decrement the counter and return a failure.
1106 if (PreambleRebuildCounter > 1) {
1107 --PreambleRebuildCounter;
1108 return 0;
1109 }
1110
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001111 // Create a temporary file for the precompiled preamble. In rare
1112 // circumstances, this can fail.
1113 std::string PreamblePCHPath = GetPreamblePCHPath();
1114 if (PreamblePCHPath.empty()) {
1115 // Try again next time.
1116 PreambleRebuildCounter = 1;
1117 return 0;
1118 }
1119
Douglas Gregor175c4a92010-07-23 23:58:40 +00001120 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor385103b2010-07-30 20:58:08 +00001121 llvm::Timer *PreambleTimer = 0;
1122 if (TimerGroup.get()) {
1123 PreambleTimer = new llvm::Timer("Precompiling preamble", *TimerGroup);
1124 PreambleTimer->startTimer();
1125 Timers.push_back(PreambleTimer);
1126 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001127
1128 // Create a new buffer that stores the preamble. The buffer also contains
1129 // extra space for the original contents of the file (which will be present
1130 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001131 // grows.
1132 PreambleReservedSize = NewPreamble.first->getBufferSize();
1133 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001134 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001135 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001136 PreambleReservedSize *= 2;
1137
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001138 // Save the preamble text for later; we'll need to compare against it for
1139 // subsequent reparses.
1140 Preamble.assign(NewPreamble.first->getBufferStart(),
1141 NewPreamble.first->getBufferStart()
1142 + NewPreamble.second.first);
1143 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1144
Douglas Gregor671947b2010-08-19 01:33:06 +00001145 delete PreambleBuffer;
1146 PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001147 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001148 FrontendOpts.Inputs[0].second);
1149 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001150 NewPreamble.first->getBufferStart(), Preamble.size());
1151 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001152 ' ', PreambleReservedSize - Preamble.size() - 1);
1153 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001154
1155 // Remap the main source file to the preamble buffer.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001156 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001157 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1158
1159 // Tell the compiler invocation to generate a temporary precompiled header.
1160 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Douglas Gregor85e51912010-10-01 01:05:22 +00001161 FrontendOpts.ChainedPCH = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001162 // FIXME: Generate the precompiled header into memory?
Douglas Gregor2cd4fd42010-09-11 17:56:52 +00001163 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001164 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1165 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001166
1167 // Create the compiler instance to use for building the precompiled preamble.
1168 CompilerInstance Clang;
1169 Clang.setInvocation(&PreambleInvocation);
1170 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1171
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001172 // Set up diagnostics, capturing all of the diagnostics produced.
Douglas Gregor44c181a2010-07-23 00:33:23 +00001173 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001174 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
1175 getDiagnostics(),
1176 StoredDiagnostics);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001177
1178 // Create the target instance.
1179 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1180 Clang.getTargetOpts()));
1181 if (!Clang.hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001182 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1183 Preamble.clear();
1184 if (CreatedPreambleBuffer)
1185 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +00001186 if (PreambleTimer)
1187 PreambleTimer->stopTimer();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001188 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001189 PreprocessorOpts.eraseRemappedFile(
1190 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001191 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001192 }
1193
1194 // Inform the target of the language options.
1195 //
1196 // FIXME: We shouldn't need to do this, the target should be immutable once
1197 // created. This complexity should be lifted elsewhere.
1198 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1199
1200 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1201 "Invocation must have exactly one source file!");
1202 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1203 "FIXME: AST inputs not yet supported here!");
1204 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1205 "IR inputs not support here!");
1206
1207 // Clear out old caches and data.
Douglas Gregoraa3e6ba2010-10-08 04:03:57 +00001208 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001209 ProcessWarningOptions(getDiagnostics(), Clang.getDiagnosticOpts());
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001210 StoredDiagnostics.erase(
1211 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver,
1212 StoredDiagnostics.end());
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001213 TopLevelDecls.clear();
1214 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001215
1216 // Create a file manager object to provide access to and cache the filesystem.
1217 Clang.setFileManager(new FileManager);
1218
1219 // Create the source manager.
1220 Clang.setSourceManager(new SourceManager(getDiagnostics()));
1221
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001222 llvm::OwningPtr<PrecompilePreambleAction> Act;
1223 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001224 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1225 Clang.getFrontendOpts().Inputs[0].first)) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001226 Clang.takeInvocation();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001227 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1228 Preamble.clear();
1229 if (CreatedPreambleBuffer)
1230 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +00001231 if (PreambleTimer)
1232 PreambleTimer->stopTimer();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001233 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001234 PreprocessorOpts.eraseRemappedFile(
1235 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001236 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001237 }
1238
1239 Act->Execute();
1240 Act->EndSourceFile();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001241 Clang.takeInvocation();
1242
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001243 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001244 // There were errors parsing the preamble, so no precompiled header was
1245 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001246 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001247 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1248 Preamble.clear();
1249 if (CreatedPreambleBuffer)
1250 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +00001251 if (PreambleTimer)
1252 PreambleTimer->stopTimer();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001253 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001254 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001255 PreprocessorOpts.eraseRemappedFile(
1256 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001257 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001258 }
1259
1260 // Keep track of the preamble we precompiled.
1261 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001262 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1263 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001264
1265 // Keep track of all of the files that the source manager knows about,
1266 // so we can verify whether they have changed or not.
1267 FilesInPreamble.clear();
1268 SourceManager &SourceMgr = Clang.getSourceManager();
1269 const llvm::MemoryBuffer *MainFileBuffer
1270 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1271 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1272 FEnd = SourceMgr.fileinfo_end();
1273 F != FEnd;
1274 ++F) {
1275 const FileEntry *File = F->second->Entry;
1276 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1277 continue;
1278
1279 FilesInPreamble[File->getName()]
1280 = std::make_pair(F->second->getSize(), File->getModificationTime());
1281 }
1282
Douglas Gregor385103b2010-07-30 20:58:08 +00001283 if (PreambleTimer)
1284 PreambleTimer->stopTimer();
Douglas Gregor06e50442010-09-27 16:43:25 +00001285
Douglas Gregoreababfb2010-08-04 05:53:38 +00001286 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001287 PreprocessorOpts.eraseRemappedFile(
1288 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001289 return CreatePaddedMainFileBuffer(NewPreamble.first,
1290 CreatedPreambleBuffer,
1291 PreambleReservedSize,
1292 FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001293}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001294
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001295void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1296 std::vector<Decl *> Resolved;
1297 Resolved.reserve(TopLevelDeclsInPreamble.size());
1298 ExternalASTSource &Source = *getASTContext().getExternalSource();
1299 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1300 // Resolve the declaration ID to an actual declaration, possibly
1301 // deserializing the declaration in the process.
1302 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1303 if (D)
1304 Resolved.push_back(D);
1305 }
1306 TopLevelDeclsInPreamble.clear();
1307 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1308}
1309
1310unsigned ASTUnit::getMaxPCHLevel() const {
1311 if (!getOnlyLocalDecls())
1312 return Decl::MaxPCHLevel;
1313
Sebastian Redl1d9f1fe2010-10-05 16:15:19 +00001314 return 0;
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001315}
1316
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001317bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1318 if (!Invocation)
1319 return true;
1320
1321 // We'll manage file buffers ourselves.
1322 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1323 Invocation->getFrontendOpts().DisableFree = false;
1324
1325 if (getenv("LIBCLANG_TIMING"))
1326 TimerGroup.reset(
1327 new llvm::TimerGroup(Invocation->getFrontendOpts().Inputs[0].second));
1328
1329
1330 llvm::MemoryBuffer *OverrideMainBuffer = 0;
1331 // FIXME: When C++ PCH is ready, allow use of it for a precompiled preamble.
1332 if (PrecompilePreamble && !Invocation->getLangOpts().CPlusPlus) {
1333 PreambleRebuildCounter = 1;
1334 OverrideMainBuffer
1335 = getMainBufferWithPrecompiledPreamble(*Invocation);
1336 }
1337
1338 llvm::Timer *ParsingTimer = 0;
1339 if (TimerGroup.get()) {
1340 ParsingTimer = new llvm::Timer("Initial parse", *TimerGroup);
1341 ParsingTimer->startTimer();
1342 Timers.push_back(ParsingTimer);
1343 }
1344
1345 bool Failed = Parse(OverrideMainBuffer);
1346 if (ParsingTimer)
1347 ParsingTimer->stopTimer();
1348
1349 return Failed;
1350}
1351
Douglas Gregorabc563f2010-07-19 21:46:24 +00001352ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1353 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1354 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001355 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001356 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001357 bool CompleteTranslationUnit,
1358 bool CacheCodeCompletionResults) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001359 if (!Diags.getPtr()) {
1360 // No diagnostics engine was provided, so create our own diagnostics object
1361 // with the default options.
1362 DiagnosticOptions DiagOpts;
1363 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
1364 }
1365
1366 // Create the AST unit.
1367 llvm::OwningPtr<ASTUnit> AST;
1368 AST.reset(new ASTUnit(false));
1369 AST->Diagnostics = Diags;
1370 AST->CaptureDiagnostics = CaptureDiagnostics;
1371 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregordf95a132010-08-09 20:45:32 +00001372 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001373 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001374 AST->Invocation.reset(CI);
1375
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001376 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001377}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001378
1379ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1380 const char **ArgEnd,
Douglas Gregor28019772010-04-05 23:52:57 +00001381 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001382 llvm::StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001383 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001384 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001385 unsigned NumRemappedFiles,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001386 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001387 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001388 bool CompleteTranslationUnit,
1389 bool CacheCodeCompletionResults) {
Douglas Gregorbdbb0042010-08-18 22:29:43 +00001390 bool CreatedDiagnosticsObject = false;
1391
Douglas Gregor28019772010-04-05 23:52:57 +00001392 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001393 // No diagnostics engine was provided, so create our own diagnostics object
1394 // with the default options.
1395 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001396 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00001397 CreatedDiagnosticsObject = true;
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001398 }
1399
Daniel Dunbar7b556682009-12-02 03:23:45 +00001400 llvm::SmallVector<const char *, 16> Args;
1401 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1402 Args.insert(Args.end(), ArgBegin, ArgEnd);
1403
1404 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1405 // also want to force it to use clang.
1406 Args.push_back("-fsyntax-only");
1407
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001408 llvm::SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1409
1410 llvm::OwningPtr<CompilerInvocation> CI;
1411 {
1412 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
1413 *Diags,
1414 StoredDiagnostics);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001415
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001416 // FIXME: We shouldn't have to pass in the path info.
1417 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
1418 "a.out", false, false, *Diags);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001419
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001420 // Don't check that inputs exist, they have been remapped.
1421 TheDriver.setCheckInputsExist(false);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001422
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001423 llvm::OwningPtr<driver::Compilation> C(
1424 TheDriver.BuildCompilation(Args.size(), Args.data()));
1425
1426 // We expect to get back exactly one command job, if we didn't something
1427 // failed.
1428 const driver::JobList &Jobs = C->getJobs();
1429 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1430 llvm::SmallString<256> Msg;
1431 llvm::raw_svector_ostream OS(Msg);
1432 C->PrintJob(OS, C->getJobs(), "; ", true);
1433 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
1434 return 0;
1435 }
1436
1437 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1438 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
1439 Diags->Report(diag::err_fe_expected_clang_command);
1440 return 0;
1441 }
1442
1443 const driver::ArgStringList &CCArgs = Cmd->getArguments();
1444 CI.reset(new CompilerInvocation);
1445 CompilerInvocation::CreateFromArgs(*CI,
1446 const_cast<const char **>(CCArgs.data()),
1447 const_cast<const char **>(CCArgs.data()) +
1448 CCArgs.size(),
1449 *Diags);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001450 }
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001451
Douglas Gregor4db64a42010-01-23 00:14:00 +00001452 // Override any files that need remapping
1453 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar807b0612010-01-30 21:47:16 +00001454 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbarb26d4832010-02-16 01:55:04 +00001455 RemappedFiles[I].second);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001456
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001457 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001458 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001459
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001460 // Create the AST unit.
1461 llvm::OwningPtr<ASTUnit> AST;
1462 AST.reset(new ASTUnit(false));
1463 AST->Diagnostics = Diags;
1464 AST->CaptureDiagnostics = CaptureDiagnostics;
1465 AST->OnlyLocalDecls = OnlyLocalDecls;
1466 AST->CompleteTranslationUnit = CompleteTranslationUnit;
1467 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1468 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1469 AST->NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1470 AST->StoredDiagnostics.swap(StoredDiagnostics);
1471 AST->Invocation.reset(CI.take());
1472 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001473}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001474
1475bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1476 if (!Invocation.get())
1477 return true;
1478
Douglas Gregor385103b2010-07-30 20:58:08 +00001479 llvm::Timer *ReparsingTimer = 0;
1480 if (TimerGroup.get()) {
1481 ReparsingTimer = new llvm::Timer("Reparse", *TimerGroup);
1482 ReparsingTimer->startTimer();
1483 Timers.push_back(ReparsingTimer);
1484 }
1485
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001486 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00001487 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1488 for (PreprocessorOptions::remapped_file_buffer_iterator
1489 R = PPOpts.remapped_file_buffer_begin(),
1490 REnd = PPOpts.remapped_file_buffer_end();
1491 R != REnd;
1492 ++R) {
1493 delete R->second;
1494 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001495 Invocation->getPreprocessorOpts().clearRemappedFiles();
1496 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1497 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1498 RemappedFiles[I].second);
1499
Douglas Gregoreababfb2010-08-04 05:53:38 +00001500 // If we have a preamble file lying around, or if we might try to
1501 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00001502 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregoreababfb2010-08-04 05:53:38 +00001503 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00001504 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001505
Douglas Gregorabc563f2010-07-19 21:46:24 +00001506 // Clear out the diagnostics state.
Douglas Gregor32be4a52010-10-11 21:37:58 +00001507 if (!OverrideMainBuffer) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001508 getDiagnostics().Reset();
Douglas Gregor32be4a52010-10-11 21:37:58 +00001509 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1510 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001511
Douglas Gregor175c4a92010-07-23 23:58:40 +00001512 // Parse the sources
Douglas Gregor754f3492010-07-24 00:38:13 +00001513 bool Result = Parse(OverrideMainBuffer);
Douglas Gregor385103b2010-07-30 20:58:08 +00001514 if (ReparsingTimer)
1515 ReparsingTimer->stopTimer();
Douglas Gregor727d93e2010-08-17 00:40:40 +00001516
1517 if (ShouldCacheCodeCompletionResults) {
1518 if (CacheCodeCompletionCoolDown > 0)
1519 --CacheCodeCompletionCoolDown;
1520 else if (top_level_size() != NumTopLevelDeclsAtLastCompletionCache)
1521 CacheCodeCompletionResults();
1522 }
1523
Douglas Gregor175c4a92010-07-23 23:58:40 +00001524 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001525}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001526
Douglas Gregor87c08a52010-08-13 22:48:40 +00001527//----------------------------------------------------------------------------//
1528// Code completion
1529//----------------------------------------------------------------------------//
1530
1531namespace {
1532 /// \brief Code completion consumer that combines the cached code-completion
1533 /// results from an ASTUnit with the code-completion results provided to it,
1534 /// then passes the result on to
1535 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1536 unsigned NormalContexts;
1537 ASTUnit &AST;
1538 CodeCompleteConsumer &Next;
1539
1540 public:
1541 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor8071e422010-08-15 06:18:01 +00001542 bool IncludeMacros, bool IncludeCodePatterns,
1543 bool IncludeGlobals)
1544 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001545 Next.isOutputBinary()), AST(AST), Next(Next)
1546 {
1547 // Compute the set of contexts in which we will look when we don't have
1548 // any information about the specific context.
1549 NormalContexts
1550 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
1551 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
1552 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1553 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1554 | (1 << (CodeCompletionContext::CCC_Statement - 1))
1555 | (1 << (CodeCompletionContext::CCC_Expression - 1))
1556 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1557 | (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
Douglas Gregor02688102010-09-14 23:59:36 +00001558 | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
Douglas Gregor52779fb2010-09-23 23:01:17 +00001559 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
1560 | (1 << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor02688102010-09-14 23:59:36 +00001561
Douglas Gregor87c08a52010-08-13 22:48:40 +00001562 if (AST.getASTContext().getLangOptions().CPlusPlus)
1563 NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1))
1564 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
1565 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
1566 }
1567
1568 virtual void ProcessCodeCompleteResults(Sema &S,
1569 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00001570 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001571 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001572
1573 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1574 OverloadCandidate *Candidates,
1575 unsigned NumCandidates) {
1576 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1577 }
1578 };
1579}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001580
Douglas Gregor5f808c22010-08-16 21:18:39 +00001581/// \brief Helper function that computes which global names are hidden by the
1582/// local code-completion results.
1583void CalculateHiddenNames(const CodeCompletionContext &Context,
John McCall0a2c5e22010-08-25 06:19:51 +00001584 CodeCompletionResult *Results,
Douglas Gregor5f808c22010-08-16 21:18:39 +00001585 unsigned NumResults,
1586 ASTContext &Ctx,
1587 llvm::StringSet<> &HiddenNames) {
1588 bool OnlyTagNames = false;
1589 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00001590 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00001591 case CodeCompletionContext::CCC_TopLevel:
1592 case CodeCompletionContext::CCC_ObjCInterface:
1593 case CodeCompletionContext::CCC_ObjCImplementation:
1594 case CodeCompletionContext::CCC_ObjCIvarList:
1595 case CodeCompletionContext::CCC_ClassStructUnion:
1596 case CodeCompletionContext::CCC_Statement:
1597 case CodeCompletionContext::CCC_Expression:
1598 case CodeCompletionContext::CCC_ObjCMessageReceiver:
1599 case CodeCompletionContext::CCC_MemberAccess:
1600 case CodeCompletionContext::CCC_Namespace:
1601 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00001602 case CodeCompletionContext::CCC_Name:
1603 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00001604 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor5f808c22010-08-16 21:18:39 +00001605 break;
1606
1607 case CodeCompletionContext::CCC_EnumTag:
1608 case CodeCompletionContext::CCC_UnionTag:
1609 case CodeCompletionContext::CCC_ClassOrStructTag:
1610 OnlyTagNames = true;
1611 break;
1612
1613 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001614 case CodeCompletionContext::CCC_MacroName:
1615 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00001616 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00001617 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00001618 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00001619 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00001620 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00001621 case CodeCompletionContext::CCC_Other:
Douglas Gregor721f3592010-08-25 18:41:16 +00001622 // We're looking for nothing, or we're looking for names that cannot
1623 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00001624 return;
1625 }
1626
John McCall0a2c5e22010-08-25 06:19:51 +00001627 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00001628 for (unsigned I = 0; I != NumResults; ++I) {
1629 if (Results[I].Kind != Result::RK_Declaration)
1630 continue;
1631
1632 unsigned IDNS
1633 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1634
1635 bool Hiding = false;
1636 if (OnlyTagNames)
1637 Hiding = (IDNS & Decl::IDNS_Tag);
1638 else {
1639 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00001640 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1641 Decl::IDNS_NonMemberOperator);
Douglas Gregor5f808c22010-08-16 21:18:39 +00001642 if (Ctx.getLangOptions().CPlusPlus)
1643 HiddenIDNS |= Decl::IDNS_Tag;
1644 Hiding = (IDNS & HiddenIDNS);
1645 }
1646
1647 if (!Hiding)
1648 continue;
1649
1650 DeclarationName Name = Results[I].Declaration->getDeclName();
1651 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1652 HiddenNames.insert(Identifier->getName());
1653 else
1654 HiddenNames.insert(Name.getAsString());
1655 }
1656}
1657
1658
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001659void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1660 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00001661 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001662 unsigned NumResults) {
1663 // Merge the results we were given with the results we cached.
1664 bool AddedResult = false;
Douglas Gregor5f808c22010-08-16 21:18:39 +00001665 unsigned InContexts
Douglas Gregor52779fb2010-09-23 23:01:17 +00001666 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
Douglas Gregor5f808c22010-08-16 21:18:39 +00001667 : (1 << (Context.getKind() - 1)));
1668
1669 // Contains the set of names that are hidden by "local" completion results.
1670 llvm::StringSet<> HiddenNames;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001671 llvm::SmallVector<CodeCompletionString *, 4> StringsToDestroy;
John McCall0a2c5e22010-08-25 06:19:51 +00001672 typedef CodeCompletionResult Result;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001673 llvm::SmallVector<Result, 8> AllResults;
1674 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00001675 C = AST.cached_completion_begin(),
1676 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001677 C != CEnd; ++C) {
1678 // If the context we are in matches any of the contexts we are
1679 // interested in, we'll add this result.
1680 if ((C->ShowInContexts & InContexts) == 0)
1681 continue;
1682
1683 // If we haven't added any results previously, do so now.
1684 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00001685 CalculateHiddenNames(Context, Results, NumResults, S.Context,
1686 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001687 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1688 AddedResult = true;
1689 }
1690
Douglas Gregor5f808c22010-08-16 21:18:39 +00001691 // Determine whether this global completion result is hidden by a local
1692 // completion result. If so, skip it.
1693 if (C->Kind != CXCursor_MacroDefinition &&
1694 HiddenNames.count(C->Completion->getTypedText()))
1695 continue;
1696
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001697 // Adjust priority based on similar type classes.
1698 unsigned Priority = C->Priority;
Douglas Gregor4125c372010-08-25 18:03:13 +00001699 CXCursorKind CursorKind = C->Kind;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001700 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001701 if (!Context.getPreferredType().isNull()) {
1702 if (C->Kind == CXCursor_MacroDefinition) {
1703 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00001704 S.getLangOptions(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001705 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001706 } else if (C->Type) {
1707 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00001708 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001709 Context.getPreferredType().getUnqualifiedType());
1710 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
1711 if (ExpectedSTC == C->TypeClass) {
1712 // We know this type is similar; check for an exact match.
1713 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00001714 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001715 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00001716 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001717 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
1718 Priority /= CCF_ExactTypeMatch;
1719 else
1720 Priority /= CCF_SimilarTypeMatch;
1721 }
1722 }
1723 }
1724
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001725 // Adjust the completion string, if required.
1726 if (C->Kind == CXCursor_MacroDefinition &&
1727 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
1728 // Create a new code-completion string that just contains the
1729 // macro name, without its arguments.
1730 Completion = new CodeCompletionString;
1731 Completion->AddTypedTextChunk(C->Completion->getTypedText());
1732 StringsToDestroy.push_back(Completion);
Douglas Gregor4125c372010-08-25 18:03:13 +00001733 CursorKind = CXCursor_NotImplemented;
1734 Priority = CCP_CodePattern;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001735 }
1736
Douglas Gregor4125c372010-08-25 18:03:13 +00001737 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00001738 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001739 }
1740
1741 // If we did not add any cached completion results, just forward the
1742 // results we were given to the next consumer.
1743 if (!AddedResult) {
1744 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
1745 return;
1746 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00001747
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001748 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
1749 AllResults.size());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001750
1751 for (unsigned I = 0, N = StringsToDestroy.size(); I != N; ++I)
1752 delete StringsToDestroy[I];
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001753}
1754
1755
1756
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001757void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
1758 RemappedFile *RemappedFiles,
1759 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00001760 bool IncludeMacros,
1761 bool IncludeCodePatterns,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001762 CodeCompleteConsumer &Consumer,
1763 Diagnostic &Diag, LangOptions &LangOpts,
1764 SourceManager &SourceMgr, FileManager &FileMgr,
Douglas Gregor2283d792010-08-20 00:59:43 +00001765 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
1766 llvm::SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001767 if (!Invocation.get())
1768 return;
1769
Douglas Gregordf95a132010-08-09 20:45:32 +00001770 llvm::Timer *CompletionTimer = 0;
1771 if (TimerGroup.get()) {
1772 llvm::SmallString<128> TimerName;
1773 llvm::raw_svector_ostream TimerNameOut(TimerName);
1774 TimerNameOut << "Code completion @ " << File << ":" << Line << ":"
1775 << Column;
1776 CompletionTimer = new llvm::Timer(TimerNameOut.str(), *TimerGroup);
1777 CompletionTimer->startTimer();
1778 Timers.push_back(CompletionTimer);
1779 }
1780
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001781 CompilerInvocation CCInvocation(*Invocation);
1782 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
1783 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001784
Douglas Gregor87c08a52010-08-13 22:48:40 +00001785 FrontendOpts.ShowMacrosInCodeCompletion
1786 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001787 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor8071e422010-08-15 06:18:01 +00001788 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
1789 = CachedCompletionResults.empty();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001790 FrontendOpts.CodeCompletionAt.FileName = File;
1791 FrontendOpts.CodeCompletionAt.Line = Line;
1792 FrontendOpts.CodeCompletionAt.Column = Column;
1793
1794 // Set the language options appropriately.
1795 LangOpts = CCInvocation.getLangOpts();
1796
1797 CompilerInstance Clang;
1798 Clang.setInvocation(&CCInvocation);
1799 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1800
1801 // Set up diagnostics, capturing any diagnostics produced.
1802 Clang.setDiagnostics(&Diag);
Douglas Gregor32be4a52010-10-11 21:37:58 +00001803 ProcessWarningOptions(Diag, CCInvocation.getDiagnosticOpts());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001804 CaptureDroppedDiagnostics Capture(true,
1805 Clang.getDiagnostics(),
1806 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001807
1808 // Create the target instance.
1809 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1810 Clang.getTargetOpts()));
1811 if (!Clang.hasTarget()) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001812 Clang.takeInvocation();
Douglas Gregorbdbb0042010-08-18 22:29:43 +00001813 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001814 }
1815
1816 // Inform the target of the language options.
1817 //
1818 // FIXME: We shouldn't need to do this, the target should be immutable once
1819 // created. This complexity should be lifted elsewhere.
1820 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1821
1822 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1823 "Invocation must have exactly one source file!");
1824 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1825 "FIXME: AST inputs not yet supported here!");
1826 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1827 "IR inputs not support here!");
1828
1829
1830 // Use the source and file managers that we were given.
1831 Clang.setFileManager(&FileMgr);
1832 Clang.setSourceManager(&SourceMgr);
1833
1834 // Remap files.
1835 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00001836 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00001837 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001838 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
1839 RemappedFiles[I].second);
Douglas Gregor2283d792010-08-20 00:59:43 +00001840 OwnedBuffers.push_back(RemappedFiles[I].second);
1841 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001842
Douglas Gregor87c08a52010-08-13 22:48:40 +00001843 // Use the code completion consumer we were given, but adding any cached
1844 // code-completion results.
1845 AugmentedCodeCompleteConsumer
1846 AugmentedConsumer(*this, Consumer, FrontendOpts.ShowMacrosInCodeCompletion,
Douglas Gregor8071e422010-08-15 06:18:01 +00001847 FrontendOpts.ShowCodePatternsInCodeCompletion,
1848 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001849 Clang.setCodeCompletionConsumer(&AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001850
Douglas Gregordf95a132010-08-09 20:45:32 +00001851 // If we have a precompiled preamble, try to use it. We only allow
1852 // the use of the precompiled preamble if we're if the completion
1853 // point is within the main file, after the end of the precompiled
1854 // preamble.
1855 llvm::MemoryBuffer *OverrideMainBuffer = 0;
1856 if (!PreambleFile.empty()) {
1857 using llvm::sys::FileStatus;
1858 llvm::sys::PathWithStatus CompleteFilePath(File);
1859 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
1860 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
1861 if (const FileStatus *MainStatus = MainPath.getFileStatus())
1862 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
Douglas Gregor2283d792010-08-20 00:59:43 +00001863 OverrideMainBuffer
Douglas Gregorc9c29a82010-08-25 18:04:15 +00001864 = getMainBufferWithPrecompiledPreamble(CCInvocation, false,
1865 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00001866 }
1867
1868 // If the main file has been overridden due to the use of a preamble,
1869 // make that override happen and introduce the preamble.
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001870 StoredDiagnostics.insert(StoredDiagnostics.end(),
1871 this->StoredDiagnostics.begin(),
1872 this->StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver);
Douglas Gregordf95a132010-08-09 20:45:32 +00001873 if (OverrideMainBuffer) {
1874 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1875 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1876 PreprocessorOpts.PrecompiledPreambleBytes.second
1877 = PreambleEndsAtStartOfLine;
1878 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
1879 PreprocessorOpts.DisablePCHValidation = true;
1880
1881 // The stored diagnostics have the old source manager. Copy them
1882 // to our output set of stored diagnostics, updating the source
1883 // manager to the one we were given.
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001884 for (unsigned I = NumStoredDiagnosticsFromDriver,
1885 N = this->StoredDiagnostics.size();
1886 I < N; ++I) {
Douglas Gregordf95a132010-08-09 20:45:32 +00001887 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
1888 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
1889 StoredDiagnostics[I].setLocation(Loc);
1890 }
Douglas Gregor4cd912a2010-10-12 00:50:20 +00001891
Douglas Gregor2283d792010-08-20 00:59:43 +00001892 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00001893 } else {
1894 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1895 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00001896 }
1897
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001898 llvm::OwningPtr<SyntaxOnlyAction> Act;
1899 Act.reset(new SyntaxOnlyAction);
1900 if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1901 Clang.getFrontendOpts().Inputs[0].first)) {
1902 Act->Execute();
1903 Act->EndSourceFile();
1904 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001905
1906 if (CompletionTimer)
1907 CompletionTimer->stopTimer();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001908
1909 // Steal back our resources.
1910 Clang.takeFileManager();
1911 Clang.takeSourceManager();
1912 Clang.takeInvocation();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001913 Clang.takeCodeCompletionConsumer();
1914}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001915
1916bool ASTUnit::Save(llvm::StringRef File) {
1917 if (getDiagnostics().hasErrorOccurred())
1918 return true;
1919
1920 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
1921 // unconditionally create a stat cache when we parse the file?
1922 std::string ErrorInfo;
Benjamin Kramer1395c5d2010-08-15 16:54:31 +00001923 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo,
1924 llvm::raw_fd_ostream::F_Binary);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001925 if (!ErrorInfo.empty() || Out.has_error())
1926 return true;
1927
1928 std::vector<unsigned char> Buffer;
1929 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00001930 ASTWriter Writer(Stream);
1931 Writer.WriteAST(getSema(), 0, 0);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001932
1933 // Write the generated bitstream to "Out".
Douglas Gregorbdbb0042010-08-18 22:29:43 +00001934 if (!Buffer.empty())
1935 Out.write((char *)&Buffer.front(), Buffer.size());
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001936 Out.close();
1937 return Out.has_error();
1938}