blob: 19d1690051e4479d8ed5a01037bd37ee0c16c98b [file] [log] [blame]
Argyrios Kyrtzidis4b562cf2009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000015#include "clang/AST/ASTContext.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000016#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
Douglas Gregorf5586f62010-08-16 18:08:11 +000018#include "clang/AST/TypeOrdering.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000019#include "clang/AST/StmtVisitor.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000020#include "clang/Driver/Compilation.h"
21#include "clang/Driver/Driver.h"
22#include "clang/Driver/Job.h"
23#include "clang/Driver/Tool.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000024#include "clang/Frontend/CompilerInstance.h"
25#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000026#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000027#include "clang/Frontend/FrontendOptions.h"
Sebastian Redl6ab7cd82010-08-18 23:57:17 +000028#include "clang/Serialization/ASTReader.h"
Sebastian Redl7faa2ec2010-08-18 23:56:37 +000029#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000030#include "clang/Lex/HeaderSearch.h"
31#include "clang/Lex/Preprocessor.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000032#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000033#include "clang/Basic/TargetInfo.h"
34#include "clang/Basic/Diagnostic.h"
Douglas Gregor349d38c2010-08-16 23:08:34 +000035#include "llvm/ADT/StringSet.h"
Douglas Gregor4db64a42010-01-23 00:14:00 +000036#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000037#include "llvm/System/Host.h"
Benjamin Kramer4a630d32009-10-18 11:34:14 +000038#include "llvm/System/Path.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000039#include "llvm/Support/raw_ostream.h"
Douglas Gregor385103b2010-07-30 20:58:08 +000040#include "llvm/Support/Timer.h"
Douglas Gregor44c181a2010-07-23 00:33:23 +000041#include <cstdlib>
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000042#include <cstdio>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000043#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000044using namespace clang;
45
Douglas Gregoreababfb2010-08-04 05:53:38 +000046/// \brief After failing to build a precompiled preamble (due to
47/// errors in the source that occurs in the preamble), the number of
48/// reparses during which we'll skip even trying to precompile the
49/// preamble.
50const unsigned DefaultPreambleRebuildInterval = 5;
51
Douglas Gregor3687e9d2010-04-05 21:10:19 +000052ASTUnit::ASTUnit(bool _MainFileIsAST)
Douglas Gregorabc563f2010-07-19 21:46:24 +000053 : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
Douglas Gregordf95a132010-08-09 20:45:32 +000054 CompleteTranslationUnit(true), ConcurrencyCheckValue(CheckUnlocked),
Douglas Gregor671947b2010-08-19 01:33:06 +000055 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Douglas Gregor727d93e2010-08-17 00:40:40 +000056 ShouldCacheCodeCompletionResults(false),
57 NumTopLevelDeclsAtLastCompletionCache(0),
Douglas Gregor8b1540c2010-08-19 00:45:44 +000058 CacheCodeCompletionCoolDown(0),
59 UnsafeToFree(false) {
Douglas Gregor385103b2010-07-30 20:58:08 +000060}
Douglas Gregor3687e9d2010-04-05 21:10:19 +000061
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000062ASTUnit::~ASTUnit() {
Douglas Gregorbdf60622010-03-05 21:16:25 +000063 ConcurrencyCheckValue = CheckLocked;
Douglas Gregorabc563f2010-07-19 21:46:24 +000064 CleanTemporaryFiles();
Douglas Gregor175c4a92010-07-23 23:58:40 +000065 if (!PreambleFile.empty())
Douglas Gregor385103b2010-07-30 20:58:08 +000066 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000067
68 // Free the buffers associated with remapped files. We are required to
69 // perform this operation here because we explicitly request that the
70 // compiler instance *not* free these buffers for each invocation of the
71 // parser.
72 if (Invocation.get()) {
73 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
74 for (PreprocessorOptions::remapped_file_buffer_iterator
75 FB = PPOpts.remapped_file_buffer_begin(),
76 FBEnd = PPOpts.remapped_file_buffer_end();
77 FB != FBEnd;
78 ++FB)
79 delete FB->second;
80 }
Douglas Gregor28233422010-07-27 14:52:07 +000081
82 delete SavedMainFileBuffer;
Douglas Gregor671947b2010-08-19 01:33:06 +000083 delete PreambleBuffer;
84
Douglas Gregor87c08a52010-08-13 22:48:40 +000085 ClearCachedCompletionResults();
86
Douglas Gregor8c8d5412010-09-24 21:18:36 +000087 if (TimerGroup)
88 TimerGroup->printAll(llvm::errs());
89
Douglas Gregor385103b2010-07-30 20:58:08 +000090 for (unsigned I = 0, N = Timers.size(); I != N; ++I)
91 delete Timers[I];
Douglas Gregorabc563f2010-07-19 21:46:24 +000092}
93
94void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor313e26c2010-02-18 23:35:40 +000095 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
96 TemporaryFiles[I].eraseFromDisk();
Douglas Gregorabc563f2010-07-19 21:46:24 +000097 TemporaryFiles.clear();
Steve Naroffe19944c2009-10-15 22:23:48 +000098}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000099
Douglas Gregor8071e422010-08-15 06:18:01 +0000100/// \brief Determine the set of code-completion contexts in which this
101/// declaration should be shown.
102static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000103 const LangOptions &LangOpts,
104 bool &IsNestedNameSpecifier) {
105 IsNestedNameSpecifier = false;
106
Douglas Gregor8071e422010-08-15 06:18:01 +0000107 if (isa<UsingShadowDecl>(ND))
108 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
109 if (!ND)
110 return 0;
111
112 unsigned Contexts = 0;
113 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
114 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
115 // Types can appear in these contexts.
116 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
117 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
118 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
119 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
120 | (1 << (CodeCompletionContext::CCC_Statement - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000121 | (1 << (CodeCompletionContext::CCC_Type - 1))
122 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000123
124 // In C++, types can appear in expressions contexts (for functional casts).
125 if (LangOpts.CPlusPlus)
126 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
127
128 // In Objective-C, message sends can send interfaces. In Objective-C++,
129 // all types are available due to functional casts.
130 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
131 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
132
133 // Deal with tag names.
134 if (isa<EnumDecl>(ND)) {
135 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
136
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000137 // Part of the nested-name-specifier in C++0x.
Douglas Gregor8071e422010-08-15 06:18:01 +0000138 if (LangOpts.CPlusPlus0x)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000139 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000140 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
141 if (Record->isUnion())
142 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
143 else
144 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
145
Douglas Gregor8071e422010-08-15 06:18:01 +0000146 if (LangOpts.CPlusPlus)
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000147 IsNestedNameSpecifier = true;
Douglas Gregor52779fb2010-09-23 23:01:17 +0000148 } else if (isa<ClassTemplateDecl>(ND))
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000149 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000150 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
151 // Values can appear in these contexts.
152 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
153 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000154 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
Douglas Gregor8071e422010-08-15 06:18:01 +0000155 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
156 } else if (isa<ObjCProtocolDecl>(ND)) {
157 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
158 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000159 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor8071e422010-08-15 06:18:01 +0000160
161 // Part of the nested-name-specifier.
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000162 IsNestedNameSpecifier = true;
Douglas Gregor8071e422010-08-15 06:18:01 +0000163 }
164
165 return Contexts;
166}
167
Douglas Gregor87c08a52010-08-13 22:48:40 +0000168void ASTUnit::CacheCodeCompletionResults() {
169 if (!TheSema)
170 return;
171
172 llvm::Timer *CachingTimer = 0;
173 if (TimerGroup.get()) {
174 CachingTimer = new llvm::Timer("Cache global code completions",
175 *TimerGroup);
176 CachingTimer->startTimer();
177 Timers.push_back(CachingTimer);
178 }
179
180 // Clear out the previous results.
181 ClearCachedCompletionResults();
182
183 // Gather the set of global code completions.
John McCall0a2c5e22010-08-25 06:19:51 +0000184 typedef CodeCompletionResult Result;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000185 llvm::SmallVector<Result, 8> Results;
186 TheSema->GatherGlobalCodeCompletions(Results);
187
188 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000189 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
190
Douglas Gregor87c08a52010-08-13 22:48:40 +0000191 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
192 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000193 case Result::RK_Declaration: {
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000194 bool IsNestedNameSpecifier = false;
Douglas Gregor8071e422010-08-15 06:18:01 +0000195 CachedCodeCompletionResult CachedResult;
196 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
197 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000198 Ctx->getLangOptions(),
199 IsNestedNameSpecifier);
Douglas Gregor8071e422010-08-15 06:18:01 +0000200 CachedResult.Priority = Results[I].Priority;
201 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000202 CachedResult.Availability = Results[I].Availability;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000203
Douglas Gregorf5586f62010-08-16 18:08:11 +0000204 // Keep track of the type of this completion in an ASTContext-agnostic
205 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000206 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000207 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000208 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000209 CachedResult.Type = 0;
210 } else {
211 CanQualType CanUsageType
212 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
213 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
214
215 // Determine whether we have already seen this type. If so, we save
216 // ourselves the work of formatting the type string by using the
217 // temporary, CanQualType-based hash table to find the associated value.
218 unsigned &TypeValue = CompletionTypes[CanUsageType];
219 if (TypeValue == 0) {
220 TypeValue = CompletionTypes.size();
221 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
222 = TypeValue;
223 }
224
225 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000226 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000227
Douglas Gregor8071e422010-08-15 06:18:01 +0000228 CachedCompletionResults.push_back(CachedResult);
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000229
230 /// Handle nested-name-specifiers in C++.
231 if (TheSema->Context.getLangOptions().CPlusPlus &&
232 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
233 // The contexts in which a nested-name-specifier can appear in C++.
234 unsigned NNSContexts
235 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
236 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
237 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
238 | (1 << (CodeCompletionContext::CCC_Statement - 1))
239 | (1 << (CodeCompletionContext::CCC_Expression - 1))
240 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
241 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
242 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
243 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000244 | (1 << (CodeCompletionContext::CCC_Type - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000245 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
246 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
Douglas Gregora5fb7c32010-08-16 23:05:20 +0000247
248 if (isa<NamespaceDecl>(Results[I].Declaration) ||
249 isa<NamespaceAliasDecl>(Results[I].Declaration))
250 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
251
252 if (unsigned RemainingContexts
253 = NNSContexts & ~CachedResult.ShowInContexts) {
254 // If there any contexts where this completion can be a
255 // nested-name-specifier but isn't already an option, create a
256 // nested-name-specifier completion.
257 Results[I].StartsNestedNameSpecifier = true;
258 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
259 CachedResult.ShowInContexts = RemainingContexts;
260 CachedResult.Priority = CCP_NestedNameSpecifier;
261 CachedResult.TypeClass = STC_Void;
262 CachedResult.Type = 0;
263 CachedCompletionResults.push_back(CachedResult);
264 }
265 }
Douglas Gregor87c08a52010-08-13 22:48:40 +0000266 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000267 }
268
Douglas Gregor87c08a52010-08-13 22:48:40 +0000269 case Result::RK_Keyword:
270 case Result::RK_Pattern:
271 // Ignore keywords and patterns; we don't care, since they are so
272 // easily regenerated.
273 break;
274
275 case Result::RK_Macro: {
276 CachedCodeCompletionResult CachedResult;
277 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
278 CachedResult.ShowInContexts
279 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
280 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
281 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
282 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
283 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
284 | (1 << (CodeCompletionContext::CCC_Statement - 1))
285 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor1fbb4472010-08-24 20:21:13 +0000286 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorf29c5232010-08-24 22:20:20 +0000287 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
Douglas Gregor02688102010-09-14 23:59:36 +0000288 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
289 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
290
Douglas Gregor2ccccb32010-08-23 18:23:48 +0000291
Douglas Gregor87c08a52010-08-13 22:48:40 +0000292 CachedResult.Priority = Results[I].Priority;
293 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor58ddb602010-08-23 23:00:57 +0000294 CachedResult.Availability = Results[I].Availability;
Douglas Gregor1827e102010-08-16 16:18:59 +0000295 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000296 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000297 CachedCompletionResults.push_back(CachedResult);
298 break;
299 }
300 }
301 Results[I].Destroy();
302 }
303
304 if (CachingTimer)
305 CachingTimer->stopTimer();
Douglas Gregor727d93e2010-08-17 00:40:40 +0000306
307 // Make a note of the state when we performed this caching.
308 NumTopLevelDeclsAtLastCompletionCache = top_level_size();
309 CacheCodeCompletionCoolDown = 15;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000310}
311
312void ASTUnit::ClearCachedCompletionResults() {
313 for (unsigned I = 0, N = CachedCompletionResults.size(); I != N; ++I)
314 delete CachedCompletionResults[I].Completion;
315 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000316 CachedCompletionTypes.clear();
Douglas Gregor87c08a52010-08-13 22:48:40 +0000317}
318
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000319namespace {
320
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000321/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000322/// a Preprocessor.
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000323class ASTInfoCollector : public ASTReaderListener {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000324 LangOptions &LangOpt;
325 HeaderSearch &HSI;
326 std::string &TargetTriple;
327 std::string &Predefines;
328 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000329
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000330 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000331
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000332public:
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000333 ASTInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000334 std::string &TargetTriple, std::string &Predefines,
335 unsigned &Counter)
336 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
337 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000339 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
340 LangOpt = LangOpts;
341 return false;
342 }
Mike Stump1eb44332009-09-09 15:08:12 +0000343
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000344 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000345 TargetTriple = Triple;
346 return false;
347 }
Mike Stump1eb44332009-09-09 15:08:12 +0000348
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000349 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000350 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000351 std::string &SuggestedPredefines) {
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000352 Predefines = Buffers[0].Data;
353 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
354 Predefines += Buffers[I].Data;
355 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000356 return false;
357 }
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000359 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000360 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
361 }
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000363 virtual void ReadCounter(unsigned Value) {
364 Counter = Value;
365 }
366};
367
Douglas Gregora88084b2010-02-18 18:08:43 +0000368class StoredDiagnosticClient : public DiagnosticClient {
369 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
370
371public:
372 explicit StoredDiagnosticClient(
373 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
374 : StoredDiags(StoredDiags) { }
375
376 virtual void HandleDiagnostic(Diagnostic::Level Level,
377 const DiagnosticInfo &Info);
378};
379
380/// \brief RAII object that optionally captures diagnostics, if
381/// there is no diagnostic client to capture them already.
382class CaptureDroppedDiagnostics {
383 Diagnostic &Diags;
384 StoredDiagnosticClient Client;
385 DiagnosticClient *PreviousClient;
386
387public:
388 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
389 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000390 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregora88084b2010-02-18 18:08:43 +0000391 {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000392 if (RequestCapture || Diags.getClient() == 0) {
393 PreviousClient = Diags.takeClient();
Douglas Gregora88084b2010-02-18 18:08:43 +0000394 Diags.setClient(&Client);
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000395 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000396 }
397
398 ~CaptureDroppedDiagnostics() {
Douglas Gregorbdbb0042010-08-18 22:29:43 +0000399 if (Diags.getClient() == &Client) {
400 Diags.takeClient();
401 Diags.setClient(PreviousClient);
402 }
Douglas Gregora88084b2010-02-18 18:08:43 +0000403 }
404};
405
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000406} // anonymous namespace
407
Douglas Gregora88084b2010-02-18 18:08:43 +0000408void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
409 const DiagnosticInfo &Info) {
410 StoredDiags.push_back(StoredDiagnostic(Level, Info));
411}
412
Steve Naroff77accc12009-09-03 18:19:54 +0000413const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000414 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000415}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000416
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000417const std::string &ASTUnit::getASTFileName() {
418 assert(isMainFileAST() && "Not an ASTUnit from an AST file!");
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000419 return static_cast<ASTReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroffe19944c2009-10-15 22:23:48 +0000420}
421
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000422ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Douglas Gregor28019772010-04-05 23:52:57 +0000423 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000424 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000425 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000426 unsigned NumRemappedFiles,
427 bool CaptureDiagnostics) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000428 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
429
Douglas Gregor28019772010-04-05 23:52:57 +0000430 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000431 // No diagnostics engine was provided, so create our own diagnostics object
432 // with the default options.
433 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +0000434 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000435 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000436
437 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000438 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor28019772010-04-05 23:52:57 +0000439 AST->Diagnostics = Diags;
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000440 AST->FileMgr.reset(new FileManager);
441 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics()));
Steve Naroff36c44642009-10-19 14:34:22 +0000442 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000443
Douglas Gregora88084b2010-02-18 18:08:43 +0000444 // If requested, capture diagnostics in the ASTUnit.
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000445 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, AST->getDiagnostics(),
Douglas Gregor405634b2010-04-05 18:10:21 +0000446 AST->StoredDiagnostics);
Douglas Gregora88084b2010-02-18 18:08:43 +0000447
Douglas Gregor4db64a42010-01-23 00:14:00 +0000448 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
449 // Create the file entry for the file that we're mapping from.
450 const FileEntry *FromFile
451 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
452 RemappedFiles[I].second->getBufferSize(),
453 0);
454 if (!FromFile) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000455 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregor4db64a42010-01-23 00:14:00 +0000456 << RemappedFiles[I].first;
Douglas Gregorc8dfe5e2010-02-27 01:32:48 +0000457 delete RemappedFiles[I].second;
Douglas Gregor4db64a42010-01-23 00:14:00 +0000458 continue;
459 }
460
461 // Override the contents of the "from" file with the contents of
462 // the "to" file.
463 AST->getSourceManager().overrideFileContents(FromFile,
464 RemappedFiles[I].second);
465 }
466
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000467 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000468
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000469 LangOptions LangInfo;
470 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
471 std::string TargetTriple;
472 std::string Predefines;
473 unsigned Counter;
474
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000475 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000476
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000477 Reader.reset(new ASTReader(AST->getSourceManager(), AST->getFileManager(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000478 AST->getDiagnostics()));
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000479 Reader->setListener(new ASTInfoCollector(LangInfo, HeaderInfo, TargetTriple,
Daniel Dunbarcc318932009-09-03 05:59:35 +0000480 Predefines, Counter));
481
Sebastian Redl571db7f2010-08-18 23:56:56 +0000482 switch (Reader->ReadAST(Filename)) {
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000483 case ASTReader::Success:
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000484 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000485
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000486 case ASTReader::Failure:
487 case ASTReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000488 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000489 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000490 }
Mike Stump1eb44332009-09-09 15:08:12 +0000491
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000492 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
493
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000494 // AST file loaded successfully. Now create the preprocessor.
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000496 // Get information about the target being compiled for.
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000497 //
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000498 // FIXME: This is broken, we should store the TargetOptions in the AST file.
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000499 TargetOptions TargetOpts;
500 TargetOpts.ABI = "";
John McCall875ab102010-08-22 06:43:33 +0000501 TargetOpts.CXXABI = "";
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000502 TargetOpts.CPU = "";
503 TargetOpts.Features.clear();
504 TargetOpts.Triple = TargetTriple;
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000505 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
506 TargetOpts));
507 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
508 *AST->Target.get(),
Daniel Dunbar31b87d82009-09-21 03:03:39 +0000509 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000510 Preprocessor &PP = *AST->PP.get();
511
Daniel Dunbard5b61262009-09-21 03:03:47 +0000512 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000513 PP.setCounterValue(Counter);
Daniel Dunbarcc318932009-09-03 05:59:35 +0000514 Reader->setPreprocessor(PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000515
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000516 // Create and initialize the ASTContext.
517
518 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar31b87d82009-09-21 03:03:39 +0000519 AST->getSourceManager(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000520 *AST->Target.get(),
521 PP.getIdentifierTable(),
522 PP.getSelectorTable(),
523 PP.getBuiltinInfo(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000524 /* size_reserve = */0));
525 ASTContext &Context = *AST->Ctx.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000526
Daniel Dunbarcc318932009-09-03 05:59:35 +0000527 Reader->InitializeContext(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000528
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000529 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000530 // source, so that declarations will be deserialized from the
Sebastian Redl3c7f4132010-08-18 23:57:06 +0000531 // AST file as needed.
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000532 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000533 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000534 Context.setExternalSource(Source);
535
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000536 // Create an AST consumer, even though it isn't used.
537 AST->Consumer.reset(new ASTConsumer);
538
Sebastian Redlc43b54c2010-08-18 23:56:43 +0000539 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000540 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
541 AST->TheSema->Initialize();
542 ReaderPtr->InitializeSema(*AST->TheSema);
543
Mike Stump1eb44332009-09-09 15:08:12 +0000544 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000545}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000546
547namespace {
548
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000549class TopLevelDeclTrackerConsumer : public ASTConsumer {
550 ASTUnit &Unit;
551
552public:
553 TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {}
554
555 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekda5a4282010-05-03 20:16:35 +0000556 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
557 Decl *D = *it;
558 // FIXME: Currently ObjC method declarations are incorrectly being
559 // reported as top-level declarations, even though their DeclContext
560 // is the containing ObjC @interface/@implementation. This is a
561 // fundamental problem in the parser right now.
562 if (isa<ObjCMethodDecl>(D))
563 continue;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000564 Unit.addTopLevelDecl(D);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000565 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000566 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000567
568 // We're not interested in "interesting" decls.
569 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000570};
571
572class TopLevelDeclTrackerAction : public ASTFrontendAction {
573public:
574 ASTUnit &Unit;
575
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000576 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
577 llvm::StringRef InFile) {
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000578 return new TopLevelDeclTrackerConsumer(Unit);
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000579 }
580
581public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000582 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
583
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000584 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000585 virtual bool usesCompleteTranslationUnit() {
586 return Unit.isCompleteTranslationUnit();
587 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000588};
589
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000590class PrecompilePreambleConsumer : public PCHGenerator {
591 ASTUnit &Unit;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000592 std::vector<Decl *> TopLevelDecls;
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000593
594public:
595 PrecompilePreambleConsumer(ASTUnit &Unit,
596 const Preprocessor &PP, bool Chaining,
597 const char *isysroot, llvm::raw_ostream *Out)
598 : PCHGenerator(PP, Chaining, isysroot, Out), Unit(Unit) { }
599
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000600 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000601 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
602 Decl *D = *it;
603 // FIXME: Currently ObjC method declarations are incorrectly being
604 // reported as top-level declarations, even though their DeclContext
605 // is the containing ObjC @interface/@implementation. This is a
606 // fundamental problem in the parser right now.
607 if (isa<ObjCMethodDecl>(D))
608 continue;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000609 TopLevelDecls.push_back(D);
610 }
611 }
612
613 virtual void HandleTranslationUnit(ASTContext &Ctx) {
614 PCHGenerator::HandleTranslationUnit(Ctx);
615 if (!Unit.getDiagnostics().hasErrorOccurred()) {
616 // Translate the top-level declarations we captured during
617 // parsing into declaration IDs in the precompiled
618 // preamble. This will allow us to deserialize those top-level
619 // declarations when requested.
620 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
621 Unit.addTopLevelDeclFromPreamble(
622 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000623 }
624 }
625};
626
627class PrecompilePreambleAction : public ASTFrontendAction {
628 ASTUnit &Unit;
629
630public:
631 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
632
633 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
634 llvm::StringRef InFile) {
635 std::string Sysroot;
636 llvm::raw_ostream *OS = 0;
637 bool Chaining;
638 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
639 OS, Chaining))
640 return 0;
641
642 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
643 Sysroot.c_str() : 0;
644 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
645 isysroot, OS);
646 }
647
648 virtual bool hasCodeCompletionSupport() const { return false; }
649 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000650 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000651};
652
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000653}
654
Douglas Gregorabc563f2010-07-19 21:46:24 +0000655/// Parse the source file into a translation unit using the given compiler
656/// invocation, replacing the current translation unit.
657///
658/// \returns True if a failure occurred that causes the ASTUnit not to
659/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +0000660bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +0000661 delete SavedMainFileBuffer;
662 SavedMainFileBuffer = 0;
663
Douglas Gregor671947b2010-08-19 01:33:06 +0000664 if (!Invocation.get()) {
665 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000666 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +0000667 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000668
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000669 // Create the compiler instance to use for building the AST.
Daniel Dunbarcb6dda12009-12-02 08:43:56 +0000670 CompilerInstance Clang;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000671 Clang.setInvocation(Invocation.take());
672 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
673
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000674 // Set up diagnostics, capturing any diagnostics that would
675 // otherwise be dropped.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000676 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000677 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
678 getDiagnostics(),
679 StoredDiagnostics);
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000680
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000681 // Create the target instance.
682 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
683 Clang.getTargetOpts()));
Douglas Gregor671947b2010-08-19 01:33:06 +0000684 if (!Clang.hasTarget()) {
685 delete OverrideMainBuffer;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000686 return true;
Douglas Gregor671947b2010-08-19 01:33:06 +0000687 }
688
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000689 // Inform the target of the language options.
690 //
691 // FIXME: We shouldn't need to do this, the target should be immutable once
692 // created. This complexity should be lifted elsewhere.
693 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000694
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000695 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
696 "Invocation must have exactly one source file!");
Daniel Dunbarc34ce3f2010-06-07 23:22:09 +0000697 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000698 "FIXME: AST inputs not yet supported here!");
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +0000699 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
700 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000701
Douglas Gregorabc563f2010-07-19 21:46:24 +0000702 // Configure the various subsystems.
703 // FIXME: Should we retain the previous file manager?
704 FileMgr.reset(new FileManager);
705 SourceMgr.reset(new SourceManager(getDiagnostics()));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000706 TheSema.reset();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000707 Ctx.reset();
708 PP.reset();
709
710 // Clear out old caches and data.
711 TopLevelDecls.clear();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000712 CleanTemporaryFiles();
713 PreprocessedEntitiesByFile.clear();
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000714
Douglas Gregorf128fed2010-08-20 00:02:33 +0000715 if (!OverrideMainBuffer) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000716 StoredDiagnostics.clear();
Douglas Gregorf128fed2010-08-20 00:02:33 +0000717 TopLevelDeclsInPreamble.clear();
718 }
719
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000720 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000721 Clang.setFileManager(&getFileManager());
722
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000723 // Create the source manager.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000724 Clang.setSourceManager(&getSourceManager());
725
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000726 // If the main file has been overridden due to the use of a preamble,
727 // make that override happen and introduce the preamble.
728 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000729 std::string PriorImplicitPCHInclude;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000730 if (OverrideMainBuffer) {
731 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
732 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
733 PreprocessorOpts.PrecompiledPreambleBytes.second
734 = PreambleEndsAtStartOfLine;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000735 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor385103b2010-07-30 20:58:08 +0000736 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000737 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +0000738
739 // Keep track of the override buffer;
740 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000741
742 // The stored diagnostic has the old source manager in it; update
743 // the locations to refer into the new source manager. Since we've
744 // been careful to make sure that the source manager's state
745 // before and after are identical, so that we can reuse the source
746 // location itself.
747 for (unsigned I = 0, N = StoredDiagnostics.size(); I != N; ++I) {
748 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
749 getSourceManager());
750 StoredDiagnostics[I].setLocation(Loc);
751 }
Douglas Gregorf128fed2010-08-20 00:02:33 +0000752 } else {
753 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
754 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000755 }
756
Douglas Gregorabc563f2010-07-19 21:46:24 +0000757 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
758 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000759 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbard3598a62010-06-07 23:23:06 +0000760 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000761 goto error;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000762
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000763 Act->Execute();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000764
Daniel Dunbar64a32ba2009-12-01 21:57:33 +0000765 // Steal the created target, context, and preprocessor, and take back the
766 // source and file managers.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000767 TheSema.reset(Clang.takeSema());
768 Consumer.reset(Clang.takeASTConsumer());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000769 Ctx.reset(Clang.takeASTContext());
770 PP.reset(Clang.takePreprocessor());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000771 Clang.takeSourceManager();
772 Clang.takeFileManager();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000773 Target.reset(Clang.takeTarget());
774
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000775 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000776
777 // Remove the overridden buffer we used for the preamble.
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000778 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000779 PreprocessorOpts.eraseRemappedFile(
780 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000781 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
782 }
783
Douglas Gregorabc563f2010-07-19 21:46:24 +0000784 Invocation.reset(Clang.takeInvocation());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000785
786 // If we were asked to cache code-completion results and don't have any
787 // results yet, do so now.
788 if (ShouldCacheCodeCompletionResults && CachedCompletionResults.empty())
789 CacheCodeCompletionResults();
790
Douglas Gregorabc563f2010-07-19 21:46:24 +0000791 return false;
792
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000793error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000794 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000795 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000796 PreprocessorOpts.eraseRemappedFile(
797 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000798 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000799 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregor671947b2010-08-19 01:33:06 +0000800 delete OverrideMainBuffer;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000801 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000802
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000803 Clang.takeSourceManager();
804 Clang.takeFileManager();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000805 Invocation.reset(Clang.takeInvocation());
806 return true;
807}
808
Douglas Gregor44c181a2010-07-23 00:33:23 +0000809/// \brief Simple function to retrieve a path for a preamble precompiled header.
810static std::string GetPreamblePCHPath() {
811 // FIXME: This is lame; sys::Path should provide this function (in particular,
812 // it should know how to find the temporary files dir).
813 // FIXME: This is really lame. I copied this code from the Driver!
Douglas Gregor424668c2010-09-11 18:05:19 +0000814 // FIXME: This is a hack so that we can override the preamble file during
815 // crash-recovery testing, which is the only case where the preamble files
816 // are not necessarily cleaned up.
817 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
818 if (TmpFile)
819 return TmpFile;
820
Douglas Gregor44c181a2010-07-23 00:33:23 +0000821 std::string Error;
822 const char *TmpDir = ::getenv("TMPDIR");
823 if (!TmpDir)
824 TmpDir = ::getenv("TEMP");
825 if (!TmpDir)
826 TmpDir = ::getenv("TMP");
Douglas Gregorc6cb2b02010-09-11 17:51:16 +0000827#ifdef LLVM_ON_WIN32
828 if (!TmpDir)
829 TmpDir = ::getenv("USERPROFILE");
830#endif
Douglas Gregor44c181a2010-07-23 00:33:23 +0000831 if (!TmpDir)
832 TmpDir = "/tmp";
833 llvm::sys::Path P(TmpDir);
Douglas Gregorc6cb2b02010-09-11 17:51:16 +0000834 P.createDirectoryOnDisk(true);
Douglas Gregor44c181a2010-07-23 00:33:23 +0000835 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +0000836 P.appendSuffix("pch");
Douglas Gregor44c181a2010-07-23 00:33:23 +0000837 if (P.createTemporaryFileOnDisk())
838 return std::string();
839
Douglas Gregor44c181a2010-07-23 00:33:23 +0000840 return P.str();
841}
842
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000843/// \brief Compute the preamble for the main file, providing the source buffer
844/// that corresponds to the main file along with a pair (bytes, start-of-line)
845/// that describes the preamble.
846std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +0000847ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
848 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000849 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000850 PreprocessorOptions &PreprocessorOpts
Douglas Gregor175c4a92010-07-23 23:58:40 +0000851 = Invocation.getPreprocessorOpts();
852 CreatedBuffer = false;
853
Douglas Gregor44c181a2010-07-23 00:33:23 +0000854 // Try to determine if the main file has been remapped, either from the
855 // command line (to another file) or directly through the compiler invocation
856 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +0000857 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000858 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
859 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
860 // Check whether there is a file-file remapping of the main file
861 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +0000862 M = PreprocessorOpts.remapped_file_begin(),
863 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000864 M != E;
865 ++M) {
866 llvm::sys::PathWithStatus MPath(M->first);
867 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
868 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
869 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000870 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000871 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000872 CreatedBuffer = false;
873 }
874
Douglas Gregor44c181a2010-07-23 00:33:23 +0000875 Buffer = llvm::MemoryBuffer::getFile(M->second);
876 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000877 return std::make_pair((llvm::MemoryBuffer*)0,
878 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000879 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000880
Douglas Gregor175c4a92010-07-23 23:58:40 +0000881 // Remove this remapping. We've captured the buffer already.
Douglas Gregor44c181a2010-07-23 00:33:23 +0000882 M = PreprocessorOpts.eraseRemappedFile(M);
883 E = PreprocessorOpts.remapped_file_end();
Daniel Dunbarc1cf1582010-08-19 19:40:40 +0000884 if (M == E)
885 break;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000886 }
887 }
888 }
889
890 // Check whether there is a file-buffer remapping. It supercedes the
891 // file-file remapping.
892 for (PreprocessorOptions::remapped_file_buffer_iterator
893 M = PreprocessorOpts.remapped_file_buffer_begin(),
894 E = PreprocessorOpts.remapped_file_buffer_end();
895 M != E;
896 ++M) {
897 llvm::sys::PathWithStatus MPath(M->first);
898 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
899 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
900 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000901 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000902 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000903 CreatedBuffer = false;
904 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000905
Douglas Gregor175c4a92010-07-23 23:58:40 +0000906 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
907
908 // Remove this remapping. We've captured the buffer already.
Douglas Gregor44c181a2010-07-23 00:33:23 +0000909 M = PreprocessorOpts.eraseRemappedFile(M);
910 E = PreprocessorOpts.remapped_file_buffer_end();
Daniel Dunbarc1cf1582010-08-19 19:40:40 +0000911 if (M == E)
912 break;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000913 }
914 }
Douglas Gregor175c4a92010-07-23 23:58:40 +0000915 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000916 }
917
918 // If the main source file was not remapped, load it now.
919 if (!Buffer) {
920 Buffer = llvm::MemoryBuffer::getFile(FrontendOpts.Inputs[0].second);
921 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000922 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000923
924 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000925 }
926
Douglas Gregordf95a132010-08-09 20:45:32 +0000927 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000928}
929
Douglas Gregor754f3492010-07-24 00:38:13 +0000930static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
931 bool DeleteOld,
932 unsigned NewSize,
933 llvm::StringRef NewName) {
934 llvm::MemoryBuffer *Result
935 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
936 memcpy(const_cast<char*>(Result->getBufferStart()),
937 Old->getBufferStart(), Old->getBufferSize());
938 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000939 ' ', NewSize - Old->getBufferSize() - 1);
940 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +0000941
942 if (DeleteOld)
943 delete Old;
944
945 return Result;
946}
947
Douglas Gregor175c4a92010-07-23 23:58:40 +0000948/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
949/// the source file.
950///
951/// This routine will compute the preamble of the main source file. If a
952/// non-trivial preamble is found, it will precompile that preamble into a
953/// precompiled header so that the precompiled preamble can be used to reduce
954/// reparsing time. If a precompiled preamble has already been constructed,
955/// this routine will determine if it is still valid and, if so, avoid
956/// rebuilding the precompiled preamble.
957///
Douglas Gregordf95a132010-08-09 20:45:32 +0000958/// \param AllowRebuild When true (the default), this routine is
959/// allowed to rebuild the precompiled preamble if it is found to be
960/// out-of-date.
961///
962/// \param MaxLines When non-zero, the maximum number of lines that
963/// can occur within the preamble.
964///
Douglas Gregor754f3492010-07-24 00:38:13 +0000965/// \returns If the precompiled preamble can be used, returns a newly-allocated
966/// buffer that should be used in place of the main file when doing so.
967/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +0000968llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregor2283d792010-08-20 00:59:43 +0000969 CompilerInvocation PreambleInvocation,
Douglas Gregordf95a132010-08-09 20:45:32 +0000970 bool AllowRebuild,
971 unsigned MaxLines) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000972 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
973 PreprocessorOptions &PreprocessorOpts
974 = PreambleInvocation.getPreprocessorOpts();
975
976 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000977 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregordf95a132010-08-09 20:45:32 +0000978 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +0000979
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000980 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000981 // We couldn't find a preamble in the main source. Clear out the current
982 // preamble, if we have one. It's obviously no good any more.
983 Preamble.clear();
984 if (!PreambleFile.empty()) {
Douglas Gregor385103b2010-07-30 20:58:08 +0000985 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000986 PreambleFile.clear();
987 }
988 if (CreatedPreambleBuffer)
989 delete NewPreamble.first;
Douglas Gregoreababfb2010-08-04 05:53:38 +0000990
991 // The next time we actually see a preamble, precompile it.
992 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +0000993 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000994 }
995
996 if (!Preamble.empty()) {
997 // We've previously computed a preamble. Check whether we have the same
998 // preamble now that we did before, and that there's enough space in
999 // the main-file buffer within the precompiled preamble to fit the
1000 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001001 if (Preamble.size() == NewPreamble.second.first &&
1002 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +00001003 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor175c4a92010-07-23 23:58:40 +00001004 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001005 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001006 // The preamble has not changed. We may be able to re-use the precompiled
1007 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001008
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001009 // Check that none of the files used by the preamble have changed.
1010 bool AnyFileChanged = false;
1011
1012 // First, make a record of those files that have been overridden via
1013 // remapping or unsaved_files.
1014 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1015 for (PreprocessorOptions::remapped_file_iterator
1016 R = PreprocessorOpts.remapped_file_begin(),
1017 REnd = PreprocessorOpts.remapped_file_end();
1018 !AnyFileChanged && R != REnd;
1019 ++R) {
1020 struct stat StatBuf;
1021 if (stat(R->second.c_str(), &StatBuf)) {
1022 // If we can't stat the file we're remapping to, assume that something
1023 // horrible happened.
1024 AnyFileChanged = true;
1025 break;
1026 }
Douglas Gregor754f3492010-07-24 00:38:13 +00001027
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001028 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1029 StatBuf.st_mtime);
1030 }
1031 for (PreprocessorOptions::remapped_file_buffer_iterator
1032 R = PreprocessorOpts.remapped_file_buffer_begin(),
1033 REnd = PreprocessorOpts.remapped_file_buffer_end();
1034 !AnyFileChanged && R != REnd;
1035 ++R) {
1036 // FIXME: Should we actually compare the contents of file->buffer
1037 // remappings?
1038 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1039 0);
1040 }
1041
1042 // Check whether anything has changed.
1043 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1044 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1045 !AnyFileChanged && F != FEnd;
1046 ++F) {
1047 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1048 = OverriddenFiles.find(F->first());
1049 if (Overridden != OverriddenFiles.end()) {
1050 // This file was remapped; check whether the newly-mapped file
1051 // matches up with the previous mapping.
1052 if (Overridden->second != F->second)
1053 AnyFileChanged = true;
1054 continue;
1055 }
1056
1057 // The file was not remapped; check whether it has changed on disk.
1058 struct stat StatBuf;
1059 if (stat(F->first(), &StatBuf)) {
1060 // If we can't stat the file, assume that something horrible happened.
1061 AnyFileChanged = true;
1062 } else if (StatBuf.st_size != F->second.first ||
1063 StatBuf.st_mtime != F->second.second)
1064 AnyFileChanged = true;
1065 }
1066
1067 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001068 // Okay! We can re-use the precompiled preamble.
1069
1070 // Set the state of the diagnostic object to mimic its state
1071 // after parsing the preamble.
1072 getDiagnostics().Reset();
1073 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 Gregor175c4a92010-07-23 23:58:40 +00001092
1093 // 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 Gregor44c181a2010-07-23 00:33:23 +00001164
1165 // Create the compiler instance to use for building the precompiled preamble.
1166 CompilerInstance Clang;
1167 Clang.setInvocation(&PreambleInvocation);
1168 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1169
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001170 // Set up diagnostics, capturing all of the diagnostics produced.
Douglas Gregor44c181a2010-07-23 00:33:23 +00001171 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001172 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
1173 getDiagnostics(),
1174 StoredDiagnostics);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001175
1176 // Create the target instance.
1177 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1178 Clang.getTargetOpts()));
1179 if (!Clang.hasTarget()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001180 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1181 Preamble.clear();
1182 if (CreatedPreambleBuffer)
1183 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +00001184 if (PreambleTimer)
1185 PreambleTimer->stopTimer();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001186 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001187 PreprocessorOpts.eraseRemappedFile(
1188 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001189 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001190 }
1191
1192 // Inform the target of the language options.
1193 //
1194 // FIXME: We shouldn't need to do this, the target should be immutable once
1195 // created. This complexity should be lifted elsewhere.
1196 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1197
1198 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1199 "Invocation must have exactly one source file!");
1200 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1201 "FIXME: AST inputs not yet supported here!");
1202 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1203 "IR inputs not support here!");
1204
1205 // Clear out old caches and data.
1206 StoredDiagnostics.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001207 TopLevelDecls.clear();
1208 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001209
1210 // Create a file manager object to provide access to and cache the filesystem.
1211 Clang.setFileManager(new FileManager);
1212
1213 // Create the source manager.
1214 Clang.setSourceManager(new SourceManager(getDiagnostics()));
1215
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001216 llvm::OwningPtr<PrecompilePreambleAction> Act;
1217 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001218 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1219 Clang.getFrontendOpts().Inputs[0].first)) {
Douglas Gregor44c181a2010-07-23 00:33:23 +00001220 Clang.takeInvocation();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001221 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1222 Preamble.clear();
1223 if (CreatedPreambleBuffer)
1224 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +00001225 if (PreambleTimer)
1226 PreambleTimer->stopTimer();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001227 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001228 PreprocessorOpts.eraseRemappedFile(
1229 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001230 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001231 }
1232
1233 Act->Execute();
1234 Act->EndSourceFile();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001235 Clang.takeInvocation();
1236
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001237 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001238 // There were errors parsing the preamble, so no precompiled header was
1239 // generated. Forget that we even tried.
Douglas Gregor06e50442010-09-27 16:43:25 +00001240 // FIXME: Should we leave a note for ourselves to try again?
Douglas Gregor175c4a92010-07-23 23:58:40 +00001241 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1242 Preamble.clear();
1243 if (CreatedPreambleBuffer)
1244 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +00001245 if (PreambleTimer)
1246 PreambleTimer->stopTimer();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001247 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001248 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor671947b2010-08-19 01:33:06 +00001249 PreprocessorOpts.eraseRemappedFile(
1250 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001251 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001252 }
1253
1254 // Keep track of the preamble we precompiled.
1255 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001256 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1257 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001258
1259 // Keep track of all of the files that the source manager knows about,
1260 // so we can verify whether they have changed or not.
1261 FilesInPreamble.clear();
1262 SourceManager &SourceMgr = Clang.getSourceManager();
1263 const llvm::MemoryBuffer *MainFileBuffer
1264 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1265 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1266 FEnd = SourceMgr.fileinfo_end();
1267 F != FEnd;
1268 ++F) {
1269 const FileEntry *File = F->second->Entry;
1270 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1271 continue;
1272
1273 FilesInPreamble[File->getName()]
1274 = std::make_pair(F->second->getSize(), File->getModificationTime());
1275 }
1276
Douglas Gregor385103b2010-07-30 20:58:08 +00001277 if (PreambleTimer)
1278 PreambleTimer->stopTimer();
Douglas Gregor06e50442010-09-27 16:43:25 +00001279
Douglas Gregoreababfb2010-08-04 05:53:38 +00001280 PreambleRebuildCounter = 1;
Douglas Gregor671947b2010-08-19 01:33:06 +00001281 PreprocessorOpts.eraseRemappedFile(
1282 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor754f3492010-07-24 00:38:13 +00001283 return CreatePaddedMainFileBuffer(NewPreamble.first,
1284 CreatedPreambleBuffer,
1285 PreambleReservedSize,
1286 FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001287}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001288
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001289void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1290 std::vector<Decl *> Resolved;
1291 Resolved.reserve(TopLevelDeclsInPreamble.size());
1292 ExternalASTSource &Source = *getASTContext().getExternalSource();
1293 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1294 // Resolve the declaration ID to an actual declaration, possibly
1295 // deserializing the declaration in the process.
1296 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1297 if (D)
1298 Resolved.push_back(D);
1299 }
1300 TopLevelDeclsInPreamble.clear();
1301 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1302}
1303
1304unsigned ASTUnit::getMaxPCHLevel() const {
1305 if (!getOnlyLocalDecls())
1306 return Decl::MaxPCHLevel;
1307
1308 unsigned Result = 0;
1309 if (isMainFileAST() || SavedMainFileBuffer)
1310 ++Result;
1311 return Result;
1312}
1313
Douglas Gregorabc563f2010-07-19 21:46:24 +00001314ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1315 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1316 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001317 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001318 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001319 bool CompleteTranslationUnit,
1320 bool CacheCodeCompletionResults) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001321 if (!Diags.getPtr()) {
1322 // No diagnostics engine was provided, so create our own diagnostics object
1323 // with the default options.
1324 DiagnosticOptions DiagOpts;
1325 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
1326 }
1327
1328 // Create the AST unit.
1329 llvm::OwningPtr<ASTUnit> AST;
1330 AST.reset(new ASTUnit(false));
1331 AST->Diagnostics = Diags;
1332 AST->CaptureDiagnostics = CaptureDiagnostics;
1333 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregordf95a132010-08-09 20:45:32 +00001334 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001335 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001336 AST->Invocation.reset(CI);
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001337 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001338
Douglas Gregor385103b2010-07-30 20:58:08 +00001339 if (getenv("LIBCLANG_TIMING"))
1340 AST->TimerGroup.reset(
1341 new llvm::TimerGroup(CI->getFrontendOpts().Inputs[0].second));
1342
1343
Douglas Gregor754f3492010-07-24 00:38:13 +00001344 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorfd0b8702010-07-28 22:12:37 +00001345 // FIXME: When C++ PCH is ready, allow use of it for a precompiled preamble.
Douglas Gregoreababfb2010-08-04 05:53:38 +00001346 if (PrecompilePreamble && !CI->getLangOpts().CPlusPlus) {
1347 AST->PreambleRebuildCounter = 1;
Douglas Gregor2283d792010-08-20 00:59:43 +00001348 OverrideMainBuffer
1349 = AST->getMainBufferWithPrecompiledPreamble(*AST->Invocation);
Douglas Gregoreababfb2010-08-04 05:53:38 +00001350 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001351
Douglas Gregor385103b2010-07-30 20:58:08 +00001352 llvm::Timer *ParsingTimer = 0;
1353 if (AST->TimerGroup.get()) {
1354 ParsingTimer = new llvm::Timer("Initial parse", *AST->TimerGroup);
1355 ParsingTimer->startTimer();
1356 AST->Timers.push_back(ParsingTimer);
1357 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001358
Douglas Gregor385103b2010-07-30 20:58:08 +00001359 bool Failed = AST->Parse(OverrideMainBuffer);
1360 if (ParsingTimer)
1361 ParsingTimer->stopTimer();
1362
1363 return Failed? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001364}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001365
1366ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1367 const char **ArgEnd,
Douglas Gregor28019772010-04-05 23:52:57 +00001368 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001369 llvm::StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001370 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001371 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001372 unsigned NumRemappedFiles,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001373 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001374 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001375 bool CompleteTranslationUnit,
1376 bool CacheCodeCompletionResults) {
Douglas Gregorbdbb0042010-08-18 22:29:43 +00001377 bool CreatedDiagnosticsObject = false;
1378
Douglas Gregor28019772010-04-05 23:52:57 +00001379 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001380 // No diagnostics engine was provided, so create our own diagnostics object
1381 // with the default options.
1382 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001383 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregorbdbb0042010-08-18 22:29:43 +00001384 CreatedDiagnosticsObject = true;
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001385 }
1386
Daniel Dunbar7b556682009-12-02 03:23:45 +00001387 llvm::SmallVector<const char *, 16> Args;
1388 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1389 Args.insert(Args.end(), ArgBegin, ArgEnd);
1390
1391 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1392 // also want to force it to use clang.
1393 Args.push_back("-fsyntax-only");
1394
Daniel Dunbar869824e2009-12-13 03:46:13 +00001395 // FIXME: We shouldn't have to pass in the path info.
Daniel Dunbar0bbad512010-07-19 00:44:04 +00001396 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001397 "a.out", false, false, *Diags);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001398
1399 // Don't check that inputs exist, they have been remapped.
1400 TheDriver.setCheckInputsExist(false);
1401
Daniel Dunbar7b556682009-12-02 03:23:45 +00001402 llvm::OwningPtr<driver::Compilation> C(
1403 TheDriver.BuildCompilation(Args.size(), Args.data()));
1404
1405 // We expect to get back exactly one command job, if we didn't something
1406 // failed.
1407 const driver::JobList &Jobs = C->getJobs();
1408 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1409 llvm::SmallString<256> Msg;
1410 llvm::raw_svector_ostream OS(Msg);
1411 C->PrintJob(OS, C->getJobs(), "; ", true);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001412 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001413 return 0;
1414 }
1415
1416 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1417 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001418 Diags->Report(diag::err_fe_expected_clang_command);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001419 return 0;
1420 }
1421
1422 const driver::ArgStringList &CCArgs = Cmd->getArguments();
Daniel Dunbar807b0612010-01-30 21:47:16 +00001423 llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
Dan Gohmancb421fa2010-04-19 16:39:44 +00001424 CompilerInvocation::CreateFromArgs(*CI,
1425 const_cast<const char **>(CCArgs.data()),
1426 const_cast<const char **>(CCArgs.data()) +
Douglas Gregor44c181a2010-07-23 00:33:23 +00001427 CCArgs.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001428 *Diags);
Daniel Dunbar1e69fe32009-12-13 03:45:58 +00001429
Douglas Gregor4db64a42010-01-23 00:14:00 +00001430 // Override any files that need remapping
1431 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar807b0612010-01-30 21:47:16 +00001432 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbarb26d4832010-02-16 01:55:04 +00001433 RemappedFiles[I].second);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001434
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001435 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001436 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001437
Douglas Gregorf4210892010-08-18 23:38:21 +00001438 CI->getFrontendOpts().DisableFree = false;
Douglas Gregora88084b2010-02-18 18:08:43 +00001439 return LoadFromCompilerInvocation(CI.take(), Diags, OnlyLocalDecls,
Douglas Gregordf95a132010-08-09 20:45:32 +00001440 CaptureDiagnostics, PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001441 CompleteTranslationUnit,
1442 CacheCodeCompletionResults);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001443}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001444
1445bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1446 if (!Invocation.get())
1447 return true;
1448
Douglas Gregor385103b2010-07-30 20:58:08 +00001449 llvm::Timer *ReparsingTimer = 0;
1450 if (TimerGroup.get()) {
1451 ReparsingTimer = new llvm::Timer("Reparse", *TimerGroup);
1452 ReparsingTimer->startTimer();
1453 Timers.push_back(ReparsingTimer);
1454 }
1455
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001456 // Remap files.
Douglas Gregorf128fed2010-08-20 00:02:33 +00001457 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1458 for (PreprocessorOptions::remapped_file_buffer_iterator
1459 R = PPOpts.remapped_file_buffer_begin(),
1460 REnd = PPOpts.remapped_file_buffer_end();
1461 R != REnd;
1462 ++R) {
1463 delete R->second;
1464 }
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001465 Invocation->getPreprocessorOpts().clearRemappedFiles();
1466 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1467 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1468 RemappedFiles[I].second);
1469
Douglas Gregoreababfb2010-08-04 05:53:38 +00001470 // If we have a preamble file lying around, or if we might try to
1471 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00001472 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregoreababfb2010-08-04 05:53:38 +00001473 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregor2283d792010-08-20 00:59:43 +00001474 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor175c4a92010-07-23 23:58:40 +00001475
Douglas Gregorabc563f2010-07-19 21:46:24 +00001476 // Clear out the diagnostics state.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001477 if (!OverrideMainBuffer)
1478 getDiagnostics().Reset();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001479
Douglas Gregor175c4a92010-07-23 23:58:40 +00001480 // Parse the sources
Douglas Gregor754f3492010-07-24 00:38:13 +00001481 bool Result = Parse(OverrideMainBuffer);
Douglas Gregor385103b2010-07-30 20:58:08 +00001482 if (ReparsingTimer)
1483 ReparsingTimer->stopTimer();
Douglas Gregor727d93e2010-08-17 00:40:40 +00001484
1485 if (ShouldCacheCodeCompletionResults) {
1486 if (CacheCodeCompletionCoolDown > 0)
1487 --CacheCodeCompletionCoolDown;
1488 else if (top_level_size() != NumTopLevelDeclsAtLastCompletionCache)
1489 CacheCodeCompletionResults();
1490 }
1491
Douglas Gregor175c4a92010-07-23 23:58:40 +00001492 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001493}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001494
Douglas Gregor87c08a52010-08-13 22:48:40 +00001495//----------------------------------------------------------------------------//
1496// Code completion
1497//----------------------------------------------------------------------------//
1498
1499namespace {
1500 /// \brief Code completion consumer that combines the cached code-completion
1501 /// results from an ASTUnit with the code-completion results provided to it,
1502 /// then passes the result on to
1503 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1504 unsigned NormalContexts;
1505 ASTUnit &AST;
1506 CodeCompleteConsumer &Next;
1507
1508 public:
1509 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor8071e422010-08-15 06:18:01 +00001510 bool IncludeMacros, bool IncludeCodePatterns,
1511 bool IncludeGlobals)
1512 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001513 Next.isOutputBinary()), AST(AST), Next(Next)
1514 {
1515 // Compute the set of contexts in which we will look when we don't have
1516 // any information about the specific context.
1517 NormalContexts
1518 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
1519 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
1520 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1521 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1522 | (1 << (CodeCompletionContext::CCC_Statement - 1))
1523 | (1 << (CodeCompletionContext::CCC_Expression - 1))
1524 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1525 | (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
Douglas Gregor02688102010-09-14 23:59:36 +00001526 | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
Douglas Gregor52779fb2010-09-23 23:01:17 +00001527 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
1528 | (1 << (CodeCompletionContext::CCC_Recovery - 1));
Douglas Gregor02688102010-09-14 23:59:36 +00001529
Douglas Gregor87c08a52010-08-13 22:48:40 +00001530 if (AST.getASTContext().getLangOptions().CPlusPlus)
1531 NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1))
1532 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
1533 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
1534 }
1535
1536 virtual void ProcessCodeCompleteResults(Sema &S,
1537 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00001538 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001539 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001540
1541 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1542 OverloadCandidate *Candidates,
1543 unsigned NumCandidates) {
1544 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1545 }
1546 };
1547}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001548
Douglas Gregor5f808c22010-08-16 21:18:39 +00001549/// \brief Helper function that computes which global names are hidden by the
1550/// local code-completion results.
1551void CalculateHiddenNames(const CodeCompletionContext &Context,
John McCall0a2c5e22010-08-25 06:19:51 +00001552 CodeCompletionResult *Results,
Douglas Gregor5f808c22010-08-16 21:18:39 +00001553 unsigned NumResults,
1554 ASTContext &Ctx,
1555 llvm::StringSet<> &HiddenNames) {
1556 bool OnlyTagNames = false;
1557 switch (Context.getKind()) {
Douglas Gregor52779fb2010-09-23 23:01:17 +00001558 case CodeCompletionContext::CCC_Recovery:
Douglas Gregor5f808c22010-08-16 21:18:39 +00001559 case CodeCompletionContext::CCC_TopLevel:
1560 case CodeCompletionContext::CCC_ObjCInterface:
1561 case CodeCompletionContext::CCC_ObjCImplementation:
1562 case CodeCompletionContext::CCC_ObjCIvarList:
1563 case CodeCompletionContext::CCC_ClassStructUnion:
1564 case CodeCompletionContext::CCC_Statement:
1565 case CodeCompletionContext::CCC_Expression:
1566 case CodeCompletionContext::CCC_ObjCMessageReceiver:
1567 case CodeCompletionContext::CCC_MemberAccess:
1568 case CodeCompletionContext::CCC_Namespace:
1569 case CodeCompletionContext::CCC_Type:
Douglas Gregor2ccccb32010-08-23 18:23:48 +00001570 case CodeCompletionContext::CCC_Name:
1571 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor02688102010-09-14 23:59:36 +00001572 case CodeCompletionContext::CCC_ParenthesizedExpression:
Douglas Gregor5f808c22010-08-16 21:18:39 +00001573 break;
1574
1575 case CodeCompletionContext::CCC_EnumTag:
1576 case CodeCompletionContext::CCC_UnionTag:
1577 case CodeCompletionContext::CCC_ClassOrStructTag:
1578 OnlyTagNames = true;
1579 break;
1580
1581 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001582 case CodeCompletionContext::CCC_MacroName:
1583 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorf29c5232010-08-24 22:20:20 +00001584 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor721f3592010-08-25 18:41:16 +00001585 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregor59a66942010-08-25 18:04:30 +00001586 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor458433d2010-08-26 15:07:07 +00001587 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor1a480c42010-08-27 17:35:51 +00001588 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor52779fb2010-09-23 23:01:17 +00001589 case CodeCompletionContext::CCC_Other:
Douglas Gregor721f3592010-08-25 18:41:16 +00001590 // We're looking for nothing, or we're looking for names that cannot
1591 // be hidden.
Douglas Gregor5f808c22010-08-16 21:18:39 +00001592 return;
1593 }
1594
John McCall0a2c5e22010-08-25 06:19:51 +00001595 typedef CodeCompletionResult Result;
Douglas Gregor5f808c22010-08-16 21:18:39 +00001596 for (unsigned I = 0; I != NumResults; ++I) {
1597 if (Results[I].Kind != Result::RK_Declaration)
1598 continue;
1599
1600 unsigned IDNS
1601 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1602
1603 bool Hiding = false;
1604 if (OnlyTagNames)
1605 Hiding = (IDNS & Decl::IDNS_Tag);
1606 else {
1607 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregora5fb7c32010-08-16 23:05:20 +00001608 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1609 Decl::IDNS_NonMemberOperator);
Douglas Gregor5f808c22010-08-16 21:18:39 +00001610 if (Ctx.getLangOptions().CPlusPlus)
1611 HiddenIDNS |= Decl::IDNS_Tag;
1612 Hiding = (IDNS & HiddenIDNS);
1613 }
1614
1615 if (!Hiding)
1616 continue;
1617
1618 DeclarationName Name = Results[I].Declaration->getDeclName();
1619 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1620 HiddenNames.insert(Identifier->getName());
1621 else
1622 HiddenNames.insert(Name.getAsString());
1623 }
1624}
1625
1626
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001627void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1628 CodeCompletionContext Context,
John McCall0a2c5e22010-08-25 06:19:51 +00001629 CodeCompletionResult *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001630 unsigned NumResults) {
1631 // Merge the results we were given with the results we cached.
1632 bool AddedResult = false;
Douglas Gregor5f808c22010-08-16 21:18:39 +00001633 unsigned InContexts
Douglas Gregor52779fb2010-09-23 23:01:17 +00001634 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
Douglas Gregor5f808c22010-08-16 21:18:39 +00001635 : (1 << (Context.getKind() - 1)));
1636
1637 // Contains the set of names that are hidden by "local" completion results.
1638 llvm::StringSet<> HiddenNames;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001639 llvm::SmallVector<CodeCompletionString *, 4> StringsToDestroy;
John McCall0a2c5e22010-08-25 06:19:51 +00001640 typedef CodeCompletionResult Result;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001641 llvm::SmallVector<Result, 8> AllResults;
1642 for (ASTUnit::cached_completion_iterator
Douglas Gregor5535d572010-08-16 21:23:13 +00001643 C = AST.cached_completion_begin(),
1644 CEnd = AST.cached_completion_end();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001645 C != CEnd; ++C) {
1646 // If the context we are in matches any of the contexts we are
1647 // interested in, we'll add this result.
1648 if ((C->ShowInContexts & InContexts) == 0)
1649 continue;
1650
1651 // If we haven't added any results previously, do so now.
1652 if (!AddedResult) {
Douglas Gregor5f808c22010-08-16 21:18:39 +00001653 CalculateHiddenNames(Context, Results, NumResults, S.Context,
1654 HiddenNames);
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001655 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1656 AddedResult = true;
1657 }
1658
Douglas Gregor5f808c22010-08-16 21:18:39 +00001659 // Determine whether this global completion result is hidden by a local
1660 // completion result. If so, skip it.
1661 if (C->Kind != CXCursor_MacroDefinition &&
1662 HiddenNames.count(C->Completion->getTypedText()))
1663 continue;
1664
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001665 // Adjust priority based on similar type classes.
1666 unsigned Priority = C->Priority;
Douglas Gregor4125c372010-08-25 18:03:13 +00001667 CXCursorKind CursorKind = C->Kind;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001668 CodeCompletionString *Completion = C->Completion;
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001669 if (!Context.getPreferredType().isNull()) {
1670 if (C->Kind == CXCursor_MacroDefinition) {
1671 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregorb05496d2010-09-20 21:11:48 +00001672 S.getLangOptions(),
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001673 Context.getPreferredType()->isAnyPointerType());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001674 } else if (C->Type) {
1675 CanQualType Expected
Douglas Gregor5535d572010-08-16 21:23:13 +00001676 = S.Context.getCanonicalType(
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001677 Context.getPreferredType().getUnqualifiedType());
1678 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
1679 if (ExpectedSTC == C->TypeClass) {
1680 // We know this type is similar; check for an exact match.
1681 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregor5535d572010-08-16 21:23:13 +00001682 = AST.getCachedCompletionTypes();
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001683 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregor5535d572010-08-16 21:23:13 +00001684 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001685 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
1686 Priority /= CCF_ExactTypeMatch;
1687 else
1688 Priority /= CCF_SimilarTypeMatch;
1689 }
1690 }
1691 }
1692
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001693 // Adjust the completion string, if required.
1694 if (C->Kind == CXCursor_MacroDefinition &&
1695 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
1696 // Create a new code-completion string that just contains the
1697 // macro name, without its arguments.
1698 Completion = new CodeCompletionString;
1699 Completion->AddTypedTextChunk(C->Completion->getTypedText());
1700 StringsToDestroy.push_back(Completion);
Douglas Gregor4125c372010-08-25 18:03:13 +00001701 CursorKind = CXCursor_NotImplemented;
1702 Priority = CCP_CodePattern;
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001703 }
1704
Douglas Gregor4125c372010-08-25 18:03:13 +00001705 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregor58ddb602010-08-23 23:00:57 +00001706 C->Availability));
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001707 }
1708
1709 // If we did not add any cached completion results, just forward the
1710 // results we were given to the next consumer.
1711 if (!AddedResult) {
1712 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
1713 return;
1714 }
Douglas Gregor1e5e6682010-08-26 13:48:20 +00001715
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001716 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
1717 AllResults.size());
Douglas Gregor1fbb4472010-08-24 20:21:13 +00001718
1719 for (unsigned I = 0, N = StringsToDestroy.size(); I != N; ++I)
1720 delete StringsToDestroy[I];
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001721}
1722
1723
1724
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001725void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
1726 RemappedFile *RemappedFiles,
1727 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00001728 bool IncludeMacros,
1729 bool IncludeCodePatterns,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001730 CodeCompleteConsumer &Consumer,
1731 Diagnostic &Diag, LangOptions &LangOpts,
1732 SourceManager &SourceMgr, FileManager &FileMgr,
Douglas Gregor2283d792010-08-20 00:59:43 +00001733 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
1734 llvm::SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001735 if (!Invocation.get())
1736 return;
1737
Douglas Gregordf95a132010-08-09 20:45:32 +00001738 llvm::Timer *CompletionTimer = 0;
1739 if (TimerGroup.get()) {
1740 llvm::SmallString<128> TimerName;
1741 llvm::raw_svector_ostream TimerNameOut(TimerName);
1742 TimerNameOut << "Code completion @ " << File << ":" << Line << ":"
1743 << Column;
1744 CompletionTimer = new llvm::Timer(TimerNameOut.str(), *TimerGroup);
1745 CompletionTimer->startTimer();
1746 Timers.push_back(CompletionTimer);
1747 }
1748
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001749 CompilerInvocation CCInvocation(*Invocation);
1750 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
1751 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001752
Douglas Gregor87c08a52010-08-13 22:48:40 +00001753 FrontendOpts.ShowMacrosInCodeCompletion
1754 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001755 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor8071e422010-08-15 06:18:01 +00001756 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
1757 = CachedCompletionResults.empty();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001758 FrontendOpts.CodeCompletionAt.FileName = File;
1759 FrontendOpts.CodeCompletionAt.Line = Line;
1760 FrontendOpts.CodeCompletionAt.Column = Column;
1761
Douglas Gregorcee235c2010-08-05 09:09:23 +00001762 // Turn on spell-checking when performing code completion. It leads
1763 // to better results.
1764 unsigned SpellChecking = CCInvocation.getLangOpts().SpellChecking;
1765 CCInvocation.getLangOpts().SpellChecking = 1;
1766
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001767 // Set the language options appropriately.
1768 LangOpts = CCInvocation.getLangOpts();
1769
1770 CompilerInstance Clang;
1771 Clang.setInvocation(&CCInvocation);
1772 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1773
1774 // Set up diagnostics, capturing any diagnostics produced.
1775 Clang.setDiagnostics(&Diag);
1776 CaptureDroppedDiagnostics Capture(true,
1777 Clang.getDiagnostics(),
1778 StoredDiagnostics);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001779
1780 // Create the target instance.
1781 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1782 Clang.getTargetOpts()));
1783 if (!Clang.hasTarget()) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001784 Clang.takeInvocation();
Douglas Gregorbdbb0042010-08-18 22:29:43 +00001785 CCInvocation.getLangOpts().SpellChecking = SpellChecking;
1786 return;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001787 }
1788
1789 // Inform the target of the language options.
1790 //
1791 // FIXME: We shouldn't need to do this, the target should be immutable once
1792 // created. This complexity should be lifted elsewhere.
1793 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1794
1795 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1796 "Invocation must have exactly one source file!");
1797 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1798 "FIXME: AST inputs not yet supported here!");
1799 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1800 "IR inputs not support here!");
1801
1802
1803 // Use the source and file managers that we were given.
1804 Clang.setFileManager(&FileMgr);
1805 Clang.setSourceManager(&SourceMgr);
1806
1807 // Remap files.
1808 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00001809 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor2283d792010-08-20 00:59:43 +00001810 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001811 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
1812 RemappedFiles[I].second);
Douglas Gregor2283d792010-08-20 00:59:43 +00001813 OwnedBuffers.push_back(RemappedFiles[I].second);
1814 }
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001815
Douglas Gregor87c08a52010-08-13 22:48:40 +00001816 // Use the code completion consumer we were given, but adding any cached
1817 // code-completion results.
1818 AugmentedCodeCompleteConsumer
1819 AugmentedConsumer(*this, Consumer, FrontendOpts.ShowMacrosInCodeCompletion,
Douglas Gregor8071e422010-08-15 06:18:01 +00001820 FrontendOpts.ShowCodePatternsInCodeCompletion,
1821 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001822 Clang.setCodeCompletionConsumer(&AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001823
Douglas Gregordf95a132010-08-09 20:45:32 +00001824 // If we have a precompiled preamble, try to use it. We only allow
1825 // the use of the precompiled preamble if we're if the completion
1826 // point is within the main file, after the end of the precompiled
1827 // preamble.
1828 llvm::MemoryBuffer *OverrideMainBuffer = 0;
1829 if (!PreambleFile.empty()) {
1830 using llvm::sys::FileStatus;
1831 llvm::sys::PathWithStatus CompleteFilePath(File);
1832 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
1833 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
1834 if (const FileStatus *MainStatus = MainPath.getFileStatus())
1835 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
Douglas Gregor2283d792010-08-20 00:59:43 +00001836 OverrideMainBuffer
Douglas Gregorc9c29a82010-08-25 18:04:15 +00001837 = getMainBufferWithPrecompiledPreamble(CCInvocation, false,
1838 Line - 1);
Douglas Gregordf95a132010-08-09 20:45:32 +00001839 }
1840
1841 // If the main file has been overridden due to the use of a preamble,
1842 // make that override happen and introduce the preamble.
1843 if (OverrideMainBuffer) {
1844 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1845 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1846 PreprocessorOpts.PrecompiledPreambleBytes.second
1847 = PreambleEndsAtStartOfLine;
1848 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
1849 PreprocessorOpts.DisablePCHValidation = true;
1850
1851 // The stored diagnostics have the old source manager. Copy them
1852 // to our output set of stored diagnostics, updating the source
1853 // manager to the one we were given.
1854 for (unsigned I = 0, N = this->StoredDiagnostics.size(); I != N; ++I) {
1855 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
1856 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
1857 StoredDiagnostics[I].setLocation(Loc);
1858 }
Douglas Gregor2283d792010-08-20 00:59:43 +00001859
1860 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregorf128fed2010-08-20 00:02:33 +00001861 } else {
1862 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1863 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregordf95a132010-08-09 20:45:32 +00001864 }
1865
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001866 llvm::OwningPtr<SyntaxOnlyAction> Act;
1867 Act.reset(new SyntaxOnlyAction);
1868 if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1869 Clang.getFrontendOpts().Inputs[0].first)) {
1870 Act->Execute();
1871 Act->EndSourceFile();
1872 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001873
1874 if (CompletionTimer)
1875 CompletionTimer->stopTimer();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001876
1877 // Steal back our resources.
1878 Clang.takeFileManager();
1879 Clang.takeSourceManager();
1880 Clang.takeInvocation();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001881 Clang.takeCodeCompletionConsumer();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001882 CCInvocation.getLangOpts().SpellChecking = SpellChecking;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001883}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001884
1885bool ASTUnit::Save(llvm::StringRef File) {
1886 if (getDiagnostics().hasErrorOccurred())
1887 return true;
1888
1889 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
1890 // unconditionally create a stat cache when we parse the file?
1891 std::string ErrorInfo;
Benjamin Kramer1395c5d2010-08-15 16:54:31 +00001892 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo,
1893 llvm::raw_fd_ostream::F_Binary);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001894 if (!ErrorInfo.empty() || Out.has_error())
1895 return true;
1896
1897 std::vector<unsigned char> Buffer;
1898 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redla4232eb2010-08-18 23:56:21 +00001899 ASTWriter Writer(Stream);
1900 Writer.WriteAST(getSema(), 0, 0);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001901
1902 // Write the generated bitstream to "Out".
Douglas Gregorbdbb0042010-08-18 22:29:43 +00001903 if (!Buffer.empty())
1904 Out.write((char *)&Buffer.front(), Buffer.size());
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001905 Out.close();
1906 return Out.has_error();
1907}