blob: 4cbb2a3f13a0e6fd772f714d4a071d98b2e40832 [file] [log] [blame]
Argyrios Kyrtzidis3a08ec12009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000015#include "clang/AST/ASTContext.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000016#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000017#include "clang/AST/DeclVisitor.h"
Douglas Gregorb61c07a2010-08-16 18:08:11 +000018#include "clang/AST/TypeOrdering.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000019#include "clang/AST/StmtVisitor.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000020#include "clang/Driver/Compilation.h"
21#include "clang/Driver/Driver.h"
22#include "clang/Driver/Job.h"
23#include "clang/Driver/Tool.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000024#include "clang/Frontend/CompilerInstance.h"
25#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000026#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar764c0822009-12-01 09:51:01 +000027#include "clang/Frontend/FrontendOptions.h"
Sebastian Redlf5b13462010-08-18 23:57:17 +000028#include "clang/Serialization/ASTReader.h"
Sebastian Redl1914c6f2010-08-18 23:56:37 +000029#include "clang/Serialization/ASTWriter.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000030#include "clang/Lex/HeaderSearch.h"
31#include "clang/Lex/Preprocessor.h"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000032#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000033#include "clang/Basic/TargetInfo.h"
34#include "clang/Basic/Diagnostic.h"
Douglas Gregor40a5a7d2010-08-16 23:08:34 +000035#include "llvm/ADT/StringSet.h"
Douglas Gregoraa98ed92010-01-23 00:14:00 +000036#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar55a17b62009-12-02 03:23:45 +000037#include "llvm/System/Host.h"
Benjamin Kramer6c839f82009-10-18 11:34:14 +000038#include "llvm/System/Path.h"
Douglas Gregor028d3e42010-08-09 20:45:32 +000039#include "llvm/Support/raw_ostream.h"
Douglas Gregor15ba0b32010-07-30 20:58:08 +000040#include "llvm/Support/Timer.h"
Douglas Gregorbe2d8c62010-07-23 00:33:23 +000041#include <cstdlib>
Zhongxing Xu318e4032010-07-23 02:15:08 +000042#include <cstdio>
Douglas Gregor0e119552010-07-31 00:40:00 +000043#include <sys/stat.h>
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000044using namespace clang;
45
Douglas Gregorbb420ab2010-08-04 05:53:38 +000046/// \brief After failing to build a precompiled preamble (due to
47/// errors in the source that occurs in the preamble), the number of
48/// reparses during which we'll skip even trying to precompile the
49/// preamble.
50const unsigned DefaultPreambleRebuildInterval = 5;
51
Douglas Gregord03e8232010-04-05 21:10:19 +000052ASTUnit::ASTUnit(bool _MainFileIsAST)
Douglas Gregoraa21cc42010-07-19 21:46:24 +000053 : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
Douglas Gregor028d3e42010-08-09 20:45:32 +000054 CompleteTranslationUnit(true), ConcurrencyCheckValue(CheckUnlocked),
Douglas Gregora0734c52010-08-19 01:33:06 +000055 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
Douglas Gregor2c8bd472010-08-17 00:40:40 +000056 ShouldCacheCodeCompletionResults(false),
57 NumTopLevelDeclsAtLastCompletionCache(0),
Douglas Gregor4740c452010-08-19 00:45:44 +000058 CacheCodeCompletionCoolDown(0),
59 UnsafeToFree(false) {
Douglas Gregor15ba0b32010-07-30 20:58:08 +000060}
Douglas Gregord03e8232010-04-05 21:10:19 +000061
Daniel Dunbar764c0822009-12-01 09:51:01 +000062ASTUnit::~ASTUnit() {
Douglas Gregor0c7c2f82010-03-05 21:16:25 +000063 ConcurrencyCheckValue = CheckLocked;
Douglas Gregoraa21cc42010-07-19 21:46:24 +000064 CleanTemporaryFiles();
Douglas Gregor4dde7492010-07-23 23:58:40 +000065 if (!PreambleFile.empty())
Douglas Gregor15ba0b32010-07-30 20:58:08 +000066 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor3f4bea02010-07-26 21:36:20 +000067
68 // Free the buffers associated with remapped files. We are required to
69 // perform this operation here because we explicitly request that the
70 // compiler instance *not* free these buffers for each invocation of the
71 // parser.
72 if (Invocation.get()) {
73 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
74 for (PreprocessorOptions::remapped_file_buffer_iterator
75 FB = PPOpts.remapped_file_buffer_begin(),
76 FBEnd = PPOpts.remapped_file_buffer_end();
77 FB != FBEnd;
78 ++FB)
79 delete FB->second;
80 }
Douglas Gregor96c04262010-07-27 14:52:07 +000081
82 delete SavedMainFileBuffer;
Douglas Gregora0734c52010-08-19 01:33:06 +000083 delete PreambleBuffer;
84
Douglas Gregorb14904c2010-08-13 22:48:40 +000085 ClearCachedCompletionResults();
86
Douglas Gregor15ba0b32010-07-30 20:58:08 +000087 for (unsigned I = 0, N = Timers.size(); I != N; ++I)
88 delete Timers[I];
Douglas Gregoraa21cc42010-07-19 21:46:24 +000089}
90
91void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor6cb5ba42010-02-18 23:35:40 +000092 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
93 TemporaryFiles[I].eraseFromDisk();
Douglas Gregoraa21cc42010-07-19 21:46:24 +000094 TemporaryFiles.clear();
Steve Naroff44cd60e2009-10-15 22:23:48 +000095}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +000096
Douglas Gregor39982192010-08-15 06:18:01 +000097/// \brief Determine the set of code-completion contexts in which this
98/// declaration should be shown.
99static unsigned getDeclShowContexts(NamedDecl *ND,
Douglas Gregor59cab552010-08-16 23:05:20 +0000100 const LangOptions &LangOpts,
101 bool &IsNestedNameSpecifier) {
102 IsNestedNameSpecifier = false;
103
Douglas Gregor39982192010-08-15 06:18:01 +0000104 if (isa<UsingShadowDecl>(ND))
105 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
106 if (!ND)
107 return 0;
108
109 unsigned Contexts = 0;
110 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
111 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
112 // Types can appear in these contexts.
113 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
114 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
115 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
116 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
117 | (1 << (CodeCompletionContext::CCC_Statement - 1))
118 | (1 << (CodeCompletionContext::CCC_Type - 1));
119
120 // In C++, types can appear in expressions contexts (for functional casts).
121 if (LangOpts.CPlusPlus)
122 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
123
124 // In Objective-C, message sends can send interfaces. In Objective-C++,
125 // all types are available due to functional casts.
126 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
127 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
128
129 // Deal with tag names.
130 if (isa<EnumDecl>(ND)) {
131 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
132
Douglas Gregor59cab552010-08-16 23:05:20 +0000133 // Part of the nested-name-specifier in C++0x.
Douglas Gregor39982192010-08-15 06:18:01 +0000134 if (LangOpts.CPlusPlus0x)
Douglas Gregor59cab552010-08-16 23:05:20 +0000135 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000136 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
137 if (Record->isUnion())
138 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
139 else
140 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
141
Douglas Gregor39982192010-08-15 06:18:01 +0000142 if (LangOpts.CPlusPlus)
Douglas Gregor59cab552010-08-16 23:05:20 +0000143 IsNestedNameSpecifier = true;
144 } else if (isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND))
145 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000146 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
147 // Values can appear in these contexts.
148 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
149 | (1 << (CodeCompletionContext::CCC_Expression - 1))
150 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
151 } else if (isa<ObjCProtocolDecl>(ND)) {
152 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
153 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
Douglas Gregor59cab552010-08-16 23:05:20 +0000154 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
Douglas Gregor39982192010-08-15 06:18:01 +0000155
156 // Part of the nested-name-specifier.
Douglas Gregor59cab552010-08-16 23:05:20 +0000157 IsNestedNameSpecifier = true;
Douglas Gregor39982192010-08-15 06:18:01 +0000158 }
159
160 return Contexts;
161}
162
Douglas Gregorb14904c2010-08-13 22:48:40 +0000163void ASTUnit::CacheCodeCompletionResults() {
164 if (!TheSema)
165 return;
166
167 llvm::Timer *CachingTimer = 0;
168 if (TimerGroup.get()) {
169 CachingTimer = new llvm::Timer("Cache global code completions",
170 *TimerGroup);
171 CachingTimer->startTimer();
172 Timers.push_back(CachingTimer);
173 }
174
175 // Clear out the previous results.
176 ClearCachedCompletionResults();
177
178 // Gather the set of global code completions.
John McCall276321a2010-08-25 06:19:51 +0000179 typedef CodeCompletionResult Result;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000180 llvm::SmallVector<Result, 8> Results;
181 TheSema->GatherGlobalCodeCompletions(Results);
182
183 // Translate global code completions into cached completions.
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000184 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
185
Douglas Gregorb14904c2010-08-13 22:48:40 +0000186 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
187 switch (Results[I].Kind) {
Douglas Gregor39982192010-08-15 06:18:01 +0000188 case Result::RK_Declaration: {
Douglas Gregor59cab552010-08-16 23:05:20 +0000189 bool IsNestedNameSpecifier = false;
Douglas Gregor39982192010-08-15 06:18:01 +0000190 CachedCodeCompletionResult CachedResult;
191 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
192 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
Douglas Gregor59cab552010-08-16 23:05:20 +0000193 Ctx->getLangOptions(),
194 IsNestedNameSpecifier);
Douglas Gregor39982192010-08-15 06:18:01 +0000195 CachedResult.Priority = Results[I].Priority;
196 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000197 CachedResult.Availability = Results[I].Availability;
Douglas Gregor24747402010-08-16 16:46:30 +0000198
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000199 // Keep track of the type of this completion in an ASTContext-agnostic
200 // way.
Douglas Gregor24747402010-08-16 16:46:30 +0000201 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000202 if (UsageType.isNull()) {
Douglas Gregor24747402010-08-16 16:46:30 +0000203 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000204 CachedResult.Type = 0;
205 } else {
206 CanQualType CanUsageType
207 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
208 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
209
210 // Determine whether we have already seen this type. If so, we save
211 // ourselves the work of formatting the type string by using the
212 // temporary, CanQualType-based hash table to find the associated value.
213 unsigned &TypeValue = CompletionTypes[CanUsageType];
214 if (TypeValue == 0) {
215 TypeValue = CompletionTypes.size();
216 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
217 = TypeValue;
218 }
219
220 CachedResult.Type = TypeValue;
Douglas Gregor24747402010-08-16 16:46:30 +0000221 }
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000222
Douglas Gregor39982192010-08-15 06:18:01 +0000223 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor59cab552010-08-16 23:05:20 +0000224
225 /// Handle nested-name-specifiers in C++.
226 if (TheSema->Context.getLangOptions().CPlusPlus &&
227 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
228 // The contexts in which a nested-name-specifier can appear in C++.
229 unsigned NNSContexts
230 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
231 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
232 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
233 | (1 << (CodeCompletionContext::CCC_Statement - 1))
234 | (1 << (CodeCompletionContext::CCC_Expression - 1))
235 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
236 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
237 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
238 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000239 | (1 << (CodeCompletionContext::CCC_Type - 1))
240 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1));
Douglas Gregor59cab552010-08-16 23:05:20 +0000241
242 if (isa<NamespaceDecl>(Results[I].Declaration) ||
243 isa<NamespaceAliasDecl>(Results[I].Declaration))
244 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
245
246 if (unsigned RemainingContexts
247 = NNSContexts & ~CachedResult.ShowInContexts) {
248 // If there any contexts where this completion can be a
249 // nested-name-specifier but isn't already an option, create a
250 // nested-name-specifier completion.
251 Results[I].StartsNestedNameSpecifier = true;
252 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
253 CachedResult.ShowInContexts = RemainingContexts;
254 CachedResult.Priority = CCP_NestedNameSpecifier;
255 CachedResult.TypeClass = STC_Void;
256 CachedResult.Type = 0;
257 CachedCompletionResults.push_back(CachedResult);
258 }
259 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000260 break;
Douglas Gregor39982192010-08-15 06:18:01 +0000261 }
262
Douglas Gregorb14904c2010-08-13 22:48:40 +0000263 case Result::RK_Keyword:
264 case Result::RK_Pattern:
265 // Ignore keywords and patterns; we don't care, since they are so
266 // easily regenerated.
267 break;
268
269 case Result::RK_Macro: {
270 CachedCodeCompletionResult CachedResult;
271 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
272 CachedResult.ShowInContexts
273 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
274 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
275 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
276 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
277 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
278 | (1 << (CodeCompletionContext::CCC_Statement - 1))
279 | (1 << (CodeCompletionContext::CCC_Expression - 1))
Douglas Gregor12785102010-08-24 20:21:13 +0000280 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
Douglas Gregorec00a262010-08-24 22:20:20 +0000281 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
282 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1));
Douglas Gregorc49f5b22010-08-23 18:23:48 +0000283
Douglas Gregorb14904c2010-08-13 22:48:40 +0000284 CachedResult.Priority = Results[I].Priority;
285 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorf757a122010-08-23 23:00:57 +0000286 CachedResult.Availability = Results[I].Availability;
Douglas Gregor6e240332010-08-16 16:18:59 +0000287 CachedResult.TypeClass = STC_Void;
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000288 CachedResult.Type = 0;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000289 CachedCompletionResults.push_back(CachedResult);
290 break;
291 }
292 }
293 Results[I].Destroy();
294 }
295
296 if (CachingTimer)
297 CachingTimer->stopTimer();
Douglas Gregor2c8bd472010-08-17 00:40:40 +0000298
299 // Make a note of the state when we performed this caching.
300 NumTopLevelDeclsAtLastCompletionCache = top_level_size();
301 CacheCodeCompletionCoolDown = 15;
Douglas Gregorb14904c2010-08-13 22:48:40 +0000302}
303
304void ASTUnit::ClearCachedCompletionResults() {
305 for (unsigned I = 0, N = CachedCompletionResults.size(); I != N; ++I)
306 delete CachedCompletionResults[I].Completion;
307 CachedCompletionResults.clear();
Douglas Gregorb61c07a2010-08-16 18:08:11 +0000308 CachedCompletionTypes.clear();
Douglas Gregorb14904c2010-08-13 22:48:40 +0000309}
310
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000311namespace {
312
Sebastian Redl2c499f62010-08-18 23:56:43 +0000313/// \brief Gathers information from ASTReader that will be used to initialize
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000314/// a Preprocessor.
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000315class ASTInfoCollector : public ASTReaderListener {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000316 LangOptions &LangOpt;
317 HeaderSearch &HSI;
318 std::string &TargetTriple;
319 std::string &Predefines;
320 unsigned &Counter;
Mike Stump11289f42009-09-09 15:08:12 +0000321
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000322 unsigned NumHeaderInfos;
Mike Stump11289f42009-09-09 15:08:12 +0000323
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000324public:
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000325 ASTInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000326 std::string &TargetTriple, std::string &Predefines,
327 unsigned &Counter)
328 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
329 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump11289f42009-09-09 15:08:12 +0000330
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000331 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
332 LangOpt = LangOpts;
333 return false;
334 }
Mike Stump11289f42009-09-09 15:08:12 +0000335
Daniel Dunbar20a682d2009-11-11 00:52:11 +0000336 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000337 TargetTriple = Triple;
338 return false;
339 }
Mike Stump11289f42009-09-09 15:08:12 +0000340
Sebastian Redl8b41f302010-07-14 23:29:55 +0000341 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar000c4ff2009-11-11 05:29:04 +0000342 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000343 std::string &SuggestedPredefines) {
Sebastian Redl8b41f302010-07-14 23:29:55 +0000344 Predefines = Buffers[0].Data;
345 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
346 Predefines += Buffers[I].Data;
347 }
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000348 return false;
349 }
Mike Stump11289f42009-09-09 15:08:12 +0000350
Douglas Gregora2f49452010-03-16 19:09:18 +0000351 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000352 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
353 }
Mike Stump11289f42009-09-09 15:08:12 +0000354
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000355 virtual void ReadCounter(unsigned Value) {
356 Counter = Value;
357 }
358};
359
Douglas Gregor33cdd812010-02-18 18:08:43 +0000360class StoredDiagnosticClient : public DiagnosticClient {
361 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
362
363public:
364 explicit StoredDiagnosticClient(
365 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
366 : StoredDiags(StoredDiags) { }
367
368 virtual void HandleDiagnostic(Diagnostic::Level Level,
369 const DiagnosticInfo &Info);
370};
371
372/// \brief RAII object that optionally captures diagnostics, if
373/// there is no diagnostic client to capture them already.
374class CaptureDroppedDiagnostics {
375 Diagnostic &Diags;
376 StoredDiagnosticClient Client;
377 DiagnosticClient *PreviousClient;
378
379public:
380 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
381 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000382 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
Douglas Gregor33cdd812010-02-18 18:08:43 +0000383 {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000384 if (RequestCapture || Diags.getClient() == 0) {
385 PreviousClient = Diags.takeClient();
Douglas Gregor33cdd812010-02-18 18:08:43 +0000386 Diags.setClient(&Client);
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000387 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000388 }
389
390 ~CaptureDroppedDiagnostics() {
Douglas Gregor2dd19f12010-08-18 22:29:43 +0000391 if (Diags.getClient() == &Client) {
392 Diags.takeClient();
393 Diags.setClient(PreviousClient);
394 }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000395 }
396};
397
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000398} // anonymous namespace
399
Douglas Gregor33cdd812010-02-18 18:08:43 +0000400void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
401 const DiagnosticInfo &Info) {
402 StoredDiags.push_back(StoredDiagnostic(Level, Info));
403}
404
Steve Naroffc0683b92009-09-03 18:19:54 +0000405const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbara8a50932009-12-02 08:44:16 +0000406 return OriginalSourceFile;
Steve Naroffc0683b92009-09-03 18:19:54 +0000407}
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000408
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000409const std::string &ASTUnit::getASTFileName() {
410 assert(isMainFileAST() && "Not an ASTUnit from an AST file!");
Sebastian Redl2c499f62010-08-18 23:56:43 +0000411 return static_cast<ASTReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroff44cd60e2009-10-15 22:23:48 +0000412}
413
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000414ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
Douglas Gregor7f95d262010-04-05 23:52:57 +0000415 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Ted Kremenek8bcb1c62009-10-17 00:34:24 +0000416 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000417 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +0000418 unsigned NumRemappedFiles,
419 bool CaptureDiagnostics) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000420 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
421
Douglas Gregor7f95d262010-04-05 23:52:57 +0000422 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000423 // No diagnostics engine was provided, so create our own diagnostics object
424 // with the default options.
425 DiagnosticOptions DiagOpts;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000426 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregord03e8232010-04-05 21:10:19 +0000427 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000428
429 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor16bef852009-10-16 20:01:17 +0000430 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor7f95d262010-04-05 23:52:57 +0000431 AST->Diagnostics = Diags;
Douglas Gregord03e8232010-04-05 21:10:19 +0000432 AST->FileMgr.reset(new FileManager);
433 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics()));
Steve Naroff505fb842009-10-19 14:34:22 +0000434 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000435
Douglas Gregor33cdd812010-02-18 18:08:43 +0000436 // If requested, capture diagnostics in the ASTUnit.
Douglas Gregord03e8232010-04-05 21:10:19 +0000437 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, AST->getDiagnostics(),
Douglas Gregora2433152010-04-05 18:10:21 +0000438 AST->StoredDiagnostics);
Douglas Gregor33cdd812010-02-18 18:08:43 +0000439
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000440 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
441 // Create the file entry for the file that we're mapping from.
442 const FileEntry *FromFile
443 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
444 RemappedFiles[I].second->getBufferSize(),
445 0);
446 if (!FromFile) {
Douglas Gregord03e8232010-04-05 21:10:19 +0000447 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000448 << RemappedFiles[I].first;
Douglas Gregor89a56c52010-02-27 01:32:48 +0000449 delete RemappedFiles[I].second;
Douglas Gregoraa98ed92010-01-23 00:14:00 +0000450 continue;
451 }
452
453 // Override the contents of the "from" file with the contents of
454 // the "to" file.
455 AST->getSourceManager().overrideFileContents(FromFile,
456 RemappedFiles[I].second);
457 }
458
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000459 // Gather Info for preprocessor construction later on.
Mike Stump11289f42009-09-09 15:08:12 +0000460
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000461 LangOptions LangInfo;
462 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
463 std::string TargetTriple;
464 std::string Predefines;
465 unsigned Counter;
466
Sebastian Redl2c499f62010-08-18 23:56:43 +0000467 llvm::OwningPtr<ASTReader> Reader;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000468
Sebastian Redl2c499f62010-08-18 23:56:43 +0000469 Reader.reset(new ASTReader(AST->getSourceManager(), AST->getFileManager(),
Douglas Gregord03e8232010-04-05 21:10:19 +0000470 AST->getDiagnostics()));
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000471 Reader->setListener(new ASTInfoCollector(LangInfo, HeaderInfo, TargetTriple,
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000472 Predefines, Counter));
473
Sebastian Redl3e31c722010-08-18 23:56:56 +0000474 switch (Reader->ReadAST(Filename)) {
Sebastian Redl2c499f62010-08-18 23:56:43 +0000475 case ASTReader::Success:
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000476 break;
Mike Stump11289f42009-09-09 15:08:12 +0000477
Sebastian Redl2c499f62010-08-18 23:56:43 +0000478 case ASTReader::Failure:
479 case ASTReader::IgnorePCH:
Douglas Gregord03e8232010-04-05 21:10:19 +0000480 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000481 return NULL;
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000482 }
Mike Stump11289f42009-09-09 15:08:12 +0000483
Daniel Dunbara8a50932009-12-02 08:44:16 +0000484 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
485
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000486 // AST file loaded successfully. Now create the preprocessor.
Mike Stump11289f42009-09-09 15:08:12 +0000487
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000488 // Get information about the target being compiled for.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000489 //
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000490 // FIXME: This is broken, we should store the TargetOptions in the AST file.
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000491 TargetOptions TargetOpts;
492 TargetOpts.ABI = "";
John McCall1c456c82010-08-22 06:43:33 +0000493 TargetOpts.CXXABI = "";
Daniel Dunbarb9bbd542009-11-15 06:48:46 +0000494 TargetOpts.CPU = "";
495 TargetOpts.Features.clear();
496 TargetOpts.Triple = TargetTriple;
Douglas Gregord03e8232010-04-05 21:10:19 +0000497 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
498 TargetOpts));
499 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
500 *AST->Target.get(),
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000501 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000502 Preprocessor &PP = *AST->PP.get();
503
Daniel Dunbarb7bbfdd2009-09-21 03:03:47 +0000504 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000505 PP.setCounterValue(Counter);
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000506 Reader->setPreprocessor(PP);
Mike Stump11289f42009-09-09 15:08:12 +0000507
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000508 // Create and initialize the ASTContext.
509
510 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar7cd285f2009-09-21 03:03:39 +0000511 AST->getSourceManager(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000512 *AST->Target.get(),
513 PP.getIdentifierTable(),
514 PP.getSelectorTable(),
515 PP.getBuiltinInfo(),
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000516 /* size_reserve = */0));
517 ASTContext &Context = *AST->Ctx.get();
Mike Stump11289f42009-09-09 15:08:12 +0000518
Daniel Dunbar2d9c7402009-09-03 05:59:35 +0000519 Reader->InitializeContext(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000520
Sebastian Redl2c499f62010-08-18 23:56:43 +0000521 // Attach the AST reader to the AST context as an external AST
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000522 // source, so that declarations will be deserialized from the
Sebastian Redld44cd6a2010-08-18 23:57:06 +0000523 // AST file as needed.
Sebastian Redl2c499f62010-08-18 23:56:43 +0000524 ASTReader *ReaderPtr = Reader.get();
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000525 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000526 Context.setExternalSource(Source);
527
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000528 // Create an AST consumer, even though it isn't used.
529 AST->Consumer.reset(new ASTConsumer);
530
Sebastian Redl2c499f62010-08-18 23:56:43 +0000531 // Create a semantic analysis object and tell the AST reader about it.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000532 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
533 AST->TheSema->Initialize();
534 ReaderPtr->InitializeSema(*AST->TheSema);
535
Mike Stump11289f42009-09-09 15:08:12 +0000536 return AST.take();
Argyrios Kyrtzidisce379752009-06-20 08:08:23 +0000537}
Daniel Dunbar764c0822009-12-01 09:51:01 +0000538
539namespace {
540
Daniel Dunbar644dca02009-12-04 08:17:33 +0000541class TopLevelDeclTrackerConsumer : public ASTConsumer {
542 ASTUnit &Unit;
543
544public:
545 TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {}
546
547 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekacc59c32010-05-03 20:16:35 +0000548 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
549 Decl *D = *it;
550 // FIXME: Currently ObjC method declarations are incorrectly being
551 // reported as top-level declarations, even though their DeclContext
552 // is the containing ObjC @interface/@implementation. This is a
553 // fundamental problem in the parser right now.
554 if (isa<ObjCMethodDecl>(D))
555 continue;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000556 Unit.addTopLevelDecl(D);
Ted Kremenekacc59c32010-05-03 20:16:35 +0000557 }
Daniel Dunbar644dca02009-12-04 08:17:33 +0000558 }
Sebastian Redleaa4ade2010-08-11 18:52:41 +0000559
560 // We're not interested in "interesting" decls.
561 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbar644dca02009-12-04 08:17:33 +0000562};
563
564class TopLevelDeclTrackerAction : public ASTFrontendAction {
565public:
566 ASTUnit &Unit;
567
Daniel Dunbar764c0822009-12-01 09:51:01 +0000568 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
569 llvm::StringRef InFile) {
Daniel Dunbar644dca02009-12-04 08:17:33 +0000570 return new TopLevelDeclTrackerConsumer(Unit);
Daniel Dunbar764c0822009-12-01 09:51:01 +0000571 }
572
573public:
Daniel Dunbar644dca02009-12-04 08:17:33 +0000574 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
575
Daniel Dunbar764c0822009-12-01 09:51:01 +0000576 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000577 virtual bool usesCompleteTranslationUnit() {
578 return Unit.isCompleteTranslationUnit();
579 }
Daniel Dunbar764c0822009-12-01 09:51:01 +0000580};
581
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000582class PrecompilePreambleConsumer : public PCHGenerator {
583 ASTUnit &Unit;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000584 std::vector<Decl *> TopLevelDecls;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000585
586public:
587 PrecompilePreambleConsumer(ASTUnit &Unit,
588 const Preprocessor &PP, bool Chaining,
589 const char *isysroot, llvm::raw_ostream *Out)
590 : PCHGenerator(PP, Chaining, isysroot, Out), Unit(Unit) { }
591
Douglas Gregore9db88f2010-08-03 19:06:41 +0000592 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000593 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
594 Decl *D = *it;
595 // FIXME: Currently ObjC method declarations are incorrectly being
596 // reported as top-level declarations, even though their DeclContext
597 // is the containing ObjC @interface/@implementation. This is a
598 // fundamental problem in the parser right now.
599 if (isa<ObjCMethodDecl>(D))
600 continue;
Douglas Gregore9db88f2010-08-03 19:06:41 +0000601 TopLevelDecls.push_back(D);
602 }
603 }
604
605 virtual void HandleTranslationUnit(ASTContext &Ctx) {
606 PCHGenerator::HandleTranslationUnit(Ctx);
607 if (!Unit.getDiagnostics().hasErrorOccurred()) {
608 // Translate the top-level declarations we captured during
609 // parsing into declaration IDs in the precompiled
610 // preamble. This will allow us to deserialize those top-level
611 // declarations when requested.
612 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
613 Unit.addTopLevelDeclFromPreamble(
614 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000615 }
616 }
617};
618
619class PrecompilePreambleAction : public ASTFrontendAction {
620 ASTUnit &Unit;
621
622public:
623 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
624
625 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
626 llvm::StringRef InFile) {
627 std::string Sysroot;
628 llvm::raw_ostream *OS = 0;
629 bool Chaining;
630 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
631 OS, Chaining))
632 return 0;
633
634 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
635 Sysroot.c_str() : 0;
636 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
637 isysroot, OS);
638 }
639
640 virtual bool hasCodeCompletionSupport() const { return false; }
641 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregor028d3e42010-08-09 20:45:32 +0000642 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000643};
644
Daniel Dunbar764c0822009-12-01 09:51:01 +0000645}
646
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000647/// Parse the source file into a translation unit using the given compiler
648/// invocation, replacing the current translation unit.
649///
650/// \returns True if a failure occurred that causes the ASTUnit not to
651/// contain any translation-unit information, false otherwise.
Douglas Gregor6481ef12010-07-24 00:38:13 +0000652bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor96c04262010-07-27 14:52:07 +0000653 delete SavedMainFileBuffer;
654 SavedMainFileBuffer = 0;
655
Douglas Gregora0734c52010-08-19 01:33:06 +0000656 if (!Invocation.get()) {
657 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000658 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000659 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000660
Daniel Dunbar764c0822009-12-01 09:51:01 +0000661 // Create the compiler instance to use for building the AST.
Daniel Dunbar7afbb8c2009-12-02 08:43:56 +0000662 CompilerInstance Clang;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000663 Clang.setInvocation(Invocation.take());
664 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
665
Douglas Gregor8e984da2010-08-04 16:47:14 +0000666 // Set up diagnostics, capturing any diagnostics that would
667 // otherwise be dropped.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000668 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor8e984da2010-08-04 16:47:14 +0000669 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
670 getDiagnostics(),
671 StoredDiagnostics);
Douglas Gregord03e8232010-04-05 21:10:19 +0000672
Daniel Dunbar764c0822009-12-01 09:51:01 +0000673 // Create the target instance.
674 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
675 Clang.getTargetOpts()));
Douglas Gregora0734c52010-08-19 01:33:06 +0000676 if (!Clang.hasTarget()) {
677 delete OverrideMainBuffer;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000678 return true;
Douglas Gregora0734c52010-08-19 01:33:06 +0000679 }
680
Daniel Dunbar764c0822009-12-01 09:51:01 +0000681 // Inform the target of the language options.
682 //
683 // FIXME: We shouldn't need to do this, the target should be immutable once
684 // created. This complexity should be lifted elsewhere.
685 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000686
Daniel Dunbar764c0822009-12-01 09:51:01 +0000687 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
688 "Invocation must have exactly one source file!");
Daniel Dunbar9b491e72010-06-07 23:22:09 +0000689 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar764c0822009-12-01 09:51:01 +0000690 "FIXME: AST inputs not yet supported here!");
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000691 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
692 "IR inputs not support here!");
Daniel Dunbar764c0822009-12-01 09:51:01 +0000693
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000694 // Configure the various subsystems.
695 // FIXME: Should we retain the previous file manager?
696 FileMgr.reset(new FileManager);
697 SourceMgr.reset(new SourceManager(getDiagnostics()));
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000698 TheSema.reset();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000699 Ctx.reset();
700 PP.reset();
701
702 // Clear out old caches and data.
703 TopLevelDecls.clear();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000704 CleanTemporaryFiles();
705 PreprocessedEntitiesByFile.clear();
Douglas Gregord9a30af2010-08-02 20:51:39 +0000706
Douglas Gregor7b02b582010-08-20 00:02:33 +0000707 if (!OverrideMainBuffer) {
Douglas Gregord9a30af2010-08-02 20:51:39 +0000708 StoredDiagnostics.clear();
Douglas Gregor7b02b582010-08-20 00:02:33 +0000709 TopLevelDeclsInPreamble.clear();
710 }
711
Daniel Dunbar764c0822009-12-01 09:51:01 +0000712 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000713 Clang.setFileManager(&getFileManager());
714
Daniel Dunbar764c0822009-12-01 09:51:01 +0000715 // Create the source manager.
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000716 Clang.setSourceManager(&getSourceManager());
717
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000718 // If the main file has been overridden due to the use of a preamble,
719 // make that override happen and introduce the preamble.
720 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
Douglas Gregor8e984da2010-08-04 16:47:14 +0000721 std::string PriorImplicitPCHInclude;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000722 if (OverrideMainBuffer) {
723 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
724 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
725 PreprocessorOpts.PrecompiledPreambleBytes.second
726 = PreambleEndsAtStartOfLine;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000727 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000728 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000729 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor96c04262010-07-27 14:52:07 +0000730
731 // Keep track of the override buffer;
732 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregord9a30af2010-08-02 20:51:39 +0000733
734 // The stored diagnostic has the old source manager in it; update
735 // the locations to refer into the new source manager. Since we've
736 // been careful to make sure that the source manager's state
737 // before and after are identical, so that we can reuse the source
738 // location itself.
739 for (unsigned I = 0, N = StoredDiagnostics.size(); I != N; ++I) {
740 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
741 getSourceManager());
742 StoredDiagnostics[I].setLocation(Loc);
743 }
Douglas Gregor7b02b582010-08-20 00:02:33 +0000744 } else {
745 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
746 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000747 }
748
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000749 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
750 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbar644dca02009-12-04 08:17:33 +0000751 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbar86546382010-06-07 23:23:06 +0000752 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar764c0822009-12-01 09:51:01 +0000753 goto error;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000754
Daniel Dunbar644dca02009-12-04 08:17:33 +0000755 Act->Execute();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000756
Daniel Dunbard2f8be32009-12-01 21:57:33 +0000757 // Steal the created target, context, and preprocessor, and take back the
758 // source and file managers.
Douglas Gregor6fd55e02010-08-13 03:15:25 +0000759 TheSema.reset(Clang.takeSema());
760 Consumer.reset(Clang.takeASTConsumer());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000761 Ctx.reset(Clang.takeASTContext());
762 PP.reset(Clang.takePreprocessor());
Daniel Dunbar764c0822009-12-01 09:51:01 +0000763 Clang.takeSourceManager();
764 Clang.takeFileManager();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000765 Target.reset(Clang.takeTarget());
766
Daniel Dunbar644dca02009-12-04 08:17:33 +0000767 Act->EndSourceFile();
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000768
769 // Remove the overridden buffer we used for the preamble.
Douglas Gregor8e984da2010-08-04 16:47:14 +0000770 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000771 PreprocessorOpts.eraseRemappedFile(
772 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor8e984da2010-08-04 16:47:14 +0000773 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
774 }
775
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000776 Invocation.reset(Clang.takeInvocation());
Douglas Gregorb14904c2010-08-13 22:48:40 +0000777
778 // If we were asked to cache code-completion results and don't have any
779 // results yet, do so now.
780 if (ShouldCacheCodeCompletionResults && CachedCompletionResults.empty())
781 CacheCodeCompletionResults();
782
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000783 return false;
784
Daniel Dunbar764c0822009-12-01 09:51:01 +0000785error:
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000786 // Remove the overridden buffer we used for the preamble.
Douglas Gregorce3a8292010-07-27 00:27:13 +0000787 if (OverrideMainBuffer) {
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000788 PreprocessorOpts.eraseRemappedFile(
789 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregorce3a8292010-07-27 00:27:13 +0000790 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000791 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregora0734c52010-08-19 01:33:06 +0000792 delete OverrideMainBuffer;
Douglas Gregorce3a8292010-07-27 00:27:13 +0000793 }
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000794
Daniel Dunbar764c0822009-12-01 09:51:01 +0000795 Clang.takeSourceManager();
796 Clang.takeFileManager();
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000797 Invocation.reset(Clang.takeInvocation());
798 return true;
799}
800
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000801/// \brief Simple function to retrieve a path for a preamble precompiled header.
802static std::string GetPreamblePCHPath() {
803 // FIXME: This is lame; sys::Path should provide this function (in particular,
804 // it should know how to find the temporary files dir).
805 // FIXME: This is really lame. I copied this code from the Driver!
806 std::string Error;
807 const char *TmpDir = ::getenv("TMPDIR");
808 if (!TmpDir)
809 TmpDir = ::getenv("TEMP");
810 if (!TmpDir)
811 TmpDir = ::getenv("TMP");
Douglas Gregorce3449f2010-09-11 17:51:16 +0000812#ifdef LLVM_ON_WIN32
813 if (!TmpDir)
814 TmpDir = ::getenv("USERPROFILE");
815#endif
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000816 if (!TmpDir)
817 TmpDir = "/tmp";
818 llvm::sys::Path P(TmpDir);
Douglas Gregorce3449f2010-09-11 17:51:16 +0000819 P.createDirectoryOnDisk(true);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000820 P.appendComponent("preamble");
Douglas Gregor20975b22010-08-11 13:06:56 +0000821 P.appendSuffix("pch");
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000822 if (P.createTemporaryFileOnDisk())
823 return std::string();
824
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000825 return P.str();
826}
827
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000828/// \brief Compute the preamble for the main file, providing the source buffer
829/// that corresponds to the main file along with a pair (bytes, start-of-line)
830/// that describes the preamble.
831std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregor028d3e42010-08-09 20:45:32 +0000832ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
833 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000834 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000835 PreprocessorOptions &PreprocessorOpts
Douglas Gregor4dde7492010-07-23 23:58:40 +0000836 = Invocation.getPreprocessorOpts();
837 CreatedBuffer = false;
838
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000839 // Try to determine if the main file has been remapped, either from the
840 // command line (to another file) or directly through the compiler invocation
841 // (to a memory buffer).
Douglas Gregor4dde7492010-07-23 23:58:40 +0000842 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000843 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
844 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
845 // Check whether there is a file-file remapping of the main file
846 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor4dde7492010-07-23 23:58:40 +0000847 M = PreprocessorOpts.remapped_file_begin(),
848 E = PreprocessorOpts.remapped_file_end();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000849 M != E;
850 ++M) {
851 llvm::sys::PathWithStatus MPath(M->first);
852 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
853 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
854 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000855 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000856 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000857 CreatedBuffer = false;
858 }
859
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000860 Buffer = llvm::MemoryBuffer::getFile(M->second);
861 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000862 return std::make_pair((llvm::MemoryBuffer*)0,
863 std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000864 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000865
Douglas Gregor4dde7492010-07-23 23:58:40 +0000866 // Remove this remapping. We've captured the buffer already.
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000867 M = PreprocessorOpts.eraseRemappedFile(M);
868 E = PreprocessorOpts.remapped_file_end();
Daniel Dunbar438c7722010-08-19 19:40:40 +0000869 if (M == E)
870 break;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000871 }
872 }
873 }
874
875 // Check whether there is a file-buffer remapping. It supercedes the
876 // file-file remapping.
877 for (PreprocessorOptions::remapped_file_buffer_iterator
878 M = PreprocessorOpts.remapped_file_buffer_begin(),
879 E = PreprocessorOpts.remapped_file_buffer_end();
880 M != E;
881 ++M) {
882 llvm::sys::PathWithStatus MPath(M->first);
883 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
884 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
885 // We found a remapping.
Douglas Gregor4dde7492010-07-23 23:58:40 +0000886 if (CreatedBuffer) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000887 delete Buffer;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000888 CreatedBuffer = false;
889 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000890
Douglas Gregor4dde7492010-07-23 23:58:40 +0000891 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
892
893 // Remove this remapping. We've captured the buffer already.
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000894 M = PreprocessorOpts.eraseRemappedFile(M);
895 E = PreprocessorOpts.remapped_file_buffer_end();
Daniel Dunbar438c7722010-08-19 19:40:40 +0000896 if (M == E)
897 break;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000898 }
899 }
Douglas Gregor4dde7492010-07-23 23:58:40 +0000900 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000901 }
902
903 // If the main source file was not remapped, load it now.
904 if (!Buffer) {
905 Buffer = llvm::MemoryBuffer::getFile(FrontendOpts.Inputs[0].second);
906 if (!Buffer)
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000907 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000908
909 CreatedBuffer = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +0000910 }
911
Douglas Gregor028d3e42010-08-09 20:45:32 +0000912 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor4dde7492010-07-23 23:58:40 +0000913}
914
Douglas Gregor6481ef12010-07-24 00:38:13 +0000915static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
916 bool DeleteOld,
917 unsigned NewSize,
918 llvm::StringRef NewName) {
919 llvm::MemoryBuffer *Result
920 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
921 memcpy(const_cast<char*>(Result->getBufferStart()),
922 Old->getBufferStart(), Old->getBufferSize());
923 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000924 ' ', NewSize - Old->getBufferSize() - 1);
925 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor6481ef12010-07-24 00:38:13 +0000926
927 if (DeleteOld)
928 delete Old;
929
930 return Result;
931}
932
Douglas Gregor4dde7492010-07-23 23:58:40 +0000933/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
934/// the source file.
935///
936/// This routine will compute the preamble of the main source file. If a
937/// non-trivial preamble is found, it will precompile that preamble into a
938/// precompiled header so that the precompiled preamble can be used to reduce
939/// reparsing time. If a precompiled preamble has already been constructed,
940/// this routine will determine if it is still valid and, if so, avoid
941/// rebuilding the precompiled preamble.
942///
Douglas Gregor028d3e42010-08-09 20:45:32 +0000943/// \param AllowRebuild When true (the default), this routine is
944/// allowed to rebuild the precompiled preamble if it is found to be
945/// out-of-date.
946///
947/// \param MaxLines When non-zero, the maximum number of lines that
948/// can occur within the preamble.
949///
Douglas Gregor6481ef12010-07-24 00:38:13 +0000950/// \returns If the precompiled preamble can be used, returns a newly-allocated
951/// buffer that should be used in place of the main file when doing so.
952/// Otherwise, returns a NULL pointer.
Douglas Gregor028d3e42010-08-09 20:45:32 +0000953llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
Douglas Gregorb97b6662010-08-20 00:59:43 +0000954 CompilerInvocation PreambleInvocation,
Douglas Gregor028d3e42010-08-09 20:45:32 +0000955 bool AllowRebuild,
956 unsigned MaxLines) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000957 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
958 PreprocessorOptions &PreprocessorOpts
959 = PreambleInvocation.getPreprocessorOpts();
960
961 bool CreatedPreambleBuffer = false;
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000962 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregor028d3e42010-08-09 20:45:32 +0000963 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor4dde7492010-07-23 23:58:40 +0000964
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000965 if (!NewPreamble.second.first) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000966 // We couldn't find a preamble in the main source. Clear out the current
967 // preamble, if we have one. It's obviously no good any more.
968 Preamble.clear();
969 if (!PreambleFile.empty()) {
Douglas Gregor15ba0b32010-07-30 20:58:08 +0000970 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor4dde7492010-07-23 23:58:40 +0000971 PreambleFile.clear();
972 }
973 if (CreatedPreambleBuffer)
974 delete NewPreamble.first;
Douglas Gregorbb420ab2010-08-04 05:53:38 +0000975
976 // The next time we actually see a preamble, precompile it.
977 PreambleRebuildCounter = 1;
Douglas Gregor6481ef12010-07-24 00:38:13 +0000978 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +0000979 }
980
981 if (!Preamble.empty()) {
982 // We've previously computed a preamble. Check whether we have the same
983 // preamble now that we did before, and that there's enough space in
984 // the main-file buffer within the precompiled preamble to fit the
985 // new main file.
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000986 if (Preamble.size() == NewPreamble.second.first &&
987 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregorf5275a82010-07-24 00:42:07 +0000988 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor4dde7492010-07-23 23:58:40 +0000989 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000990 NewPreamble.second.first) == 0) {
Douglas Gregor4dde7492010-07-23 23:58:40 +0000991 // The preamble has not changed. We may be able to re-use the precompiled
992 // preamble.
Douglas Gregord9a30af2010-08-02 20:51:39 +0000993
Douglas Gregor0e119552010-07-31 00:40:00 +0000994 // Check that none of the files used by the preamble have changed.
995 bool AnyFileChanged = false;
996
997 // First, make a record of those files that have been overridden via
998 // remapping or unsaved_files.
999 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1000 for (PreprocessorOptions::remapped_file_iterator
1001 R = PreprocessorOpts.remapped_file_begin(),
1002 REnd = PreprocessorOpts.remapped_file_end();
1003 !AnyFileChanged && R != REnd;
1004 ++R) {
1005 struct stat StatBuf;
1006 if (stat(R->second.c_str(), &StatBuf)) {
1007 // If we can't stat the file we're remapping to, assume that something
1008 // horrible happened.
1009 AnyFileChanged = true;
1010 break;
1011 }
Douglas Gregor6481ef12010-07-24 00:38:13 +00001012
Douglas Gregor0e119552010-07-31 00:40:00 +00001013 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1014 StatBuf.st_mtime);
1015 }
1016 for (PreprocessorOptions::remapped_file_buffer_iterator
1017 R = PreprocessorOpts.remapped_file_buffer_begin(),
1018 REnd = PreprocessorOpts.remapped_file_buffer_end();
1019 !AnyFileChanged && R != REnd;
1020 ++R) {
1021 // FIXME: Should we actually compare the contents of file->buffer
1022 // remappings?
1023 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1024 0);
1025 }
1026
1027 // Check whether anything has changed.
1028 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1029 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1030 !AnyFileChanged && F != FEnd;
1031 ++F) {
1032 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1033 = OverriddenFiles.find(F->first());
1034 if (Overridden != OverriddenFiles.end()) {
1035 // This file was remapped; check whether the newly-mapped file
1036 // matches up with the previous mapping.
1037 if (Overridden->second != F->second)
1038 AnyFileChanged = true;
1039 continue;
1040 }
1041
1042 // The file was not remapped; check whether it has changed on disk.
1043 struct stat StatBuf;
1044 if (stat(F->first(), &StatBuf)) {
1045 // If we can't stat the file, assume that something horrible happened.
1046 AnyFileChanged = true;
1047 } else if (StatBuf.st_size != F->second.first ||
1048 StatBuf.st_mtime != F->second.second)
1049 AnyFileChanged = true;
1050 }
1051
1052 if (!AnyFileChanged) {
Douglas Gregord9a30af2010-08-02 20:51:39 +00001053 // Okay! We can re-use the precompiled preamble.
1054
1055 // Set the state of the diagnostic object to mimic its state
1056 // after parsing the preamble.
1057 getDiagnostics().Reset();
1058 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1059 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
1060 StoredDiagnostics.erase(
1061 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
1062 StoredDiagnostics.end());
1063
1064 // Create a version of the main file buffer that is padded to
1065 // buffer size we reserved when creating the preamble.
Douglas Gregor0e119552010-07-31 00:40:00 +00001066 return CreatePaddedMainFileBuffer(NewPreamble.first,
1067 CreatedPreambleBuffer,
1068 PreambleReservedSize,
1069 FrontendOpts.Inputs[0].second);
1070 }
Douglas Gregor4dde7492010-07-23 23:58:40 +00001071 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001072
1073 // If we aren't allowed to rebuild the precompiled preamble, just
1074 // return now.
1075 if (!AllowRebuild)
1076 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001077
1078 // We can't reuse the previously-computed preamble. Build a new one.
1079 Preamble.clear();
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001080 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001081 PreambleRebuildCounter = 1;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001082 } else if (!AllowRebuild) {
1083 // We aren't allowed to rebuild the precompiled preamble; just
1084 // return now.
1085 return 0;
1086 }
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001087
1088 // If the preamble rebuild counter > 1, it's because we previously
1089 // failed to build a preamble and we're not yet ready to try
1090 // again. Decrement the counter and return a failure.
1091 if (PreambleRebuildCounter > 1) {
1092 --PreambleRebuildCounter;
1093 return 0;
1094 }
1095
Douglas Gregore10f0e52010-09-11 17:56:52 +00001096 // Create a temporary file for the precompiled preamble. In rare
1097 // circumstances, this can fail.
1098 std::string PreamblePCHPath = GetPreamblePCHPath();
1099 if (PreamblePCHPath.empty()) {
1100 // Try again next time.
1101 PreambleRebuildCounter = 1;
1102 return 0;
1103 }
1104
Douglas Gregor4dde7492010-07-23 23:58:40 +00001105 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001106 llvm::Timer *PreambleTimer = 0;
1107 if (TimerGroup.get()) {
1108 PreambleTimer = new llvm::Timer("Precompiling preamble", *TimerGroup);
1109 PreambleTimer->startTimer();
1110 Timers.push_back(PreambleTimer);
1111 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001112
1113 // Create a new buffer that stores the preamble. The buffer also contains
1114 // extra space for the original contents of the file (which will be present
1115 // when we actually parse the file) along with more room in case the file
Douglas Gregor4dde7492010-07-23 23:58:40 +00001116 // grows.
1117 PreambleReservedSize = NewPreamble.first->getBufferSize();
1118 if (PreambleReservedSize < 4096)
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001119 PreambleReservedSize = 8191;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001120 else
Douglas Gregor4dde7492010-07-23 23:58:40 +00001121 PreambleReservedSize *= 2;
1122
Douglas Gregord9a30af2010-08-02 20:51:39 +00001123 // Save the preamble text for later; we'll need to compare against it for
1124 // subsequent reparses.
1125 Preamble.assign(NewPreamble.first->getBufferStart(),
1126 NewPreamble.first->getBufferStart()
1127 + NewPreamble.second.first);
1128 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1129
Douglas Gregora0734c52010-08-19 01:33:06 +00001130 delete PreambleBuffer;
1131 PreambleBuffer
Douglas Gregor4dde7492010-07-23 23:58:40 +00001132 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001133 FrontendOpts.Inputs[0].second);
1134 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor4dde7492010-07-23 23:58:40 +00001135 NewPreamble.first->getBufferStart(), Preamble.size());
1136 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001137 ' ', PreambleReservedSize - Preamble.size() - 1);
1138 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001139
1140 // Remap the main source file to the preamble buffer.
Douglas Gregor4dde7492010-07-23 23:58:40 +00001141 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001142 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1143
1144 // Tell the compiler invocation to generate a temporary precompiled header.
1145 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Sebastian Redle98428d2010-08-06 00:35:11 +00001146 // FIXME: Set ChainedPCH unconditionally, once it is ready.
1147 if (::getenv("LIBCLANG_CHAINING"))
1148 FrontendOpts.ChainedPCH = true;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001149 // FIXME: Generate the precompiled header into memory?
Douglas Gregore10f0e52010-09-11 17:56:52 +00001150 FrontendOpts.OutputFile = PreamblePCHPath;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001151
1152 // Create the compiler instance to use for building the precompiled preamble.
1153 CompilerInstance Clang;
1154 Clang.setInvocation(&PreambleInvocation);
1155 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1156
Douglas Gregor8e984da2010-08-04 16:47:14 +00001157 // Set up diagnostics, capturing all of the diagnostics produced.
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001158 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor8e984da2010-08-04 16:47:14 +00001159 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
1160 getDiagnostics(),
1161 StoredDiagnostics);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001162
1163 // Create the target instance.
1164 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1165 Clang.getTargetOpts()));
1166 if (!Clang.hasTarget()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001167 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1168 Preamble.clear();
1169 if (CreatedPreambleBuffer)
1170 delete NewPreamble.first;
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001171 if (PreambleTimer)
1172 PreambleTimer->stopTimer();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001173 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001174 PreprocessorOpts.eraseRemappedFile(
1175 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001176 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001177 }
1178
1179 // Inform the target of the language options.
1180 //
1181 // FIXME: We shouldn't need to do this, the target should be immutable once
1182 // created. This complexity should be lifted elsewhere.
1183 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1184
1185 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1186 "Invocation must have exactly one source file!");
1187 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1188 "FIXME: AST inputs not yet supported here!");
1189 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1190 "IR inputs not support here!");
1191
1192 // Clear out old caches and data.
1193 StoredDiagnostics.clear();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001194 TopLevelDecls.clear();
1195 TopLevelDeclsInPreamble.clear();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001196
1197 // Create a file manager object to provide access to and cache the filesystem.
1198 Clang.setFileManager(new FileManager);
1199
1200 // Create the source manager.
1201 Clang.setSourceManager(new SourceManager(getDiagnostics()));
1202
Douglas Gregor48c8cd32010-08-03 08:14:03 +00001203 llvm::OwningPtr<PrecompilePreambleAction> Act;
1204 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001205 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1206 Clang.getFrontendOpts().Inputs[0].first)) {
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001207 Clang.takeInvocation();
Douglas Gregor4dde7492010-07-23 23:58:40 +00001208 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1209 Preamble.clear();
1210 if (CreatedPreambleBuffer)
1211 delete NewPreamble.first;
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001212 if (PreambleTimer)
1213 PreambleTimer->stopTimer();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001214 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001215 PreprocessorOpts.eraseRemappedFile(
1216 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001217 return 0;
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001218 }
1219
1220 Act->Execute();
1221 Act->EndSourceFile();
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001222 Clang.takeInvocation();
1223
Douglas Gregore9db88f2010-08-03 19:06:41 +00001224 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor4dde7492010-07-23 23:58:40 +00001225 // There were errors parsing the preamble, so no precompiled header was
1226 // generated. Forget that we even tried.
1227 // FIXME: Should we leave a note for ourselves to try again?
1228 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1229 Preamble.clear();
1230 if (CreatedPreambleBuffer)
1231 delete NewPreamble.first;
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001232 if (PreambleTimer)
1233 PreambleTimer->stopTimer();
Douglas Gregore9db88f2010-08-03 19:06:41 +00001234 TopLevelDeclsInPreamble.clear();
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001235 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregora0734c52010-08-19 01:33:06 +00001236 PreprocessorOpts.eraseRemappedFile(
1237 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001238 return 0;
Douglas Gregor4dde7492010-07-23 23:58:40 +00001239 }
1240
1241 // Keep track of the preamble we precompiled.
1242 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregord9a30af2010-08-02 20:51:39 +00001243 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1244 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregor0e119552010-07-31 00:40:00 +00001245
1246 // Keep track of all of the files that the source manager knows about,
1247 // so we can verify whether they have changed or not.
1248 FilesInPreamble.clear();
1249 SourceManager &SourceMgr = Clang.getSourceManager();
1250 const llvm::MemoryBuffer *MainFileBuffer
1251 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1252 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1253 FEnd = SourceMgr.fileinfo_end();
1254 F != FEnd;
1255 ++F) {
1256 const FileEntry *File = F->second->Entry;
1257 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1258 continue;
1259
1260 FilesInPreamble[File->getName()]
1261 = std::make_pair(F->second->getSize(), File->getModificationTime());
1262 }
1263
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001264 if (PreambleTimer)
1265 PreambleTimer->stopTimer();
1266
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001267 PreambleRebuildCounter = 1;
Douglas Gregora0734c52010-08-19 01:33:06 +00001268 PreprocessorOpts.eraseRemappedFile(
1269 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor6481ef12010-07-24 00:38:13 +00001270 return CreatePaddedMainFileBuffer(NewPreamble.first,
1271 CreatedPreambleBuffer,
1272 PreambleReservedSize,
1273 FrontendOpts.Inputs[0].second);
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001274}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001275
Douglas Gregore9db88f2010-08-03 19:06:41 +00001276void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1277 std::vector<Decl *> Resolved;
1278 Resolved.reserve(TopLevelDeclsInPreamble.size());
1279 ExternalASTSource &Source = *getASTContext().getExternalSource();
1280 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1281 // Resolve the declaration ID to an actual declaration, possibly
1282 // deserializing the declaration in the process.
1283 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1284 if (D)
1285 Resolved.push_back(D);
1286 }
1287 TopLevelDeclsInPreamble.clear();
1288 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1289}
1290
1291unsigned ASTUnit::getMaxPCHLevel() const {
1292 if (!getOnlyLocalDecls())
1293 return Decl::MaxPCHLevel;
1294
1295 unsigned Result = 0;
1296 if (isMainFileAST() || SavedMainFileBuffer)
1297 ++Result;
1298 return Result;
1299}
1300
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001301ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1302 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1303 bool OnlyLocalDecls,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001304 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001305 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001306 bool CompleteTranslationUnit,
1307 bool CacheCodeCompletionResults) {
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001308 if (!Diags.getPtr()) {
1309 // No diagnostics engine was provided, so create our own diagnostics object
1310 // with the default options.
1311 DiagnosticOptions DiagOpts;
1312 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
1313 }
1314
1315 // Create the AST unit.
1316 llvm::OwningPtr<ASTUnit> AST;
1317 AST.reset(new ASTUnit(false));
1318 AST->Diagnostics = Diags;
1319 AST->CaptureDiagnostics = CaptureDiagnostics;
1320 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001321 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregorb14904c2010-08-13 22:48:40 +00001322 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001323 AST->Invocation.reset(CI);
Douglas Gregor3f4bea02010-07-26 21:36:20 +00001324 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001325
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001326 if (getenv("LIBCLANG_TIMING"))
1327 AST->TimerGroup.reset(
1328 new llvm::TimerGroup(CI->getFrontendOpts().Inputs[0].second));
1329
1330
Douglas Gregor6481ef12010-07-24 00:38:13 +00001331 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregora5fd5222010-07-28 22:12:37 +00001332 // FIXME: When C++ PCH is ready, allow use of it for a precompiled preamble.
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001333 if (PrecompilePreamble && !CI->getLangOpts().CPlusPlus) {
1334 AST->PreambleRebuildCounter = 1;
Douglas Gregorb97b6662010-08-20 00:59:43 +00001335 OverrideMainBuffer
1336 = AST->getMainBufferWithPrecompiledPreamble(*AST->Invocation);
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001337 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001338
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001339 llvm::Timer *ParsingTimer = 0;
1340 if (AST->TimerGroup.get()) {
1341 ParsingTimer = new llvm::Timer("Initial parse", *AST->TimerGroup);
1342 ParsingTimer->startTimer();
1343 AST->Timers.push_back(ParsingTimer);
1344 }
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001345
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001346 bool Failed = AST->Parse(OverrideMainBuffer);
1347 if (ParsingTimer)
1348 ParsingTimer->stopTimer();
1349
1350 return Failed? 0 : AST.take();
Daniel Dunbar764c0822009-12-01 09:51:01 +00001351}
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001352
1353ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1354 const char **ArgEnd,
Douglas Gregor7f95d262010-04-05 23:52:57 +00001355 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar8d4a2022009-12-13 03:46:13 +00001356 llvm::StringRef ResourceFilesPath,
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001357 bool OnlyLocalDecls,
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001358 RemappedFile *RemappedFiles,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001359 unsigned NumRemappedFiles,
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001360 bool CaptureDiagnostics,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001361 bool PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001362 bool CompleteTranslationUnit,
1363 bool CacheCodeCompletionResults) {
Douglas Gregor2dd19f12010-08-18 22:29:43 +00001364 bool CreatedDiagnosticsObject = false;
1365
Douglas Gregor7f95d262010-04-05 23:52:57 +00001366 if (!Diags.getPtr()) {
Douglas Gregord03e8232010-04-05 21:10:19 +00001367 // No diagnostics engine was provided, so create our own diagnostics object
1368 // with the default options.
1369 DiagnosticOptions DiagOpts;
Douglas Gregor7f95d262010-04-05 23:52:57 +00001370 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregor2dd19f12010-08-18 22:29:43 +00001371 CreatedDiagnosticsObject = true;
Douglas Gregord03e8232010-04-05 21:10:19 +00001372 }
1373
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001374 llvm::SmallVector<const char *, 16> Args;
1375 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1376 Args.insert(Args.end(), ArgBegin, ArgEnd);
1377
1378 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1379 // also want to force it to use clang.
1380 Args.push_back("-fsyntax-only");
1381
Daniel Dunbar8d4a2022009-12-13 03:46:13 +00001382 // FIXME: We shouldn't have to pass in the path info.
Daniel Dunbare38764c2010-07-19 00:44:04 +00001383 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
Douglas Gregord03e8232010-04-05 21:10:19 +00001384 "a.out", false, false, *Diags);
Daniel Dunbarfcf2d422010-01-25 00:44:02 +00001385
1386 // Don't check that inputs exist, they have been remapped.
1387 TheDriver.setCheckInputsExist(false);
1388
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001389 llvm::OwningPtr<driver::Compilation> C(
1390 TheDriver.BuildCompilation(Args.size(), Args.data()));
1391
1392 // We expect to get back exactly one command job, if we didn't something
1393 // failed.
1394 const driver::JobList &Jobs = C->getJobs();
1395 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1396 llvm::SmallString<256> Msg;
1397 llvm::raw_svector_ostream OS(Msg);
1398 C->PrintJob(OS, C->getJobs(), "; ", true);
Douglas Gregord03e8232010-04-05 21:10:19 +00001399 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001400 return 0;
1401 }
1402
1403 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1404 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
Douglas Gregord03e8232010-04-05 21:10:19 +00001405 Diags->Report(diag::err_fe_expected_clang_command);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001406 return 0;
1407 }
1408
1409 const driver::ArgStringList &CCArgs = Cmd->getArguments();
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001410 llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
Dan Gohman145f3f12010-04-19 16:39:44 +00001411 CompilerInvocation::CreateFromArgs(*CI,
1412 const_cast<const char **>(CCArgs.data()),
1413 const_cast<const char **>(CCArgs.data()) +
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001414 CCArgs.size(),
Douglas Gregord03e8232010-04-05 21:10:19 +00001415 *Diags);
Daniel Dunbard6136772009-12-13 03:45:58 +00001416
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001417 // Override any files that need remapping
1418 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001419 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbar19511922010-02-16 01:55:04 +00001420 RemappedFiles[I].second);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001421
Daniel Dunbara5a166d2009-12-15 00:06:45 +00001422 // Override the resources path.
Daniel Dunbar6b03ece2010-01-30 21:47:16 +00001423 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001424
Douglas Gregor4c6ed902010-08-18 23:38:21 +00001425 CI->getFrontendOpts().DisableFree = false;
Douglas Gregor33cdd812010-02-18 18:08:43 +00001426 return LoadFromCompilerInvocation(CI.take(), Diags, OnlyLocalDecls,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001427 CaptureDiagnostics, PrecompilePreamble,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001428 CompleteTranslationUnit,
1429 CacheCodeCompletionResults);
Daniel Dunbar55a17b62009-12-02 03:23:45 +00001430}
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001431
1432bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1433 if (!Invocation.get())
1434 return true;
1435
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001436 llvm::Timer *ReparsingTimer = 0;
1437 if (TimerGroup.get()) {
1438 ReparsingTimer = new llvm::Timer("Reparse", *TimerGroup);
1439 ReparsingTimer->startTimer();
1440 Timers.push_back(ReparsingTimer);
1441 }
1442
Douglas Gregor0e119552010-07-31 00:40:00 +00001443 // Remap files.
Douglas Gregor7b02b582010-08-20 00:02:33 +00001444 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1445 for (PreprocessorOptions::remapped_file_buffer_iterator
1446 R = PPOpts.remapped_file_buffer_begin(),
1447 REnd = PPOpts.remapped_file_buffer_end();
1448 R != REnd;
1449 ++R) {
1450 delete R->second;
1451 }
Douglas Gregor0e119552010-07-31 00:40:00 +00001452 Invocation->getPreprocessorOpts().clearRemappedFiles();
1453 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1454 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1455 RemappedFiles[I].second);
1456
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001457 // If we have a preamble file lying around, or if we might try to
1458 // build a precompiled preamble, do so now.
Douglas Gregor6481ef12010-07-24 00:38:13 +00001459 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorbb420ab2010-08-04 05:53:38 +00001460 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregorb97b6662010-08-20 00:59:43 +00001461 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
Douglas Gregor4dde7492010-07-23 23:58:40 +00001462
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001463 // Clear out the diagnostics state.
Douglas Gregord9a30af2010-08-02 20:51:39 +00001464 if (!OverrideMainBuffer)
1465 getDiagnostics().Reset();
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001466
Douglas Gregor4dde7492010-07-23 23:58:40 +00001467 // Parse the sources
Douglas Gregor6481ef12010-07-24 00:38:13 +00001468 bool Result = Parse(OverrideMainBuffer);
Douglas Gregor15ba0b32010-07-30 20:58:08 +00001469 if (ReparsingTimer)
1470 ReparsingTimer->stopTimer();
Douglas Gregor2c8bd472010-08-17 00:40:40 +00001471
1472 if (ShouldCacheCodeCompletionResults) {
1473 if (CacheCodeCompletionCoolDown > 0)
1474 --CacheCodeCompletionCoolDown;
1475 else if (top_level_size() != NumTopLevelDeclsAtLastCompletionCache)
1476 CacheCodeCompletionResults();
1477 }
1478
Douglas Gregor4dde7492010-07-23 23:58:40 +00001479 return Result;
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001480}
Douglas Gregor8e984da2010-08-04 16:47:14 +00001481
Douglas Gregorb14904c2010-08-13 22:48:40 +00001482//----------------------------------------------------------------------------//
1483// Code completion
1484//----------------------------------------------------------------------------//
1485
1486namespace {
1487 /// \brief Code completion consumer that combines the cached code-completion
1488 /// results from an ASTUnit with the code-completion results provided to it,
1489 /// then passes the result on to
1490 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1491 unsigned NormalContexts;
1492 ASTUnit &AST;
1493 CodeCompleteConsumer &Next;
1494
1495 public:
1496 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor39982192010-08-15 06:18:01 +00001497 bool IncludeMacros, bool IncludeCodePatterns,
1498 bool IncludeGlobals)
1499 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregorb14904c2010-08-13 22:48:40 +00001500 Next.isOutputBinary()), AST(AST), Next(Next)
1501 {
1502 // Compute the set of contexts in which we will look when we don't have
1503 // any information about the specific context.
1504 NormalContexts
1505 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
1506 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
1507 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1508 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1509 | (1 << (CodeCompletionContext::CCC_Statement - 1))
1510 | (1 << (CodeCompletionContext::CCC_Expression - 1))
1511 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1512 | (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
1513 | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
1514
1515 if (AST.getASTContext().getLangOptions().CPlusPlus)
1516 NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1))
1517 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
1518 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
1519 }
1520
1521 virtual void ProcessCodeCompleteResults(Sema &S,
1522 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001523 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001524 unsigned NumResults);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001525
1526 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1527 OverloadCandidate *Candidates,
1528 unsigned NumCandidates) {
1529 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1530 }
1531 };
1532}
Douglas Gregord46cf182010-08-16 20:01:48 +00001533
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001534/// \brief Helper function that computes which global names are hidden by the
1535/// local code-completion results.
1536void CalculateHiddenNames(const CodeCompletionContext &Context,
John McCall276321a2010-08-25 06:19:51 +00001537 CodeCompletionResult *Results,
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001538 unsigned NumResults,
1539 ASTContext &Ctx,
1540 llvm::StringSet<> &HiddenNames) {
1541 bool OnlyTagNames = false;
1542 switch (Context.getKind()) {
1543 case CodeCompletionContext::CCC_Other:
1544 case CodeCompletionContext::CCC_TopLevel:
1545 case CodeCompletionContext::CCC_ObjCInterface:
1546 case CodeCompletionContext::CCC_ObjCImplementation:
1547 case CodeCompletionContext::CCC_ObjCIvarList:
1548 case CodeCompletionContext::CCC_ClassStructUnion:
1549 case CodeCompletionContext::CCC_Statement:
1550 case CodeCompletionContext::CCC_Expression:
1551 case CodeCompletionContext::CCC_ObjCMessageReceiver:
1552 case CodeCompletionContext::CCC_MemberAccess:
1553 case CodeCompletionContext::CCC_Namespace:
1554 case CodeCompletionContext::CCC_Type:
Douglas Gregorc49f5b22010-08-23 18:23:48 +00001555 case CodeCompletionContext::CCC_Name:
1556 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001557 break;
1558
1559 case CodeCompletionContext::CCC_EnumTag:
1560 case CodeCompletionContext::CCC_UnionTag:
1561 case CodeCompletionContext::CCC_ClassOrStructTag:
1562 OnlyTagNames = true;
1563 break;
1564
1565 case CodeCompletionContext::CCC_ObjCProtocolName:
Douglas Gregor12785102010-08-24 20:21:13 +00001566 case CodeCompletionContext::CCC_MacroName:
1567 case CodeCompletionContext::CCC_MacroNameUse:
Douglas Gregorec00a262010-08-24 22:20:20 +00001568 case CodeCompletionContext::CCC_PreprocessorExpression:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001569 case CodeCompletionContext::CCC_PreprocessorDirective:
Douglas Gregorea147052010-08-25 18:04:30 +00001570 case CodeCompletionContext::CCC_NaturalLanguage:
Douglas Gregor67c692c2010-08-26 15:07:07 +00001571 case CodeCompletionContext::CCC_SelectorName:
Douglas Gregor28c78432010-08-27 17:35:51 +00001572 case CodeCompletionContext::CCC_TypeQualifiers:
Douglas Gregor0de55ce2010-08-25 18:41:16 +00001573 // We're looking for nothing, or we're looking for names that cannot
1574 // be hidden.
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001575 return;
1576 }
1577
John McCall276321a2010-08-25 06:19:51 +00001578 typedef CodeCompletionResult Result;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001579 for (unsigned I = 0; I != NumResults; ++I) {
1580 if (Results[I].Kind != Result::RK_Declaration)
1581 continue;
1582
1583 unsigned IDNS
1584 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
1585
1586 bool Hiding = false;
1587 if (OnlyTagNames)
1588 Hiding = (IDNS & Decl::IDNS_Tag);
1589 else {
1590 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
Douglas Gregor59cab552010-08-16 23:05:20 +00001591 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
1592 Decl::IDNS_NonMemberOperator);
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001593 if (Ctx.getLangOptions().CPlusPlus)
1594 HiddenIDNS |= Decl::IDNS_Tag;
1595 Hiding = (IDNS & HiddenIDNS);
1596 }
1597
1598 if (!Hiding)
1599 continue;
1600
1601 DeclarationName Name = Results[I].Declaration->getDeclName();
1602 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
1603 HiddenNames.insert(Identifier->getName());
1604 else
1605 HiddenNames.insert(Name.getAsString());
1606 }
1607}
1608
1609
Douglas Gregord46cf182010-08-16 20:01:48 +00001610void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1611 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +00001612 CodeCompletionResult *Results,
Douglas Gregord46cf182010-08-16 20:01:48 +00001613 unsigned NumResults) {
1614 // Merge the results we were given with the results we cached.
1615 bool AddedResult = false;
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001616 unsigned InContexts
1617 = (Context.getKind() == CodeCompletionContext::CCC_Other? NormalContexts
1618 : (1 << (Context.getKind() - 1)));
1619
1620 // Contains the set of names that are hidden by "local" completion results.
1621 llvm::StringSet<> HiddenNames;
Douglas Gregor12785102010-08-24 20:21:13 +00001622 llvm::SmallVector<CodeCompletionString *, 4> StringsToDestroy;
John McCall276321a2010-08-25 06:19:51 +00001623 typedef CodeCompletionResult Result;
Douglas Gregord46cf182010-08-16 20:01:48 +00001624 llvm::SmallVector<Result, 8> AllResults;
1625 for (ASTUnit::cached_completion_iterator
Douglas Gregordf239672010-08-16 21:23:13 +00001626 C = AST.cached_completion_begin(),
1627 CEnd = AST.cached_completion_end();
Douglas Gregord46cf182010-08-16 20:01:48 +00001628 C != CEnd; ++C) {
1629 // If the context we are in matches any of the contexts we are
1630 // interested in, we'll add this result.
1631 if ((C->ShowInContexts & InContexts) == 0)
1632 continue;
1633
1634 // If we haven't added any results previously, do so now.
1635 if (!AddedResult) {
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001636 CalculateHiddenNames(Context, Results, NumResults, S.Context,
1637 HiddenNames);
Douglas Gregord46cf182010-08-16 20:01:48 +00001638 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1639 AddedResult = true;
1640 }
1641
Douglas Gregor6199f2d2010-08-16 21:18:39 +00001642 // Determine whether this global completion result is hidden by a local
1643 // completion result. If so, skip it.
1644 if (C->Kind != CXCursor_MacroDefinition &&
1645 HiddenNames.count(C->Completion->getTypedText()))
1646 continue;
1647
Douglas Gregord46cf182010-08-16 20:01:48 +00001648 // Adjust priority based on similar type classes.
1649 unsigned Priority = C->Priority;
Douglas Gregor8850aa32010-08-25 18:03:13 +00001650 CXCursorKind CursorKind = C->Kind;
Douglas Gregor12785102010-08-24 20:21:13 +00001651 CodeCompletionString *Completion = C->Completion;
Douglas Gregord46cf182010-08-16 20:01:48 +00001652 if (!Context.getPreferredType().isNull()) {
1653 if (C->Kind == CXCursor_MacroDefinition) {
1654 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
Douglas Gregor12785102010-08-24 20:21:13 +00001655 Context.getPreferredType()->isAnyPointerType());
Douglas Gregord46cf182010-08-16 20:01:48 +00001656 } else if (C->Type) {
1657 CanQualType Expected
Douglas Gregordf239672010-08-16 21:23:13 +00001658 = S.Context.getCanonicalType(
Douglas Gregord46cf182010-08-16 20:01:48 +00001659 Context.getPreferredType().getUnqualifiedType());
1660 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
1661 if (ExpectedSTC == C->TypeClass) {
1662 // We know this type is similar; check for an exact match.
1663 llvm::StringMap<unsigned> &CachedCompletionTypes
Douglas Gregordf239672010-08-16 21:23:13 +00001664 = AST.getCachedCompletionTypes();
Douglas Gregord46cf182010-08-16 20:01:48 +00001665 llvm::StringMap<unsigned>::iterator Pos
Douglas Gregordf239672010-08-16 21:23:13 +00001666 = CachedCompletionTypes.find(QualType(Expected).getAsString());
Douglas Gregord46cf182010-08-16 20:01:48 +00001667 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
1668 Priority /= CCF_ExactTypeMatch;
1669 else
1670 Priority /= CCF_SimilarTypeMatch;
1671 }
1672 }
1673 }
1674
Douglas Gregor12785102010-08-24 20:21:13 +00001675 // Adjust the completion string, if required.
1676 if (C->Kind == CXCursor_MacroDefinition &&
1677 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
1678 // Create a new code-completion string that just contains the
1679 // macro name, without its arguments.
1680 Completion = new CodeCompletionString;
1681 Completion->AddTypedTextChunk(C->Completion->getTypedText());
1682 StringsToDestroy.push_back(Completion);
Douglas Gregor8850aa32010-08-25 18:03:13 +00001683 CursorKind = CXCursor_NotImplemented;
1684 Priority = CCP_CodePattern;
Douglas Gregor12785102010-08-24 20:21:13 +00001685 }
1686
Douglas Gregor8850aa32010-08-25 18:03:13 +00001687 AllResults.push_back(Result(Completion, Priority, CursorKind,
Douglas Gregorf757a122010-08-23 23:00:57 +00001688 C->Availability));
Douglas Gregord46cf182010-08-16 20:01:48 +00001689 }
1690
1691 // If we did not add any cached completion results, just forward the
1692 // results we were given to the next consumer.
1693 if (!AddedResult) {
1694 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
1695 return;
1696 }
Douglas Gregor49f67ce2010-08-26 13:48:20 +00001697
Douglas Gregord46cf182010-08-16 20:01:48 +00001698 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
1699 AllResults.size());
Douglas Gregor12785102010-08-24 20:21:13 +00001700
1701 for (unsigned I = 0, N = StringsToDestroy.size(); I != N; ++I)
1702 delete StringsToDestroy[I];
Douglas Gregord46cf182010-08-16 20:01:48 +00001703}
1704
1705
1706
Douglas Gregor8e984da2010-08-04 16:47:14 +00001707void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
1708 RemappedFile *RemappedFiles,
1709 unsigned NumRemappedFiles,
Douglas Gregorb68bc592010-08-05 09:09:23 +00001710 bool IncludeMacros,
1711 bool IncludeCodePatterns,
Douglas Gregor8e984da2010-08-04 16:47:14 +00001712 CodeCompleteConsumer &Consumer,
1713 Diagnostic &Diag, LangOptions &LangOpts,
1714 SourceManager &SourceMgr, FileManager &FileMgr,
Douglas Gregorb97b6662010-08-20 00:59:43 +00001715 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
1716 llvm::SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001717 if (!Invocation.get())
1718 return;
1719
Douglas Gregor028d3e42010-08-09 20:45:32 +00001720 llvm::Timer *CompletionTimer = 0;
1721 if (TimerGroup.get()) {
1722 llvm::SmallString<128> TimerName;
1723 llvm::raw_svector_ostream TimerNameOut(TimerName);
1724 TimerNameOut << "Code completion @ " << File << ":" << Line << ":"
1725 << Column;
1726 CompletionTimer = new llvm::Timer(TimerNameOut.str(), *TimerGroup);
1727 CompletionTimer->startTimer();
1728 Timers.push_back(CompletionTimer);
1729 }
1730
Douglas Gregor8e984da2010-08-04 16:47:14 +00001731 CompilerInvocation CCInvocation(*Invocation);
1732 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
1733 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
Douglas Gregorb68bc592010-08-05 09:09:23 +00001734
Douglas Gregorb14904c2010-08-13 22:48:40 +00001735 FrontendOpts.ShowMacrosInCodeCompletion
1736 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorb68bc592010-08-05 09:09:23 +00001737 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor39982192010-08-15 06:18:01 +00001738 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
1739 = CachedCompletionResults.empty();
Douglas Gregor8e984da2010-08-04 16:47:14 +00001740 FrontendOpts.CodeCompletionAt.FileName = File;
1741 FrontendOpts.CodeCompletionAt.Line = Line;
1742 FrontendOpts.CodeCompletionAt.Column = Column;
1743
Douglas Gregorb68bc592010-08-05 09:09:23 +00001744 // Turn on spell-checking when performing code completion. It leads
1745 // to better results.
1746 unsigned SpellChecking = CCInvocation.getLangOpts().SpellChecking;
1747 CCInvocation.getLangOpts().SpellChecking = 1;
1748
Douglas Gregor8e984da2010-08-04 16:47:14 +00001749 // Set the language options appropriately.
1750 LangOpts = CCInvocation.getLangOpts();
1751
1752 CompilerInstance Clang;
1753 Clang.setInvocation(&CCInvocation);
1754 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1755
1756 // Set up diagnostics, capturing any diagnostics produced.
1757 Clang.setDiagnostics(&Diag);
1758 CaptureDroppedDiagnostics Capture(true,
1759 Clang.getDiagnostics(),
1760 StoredDiagnostics);
Douglas Gregor8e984da2010-08-04 16:47:14 +00001761
1762 // Create the target instance.
1763 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1764 Clang.getTargetOpts()));
1765 if (!Clang.hasTarget()) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001766 Clang.takeInvocation();
Douglas Gregor2dd19f12010-08-18 22:29:43 +00001767 CCInvocation.getLangOpts().SpellChecking = SpellChecking;
1768 return;
Douglas Gregor8e984da2010-08-04 16:47:14 +00001769 }
1770
1771 // Inform the target of the language options.
1772 //
1773 // FIXME: We shouldn't need to do this, the target should be immutable once
1774 // created. This complexity should be lifted elsewhere.
1775 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1776
1777 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1778 "Invocation must have exactly one source file!");
1779 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1780 "FIXME: AST inputs not yet supported here!");
1781 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1782 "IR inputs not support here!");
1783
1784
1785 // Use the source and file managers that we were given.
1786 Clang.setFileManager(&FileMgr);
1787 Clang.setSourceManager(&SourceMgr);
1788
1789 // Remap files.
1790 PreprocessorOpts.clearRemappedFiles();
Douglas Gregord8a5dba2010-08-04 17:07:00 +00001791 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregorb97b6662010-08-20 00:59:43 +00001792 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
Douglas Gregor8e984da2010-08-04 16:47:14 +00001793 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
1794 RemappedFiles[I].second);
Douglas Gregorb97b6662010-08-20 00:59:43 +00001795 OwnedBuffers.push_back(RemappedFiles[I].second);
1796 }
Douglas Gregor8e984da2010-08-04 16:47:14 +00001797
Douglas Gregorb14904c2010-08-13 22:48:40 +00001798 // Use the code completion consumer we were given, but adding any cached
1799 // code-completion results.
1800 AugmentedCodeCompleteConsumer
1801 AugmentedConsumer(*this, Consumer, FrontendOpts.ShowMacrosInCodeCompletion,
Douglas Gregor39982192010-08-15 06:18:01 +00001802 FrontendOpts.ShowCodePatternsInCodeCompletion,
1803 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Douglas Gregorb14904c2010-08-13 22:48:40 +00001804 Clang.setCodeCompletionConsumer(&AugmentedConsumer);
Douglas Gregor8e984da2010-08-04 16:47:14 +00001805
Douglas Gregor028d3e42010-08-09 20:45:32 +00001806 // If we have a precompiled preamble, try to use it. We only allow
1807 // the use of the precompiled preamble if we're if the completion
1808 // point is within the main file, after the end of the precompiled
1809 // preamble.
1810 llvm::MemoryBuffer *OverrideMainBuffer = 0;
1811 if (!PreambleFile.empty()) {
1812 using llvm::sys::FileStatus;
1813 llvm::sys::PathWithStatus CompleteFilePath(File);
1814 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
1815 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
1816 if (const FileStatus *MainStatus = MainPath.getFileStatus())
1817 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
Douglas Gregorb97b6662010-08-20 00:59:43 +00001818 OverrideMainBuffer
Douglas Gregor8e817b62010-08-25 18:04:15 +00001819 = getMainBufferWithPrecompiledPreamble(CCInvocation, false,
1820 Line - 1);
Douglas Gregor028d3e42010-08-09 20:45:32 +00001821 }
1822
1823 // If the main file has been overridden due to the use of a preamble,
1824 // make that override happen and introduce the preamble.
1825 if (OverrideMainBuffer) {
1826 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1827 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1828 PreprocessorOpts.PrecompiledPreambleBytes.second
1829 = PreambleEndsAtStartOfLine;
1830 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
1831 PreprocessorOpts.DisablePCHValidation = true;
1832
1833 // The stored diagnostics have the old source manager. Copy them
1834 // to our output set of stored diagnostics, updating the source
1835 // manager to the one we were given.
1836 for (unsigned I = 0, N = this->StoredDiagnostics.size(); I != N; ++I) {
1837 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
1838 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
1839 StoredDiagnostics[I].setLocation(Loc);
1840 }
Douglas Gregorb97b6662010-08-20 00:59:43 +00001841
1842 OwnedBuffers.push_back(OverrideMainBuffer);
Douglas Gregor7b02b582010-08-20 00:02:33 +00001843 } else {
1844 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1845 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001846 }
1847
Douglas Gregor8e984da2010-08-04 16:47:14 +00001848 llvm::OwningPtr<SyntaxOnlyAction> Act;
1849 Act.reset(new SyntaxOnlyAction);
1850 if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1851 Clang.getFrontendOpts().Inputs[0].first)) {
1852 Act->Execute();
1853 Act->EndSourceFile();
1854 }
Douglas Gregor028d3e42010-08-09 20:45:32 +00001855
1856 if (CompletionTimer)
1857 CompletionTimer->stopTimer();
Douglas Gregor8e984da2010-08-04 16:47:14 +00001858
1859 // Steal back our resources.
1860 Clang.takeFileManager();
1861 Clang.takeSourceManager();
1862 Clang.takeInvocation();
Douglas Gregor8e984da2010-08-04 16:47:14 +00001863 Clang.takeCodeCompletionConsumer();
Douglas Gregorb68bc592010-08-05 09:09:23 +00001864 CCInvocation.getLangOpts().SpellChecking = SpellChecking;
Douglas Gregor8e984da2010-08-04 16:47:14 +00001865}
Douglas Gregore9386682010-08-13 05:36:37 +00001866
1867bool ASTUnit::Save(llvm::StringRef File) {
1868 if (getDiagnostics().hasErrorOccurred())
1869 return true;
1870
1871 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
1872 // unconditionally create a stat cache when we parse the file?
1873 std::string ErrorInfo;
Benjamin Kramer340045b2010-08-15 16:54:31 +00001874 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo,
1875 llvm::raw_fd_ostream::F_Binary);
Douglas Gregore9386682010-08-13 05:36:37 +00001876 if (!ErrorInfo.empty() || Out.has_error())
1877 return true;
1878
1879 std::vector<unsigned char> Buffer;
1880 llvm::BitstreamWriter Stream(Buffer);
Sebastian Redl55c0ad52010-08-18 23:56:21 +00001881 ASTWriter Writer(Stream);
1882 Writer.WriteAST(getSema(), 0, 0);
Douglas Gregore9386682010-08-13 05:36:37 +00001883
1884 // Write the generated bitstream to "Out".
Douglas Gregor2dd19f12010-08-18 22:29:43 +00001885 if (!Buffer.empty())
1886 Out.write((char *)&Buffer.front(), Buffer.size());
Douglas Gregore9386682010-08-13 05:36:37 +00001887 Out.close();
1888 return Out.has_error();
1889}