blob: 2c827e41da8e14e62fca804e294f1ccd12e80583 [file] [log] [blame]
Argyrios Kyrtzidis4b562cf2009-06-20 08:27:14 +00001//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTUnit Implementation.
11//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000014#include "clang/Frontend/ASTUnit.h"
Douglas Gregor1d715ac2010-08-03 08:14:03 +000015#include "clang/Frontend/PCHWriter.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000016#include "clang/AST/ASTContext.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000017#include "clang/AST/ASTConsumer.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000018#include "clang/AST/DeclVisitor.h"
Douglas Gregorf5586f62010-08-16 18:08:11 +000019#include "clang/AST/TypeOrdering.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000020#include "clang/AST/StmtVisitor.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000021#include "clang/Driver/Compilation.h"
22#include "clang/Driver/Driver.h"
23#include "clang/Driver/Job.h"
24#include "clang/Driver/Tool.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000025#include "clang/Frontend/CompilerInstance.h"
26#include "clang/Frontend/FrontendActions.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000027#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000028#include "clang/Frontend/FrontendOptions.h"
Douglas Gregor1d715ac2010-08-03 08:14:03 +000029#include "clang/Frontend/PCHReader.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000030#include "clang/Lex/HeaderSearch.h"
31#include "clang/Lex/Preprocessor.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000032#include "clang/Basic/TargetOptions.h"
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000033#include "clang/Basic/TargetInfo.h"
34#include "clang/Basic/Diagnostic.h"
Douglas Gregor4db64a42010-01-23 00:14:00 +000035#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar7b556682009-12-02 03:23:45 +000036#include "llvm/System/Host.h"
Benjamin Kramer4a630d32009-10-18 11:34:14 +000037#include "llvm/System/Path.h"
Douglas Gregordf95a132010-08-09 20:45:32 +000038#include "llvm/Support/raw_ostream.h"
Douglas Gregor385103b2010-07-30 20:58:08 +000039#include "llvm/Support/Timer.h"
Douglas Gregor44c181a2010-07-23 00:33:23 +000040#include <cstdlib>
Zhongxing Xuad23ebe2010-07-23 02:15:08 +000041#include <cstdio>
Douglas Gregorcc5888d2010-07-31 00:40:00 +000042#include <sys/stat.h>
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000043using namespace clang;
44
Douglas Gregoreababfb2010-08-04 05:53:38 +000045/// \brief After failing to build a precompiled preamble (due to
46/// errors in the source that occurs in the preamble), the number of
47/// reparses during which we'll skip even trying to precompile the
48/// preamble.
49const unsigned DefaultPreambleRebuildInterval = 5;
50
Douglas Gregor3687e9d2010-04-05 21:10:19 +000051ASTUnit::ASTUnit(bool _MainFileIsAST)
Douglas Gregorabc563f2010-07-19 21:46:24 +000052 : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
Douglas Gregordf95a132010-08-09 20:45:32 +000053 CompleteTranslationUnit(true), ConcurrencyCheckValue(CheckUnlocked),
Douglas Gregor87c08a52010-08-13 22:48:40 +000054 PreambleRebuildCounter(0), SavedMainFileBuffer(0),
55 ShouldCacheCodeCompletionResults(false) {
Douglas Gregor385103b2010-07-30 20:58:08 +000056}
Douglas Gregor3687e9d2010-04-05 21:10:19 +000057
Daniel Dunbar521bf9c2009-12-01 09:51:01 +000058ASTUnit::~ASTUnit() {
Douglas Gregorbdf60622010-03-05 21:16:25 +000059 ConcurrencyCheckValue = CheckLocked;
Douglas Gregorabc563f2010-07-19 21:46:24 +000060 CleanTemporaryFiles();
Douglas Gregor175c4a92010-07-23 23:58:40 +000061 if (!PreambleFile.empty())
Douglas Gregor385103b2010-07-30 20:58:08 +000062 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +000063
64 // Free the buffers associated with remapped files. We are required to
65 // perform this operation here because we explicitly request that the
66 // compiler instance *not* free these buffers for each invocation of the
67 // parser.
68 if (Invocation.get()) {
69 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
70 for (PreprocessorOptions::remapped_file_buffer_iterator
71 FB = PPOpts.remapped_file_buffer_begin(),
72 FBEnd = PPOpts.remapped_file_buffer_end();
73 FB != FBEnd;
74 ++FB)
75 delete FB->second;
76 }
Douglas Gregor28233422010-07-27 14:52:07 +000077
78 delete SavedMainFileBuffer;
Douglas Gregor385103b2010-07-30 20:58:08 +000079
Douglas Gregor87c08a52010-08-13 22:48:40 +000080 ClearCachedCompletionResults();
81
Douglas Gregor385103b2010-07-30 20:58:08 +000082 for (unsigned I = 0, N = Timers.size(); I != N; ++I)
83 delete Timers[I];
Douglas Gregorabc563f2010-07-19 21:46:24 +000084}
85
86void ASTUnit::CleanTemporaryFiles() {
Douglas Gregor313e26c2010-02-18 23:35:40 +000087 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
88 TemporaryFiles[I].eraseFromDisk();
Douglas Gregorabc563f2010-07-19 21:46:24 +000089 TemporaryFiles.clear();
Steve Naroffe19944c2009-10-15 22:23:48 +000090}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +000091
Douglas Gregor8071e422010-08-15 06:18:01 +000092/// \brief Determine the set of code-completion contexts in which this
93/// declaration should be shown.
94static unsigned getDeclShowContexts(NamedDecl *ND,
95 const LangOptions &LangOpts) {
96 if (isa<UsingShadowDecl>(ND))
97 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
98 if (!ND)
99 return 0;
100
101 unsigned Contexts = 0;
102 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
103 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
104 // Types can appear in these contexts.
105 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
106 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
107 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
108 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
109 | (1 << (CodeCompletionContext::CCC_Statement - 1))
110 | (1 << (CodeCompletionContext::CCC_Type - 1));
111
112 // In C++, types can appear in expressions contexts (for functional casts).
113 if (LangOpts.CPlusPlus)
114 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
115
116 // In Objective-C, message sends can send interfaces. In Objective-C++,
117 // all types are available due to functional casts.
118 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
119 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
120
121 // Deal with tag names.
122 if (isa<EnumDecl>(ND)) {
123 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
124
125 // Part of the nested-name-specifier.
126 if (LangOpts.CPlusPlus0x)
127 Contexts |= (1 << (CodeCompletionContext::CCC_MemberAccess - 1));
128 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
129 if (Record->isUnion())
130 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
131 else
132 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
133
134 // Part of the nested-name-specifier.
135 if (LangOpts.CPlusPlus)
136 Contexts |= (1 << (CodeCompletionContext::CCC_MemberAccess - 1));
137 }
138 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
139 // Values can appear in these contexts.
140 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
141 | (1 << (CodeCompletionContext::CCC_Expression - 1))
142 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
143 } else if (isa<ObjCProtocolDecl>(ND)) {
144 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
145 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
146 Contexts = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
147 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
148 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
149 | (1 << (CodeCompletionContext::CCC_Statement - 1))
150 | (1 << (CodeCompletionContext::CCC_Expression - 1))
151 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
152 | (1 << (CodeCompletionContext::CCC_Namespace - 1));
153
154 // Part of the nested-name-specifier.
155 Contexts |= (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
156 | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
157 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
158 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
159 | (1 << (CodeCompletionContext::CCC_Type - 1));
160 }
161
162 return Contexts;
163}
164
Douglas Gregor87c08a52010-08-13 22:48:40 +0000165void ASTUnit::CacheCodeCompletionResults() {
166 if (!TheSema)
167 return;
168
169 llvm::Timer *CachingTimer = 0;
170 if (TimerGroup.get()) {
171 CachingTimer = new llvm::Timer("Cache global code completions",
172 *TimerGroup);
173 CachingTimer->startTimer();
174 Timers.push_back(CachingTimer);
175 }
176
177 // Clear out the previous results.
178 ClearCachedCompletionResults();
179
180 // Gather the set of global code completions.
181 typedef CodeCompleteConsumer::Result Result;
182 llvm::SmallVector<Result, 8> Results;
183 TheSema->GatherGlobalCodeCompletions(Results);
184
185 // Translate global code completions into cached completions.
Douglas Gregorf5586f62010-08-16 18:08:11 +0000186 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
187
Douglas Gregor87c08a52010-08-13 22:48:40 +0000188 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
189 switch (Results[I].Kind) {
Douglas Gregor8071e422010-08-15 06:18:01 +0000190 case Result::RK_Declaration: {
191 CachedCodeCompletionResult CachedResult;
192 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
193 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
194 Ctx->getLangOptions());
195 CachedResult.Priority = Results[I].Priority;
196 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000197
Douglas Gregorf5586f62010-08-16 18:08:11 +0000198 // Keep track of the type of this completion in an ASTContext-agnostic
199 // way.
Douglas Gregorc4421e92010-08-16 16:46:30 +0000200 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
Douglas Gregorf5586f62010-08-16 18:08:11 +0000201 if (UsageType.isNull()) {
Douglas Gregorc4421e92010-08-16 16:46:30 +0000202 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000203 CachedResult.Type = 0;
204 } else {
205 CanQualType CanUsageType
206 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
207 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
208
209 // Determine whether we have already seen this type. If so, we save
210 // ourselves the work of formatting the type string by using the
211 // temporary, CanQualType-based hash table to find the associated value.
212 unsigned &TypeValue = CompletionTypes[CanUsageType];
213 if (TypeValue == 0) {
214 TypeValue = CompletionTypes.size();
215 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
216 = TypeValue;
217 }
218
219 CachedResult.Type = TypeValue;
Douglas Gregorc4421e92010-08-16 16:46:30 +0000220 }
Douglas Gregorf5586f62010-08-16 18:08:11 +0000221
Douglas Gregor8071e422010-08-15 06:18:01 +0000222 CachedCompletionResults.push_back(CachedResult);
Douglas Gregor87c08a52010-08-13 22:48:40 +0000223 break;
Douglas Gregor8071e422010-08-15 06:18:01 +0000224 }
225
Douglas Gregor87c08a52010-08-13 22:48:40 +0000226 case Result::RK_Keyword:
227 case Result::RK_Pattern:
228 // Ignore keywords and patterns; we don't care, since they are so
229 // easily regenerated.
230 break;
231
232 case Result::RK_Macro: {
233 CachedCodeCompletionResult CachedResult;
234 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema);
235 CachedResult.ShowInContexts
236 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
237 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
238 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
239 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
240 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
241 | (1 << (CodeCompletionContext::CCC_Statement - 1))
242 | (1 << (CodeCompletionContext::CCC_Expression - 1))
243 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
244 CachedResult.Priority = Results[I].Priority;
245 CachedResult.Kind = Results[I].CursorKind;
Douglas Gregor1827e102010-08-16 16:18:59 +0000246 CachedResult.TypeClass = STC_Void;
Douglas Gregorf5586f62010-08-16 18:08:11 +0000247 CachedResult.Type = 0;
Douglas Gregor87c08a52010-08-13 22:48:40 +0000248 CachedCompletionResults.push_back(CachedResult);
249 break;
250 }
251 }
252 Results[I].Destroy();
253 }
254
255 if (CachingTimer)
256 CachingTimer->stopTimer();
257}
258
259void ASTUnit::ClearCachedCompletionResults() {
260 for (unsigned I = 0, N = CachedCompletionResults.size(); I != N; ++I)
261 delete CachedCompletionResults[I].Completion;
262 CachedCompletionResults.clear();
Douglas Gregorf5586f62010-08-16 18:08:11 +0000263 CachedCompletionTypes.clear();
Douglas Gregor87c08a52010-08-13 22:48:40 +0000264}
265
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000266namespace {
267
268/// \brief Gathers information from PCHReader that will be used to initialize
269/// a Preprocessor.
Benjamin Kramerbd218282009-11-28 10:07:24 +0000270class PCHInfoCollector : public PCHReaderListener {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000271 LangOptions &LangOpt;
272 HeaderSearch &HSI;
273 std::string &TargetTriple;
274 std::string &Predefines;
275 unsigned &Counter;
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000277 unsigned NumHeaderInfos;
Mike Stump1eb44332009-09-09 15:08:12 +0000278
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000279public:
280 PCHInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
281 std::string &TargetTriple, std::string &Predefines,
282 unsigned &Counter)
283 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
284 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000285
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000286 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
287 LangOpt = LangOpts;
288 return false;
289 }
Mike Stump1eb44332009-09-09 15:08:12 +0000290
Daniel Dunbardc3c0d22009-11-11 00:52:11 +0000291 virtual bool ReadTargetTriple(llvm::StringRef Triple) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000292 TargetTriple = Triple;
293 return false;
294 }
Mike Stump1eb44332009-09-09 15:08:12 +0000295
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000296 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
Daniel Dunbar7b5a1212009-11-11 05:29:04 +0000297 llvm::StringRef OriginalFileName,
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000298 std::string &SuggestedPredefines) {
Sebastian Redlcb481aa2010-07-14 23:29:55 +0000299 Predefines = Buffers[0].Data;
300 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
301 Predefines += Buffers[I].Data;
302 }
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000303 return false;
304 }
Mike Stump1eb44332009-09-09 15:08:12 +0000305
Douglas Gregorec1afbf2010-03-16 19:09:18 +0000306 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000307 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
308 }
Mike Stump1eb44332009-09-09 15:08:12 +0000309
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000310 virtual void ReadCounter(unsigned Value) {
311 Counter = Value;
312 }
313};
314
Douglas Gregora88084b2010-02-18 18:08:43 +0000315class StoredDiagnosticClient : public DiagnosticClient {
316 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
317
318public:
319 explicit StoredDiagnosticClient(
320 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
321 : StoredDiags(StoredDiags) { }
322
323 virtual void HandleDiagnostic(Diagnostic::Level Level,
324 const DiagnosticInfo &Info);
325};
326
327/// \brief RAII object that optionally captures diagnostics, if
328/// there is no diagnostic client to capture them already.
329class CaptureDroppedDiagnostics {
330 Diagnostic &Diags;
331 StoredDiagnosticClient Client;
332 DiagnosticClient *PreviousClient;
333
334public:
335 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
336 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
337 : Diags(Diags), Client(StoredDiags), PreviousClient(Diags.getClient())
338 {
339 if (RequestCapture || Diags.getClient() == 0)
340 Diags.setClient(&Client);
341 }
342
343 ~CaptureDroppedDiagnostics() {
344 Diags.setClient(PreviousClient);
345 }
346};
347
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000348} // anonymous namespace
349
Douglas Gregora88084b2010-02-18 18:08:43 +0000350void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
351 const DiagnosticInfo &Info) {
352 StoredDiags.push_back(StoredDiagnostic(Level, Info));
353}
354
Steve Naroff77accc12009-09-03 18:19:54 +0000355const std::string &ASTUnit::getOriginalSourceFileName() {
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000356 return OriginalSourceFile;
Steve Naroff77accc12009-09-03 18:19:54 +0000357}
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000358
Steve Naroffe19944c2009-10-15 22:23:48 +0000359const std::string &ASTUnit::getPCHFileName() {
Daniel Dunbarc7822db2009-12-02 21:47:43 +0000360 assert(isMainFileAST() && "Not an ASTUnit from a PCH file!");
Benjamin Kramer7297c182010-01-30 16:23:25 +0000361 return static_cast<PCHReader *>(Ctx->getExternalSource())->getFileName();
Steve Naroffe19944c2009-10-15 22:23:48 +0000362}
363
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000364ASTUnit *ASTUnit::LoadFromPCHFile(const std::string &Filename,
Douglas Gregor28019772010-04-05 23:52:57 +0000365 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Ted Kremenek5cf48762009-10-17 00:34:24 +0000366 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +0000367 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +0000368 unsigned NumRemappedFiles,
369 bool CaptureDiagnostics) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000370 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
371
Douglas Gregor28019772010-04-05 23:52:57 +0000372 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000373 // No diagnostics engine was provided, so create our own diagnostics object
374 // with the default options.
375 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +0000376 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000377 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000378
379 AST->CaptureDiagnostics = CaptureDiagnostics;
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000380 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregor28019772010-04-05 23:52:57 +0000381 AST->Diagnostics = Diags;
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000382 AST->FileMgr.reset(new FileManager);
383 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics()));
Steve Naroff36c44642009-10-19 14:34:22 +0000384 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000385
Douglas Gregora88084b2010-02-18 18:08:43 +0000386 // If requested, capture diagnostics in the ASTUnit.
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000387 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, AST->getDiagnostics(),
Douglas Gregor405634b2010-04-05 18:10:21 +0000388 AST->StoredDiagnostics);
Douglas Gregora88084b2010-02-18 18:08:43 +0000389
Douglas Gregor4db64a42010-01-23 00:14:00 +0000390 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
391 // Create the file entry for the file that we're mapping from.
392 const FileEntry *FromFile
393 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
394 RemappedFiles[I].second->getBufferSize(),
395 0);
396 if (!FromFile) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000397 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
Douglas Gregor4db64a42010-01-23 00:14:00 +0000398 << RemappedFiles[I].first;
Douglas Gregorc8dfe5e2010-02-27 01:32:48 +0000399 delete RemappedFiles[I].second;
Douglas Gregor4db64a42010-01-23 00:14:00 +0000400 continue;
401 }
402
403 // Override the contents of the "from" file with the contents of
404 // the "to" file.
405 AST->getSourceManager().overrideFileContents(FromFile,
406 RemappedFiles[I].second);
407 }
408
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000409 // Gather Info for preprocessor construction later on.
Mike Stump1eb44332009-09-09 15:08:12 +0000410
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000411 LangOptions LangInfo;
412 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
413 std::string TargetTriple;
414 std::string Predefines;
415 unsigned Counter;
416
Daniel Dunbarbce6f622009-09-03 05:59:50 +0000417 llvm::OwningPtr<PCHReader> Reader;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000418
Ted Kremenekfc062212009-10-19 21:44:57 +0000419 Reader.reset(new PCHReader(AST->getSourceManager(), AST->getFileManager(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000420 AST->getDiagnostics()));
Daniel Dunbarcc318932009-09-03 05:59:35 +0000421 Reader->setListener(new PCHInfoCollector(LangInfo, HeaderInfo, TargetTriple,
422 Predefines, Counter));
423
424 switch (Reader->ReadPCH(Filename)) {
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000425 case PCHReader::Success:
426 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000427
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000428 case PCHReader::Failure:
Argyrios Kyrtzidis106c9982009-06-25 18:22:30 +0000429 case PCHReader::IgnorePCH:
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000430 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000431 return NULL;
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000432 }
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Daniel Dunbar68d40e22009-12-02 08:44:16 +0000434 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
435
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000436 // PCH loaded successfully. Now create the preprocessor.
Mike Stump1eb44332009-09-09 15:08:12 +0000437
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000438 // Get information about the target being compiled for.
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000439 //
440 // FIXME: This is broken, we should store the TargetOptions in the PCH.
441 TargetOptions TargetOpts;
442 TargetOpts.ABI = "";
Charles Davis98b7c5c2010-06-11 01:06:47 +0000443 TargetOpts.CXXABI = "itanium";
Daniel Dunbard58c03f2009-11-15 06:48:46 +0000444 TargetOpts.CPU = "";
445 TargetOpts.Features.clear();
446 TargetOpts.Triple = TargetTriple;
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000447 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
448 TargetOpts));
449 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
450 *AST->Target.get(),
Daniel Dunbar31b87d82009-09-21 03:03:39 +0000451 AST->getSourceManager(), HeaderInfo));
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000452 Preprocessor &PP = *AST->PP.get();
453
Daniel Dunbard5b61262009-09-21 03:03:47 +0000454 PP.setPredefines(Reader->getSuggestedPredefines());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000455 PP.setCounterValue(Counter);
Daniel Dunbarcc318932009-09-03 05:59:35 +0000456 Reader->setPreprocessor(PP);
Mike Stump1eb44332009-09-09 15:08:12 +0000457
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000458 // Create and initialize the ASTContext.
459
460 AST->Ctx.reset(new ASTContext(LangInfo,
Daniel Dunbar31b87d82009-09-21 03:03:39 +0000461 AST->getSourceManager(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000462 *AST->Target.get(),
463 PP.getIdentifierTable(),
464 PP.getSelectorTable(),
465 PP.getBuiltinInfo(),
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000466 /* size_reserve = */0));
467 ASTContext &Context = *AST->Ctx.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000468
Daniel Dunbarcc318932009-09-03 05:59:35 +0000469 Reader->InitializeContext(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000470
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000471 // Attach the PCH reader to the AST context as an external AST
472 // source, so that declarations will be deserialized from the
473 // PCH file as needed.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000474 PCHReader *ReaderPtr = Reader.get();
475 llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000476 Context.setExternalSource(Source);
477
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000478 // Create an AST consumer, even though it isn't used.
479 AST->Consumer.reset(new ASTConsumer);
480
481 // Create a semantic analysis object and tell the PCH reader about it.
482 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
483 AST->TheSema->Initialize();
484 ReaderPtr->InitializeSema(*AST->TheSema);
485
Mike Stump1eb44332009-09-09 15:08:12 +0000486 return AST.take();
Argyrios Kyrtzidis0853a022009-06-20 08:08:23 +0000487}
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000488
489namespace {
490
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000491class TopLevelDeclTrackerConsumer : public ASTConsumer {
492 ASTUnit &Unit;
493
494public:
495 TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {}
496
497 void HandleTopLevelDecl(DeclGroupRef D) {
Ted Kremenekda5a4282010-05-03 20:16:35 +0000498 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
499 Decl *D = *it;
500 // FIXME: Currently ObjC method declarations are incorrectly being
501 // reported as top-level declarations, even though their DeclContext
502 // is the containing ObjC @interface/@implementation. This is a
503 // fundamental problem in the parser right now.
504 if (isa<ObjCMethodDecl>(D))
505 continue;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000506 Unit.addTopLevelDecl(D);
Ted Kremenekda5a4282010-05-03 20:16:35 +0000507 }
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000508 }
Sebastian Redl27372b42010-08-11 18:52:41 +0000509
510 // We're not interested in "interesting" decls.
511 void HandleInterestingDecl(DeclGroupRef) {}
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000512};
513
514class TopLevelDeclTrackerAction : public ASTFrontendAction {
515public:
516 ASTUnit &Unit;
517
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000518 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
519 llvm::StringRef InFile) {
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000520 return new TopLevelDeclTrackerConsumer(Unit);
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000521 }
522
523public:
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000524 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
525
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000526 virtual bool hasCodeCompletionSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000527 virtual bool usesCompleteTranslationUnit() {
528 return Unit.isCompleteTranslationUnit();
529 }
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000530};
531
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000532class PrecompilePreambleConsumer : public PCHGenerator {
533 ASTUnit &Unit;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000534 std::vector<Decl *> TopLevelDecls;
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000535
536public:
537 PrecompilePreambleConsumer(ASTUnit &Unit,
538 const Preprocessor &PP, bool Chaining,
539 const char *isysroot, llvm::raw_ostream *Out)
540 : PCHGenerator(PP, Chaining, isysroot, Out), Unit(Unit) { }
541
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000542 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000543 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
544 Decl *D = *it;
545 // FIXME: Currently ObjC method declarations are incorrectly being
546 // reported as top-level declarations, even though their DeclContext
547 // is the containing ObjC @interface/@implementation. This is a
548 // fundamental problem in the parser right now.
549 if (isa<ObjCMethodDecl>(D))
550 continue;
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000551 TopLevelDecls.push_back(D);
552 }
553 }
554
555 virtual void HandleTranslationUnit(ASTContext &Ctx) {
556 PCHGenerator::HandleTranslationUnit(Ctx);
557 if (!Unit.getDiagnostics().hasErrorOccurred()) {
558 // Translate the top-level declarations we captured during
559 // parsing into declaration IDs in the precompiled
560 // preamble. This will allow us to deserialize those top-level
561 // declarations when requested.
562 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
563 Unit.addTopLevelDeclFromPreamble(
564 getWriter().getDeclID(TopLevelDecls[I]));
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000565 }
566 }
567};
568
569class PrecompilePreambleAction : public ASTFrontendAction {
570 ASTUnit &Unit;
571
572public:
573 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
574
575 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
576 llvm::StringRef InFile) {
577 std::string Sysroot;
578 llvm::raw_ostream *OS = 0;
579 bool Chaining;
580 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
581 OS, Chaining))
582 return 0;
583
584 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
585 Sysroot.c_str() : 0;
586 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
587 isysroot, OS);
588 }
589
590 virtual bool hasCodeCompletionSupport() const { return false; }
591 virtual bool hasASTFileSupport() const { return false; }
Douglas Gregordf95a132010-08-09 20:45:32 +0000592 virtual bool usesCompleteTranslationUnit() { return false; }
Douglas Gregor1d715ac2010-08-03 08:14:03 +0000593};
594
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000595}
596
Douglas Gregorabc563f2010-07-19 21:46:24 +0000597/// Parse the source file into a translation unit using the given compiler
598/// invocation, replacing the current translation unit.
599///
600/// \returns True if a failure occurred that causes the ASTUnit not to
601/// contain any translation-unit information, false otherwise.
Douglas Gregor754f3492010-07-24 00:38:13 +0000602bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
Douglas Gregor28233422010-07-27 14:52:07 +0000603 delete SavedMainFileBuffer;
604 SavedMainFileBuffer = 0;
605
Douglas Gregorabc563f2010-07-19 21:46:24 +0000606 if (!Invocation.get())
607 return true;
608
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000609 // Create the compiler instance to use for building the AST.
Daniel Dunbarcb6dda12009-12-02 08:43:56 +0000610 CompilerInstance Clang;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000611 Clang.setInvocation(Invocation.take());
612 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
613
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000614 // Set up diagnostics, capturing any diagnostics that would
615 // otherwise be dropped.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000616 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000617 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
618 getDiagnostics(),
619 StoredDiagnostics);
Douglas Gregorabc563f2010-07-19 21:46:24 +0000620 Clang.setDiagnosticClient(getDiagnostics().getClient());
Douglas Gregor3687e9d2010-04-05 21:10:19 +0000621
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000622 // Create the target instance.
623 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
624 Clang.getTargetOpts()));
Douglas Gregora88084b2010-02-18 18:08:43 +0000625 if (!Clang.hasTarget()) {
Douglas Gregora88084b2010-02-18 18:08:43 +0000626 Clang.takeDiagnosticClient();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000627 return true;
Douglas Gregora88084b2010-02-18 18:08:43 +0000628 }
Douglas Gregorabc563f2010-07-19 21:46:24 +0000629
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000630 // Inform the target of the language options.
631 //
632 // FIXME: We shouldn't need to do this, the target should be immutable once
633 // created. This complexity should be lifted elsewhere.
634 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000635
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000636 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
637 "Invocation must have exactly one source file!");
Daniel Dunbarc34ce3f2010-06-07 23:22:09 +0000638 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000639 "FIXME: AST inputs not yet supported here!");
Daniel Dunbarfaddc3e2010-06-07 23:26:47 +0000640 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
641 "IR inputs not support here!");
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000642
Douglas Gregorabc563f2010-07-19 21:46:24 +0000643 // Configure the various subsystems.
644 // FIXME: Should we retain the previous file manager?
645 FileMgr.reset(new FileManager);
646 SourceMgr.reset(new SourceManager(getDiagnostics()));
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000647 TheSema.reset();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000648 Ctx.reset();
649 PP.reset();
650
651 // Clear out old caches and data.
652 TopLevelDecls.clear();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000653 CleanTemporaryFiles();
654 PreprocessedEntitiesByFile.clear();
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000655
656 if (!OverrideMainBuffer)
657 StoredDiagnostics.clear();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000658
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000659 // Create a file manager object to provide access to and cache the filesystem.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000660 Clang.setFileManager(&getFileManager());
661
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000662 // Create the source manager.
Douglas Gregorabc563f2010-07-19 21:46:24 +0000663 Clang.setSourceManager(&getSourceManager());
664
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000665 // If the main file has been overridden due to the use of a preamble,
666 // make that override happen and introduce the preamble.
667 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000668 std::string PriorImplicitPCHInclude;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000669 if (OverrideMainBuffer) {
670 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
671 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
672 PreprocessorOpts.PrecompiledPreambleBytes.second
673 = PreambleEndsAtStartOfLine;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000674 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
Douglas Gregor385103b2010-07-30 20:58:08 +0000675 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000676 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor28233422010-07-27 14:52:07 +0000677
678 // Keep track of the override buffer;
679 SavedMainFileBuffer = OverrideMainBuffer;
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000680
681 // The stored diagnostic has the old source manager in it; update
682 // the locations to refer into the new source manager. Since we've
683 // been careful to make sure that the source manager's state
684 // before and after are identical, so that we can reuse the source
685 // location itself.
686 for (unsigned I = 0, N = StoredDiagnostics.size(); I != N; ++I) {
687 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
688 getSourceManager());
689 StoredDiagnostics[I].setLocation(Loc);
690 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000691 }
692
Douglas Gregorabc563f2010-07-19 21:46:24 +0000693 llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
694 Act.reset(new TopLevelDeclTrackerAction(*this));
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000695 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
Daniel Dunbard3598a62010-06-07 23:23:06 +0000696 Clang.getFrontendOpts().Inputs[0].first))
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000697 goto error;
Douglas Gregorabc563f2010-07-19 21:46:24 +0000698
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000699 Act->Execute();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000700
Daniel Dunbar64a32ba2009-12-01 21:57:33 +0000701 // Steal the created target, context, and preprocessor, and take back the
702 // source and file managers.
Douglas Gregor914ed9d2010-08-13 03:15:25 +0000703 TheSema.reset(Clang.takeSema());
704 Consumer.reset(Clang.takeASTConsumer());
Douglas Gregorabc563f2010-07-19 21:46:24 +0000705 Ctx.reset(Clang.takeASTContext());
706 PP.reset(Clang.takePreprocessor());
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000707 Clang.takeSourceManager();
708 Clang.takeFileManager();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000709 Target.reset(Clang.takeTarget());
710
Daniel Dunbarf772d1e2009-12-04 08:17:33 +0000711 Act->EndSourceFile();
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000712
713 // Remove the overridden buffer we used for the preamble.
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000714 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000715 PreprocessorOpts.eraseRemappedFile(
716 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000717 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
718 }
719
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000720 Clang.takeDiagnosticClient();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000721
722 Invocation.reset(Clang.takeInvocation());
Douglas Gregor87c08a52010-08-13 22:48:40 +0000723
724 // If we were asked to cache code-completion results and don't have any
725 // results yet, do so now.
726 if (ShouldCacheCodeCompletionResults && CachedCompletionResults.empty())
727 CacheCodeCompletionResults();
728
Douglas Gregorabc563f2010-07-19 21:46:24 +0000729 return false;
730
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000731error:
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000732 // Remove the overridden buffer we used for the preamble.
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000733 if (OverrideMainBuffer) {
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000734 PreprocessorOpts.eraseRemappedFile(
735 PreprocessorOpts.remapped_file_buffer_end() - 1);
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000736 PreprocessorOpts.DisablePCHValidation = true;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +0000737 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
Douglas Gregorfae3b2f2010-07-27 00:27:13 +0000738 }
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000739
Daniel Dunbar521bf9c2009-12-01 09:51:01 +0000740 Clang.takeSourceManager();
741 Clang.takeFileManager();
742 Clang.takeDiagnosticClient();
Douglas Gregorabc563f2010-07-19 21:46:24 +0000743 Invocation.reset(Clang.takeInvocation());
744 return true;
745}
746
Douglas Gregor44c181a2010-07-23 00:33:23 +0000747/// \brief Simple function to retrieve a path for a preamble precompiled header.
748static std::string GetPreamblePCHPath() {
749 // FIXME: This is lame; sys::Path should provide this function (in particular,
750 // it should know how to find the temporary files dir).
751 // FIXME: This is really lame. I copied this code from the Driver!
752 std::string Error;
753 const char *TmpDir = ::getenv("TMPDIR");
754 if (!TmpDir)
755 TmpDir = ::getenv("TEMP");
756 if (!TmpDir)
757 TmpDir = ::getenv("TMP");
758 if (!TmpDir)
759 TmpDir = "/tmp";
760 llvm::sys::Path P(TmpDir);
761 P.appendComponent("preamble");
Douglas Gregor6bf18302010-08-11 13:06:56 +0000762 P.appendSuffix("pch");
Douglas Gregor44c181a2010-07-23 00:33:23 +0000763 if (P.createTemporaryFileOnDisk())
764 return std::string();
765
Douglas Gregor44c181a2010-07-23 00:33:23 +0000766 return P.str();
767}
768
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000769/// \brief Compute the preamble for the main file, providing the source buffer
770/// that corresponds to the main file along with a pair (bytes, start-of-line)
771/// that describes the preamble.
772std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
Douglas Gregordf95a132010-08-09 20:45:32 +0000773ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
774 unsigned MaxLines, bool &CreatedBuffer) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000775 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000776 PreprocessorOptions &PreprocessorOpts
Douglas Gregor175c4a92010-07-23 23:58:40 +0000777 = Invocation.getPreprocessorOpts();
778 CreatedBuffer = false;
779
Douglas Gregor44c181a2010-07-23 00:33:23 +0000780 // Try to determine if the main file has been remapped, either from the
781 // command line (to another file) or directly through the compiler invocation
782 // (to a memory buffer).
Douglas Gregor175c4a92010-07-23 23:58:40 +0000783 llvm::MemoryBuffer *Buffer = 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000784 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
785 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
786 // Check whether there is a file-file remapping of the main file
787 for (PreprocessorOptions::remapped_file_iterator
Douglas Gregor175c4a92010-07-23 23:58:40 +0000788 M = PreprocessorOpts.remapped_file_begin(),
789 E = PreprocessorOpts.remapped_file_end();
Douglas Gregor44c181a2010-07-23 00:33:23 +0000790 M != E;
791 ++M) {
792 llvm::sys::PathWithStatus MPath(M->first);
793 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
794 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
795 // We found a remapping. Try to load the resulting, remapped source.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000796 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000797 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000798 CreatedBuffer = false;
799 }
800
Douglas Gregor44c181a2010-07-23 00:33:23 +0000801 Buffer = llvm::MemoryBuffer::getFile(M->second);
802 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000803 return std::make_pair((llvm::MemoryBuffer*)0,
804 std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000805 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000806
Douglas Gregor175c4a92010-07-23 23:58:40 +0000807 // Remove this remapping. We've captured the buffer already.
Douglas Gregor44c181a2010-07-23 00:33:23 +0000808 M = PreprocessorOpts.eraseRemappedFile(M);
809 E = PreprocessorOpts.remapped_file_end();
810 }
811 }
812 }
813
814 // Check whether there is a file-buffer remapping. It supercedes the
815 // file-file remapping.
816 for (PreprocessorOptions::remapped_file_buffer_iterator
817 M = PreprocessorOpts.remapped_file_buffer_begin(),
818 E = PreprocessorOpts.remapped_file_buffer_end();
819 M != E;
820 ++M) {
821 llvm::sys::PathWithStatus MPath(M->first);
822 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
823 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
824 // We found a remapping.
Douglas Gregor175c4a92010-07-23 23:58:40 +0000825 if (CreatedBuffer) {
Douglas Gregor44c181a2010-07-23 00:33:23 +0000826 delete Buffer;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000827 CreatedBuffer = false;
828 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000829
Douglas Gregor175c4a92010-07-23 23:58:40 +0000830 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
831
832 // Remove this remapping. We've captured the buffer already.
Douglas Gregor44c181a2010-07-23 00:33:23 +0000833 M = PreprocessorOpts.eraseRemappedFile(M);
834 E = PreprocessorOpts.remapped_file_buffer_end();
835 }
836 }
Douglas Gregor175c4a92010-07-23 23:58:40 +0000837 }
Douglas Gregor44c181a2010-07-23 00:33:23 +0000838 }
839
840 // If the main source file was not remapped, load it now.
841 if (!Buffer) {
842 Buffer = llvm::MemoryBuffer::getFile(FrontendOpts.Inputs[0].second);
843 if (!Buffer)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000844 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000845
846 CreatedBuffer = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +0000847 }
848
Douglas Gregordf95a132010-08-09 20:45:32 +0000849 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
Douglas Gregor175c4a92010-07-23 23:58:40 +0000850}
851
Douglas Gregor754f3492010-07-24 00:38:13 +0000852static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
853 bool DeleteOld,
854 unsigned NewSize,
855 llvm::StringRef NewName) {
856 llvm::MemoryBuffer *Result
857 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
858 memcpy(const_cast<char*>(Result->getBufferStart()),
859 Old->getBufferStart(), Old->getBufferSize());
860 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000861 ' ', NewSize - Old->getBufferSize() - 1);
862 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
Douglas Gregor754f3492010-07-24 00:38:13 +0000863
864 if (DeleteOld)
865 delete Old;
866
867 return Result;
868}
869
Douglas Gregor175c4a92010-07-23 23:58:40 +0000870/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
871/// the source file.
872///
873/// This routine will compute the preamble of the main source file. If a
874/// non-trivial preamble is found, it will precompile that preamble into a
875/// precompiled header so that the precompiled preamble can be used to reduce
876/// reparsing time. If a precompiled preamble has already been constructed,
877/// this routine will determine if it is still valid and, if so, avoid
878/// rebuilding the precompiled preamble.
879///
Douglas Gregordf95a132010-08-09 20:45:32 +0000880/// \param AllowRebuild When true (the default), this routine is
881/// allowed to rebuild the precompiled preamble if it is found to be
882/// out-of-date.
883///
884/// \param MaxLines When non-zero, the maximum number of lines that
885/// can occur within the preamble.
886///
Douglas Gregor754f3492010-07-24 00:38:13 +0000887/// \returns If the precompiled preamble can be used, returns a newly-allocated
888/// buffer that should be used in place of the main file when doing so.
889/// Otherwise, returns a NULL pointer.
Douglas Gregordf95a132010-08-09 20:45:32 +0000890llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
891 bool AllowRebuild,
892 unsigned MaxLines) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000893 CompilerInvocation PreambleInvocation(*Invocation);
894 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
895 PreprocessorOptions &PreprocessorOpts
896 = PreambleInvocation.getPreprocessorOpts();
897
898 bool CreatedPreambleBuffer = false;
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000899 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
Douglas Gregordf95a132010-08-09 20:45:32 +0000900 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
Douglas Gregor175c4a92010-07-23 23:58:40 +0000901
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000902 if (!NewPreamble.second.first) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000903 // We couldn't find a preamble in the main source. Clear out the current
904 // preamble, if we have one. It's obviously no good any more.
905 Preamble.clear();
906 if (!PreambleFile.empty()) {
Douglas Gregor385103b2010-07-30 20:58:08 +0000907 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregor175c4a92010-07-23 23:58:40 +0000908 PreambleFile.clear();
909 }
910 if (CreatedPreambleBuffer)
911 delete NewPreamble.first;
Douglas Gregoreababfb2010-08-04 05:53:38 +0000912
913 // The next time we actually see a preamble, precompile it.
914 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +0000915 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +0000916 }
917
918 if (!Preamble.empty()) {
919 // We've previously computed a preamble. Check whether we have the same
920 // preamble now that we did before, and that there's enough space in
921 // the main-file buffer within the precompiled preamble to fit the
922 // new main file.
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000923 if (Preamble.size() == NewPreamble.second.first &&
924 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
Douglas Gregor592508e2010-07-24 00:42:07 +0000925 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
Douglas Gregor175c4a92010-07-23 23:58:40 +0000926 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000927 NewPreamble.second.first) == 0) {
Douglas Gregor175c4a92010-07-23 23:58:40 +0000928 // The preamble has not changed. We may be able to re-use the precompiled
929 // preamble.
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000930
Douglas Gregorcc5888d2010-07-31 00:40:00 +0000931 // Check that none of the files used by the preamble have changed.
932 bool AnyFileChanged = false;
933
934 // First, make a record of those files that have been overridden via
935 // remapping or unsaved_files.
936 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
937 for (PreprocessorOptions::remapped_file_iterator
938 R = PreprocessorOpts.remapped_file_begin(),
939 REnd = PreprocessorOpts.remapped_file_end();
940 !AnyFileChanged && R != REnd;
941 ++R) {
942 struct stat StatBuf;
943 if (stat(R->second.c_str(), &StatBuf)) {
944 // If we can't stat the file we're remapping to, assume that something
945 // horrible happened.
946 AnyFileChanged = true;
947 break;
948 }
Douglas Gregor754f3492010-07-24 00:38:13 +0000949
Douglas Gregorcc5888d2010-07-31 00:40:00 +0000950 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
951 StatBuf.st_mtime);
952 }
953 for (PreprocessorOptions::remapped_file_buffer_iterator
954 R = PreprocessorOpts.remapped_file_buffer_begin(),
955 REnd = PreprocessorOpts.remapped_file_buffer_end();
956 !AnyFileChanged && R != REnd;
957 ++R) {
958 // FIXME: Should we actually compare the contents of file->buffer
959 // remappings?
960 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
961 0);
962 }
963
964 // Check whether anything has changed.
965 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
966 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
967 !AnyFileChanged && F != FEnd;
968 ++F) {
969 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
970 = OverriddenFiles.find(F->first());
971 if (Overridden != OverriddenFiles.end()) {
972 // This file was remapped; check whether the newly-mapped file
973 // matches up with the previous mapping.
974 if (Overridden->second != F->second)
975 AnyFileChanged = true;
976 continue;
977 }
978
979 // The file was not remapped; check whether it has changed on disk.
980 struct stat StatBuf;
981 if (stat(F->first(), &StatBuf)) {
982 // If we can't stat the file, assume that something horrible happened.
983 AnyFileChanged = true;
984 } else if (StatBuf.st_size != F->second.first ||
985 StatBuf.st_mtime != F->second.second)
986 AnyFileChanged = true;
987 }
988
989 if (!AnyFileChanged) {
Douglas Gregorc0659ec2010-08-02 20:51:39 +0000990 // Okay! We can re-use the precompiled preamble.
991
992 // Set the state of the diagnostic object to mimic its state
993 // after parsing the preamble.
994 getDiagnostics().Reset();
995 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
996 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
997 StoredDiagnostics.erase(
998 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
999 StoredDiagnostics.end());
1000
1001 // Create a version of the main file buffer that is padded to
1002 // buffer size we reserved when creating the preamble.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001003 return CreatePaddedMainFileBuffer(NewPreamble.first,
1004 CreatedPreambleBuffer,
1005 PreambleReservedSize,
1006 FrontendOpts.Inputs[0].second);
1007 }
Douglas Gregor175c4a92010-07-23 23:58:40 +00001008 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001009
1010 // If we aren't allowed to rebuild the precompiled preamble, just
1011 // return now.
1012 if (!AllowRebuild)
1013 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001014
1015 // We can't reuse the previously-computed preamble. Build a new one.
1016 Preamble.clear();
Douglas Gregor385103b2010-07-30 20:58:08 +00001017 llvm::sys::Path(PreambleFile).eraseFromDisk();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001018 PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001019 } else if (!AllowRebuild) {
1020 // We aren't allowed to rebuild the precompiled preamble; just
1021 // return now.
1022 return 0;
1023 }
Douglas Gregoreababfb2010-08-04 05:53:38 +00001024
1025 // If the preamble rebuild counter > 1, it's because we previously
1026 // failed to build a preamble and we're not yet ready to try
1027 // again. Decrement the counter and return a failure.
1028 if (PreambleRebuildCounter > 1) {
1029 --PreambleRebuildCounter;
1030 return 0;
1031 }
1032
Douglas Gregor175c4a92010-07-23 23:58:40 +00001033 // We did not previously compute a preamble, or it can't be reused anyway.
Douglas Gregor385103b2010-07-30 20:58:08 +00001034 llvm::Timer *PreambleTimer = 0;
1035 if (TimerGroup.get()) {
1036 PreambleTimer = new llvm::Timer("Precompiling preamble", *TimerGroup);
1037 PreambleTimer->startTimer();
1038 Timers.push_back(PreambleTimer);
1039 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001040
1041 // Create a new buffer that stores the preamble. The buffer also contains
1042 // extra space for the original contents of the file (which will be present
1043 // when we actually parse the file) along with more room in case the file
Douglas Gregor175c4a92010-07-23 23:58:40 +00001044 // grows.
1045 PreambleReservedSize = NewPreamble.first->getBufferSize();
1046 if (PreambleReservedSize < 4096)
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001047 PreambleReservedSize = 8191;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001048 else
Douglas Gregor175c4a92010-07-23 23:58:40 +00001049 PreambleReservedSize *= 2;
1050
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001051 // Save the preamble text for later; we'll need to compare against it for
1052 // subsequent reparses.
1053 Preamble.assign(NewPreamble.first->getBufferStart(),
1054 NewPreamble.first->getBufferStart()
1055 + NewPreamble.second.first);
1056 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1057
Douglas Gregor44c181a2010-07-23 00:33:23 +00001058 llvm::MemoryBuffer *PreambleBuffer
Douglas Gregor175c4a92010-07-23 23:58:40 +00001059 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001060 FrontendOpts.Inputs[0].second);
1061 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
Douglas Gregor175c4a92010-07-23 23:58:40 +00001062 NewPreamble.first->getBufferStart(), Preamble.size());
1063 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001064 ' ', PreambleReservedSize - Preamble.size() - 1);
1065 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
Douglas Gregor44c181a2010-07-23 00:33:23 +00001066
1067 // Remap the main source file to the preamble buffer.
Douglas Gregor175c4a92010-07-23 23:58:40 +00001068 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001069 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1070
1071 // Tell the compiler invocation to generate a temporary precompiled header.
1072 FrontendOpts.ProgramAction = frontend::GeneratePCH;
Sebastian Redlf65339e2010-08-06 00:35:11 +00001073 // FIXME: Set ChainedPCH unconditionally, once it is ready.
1074 if (::getenv("LIBCLANG_CHAINING"))
1075 FrontendOpts.ChainedPCH = true;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001076 // FIXME: Generate the precompiled header into memory?
Douglas Gregor385103b2010-07-30 20:58:08 +00001077 FrontendOpts.OutputFile = GetPreamblePCHPath();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001078
1079 // Create the compiler instance to use for building the precompiled preamble.
1080 CompilerInstance Clang;
1081 Clang.setInvocation(&PreambleInvocation);
1082 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1083
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001084 // Set up diagnostics, capturing all of the diagnostics produced.
Douglas Gregor44c181a2010-07-23 00:33:23 +00001085 Clang.setDiagnostics(&getDiagnostics());
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001086 CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
1087 getDiagnostics(),
1088 StoredDiagnostics);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001089 Clang.setDiagnosticClient(getDiagnostics().getClient());
1090
1091 // Create the target instance.
1092 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1093 Clang.getTargetOpts()));
1094 if (!Clang.hasTarget()) {
1095 Clang.takeDiagnosticClient();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001096 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1097 Preamble.clear();
1098 if (CreatedPreambleBuffer)
1099 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +00001100 if (PreambleTimer)
1101 PreambleTimer->stopTimer();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001102 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor754f3492010-07-24 00:38:13 +00001103 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001104 }
1105
1106 // Inform the target of the language options.
1107 //
1108 // FIXME: We shouldn't need to do this, the target should be immutable once
1109 // created. This complexity should be lifted elsewhere.
1110 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1111
1112 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1113 "Invocation must have exactly one source file!");
1114 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1115 "FIXME: AST inputs not yet supported here!");
1116 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1117 "IR inputs not support here!");
1118
1119 // Clear out old caches and data.
1120 StoredDiagnostics.clear();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001121 TopLevelDecls.clear();
1122 TopLevelDeclsInPreamble.clear();
Douglas Gregor44c181a2010-07-23 00:33:23 +00001123
1124 // Create a file manager object to provide access to and cache the filesystem.
1125 Clang.setFileManager(new FileManager);
1126
1127 // Create the source manager.
1128 Clang.setSourceManager(new SourceManager(getDiagnostics()));
1129
Douglas Gregor1d715ac2010-08-03 08:14:03 +00001130 llvm::OwningPtr<PrecompilePreambleAction> Act;
1131 Act.reset(new PrecompilePreambleAction(*this));
Douglas Gregor44c181a2010-07-23 00:33:23 +00001132 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1133 Clang.getFrontendOpts().Inputs[0].first)) {
1134 Clang.takeDiagnosticClient();
1135 Clang.takeInvocation();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001136 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1137 Preamble.clear();
1138 if (CreatedPreambleBuffer)
1139 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +00001140 if (PreambleTimer)
1141 PreambleTimer->stopTimer();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001142 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor385103b2010-07-30 20:58:08 +00001143
Douglas Gregor754f3492010-07-24 00:38:13 +00001144 return 0;
Douglas Gregor44c181a2010-07-23 00:33:23 +00001145 }
1146
1147 Act->Execute();
1148 Act->EndSourceFile();
1149 Clang.takeDiagnosticClient();
1150 Clang.takeInvocation();
1151
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001152 if (Diagnostics->hasErrorOccurred()) {
Douglas Gregor175c4a92010-07-23 23:58:40 +00001153 // There were errors parsing the preamble, so no precompiled header was
1154 // generated. Forget that we even tried.
1155 // FIXME: Should we leave a note for ourselves to try again?
1156 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1157 Preamble.clear();
1158 if (CreatedPreambleBuffer)
1159 delete NewPreamble.first;
Douglas Gregor385103b2010-07-30 20:58:08 +00001160 if (PreambleTimer)
1161 PreambleTimer->stopTimer();
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001162 TopLevelDeclsInPreamble.clear();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001163 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
Douglas Gregor754f3492010-07-24 00:38:13 +00001164 return 0;
Douglas Gregor175c4a92010-07-23 23:58:40 +00001165 }
1166
1167 // Keep track of the preamble we precompiled.
1168 PreambleFile = FrontendOpts.OutputFile;
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001169 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
1170 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001171
1172 // Keep track of all of the files that the source manager knows about,
1173 // so we can verify whether they have changed or not.
1174 FilesInPreamble.clear();
1175 SourceManager &SourceMgr = Clang.getSourceManager();
1176 const llvm::MemoryBuffer *MainFileBuffer
1177 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1178 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1179 FEnd = SourceMgr.fileinfo_end();
1180 F != FEnd;
1181 ++F) {
1182 const FileEntry *File = F->second->Entry;
1183 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1184 continue;
1185
1186 FilesInPreamble[File->getName()]
1187 = std::make_pair(F->second->getSize(), File->getModificationTime());
1188 }
1189
Douglas Gregor385103b2010-07-30 20:58:08 +00001190 if (PreambleTimer)
1191 PreambleTimer->stopTimer();
1192
Douglas Gregoreababfb2010-08-04 05:53:38 +00001193 PreambleRebuildCounter = 1;
Douglas Gregor754f3492010-07-24 00:38:13 +00001194 return CreatePaddedMainFileBuffer(NewPreamble.first,
1195 CreatedPreambleBuffer,
1196 PreambleReservedSize,
1197 FrontendOpts.Inputs[0].second);
Douglas Gregor44c181a2010-07-23 00:33:23 +00001198}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001199
Douglas Gregoreb8837b2010-08-03 19:06:41 +00001200void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1201 std::vector<Decl *> Resolved;
1202 Resolved.reserve(TopLevelDeclsInPreamble.size());
1203 ExternalASTSource &Source = *getASTContext().getExternalSource();
1204 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1205 // Resolve the declaration ID to an actual declaration, possibly
1206 // deserializing the declaration in the process.
1207 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1208 if (D)
1209 Resolved.push_back(D);
1210 }
1211 TopLevelDeclsInPreamble.clear();
1212 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1213}
1214
1215unsigned ASTUnit::getMaxPCHLevel() const {
1216 if (!getOnlyLocalDecls())
1217 return Decl::MaxPCHLevel;
1218
1219 unsigned Result = 0;
1220 if (isMainFileAST() || SavedMainFileBuffer)
1221 ++Result;
1222 return Result;
1223}
1224
Douglas Gregorabc563f2010-07-19 21:46:24 +00001225ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1226 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1227 bool OnlyLocalDecls,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001228 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001229 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001230 bool CompleteTranslationUnit,
1231 bool CacheCodeCompletionResults) {
Douglas Gregorabc563f2010-07-19 21:46:24 +00001232 if (!Diags.getPtr()) {
1233 // No diagnostics engine was provided, so create our own diagnostics object
1234 // with the default options.
1235 DiagnosticOptions DiagOpts;
1236 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
1237 }
1238
1239 // Create the AST unit.
1240 llvm::OwningPtr<ASTUnit> AST;
1241 AST.reset(new ASTUnit(false));
1242 AST->Diagnostics = Diags;
1243 AST->CaptureDiagnostics = CaptureDiagnostics;
1244 AST->OnlyLocalDecls = OnlyLocalDecls;
Douglas Gregordf95a132010-08-09 20:45:32 +00001245 AST->CompleteTranslationUnit = CompleteTranslationUnit;
Douglas Gregor87c08a52010-08-13 22:48:40 +00001246 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001247 AST->Invocation.reset(CI);
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +00001248 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001249
Douglas Gregor385103b2010-07-30 20:58:08 +00001250 if (getenv("LIBCLANG_TIMING"))
1251 AST->TimerGroup.reset(
1252 new llvm::TimerGroup(CI->getFrontendOpts().Inputs[0].second));
1253
1254
Douglas Gregor754f3492010-07-24 00:38:13 +00001255 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregorfd0b8702010-07-28 22:12:37 +00001256 // FIXME: When C++ PCH is ready, allow use of it for a precompiled preamble.
Douglas Gregoreababfb2010-08-04 05:53:38 +00001257 if (PrecompilePreamble && !CI->getLangOpts().CPlusPlus) {
1258 AST->PreambleRebuildCounter = 1;
Douglas Gregordf95a132010-08-09 20:45:32 +00001259 OverrideMainBuffer = AST->getMainBufferWithPrecompiledPreamble();
Douglas Gregoreababfb2010-08-04 05:53:38 +00001260 }
Douglas Gregor44c181a2010-07-23 00:33:23 +00001261
Douglas Gregor385103b2010-07-30 20:58:08 +00001262 llvm::Timer *ParsingTimer = 0;
1263 if (AST->TimerGroup.get()) {
1264 ParsingTimer = new llvm::Timer("Initial parse", *AST->TimerGroup);
1265 ParsingTimer->startTimer();
1266 AST->Timers.push_back(ParsingTimer);
1267 }
Douglas Gregorabc563f2010-07-19 21:46:24 +00001268
Douglas Gregor385103b2010-07-30 20:58:08 +00001269 bool Failed = AST->Parse(OverrideMainBuffer);
1270 if (ParsingTimer)
1271 ParsingTimer->stopTimer();
1272
1273 return Failed? 0 : AST.take();
Daniel Dunbar521bf9c2009-12-01 09:51:01 +00001274}
Daniel Dunbar7b556682009-12-02 03:23:45 +00001275
1276ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1277 const char **ArgEnd,
Douglas Gregor28019772010-04-05 23:52:57 +00001278 llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
Daniel Dunbar869824e2009-12-13 03:46:13 +00001279 llvm::StringRef ResourceFilesPath,
Daniel Dunbar7b556682009-12-02 03:23:45 +00001280 bool OnlyLocalDecls,
Douglas Gregor4db64a42010-01-23 00:14:00 +00001281 RemappedFile *RemappedFiles,
Douglas Gregora88084b2010-02-18 18:08:43 +00001282 unsigned NumRemappedFiles,
Douglas Gregor44c181a2010-07-23 00:33:23 +00001283 bool CaptureDiagnostics,
Douglas Gregordf95a132010-08-09 20:45:32 +00001284 bool PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001285 bool CompleteTranslationUnit,
1286 bool CacheCodeCompletionResults) {
Douglas Gregor28019772010-04-05 23:52:57 +00001287 if (!Diags.getPtr()) {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001288 // No diagnostics engine was provided, so create our own diagnostics object
1289 // with the default options.
1290 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00001291 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001292 }
1293
Daniel Dunbar7b556682009-12-02 03:23:45 +00001294 llvm::SmallVector<const char *, 16> Args;
1295 Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1296 Args.insert(Args.end(), ArgBegin, ArgEnd);
1297
1298 // FIXME: Find a cleaner way to force the driver into restricted modes. We
1299 // also want to force it to use clang.
1300 Args.push_back("-fsyntax-only");
1301
Daniel Dunbar869824e2009-12-13 03:46:13 +00001302 // FIXME: We shouldn't have to pass in the path info.
Daniel Dunbar0bbad512010-07-19 00:44:04 +00001303 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001304 "a.out", false, false, *Diags);
Daniel Dunbar3bd54cc2010-01-25 00:44:02 +00001305
1306 // Don't check that inputs exist, they have been remapped.
1307 TheDriver.setCheckInputsExist(false);
1308
Daniel Dunbar7b556682009-12-02 03:23:45 +00001309 llvm::OwningPtr<driver::Compilation> C(
1310 TheDriver.BuildCompilation(Args.size(), Args.data()));
1311
1312 // We expect to get back exactly one command job, if we didn't something
1313 // failed.
1314 const driver::JobList &Jobs = C->getJobs();
1315 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1316 llvm::SmallString<256> Msg;
1317 llvm::raw_svector_ostream OS(Msg);
1318 C->PrintJob(OS, C->getJobs(), "; ", true);
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001319 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
Daniel Dunbar7b556682009-12-02 03:23:45 +00001320 return 0;
1321 }
1322
1323 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1324 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001325 Diags->Report(diag::err_fe_expected_clang_command);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001326 return 0;
1327 }
1328
1329 const driver::ArgStringList &CCArgs = Cmd->getArguments();
Daniel Dunbar807b0612010-01-30 21:47:16 +00001330 llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
Dan Gohmancb421fa2010-04-19 16:39:44 +00001331 CompilerInvocation::CreateFromArgs(*CI,
1332 const_cast<const char **>(CCArgs.data()),
1333 const_cast<const char **>(CCArgs.data()) +
Douglas Gregor44c181a2010-07-23 00:33:23 +00001334 CCArgs.size(),
Douglas Gregor3687e9d2010-04-05 21:10:19 +00001335 *Diags);
Daniel Dunbar1e69fe32009-12-13 03:45:58 +00001336
Douglas Gregor4db64a42010-01-23 00:14:00 +00001337 // Override any files that need remapping
1338 for (unsigned I = 0; I != NumRemappedFiles; ++I)
Daniel Dunbar807b0612010-01-30 21:47:16 +00001339 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
Daniel Dunbarb26d4832010-02-16 01:55:04 +00001340 RemappedFiles[I].second);
Douglas Gregor4db64a42010-01-23 00:14:00 +00001341
Daniel Dunbar8b9adfe2009-12-15 00:06:45 +00001342 // Override the resources path.
Daniel Dunbar807b0612010-01-30 21:47:16 +00001343 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
Daniel Dunbar7b556682009-12-02 03:23:45 +00001344
Daniel Dunbarb26d4832010-02-16 01:55:04 +00001345 CI->getFrontendOpts().DisableFree = true;
Douglas Gregora88084b2010-02-18 18:08:43 +00001346 return LoadFromCompilerInvocation(CI.take(), Diags, OnlyLocalDecls,
Douglas Gregordf95a132010-08-09 20:45:32 +00001347 CaptureDiagnostics, PrecompilePreamble,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001348 CompleteTranslationUnit,
1349 CacheCodeCompletionResults);
Daniel Dunbar7b556682009-12-02 03:23:45 +00001350}
Douglas Gregorabc563f2010-07-19 21:46:24 +00001351
1352bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1353 if (!Invocation.get())
1354 return true;
1355
Douglas Gregor385103b2010-07-30 20:58:08 +00001356 llvm::Timer *ReparsingTimer = 0;
1357 if (TimerGroup.get()) {
1358 ReparsingTimer = new llvm::Timer("Reparse", *TimerGroup);
1359 ReparsingTimer->startTimer();
1360 Timers.push_back(ReparsingTimer);
1361 }
1362
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001363 // Remap files.
Douglas Gregorcc5888d2010-07-31 00:40:00 +00001364 Invocation->getPreprocessorOpts().clearRemappedFiles();
1365 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1366 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1367 RemappedFiles[I].second);
1368
Douglas Gregoreababfb2010-08-04 05:53:38 +00001369 // If we have a preamble file lying around, or if we might try to
1370 // build a precompiled preamble, do so now.
Douglas Gregor754f3492010-07-24 00:38:13 +00001371 llvm::MemoryBuffer *OverrideMainBuffer = 0;
Douglas Gregoreababfb2010-08-04 05:53:38 +00001372 if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
Douglas Gregordf95a132010-08-09 20:45:32 +00001373 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001374
Douglas Gregorabc563f2010-07-19 21:46:24 +00001375 // Clear out the diagnostics state.
Douglas Gregorc0659ec2010-08-02 20:51:39 +00001376 if (!OverrideMainBuffer)
1377 getDiagnostics().Reset();
Douglas Gregorabc563f2010-07-19 21:46:24 +00001378
Douglas Gregor175c4a92010-07-23 23:58:40 +00001379 // Parse the sources
Douglas Gregor754f3492010-07-24 00:38:13 +00001380 bool Result = Parse(OverrideMainBuffer);
Douglas Gregor385103b2010-07-30 20:58:08 +00001381 if (ReparsingTimer)
1382 ReparsingTimer->stopTimer();
Douglas Gregor175c4a92010-07-23 23:58:40 +00001383 return Result;
Douglas Gregorabc563f2010-07-19 21:46:24 +00001384}
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001385
Douglas Gregor87c08a52010-08-13 22:48:40 +00001386//----------------------------------------------------------------------------//
1387// Code completion
1388//----------------------------------------------------------------------------//
1389
1390namespace {
1391 /// \brief Code completion consumer that combines the cached code-completion
1392 /// results from an ASTUnit with the code-completion results provided to it,
1393 /// then passes the result on to
1394 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1395 unsigned NormalContexts;
1396 ASTUnit &AST;
1397 CodeCompleteConsumer &Next;
1398
1399 public:
1400 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
Douglas Gregor8071e422010-08-15 06:18:01 +00001401 bool IncludeMacros, bool IncludeCodePatterns,
1402 bool IncludeGlobals)
1403 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
Douglas Gregor87c08a52010-08-13 22:48:40 +00001404 Next.isOutputBinary()), AST(AST), Next(Next)
1405 {
1406 // Compute the set of contexts in which we will look when we don't have
1407 // any information about the specific context.
1408 NormalContexts
1409 = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
1410 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
1411 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1412 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1413 | (1 << (CodeCompletionContext::CCC_Statement - 1))
1414 | (1 << (CodeCompletionContext::CCC_Expression - 1))
1415 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1416 | (1 << (CodeCompletionContext::CCC_MemberAccess - 1))
1417 | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
1418
1419 if (AST.getASTContext().getLangOptions().CPlusPlus)
1420 NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1))
1421 | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
1422 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
1423 }
1424
1425 virtual void ProcessCodeCompleteResults(Sema &S,
1426 CodeCompletionContext Context,
1427 Result *Results,
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001428 unsigned NumResults);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001429
1430 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1431 OverloadCandidate *Candidates,
1432 unsigned NumCandidates) {
1433 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
1434 }
1435 };
1436}
Douglas Gregor697ca6d2010-08-16 20:01:48 +00001437
1438void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
1439 CodeCompletionContext Context,
1440 Result *Results,
1441 unsigned NumResults) {
1442 // Merge the results we were given with the results we cached.
1443 bool AddedResult = false;
1444 unsigned InContexts =
1445 (Context.getKind() == CodeCompletionContext::CCC_Other? NormalContexts
1446 : (1 << (Context.getKind() - 1)));
1447 typedef CodeCompleteConsumer::Result Result;
1448 llvm::SmallVector<Result, 8> AllResults;
1449 for (ASTUnit::cached_completion_iterator
1450 C = AST.cached_completion_begin(),
1451 CEnd = AST.cached_completion_end();
1452 C != CEnd; ++C) {
1453 // If the context we are in matches any of the contexts we are
1454 // interested in, we'll add this result.
1455 if ((C->ShowInContexts & InContexts) == 0)
1456 continue;
1457
1458 // If we haven't added any results previously, do so now.
1459 if (!AddedResult) {
1460 AllResults.insert(AllResults.end(), Results, Results + NumResults);
1461 AddedResult = true;
1462 }
1463
1464 // Adjust priority based on similar type classes.
1465 unsigned Priority = C->Priority;
1466 if (!Context.getPreferredType().isNull()) {
1467 if (C->Kind == CXCursor_MacroDefinition) {
1468 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
1469 Context.getPreferredType()->isAnyPointerType());
1470 } else if (C->Type) {
1471 CanQualType Expected
1472 = S.Context.getCanonicalType(
1473 Context.getPreferredType().getUnqualifiedType());
1474 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
1475 if (ExpectedSTC == C->TypeClass) {
1476 // We know this type is similar; check for an exact match.
1477 llvm::StringMap<unsigned> &CachedCompletionTypes
1478 = AST.getCachedCompletionTypes();
1479 llvm::StringMap<unsigned>::iterator Pos
1480 = CachedCompletionTypes.find(QualType(Expected).getAsString());
1481 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
1482 Priority /= CCF_ExactTypeMatch;
1483 else
1484 Priority /= CCF_SimilarTypeMatch;
1485 }
1486 }
1487 }
1488
1489 AllResults.push_back(Result(C->Completion, Priority, C->Kind));
1490 }
1491
1492 // If we did not add any cached completion results, just forward the
1493 // results we were given to the next consumer.
1494 if (!AddedResult) {
1495 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
1496 return;
1497 }
1498
1499 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
1500 AllResults.size());
1501}
1502
1503
1504
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001505void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
1506 RemappedFile *RemappedFiles,
1507 unsigned NumRemappedFiles,
Douglas Gregorcee235c2010-08-05 09:09:23 +00001508 bool IncludeMacros,
1509 bool IncludeCodePatterns,
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001510 CodeCompleteConsumer &Consumer,
1511 Diagnostic &Diag, LangOptions &LangOpts,
1512 SourceManager &SourceMgr, FileManager &FileMgr,
1513 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics) {
1514 if (!Invocation.get())
1515 return;
1516
Douglas Gregordf95a132010-08-09 20:45:32 +00001517 llvm::Timer *CompletionTimer = 0;
1518 if (TimerGroup.get()) {
1519 llvm::SmallString<128> TimerName;
1520 llvm::raw_svector_ostream TimerNameOut(TimerName);
1521 TimerNameOut << "Code completion @ " << File << ":" << Line << ":"
1522 << Column;
1523 CompletionTimer = new llvm::Timer(TimerNameOut.str(), *TimerGroup);
1524 CompletionTimer->startTimer();
1525 Timers.push_back(CompletionTimer);
1526 }
1527
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001528 CompilerInvocation CCInvocation(*Invocation);
1529 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
1530 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001531
Douglas Gregor87c08a52010-08-13 22:48:40 +00001532 FrontendOpts.ShowMacrosInCodeCompletion
1533 = IncludeMacros && CachedCompletionResults.empty();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001534 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
Douglas Gregor8071e422010-08-15 06:18:01 +00001535 FrontendOpts.ShowGlobalSymbolsInCodeCompletion
1536 = CachedCompletionResults.empty();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001537 FrontendOpts.CodeCompletionAt.FileName = File;
1538 FrontendOpts.CodeCompletionAt.Line = Line;
1539 FrontendOpts.CodeCompletionAt.Column = Column;
1540
Douglas Gregorcee235c2010-08-05 09:09:23 +00001541 // Turn on spell-checking when performing code completion. It leads
1542 // to better results.
1543 unsigned SpellChecking = CCInvocation.getLangOpts().SpellChecking;
1544 CCInvocation.getLangOpts().SpellChecking = 1;
1545
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001546 // Set the language options appropriately.
1547 LangOpts = CCInvocation.getLangOpts();
1548
1549 CompilerInstance Clang;
1550 Clang.setInvocation(&CCInvocation);
1551 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1552
1553 // Set up diagnostics, capturing any diagnostics produced.
1554 Clang.setDiagnostics(&Diag);
1555 CaptureDroppedDiagnostics Capture(true,
1556 Clang.getDiagnostics(),
1557 StoredDiagnostics);
1558 Clang.setDiagnosticClient(Diag.getClient());
1559
1560 // Create the target instance.
1561 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1562 Clang.getTargetOpts()));
1563 if (!Clang.hasTarget()) {
1564 Clang.takeDiagnosticClient();
1565 Clang.takeInvocation();
1566 }
1567
1568 // Inform the target of the language options.
1569 //
1570 // FIXME: We shouldn't need to do this, the target should be immutable once
1571 // created. This complexity should be lifted elsewhere.
1572 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1573
1574 assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1575 "Invocation must have exactly one source file!");
1576 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1577 "FIXME: AST inputs not yet supported here!");
1578 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1579 "IR inputs not support here!");
1580
1581
1582 // Use the source and file managers that we were given.
1583 Clang.setFileManager(&FileMgr);
1584 Clang.setSourceManager(&SourceMgr);
1585
1586 // Remap files.
1587 PreprocessorOpts.clearRemappedFiles();
Douglas Gregorb75d3df2010-08-04 17:07:00 +00001588 PreprocessorOpts.RetainRemappedFileBuffers = true;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001589 for (unsigned I = 0; I != NumRemappedFiles; ++I)
1590 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
1591 RemappedFiles[I].second);
1592
Douglas Gregor87c08a52010-08-13 22:48:40 +00001593 // Use the code completion consumer we were given, but adding any cached
1594 // code-completion results.
1595 AugmentedCodeCompleteConsumer
1596 AugmentedConsumer(*this, Consumer, FrontendOpts.ShowMacrosInCodeCompletion,
Douglas Gregor8071e422010-08-15 06:18:01 +00001597 FrontendOpts.ShowCodePatternsInCodeCompletion,
1598 FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
Douglas Gregor87c08a52010-08-13 22:48:40 +00001599 Clang.setCodeCompletionConsumer(&AugmentedConsumer);
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001600
Douglas Gregordf95a132010-08-09 20:45:32 +00001601 // If we have a precompiled preamble, try to use it. We only allow
1602 // the use of the precompiled preamble if we're if the completion
1603 // point is within the main file, after the end of the precompiled
1604 // preamble.
1605 llvm::MemoryBuffer *OverrideMainBuffer = 0;
1606 if (!PreambleFile.empty()) {
1607 using llvm::sys::FileStatus;
1608 llvm::sys::PathWithStatus CompleteFilePath(File);
1609 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
1610 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
1611 if (const FileStatus *MainStatus = MainPath.getFileStatus())
1612 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
1613 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(false,
1614 Line);
1615 }
1616
1617 // If the main file has been overridden due to the use of a preamble,
1618 // make that override happen and introduce the preamble.
1619 if (OverrideMainBuffer) {
1620 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1621 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1622 PreprocessorOpts.PrecompiledPreambleBytes.second
1623 = PreambleEndsAtStartOfLine;
1624 PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
1625 PreprocessorOpts.DisablePCHValidation = true;
1626
1627 // The stored diagnostics have the old source manager. Copy them
1628 // to our output set of stored diagnostics, updating the source
1629 // manager to the one we were given.
1630 for (unsigned I = 0, N = this->StoredDiagnostics.size(); I != N; ++I) {
1631 StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
1632 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
1633 StoredDiagnostics[I].setLocation(Loc);
1634 }
1635 }
1636
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001637 llvm::OwningPtr<SyntaxOnlyAction> Act;
1638 Act.reset(new SyntaxOnlyAction);
1639 if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1640 Clang.getFrontendOpts().Inputs[0].first)) {
1641 Act->Execute();
1642 Act->EndSourceFile();
1643 }
Douglas Gregordf95a132010-08-09 20:45:32 +00001644
1645 if (CompletionTimer)
1646 CompletionTimer->stopTimer();
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001647
1648 // Steal back our resources.
Douglas Gregordf95a132010-08-09 20:45:32 +00001649 delete OverrideMainBuffer;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001650 Clang.takeFileManager();
1651 Clang.takeSourceManager();
1652 Clang.takeInvocation();
1653 Clang.takeDiagnosticClient();
1654 Clang.takeCodeCompletionConsumer();
Douglas Gregorcee235c2010-08-05 09:09:23 +00001655 CCInvocation.getLangOpts().SpellChecking = SpellChecking;
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00001656}
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001657
1658bool ASTUnit::Save(llvm::StringRef File) {
1659 if (getDiagnostics().hasErrorOccurred())
1660 return true;
1661
1662 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
1663 // unconditionally create a stat cache when we parse the file?
1664 std::string ErrorInfo;
Benjamin Kramer1395c5d2010-08-15 16:54:31 +00001665 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo,
1666 llvm::raw_fd_ostream::F_Binary);
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001667 if (!ErrorInfo.empty() || Out.has_error())
1668 return true;
1669
1670 std::vector<unsigned char> Buffer;
1671 llvm::BitstreamWriter Stream(Buffer);
1672 PCHWriter Writer(Stream);
1673 Writer.WritePCH(getSema(), 0, 0);
1674
1675 // Write the generated bitstream to "Out".
1676 Out.write((char *)&Buffer.front(), Buffer.size());
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00001677 Out.close();
1678 return Out.has_error();
1679}